javascript - 无需登录即可使用 GAPI 获取 Google Analytics 数据

标签 javascript google-analytics oauth-2.0 google-api-js-client

我有一个新闻网站,我必须使用谷歌分析跟踪的数据来显示“当天访问量最大的 5 个新闻”,但我还没有成功。我发现的每个代码示例都会显示一个登录弹出窗口,就好像他将他的谷歌帐户与分析中的数据相关联一样,但显然情况并非如此。 我正在尝试将其与 JS 一起使用,类似这样

<script src="https://apis.google.com/js/client:platform.js"></script>

...



<script>
    function start() {
      // 2. Initialize the JavaScript client library.
      gapi.client.load('analytics', 'v3').then(function() {
        gapi.client.init({
          'apiKey': 'SOME_API_KEY',
          'clientId': 'SOME_CLIENT_ID',
          'scope': 'https://www.googleapis.com/auth/analytics.readonly',
        }).then(function() {
            return gapi.client.analytics.data.ga.get({
              'ids': 'ga:' + "SOME_ID",
              'start-date': 'yesterday',
              'end-date': 'today',
              'metrics': 'ga:pageviews',
              'dimensions': 'ga:pagetitle',
              'max-results': '5',
              'sort': '-ga:pageviews,-ga:date'
            });
        }).then(function(response) {
          console.log(response  );
        }, function(reason) {
          console.log(reason)
          console.log('Error: ' + reason.result.error.message);
        });
      });
    };
    gapi.load('client', start);
</script>

我收到了这样的回复:

{result: {…}, body: "{↵  "error": {↵    "code": 401,↵    "message": "Re…project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵", headers: {…}, status: 401, statusText: null}
body
:
"{↵  "error": {↵    "code": 401,↵    "message": "Request is missing required authentication credential. 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"↵  }↵}↵"

我错过了什么?

最佳答案

我不确定您是否能够使用 NodeJS。但是如果你使用 google-oauth-jwt图书馆或 googleapis图书馆。参见 this link有关使用 NodeJS 的 googleapis 的示例教程。

您需要使用服务帐户中的 key ,因此您需要创建一个服务帐户。您可以使用 googleapis.auth.JWT 使用访问 token 登录,这需要您的服务帐户电子邮件地址、私钥和范围 [' https://www.googleapis.com/auth/analytics.readonly ']

我将向您展示我的一个项目中的一些示例代码:

Googleapis 库 NodeJS(我使用的是 express,我在路由中使用了 promise 来获取 key 和 google api 数据)

var jwtClient = new google.auth.JWT(
            '[your serviceaccount@emailaddress]',  
            path.join(__dirname, '../.', '/files/KEY.json'),//path to your json key file]
            null,
            ['https://www.googleapis.com/auth/analytics.readonly'] //scope
        );

        jwtClient.authorize(function (err, tokens) {
            console.log('jwtClient.authorize() started');

            //console.log(tokens);
            if (err) {
                console.log('error in authorization:' + err);
                return;
            } else {
                console.log('authorization success!');
                console.log(tokens);
                return tokens;
            }
        });



var VIEW_ID = 'ga:[yourviewid]';
    analytics.data.ga.get({
        'auth': jwtClient,
        'ids': VIEW_ID,
        'metrics': 'ga:uniquePageviews',
        'dimensions': 'ga:pagePath',
        'start-date': 'today',
        'end-date': 'today',
        'sort': '-ga:uniquePageviews',
        'max-results': 5,

    }, function (err, response) {
        if (err) {
            console.log(err);
            return;
        }
        //console.log(JSON.stringify(response, null, 4));
        return JSON.stringify(response, null, 4);
    });

带有路由和 Google-oauth-jwt 的示例图书馆

var express = require('express');
var router = express.Router();
var googleAuth = require('google-oauth-jwt');

router.get('/login', function(req, res, next) {
      googleAuth.authenticate({
        email: 'yourserviceaccount@project.iam.gserviceaccount.com',
        // use the PEM file we generated from the downloaded key
        key: "-----BEGIN PRIVATE KEY-----\nMII [your big ass private key which can be obtained by using a file too.-----END PRIVATE KEY-----\n",
        // specify the scopes you wish to access
        scopes: ['https://www.googleapis.com/auth/analytics.readonly']
        }, function (err, token) {
          res.json({token: token});
      });
    });

关于javascript - 无需登录即可使用 GAPI 获取 Google Analytics 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47688423/

相关文章:

javascript - 我需要有关如何从 Node js 在 sql server 中插入的帮助

magento - 如何拆分 (A/B) 测试 Magento 产品页面

javascript - 延迟运行跟踪代码好吗

spring-security - 为什么资源服务器必须知道 Spring OAuth2 中的 client_id?

java - 无法从我的 Oauth 服务器获取 token

javascript - JS while 循环不会在 true 处停止

javascript - 在 Chrome 扩展程序中打开新标签页

javascript - 基于 cookie 值的谷歌分析数据

api - oAuth2 - WSO2 API 管理器和身份服务器集成

javascript - 工具提示不适用于初始绘图,但在绘图更改后开始工作