8

I am creating a dashboard using Atlasboard.

I need to access the Google analytics data such as page views etc. where I will run some queries shown here.

Is there a way to access my Google analytics data without this consent page appearing? enter image description here

I am using the google-api-nodejs-client api.

I found this post where someone mentions using a service account. But I can't find anyway to get this working in JavaScript.

Any help would be great!

4

3 回答 3

10

我终于设法找到解决这个问题的方法!!!这是解决方案:)

这是假设您已经拥有一个 Google 分析帐户,该帐户具有站点数据(例如视图)并安装了请求googleapis模块。

首先,您需要在console.developers.google.com创建一个 Google 控制台帐户。

在谷歌控制台:

  • 创建一个具有合适名称的项目,例如dashboard1。
  • 从左侧菜单打开 API's & Auth -> 打开 API 选项卡 -> 打开分析 API。
  • 打开凭据选项卡 -> 创建新的客户端 ID -> 选择服务帐户
  • 密钥应自动下载 -> 单击密钥并按照说明进行操作 -> 默认密码为“notasecret” -> 然后它将输出一个 .pem 文件
  • 服务帐户将有一个电子邮件地址,例如 123434234324f34f5fd4ww5f@developer.gserviceaccount.com

现在转到www.google.com/analytics上的 Google 分析帐户:

在仪表板作业中(使用 nodejs 的服务器端):

使用此代码:

    var fs = require('fs'),
        crypto = require('crypto'),
        request = require('request'); // This is an external module (https://github.com/mikeal/request)

    var authHeader = {
            'alg': 'RS256',
            'typ': 'JWT'
        },
        authClaimSet = {
            'iss': '#######SERVICE ACCOUNT EMAIL GOES HERE#######', // Service account email
            'scope': 'https://www.googleapis.com/auth/analytics.readonly', // We MUST tell them we just want to read data
            'aud': 'https://accounts.google.com/o/oauth2/token'
        },
        SIGNATURE_ALGORITHM = 'RSA-SHA256',
        SIGNATURE_ENCODE_METHOD = 'base64',
        GA_KEY_PATH = '#######DIRECTORY TO YOUR .PEM KEY#######', //finds current directory then appends private key to the directory
        gaKey;

    function urlEscape(source) {
        return source.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
    }

    function base64Encode(obj) {
        var encoded = new Buffer(JSON.stringify(obj), 'utf8').toString('base64');
        return urlEscape(encoded);
    }

    function readPrivateKey() {
        if (!gaKey) {
            gaKey = fs.readFileSync(GA_KEY_PATH, 'utf8');
        }
        return gaKey;
    }

    var authorize = function(callback) {

        var self = this,
            now = parseInt(Date.now() / 1000, 10), // Google wants us to use seconds
            cipher,
            signatureInput,
            signatureKey = readPrivateKey(),
            signature,
            jwt;

        // Setup time values
        authClaimSet.iat = now;
        authClaimSet.exp = now + 60; // Token valid for one minute

        // Setup JWT source
        signatureInput = base64Encode(authHeader) + '.' + base64Encode(authClaimSet);

        // Generate JWT
        cipher = crypto.createSign('RSA-SHA256');
        cipher.update(signatureInput);
        signature = cipher.sign(signatureKey, 'base64');
        jwt = signatureInput + '.' + urlEscape(signature);

        // Send request to authorize this application
        request({
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            uri: 'https://accounts.google.com/o/oauth2/token',
            body: 'grant_type=' + escape('urn:ietf:params:oauth:grant-type:jwt-bearer') +
                '&assertion=' + jwt
        }, function(error, response, body) {
            if (error) {
                console.log(error);
                callback(new Error(error));
            } else {
                var gaResult = JSON.parse(body);
                if (gaResult.error) {
                    callback(new Error(gaResult.error));
                } else {
                    callback(null, gaResult.access_token);
                    console.log(gaResult);
                    console.log("Authorized");
                    ###########IF IT REACHES THIS STAGE THE ACCOUNT HAS BEEN AUTHORIZED##############
                }
            }
        });

    };



    var request = require('request'),
        qs = require('querystring');

    authorize(function(err, token) {
        if (!err) {
            // Query the number of total visits for a month
            ############requestConfig################
            var requestConfig = {
                'ids': 'ga:#######PROJECT ID GOES HERE#######',
                'dimensions': 'ga:country',
                'metrics': 'ga:users',
                'sort': '-ga:users',
                'start-date': '2014-04-08',
                'end-date': '2014-04-22',
                'max-results': '10'
            };

            request({
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token // Here is where we use the auth token
                },
                uri: 'https://www.googleapis.com/analytics/v3/data/ga?' + qs.stringify(requestConfig)
            }, function(error, resp, body) {
                console.log(body);
                var data = JSON.parse(body);
                console.log(data);
            });
        }
    });

请记住输入您自己的服务电子邮件帐户、GA_KEY_PATH 和 IDS

您可以通过更改 requestConfig 来谷歌分析数据。我用这个谷歌分析查询工具来帮助我: http: //ga-dev-tools.appspot.com/explorer/

然后应该在控制台中输出数据。

希望这可以帮助 :)

于 2014-04-22T14:21:43.573 回答
4

除了 smj2393 的答案,对于那些想要创建特定 URL 来检索 Google Analytics API 提供的 JSON 的人,这里有一个 Node Express 路由的示例。您需要安装官方的 Google API Node npm 包 ( https://www.npmjs.org/package/googleapis )。

var google = require('googleapis');
var analytics = google.analytics('v3');
var ENV = process.env;

//get key.p12 in Google Developer console
//Extract it with : openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem
//Get GOOGLE_API_EMAIL in Google Developer console (Service Account)
//Get GOOGLE_ANALYTICS_VIEW_ID in Google Analytics Console : Admin -> View -> View Parameters -> View ID
//Add GOOGLE_API_EMAIL in the Google Analytics account users

var authClient = new google.auth.JWT(
    ENV.GOOGLE_API_EMAIL,
    './keys/googlekey.pem', //path to .pem
    null,
    // Scopes can be specified either as an array or as a single, space-delimited string
    ['https://www.googleapis.com/auth/analytics.readonly']);

module.exports = function(req, res, next) {
  var startDate = (req.query.start_date) ? req.query.start_date : '7daysAgo';
  var endDate = (req.query.end_date) ? req.query.end_date : 'yesterday';

  authClient.authorize(function(err, tokens) {
    if (err) {
      console.log(err);
      return;
    }

    // Make an authorized request to list analytics files.
    // list of dimensions and metrics : https://developers.google.com/analytics/devguides/reporting/core/dimsmets
    analytics.data.ga.get({
      auth: authClient,
      "ids":'ga:'+ENV.GOOGLE_ANALYTICS_VIEW_ID,
      "start-date":startDate,
      "end-date":endDate,
      "metrics":"ga:sessions,ga:pageviews",
      "dimensions":"ga:deviceCategory"

      }, function(err, result) {
        console.log(err);
        console.log(result);
        if(!err){
          res.json(result);
        }
        else{
          next();
        }
    });
  });
}

此路由将显示一个 JSON,表示设备(台式机、移动设备和平板电脑)的会话数和 pageViews 数。您可以使用 GET 参数传递 start_date 或 end_date。

希望这有帮助。

于 2014-11-14T16:38:18.160 回答
0

google-analytics从 Atlasboard Atlassian 包中查看作业。它使用Google APIs Node.js Client npm 包:

https://bitbucket.org/atlassian/atlasboard-atlassian-package/src/master/jobs/google-analytics/google-analytics.js?at=master&fileviewer=file-view-default

您可以使用它与实时或经典的 Google Analytics API 对话。

于 2015-11-06T21:41:48.810 回答