如何在Google Analytics请求中获取用户特定数据?

时间:2015-07-27 08:23:22

标签: node.js google-analytics google-analytics-api

我正在尝试创建一个网络应用,用户可以通过OAuth2授予​​对其Google Analytics帐户的访问权限。在积极响应之后,我想向该用户的GA数据发出请求(在实际应用中,请求将“离线”)。但是在打电话时:

google.analytics('v3').data.ga.get(params, callback);

params应包含ids,该列表应为用户的“表格ID”列表。我如何获得这些ID?是否有必要通过另一个profile-scoped-request获取此信息?

代码:

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var clientId = '123-123.apps.googleusercontent.com';
var clientSecret = 'abc';
var redirectUrl = 'http://localhost:8080/redirect';

var authRequest = function(req, res) {
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
  var scopes = [ 'https://www.googleapis.com/auth/analytics.readonly' ],
      params = { state: 'some-data', access_type: 'offline', scope: scopes };
  var url = oauth2Client.generateAuthUrl(params);
  res.redirect(301, url); // will return to "authResult()"
};

var _sampleAnalytics = function(req, res, oauthClient) {
 var params = {
    auth: oauthClient,
    metrics: 'ga:visitors,ga:visits,ga:pageviews',
    'start-date': '2015-06-01',
    'end-date': '2015-06-30',
    ids: ['ga:123456789'] // <== How to get this parameter?
  };
  google.analytics('v3').data.ga.get(params, function(err, response) {
    // todo
  });
};

var authResult = function (req, res) {
  if (req.query.error) {
    return handleError(res, req.query.error);
  }

  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
  oauth2Client.getToken(code, function(err, tokens) {
    // Now tokens contains an access_token and an optional refresh_token. Save them.
    if(err) {
      return handleError(res, err);
    } else {
      oauth2Client.setCredentials(tokens);
      _sampleAnalytics(req, res, oauth2Client);
    }
  });
};

1 个答案:

答案 0 :(得分:2)

好的,这很简单。我只需再打一次电话:

google.analytics('v3').management.accountSummaries.list(params, function(err, result) {
// ...
});

result将包含所有必需的信息。