【问题标题】:How do I get an access token from Google Analytics using a service account?如何使用服务帐户从 Google Analytics 获取访问令牌?
【发布时间】:2016-04-29 01:29:39
【问题描述】:
【问题讨论】:
标签:
rest
curl
google-analytics
service-accounts
【解决方案1】:
Server Side Authorization Embed API 演示有一个这样做的例子。该示例使用适用于 Python 的 Google API 客户端库,但是,正如 @DalmTo 在他们的评论中提到的那样,您可以查看它在后台复制请求的行为。
获取访问令牌的代码如下所示:
import json
from oauth2client.client import SignedJwtAssertionCredentials
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'
# Load the key file's private data.
with open(KEY_FILEPATH) as key_file:
_key_data = json.load(key_file)
# Construct a credentials objects from the key data and OAuth2 scope.
_credentials = SignedJwtAssertionCredentials(
_key_data['client_email'], _key_data['private_key'], SCOPE)
# Defines a method to get an access token from the credentials object.
# The access token is automatically refreshed if it has expired.
def get_access_token():
return _credentials.get_access_token().access_token