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

How to show google analytics of my website in my backend

本文关键字:谷歌 网站 我的 后台 显示      更新时间:2023-09-26

我想在我的管理面板上显示我的谷歌分析。我使用了谷歌分析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错误。

可能是它愚蠢的问题。但我不知道该怎么做。请有人帮我。

您是否调用了getAuthResponse?此方法返回您需要使用的访问令牌。

getAuthResponse()

返回:对象

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

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

不幸的是,您跳过了链接文档中的步骤3。

步骤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

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