我们已经在Google Analytics(分析)中设置了一个分析项目,并为该服务帐户创建了凭据,现在我们可以使用.json文件来获取记录。
KEY_FILE_LOCATION = 'config.json'
VIEW_ID = 'XXXXXX'
def initialize_analyticsreporting():
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
但是我们想通过调用POST API来获取记录 https://analyticsreporting.googleapis.com/v4/reports:batchGet在授权标头中使用JWT令牌。 我们正在创建的令牌是有效的,但我们收到了“未授权”错误。
def build_jwt(private_key, client_email, client_id, private_key_id):
try:
iat = time.time()
exp = iat + 3600
payload = {'iss': client_email,
'sub': client_email,
'aud': 'https://analyticsreporting.googleapis.com/v4/reports:batchGet',
'iat': iat,
'exp': exp}
additional_headers = {'kid': private_key_id}
signed_jwt = jwt.encode(payload, private_key, algorithm='RS256',headers=additional_headers)
return signed_jwt
except Exception as e:
print(e)
headers = {"Content-Type": "application/json", "authorization": "Bearer " + signed_jwt.decode("utf-8")}
response = requests.post(URL, json=data, headers=headers)
这是我们得到的以下错误
{'error': {'code': 401, 'message': 'Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.', 'status': 'UNAUTHENTICATED'}}
我们使用的有效载荷有问题吗?或是否存在此错误的参考链接?