我正在尝试按照以下说明在服务器应用程序中连接到 Google Analytics:https ://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py 。此页面建议使用 P12 密钥,但出于业务原因我需要使用 JSON 密钥(在开发人员控制台的密钥生成页面上也“推荐”)。
当我使用 P12 文件时,代码示例对我来说很好 -authorize
和build
调用都可以工作,然后我可以正确使用 API。我不能使用 JSON 文件。这是一个最小的例子:
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
import json
import base64
import httplib2
def authorize(ga_email, ga_secret):
jwt = SignedJwtAssertionCredentials(ga_email, ga_secret, scope=self.ga_scope, private_key_password='notasecret')
http = jwt.authorize(httplib2.Http())
return build('analytics', 'v3', http=http)
# this works
ga_email = 'random@words.gserviceaccount.com'
with open('client_secrets.p12', 'rb') as f:
ga_secret = f.read()
service = authorize(ga_email, ga_secret)
# this fails
with open('client_secrets.json', 'r') as f:
json_data = json.load(f)
ga_email = json_data['client_email']
ga_secret_json = json_data['private_key']
ga_secret_b64 = ''.join(ga_secret_json.split('\n')[1:-2])
ga_secret_bin = base64.b64decode(ga_secret_b64)
ga_secret = ga_secret_bin # or ga_secret_b64 or ga_secret_json
service = authorize(ga_email, ga_secret)
JSON 尝试失败并出现此错误(使用 ga_secret_bin):
File "/usr/local/lib/python2.7/dist-packages/pyOpenSSL-0.15.1-py2.7.egg/OpenSSL/_util.py", line 48, in exception_from_error_queue
raise exception_type(errors)
Error: [('asn1 encoding routines', 'ASN1_CHECK_TLEN', 'wrong tag'), ('asn1 encoding routines', 'ASN1_TEMPLATE_EX_D2I', 'nested asn1 error'), ('asn1 encoding routines', 'ASN1_TEMPLATE_NOEXP_D2I', 'nested asn1 error')]
或类似(使用 ga_secret_json 或 ga_secret_b64):
Error: [('asn1 encoding routines', 'ASN1_CHECK_TLEN', 'wrong tag'), ('asn1 encoding routines', 'ASN1_ITEM_EX_D2I', 'nested asn1 error')]
我尝试了其他一些排列:字符串处理和 base64 解码的变化,不使用private_key_password
arg 等等。我还尝试根据在使用 P12 密钥创建凭据对象后from_json
的输出填充电子邮件、密钥和其他字段来使用。to_json
我想我错过了一些简单的东西,但我对 OpenSSL 不是很熟悉,所以我不知道要寻找什么。