如何在我的后端显示我的网站的谷歌分析

时间:2015-12-23 14:07:58

标签: javascript json google-analytics google-analytics-api

我想在我的管理面板上显示我的Google分析。我跟着google analytics api。我创建了服务端授权并下载了json数据

{
    "type": "service_account",
    "project_id": "xxxx",
    "private_key_id": "xxxxxxxxxxxxxxxxx",
    "private_key": "-----BEGIN PRIVATE KEY-----xxxxxxxxx-----END PRIVATE KEY-----\n",
     "client_email": "xxxxxxxxxxxxxx",
     "client_id": "xxxxxxxxxxxxxxx",
     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
     "token_uri": "https://accounts.google.com/o/oauth2/token",
     "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
     "client_x509_cert_url":"xxxxxx"
}

创建上面的json并复制了该教程中提到的js代码。

在js代码中,它要求

   gapi.analytics.auth.authorize({
      'serverAuth': {
      'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}'
      }
   });

这里的问题是我找不到ACCESS_TOKEN。我刚刚用私钥,客户端ID,私钥ID替换并尝试但是它显示401错误。

可能是它的愚蠢问题。但我不知道如何得到这个。请有人帮助我。

2 个答案:

答案 0 :(得分:1)

您致电getAuthResponse了吗?此方法返回您需要使用的访问令牌。

  

getAuthResponse()

     

返回:对象

     

获取原始授权返回的身份验证数据   请求。返回的对象包括访问令牌,可以是   通常手动进行经过身份验证的请求。

请参阅此处https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference?hl=en

答案 1 :(得分:0)

不幸的是,你跳过step 3 from the linked documentation

步骤3:使用JSON密钥数据来请求访问令牌

访问令牌是从运行python代码获得的:

# service-account.py

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

您链接的示例是opensource,此方法在服务器端调用,访问令牌通过Web应用程序模板变量返回。