谷歌分析API我可以使用我自己的谷歌帐户向其他人显示报告吗?

2024-09-04 19:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的客户经营着一个实现谷歌分析(跟踪)的网站。在

她想向利益相关者报告一些核心统计数据(页面浏览量)。在

利益相关者不应该访问我的客户谷歌(分析)帐户。在

是否可以使用Google Analytics API向未使用自己的Google帐户登录的用户报告?在

更新/解决

我发现实现这一点的最简单的方法是使用python获得一个“bearer”访问令牌。 您只需要一个Google服务帐户和一个私钥(api&auth>;凭证)。 让javascript客户机从服务器请求访问令牌并使用gapi.auth.setToken方法进行授权。现在您可以调用像gapi.client.analytics.management.accounts.list这样的方法。在

注意:您确实需要激活dedeveloper console中的分析API,我还必须使用openssl创建一个PEM文件,以便让rsa模块接受密钥。在

下面是我使用的python代码(简化版)。在

from os import path
import base64
import rsa
import json
import calendar
import datetime
import urllib
iat = calendar.timegm(datetime.datetime.utcnow().utctimetuple())
exp = iat + 3600
header = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9" # {"alg":"RS256","typ":"JWT"}
claimset = {
   'iss': "MY_DEVELOPER_ACCOUNT@developer.gserviceaccount.com",
   'scope': "https://www.googleapis.com/auth/analytics.readonly",
   'aud': "https://accounts.google.com/o/oauth2/token",
   'exp': exp,
   'iat': iat
}
claimset = json.dumps(claimset).encode('utf-8')
claimset = base64.urlsafe_b64encode(claimset)
signature = "%s.%s" % (header, claimset)
signature = rsa.sign(signature.encode('utf-8'), rsa.PrivateKey.load_pkcs1(open(PATH_TO_PRIVATE_KEY).read(), format='PEM'), 'SHA-256')
signature = base64.urlsafe_b64encode(signature)
postdata = {
   'grant_type': "urn:ietf:params:oauth:grant-type:jwt-bearer",
   'assertion': "%s.%s.%s" % (header, claimset, signature)
}
response = json.loads(urllib.urlopen("https://accounts.google.com/o/oauth2/token", urllib.urlencode(postdata)).read())
print response

Tags: 方法importcomauthjsondatetimegoogle帐户
1条回答
网友
1楼 · 发布于 2024-09-04 19:38:23

你应该看看Using OAuth 2.0 for Server to Server Applications。在

通过添加服务帐户电子邮件到您的客户谷歌分析帐户作为一个用户只需给它简单的读取访问。然后,您就可以使用服务帐户访问googleanalytics API并显示客户想要的统计数据。无需登录,他们将只能看到你选择的信息,从谷歌分析API。在

相关问题 更多 >