我正在尝试创建一个网络应用程序,用户可以通过 OAuth2 授予对其 Google Analytics 帐户的访问权限。在得到积极响应后,我想向该用户的 GA 数据发出请求(在实际应用程序中,该请求将“离线”发出)。但是调用时:
google.analytics('v3').data.ga.get(params, callback);
params
应包含 ids
,它应该是用户的“表 ID”列表。我如何获得这些 ID?是否有必要通过另一个配置文件范围的请求来获取此信息?
代码:
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);
}
});
};
最佳答案
好的,这很简单。我只需要再次调用电话:
google.analytics('v3').management.accountSummaries.list(params, function(err, result) {
// ...
});
结果
将包含所有必需的信息。
关于node.js - 如何获取有关 Google Analytics 请求的用户特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31648184/