更新:我已经把代码变成了NPM 模块。
我已经为服务帐户创建了一个 JWT 令牌,并且我可以访问用户数据,但我想获取我的分析数据以使用它来驱动我网站上的内容。
注意:我不知道有没有比这更好的方法,但是现有的 npm 工具似乎要求你输入密码。结果,我最终使用了 REST 调用而不是gapi
工具。
这是我得到的错误
{ error:
{ errors: [ [Object] ],
code: 403,
message: 'User does not have any Google Analytics account.' } }
这是我正在使用的用于用户数据的代码。
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var scopes = [
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/analytics.readonly'
];
var d = new Date();
var seconds = d.getTime() / 1000 + 60*59;
var SERVICE_CLIENT_ID = "xxxxxxx-0h21osagsg02eqk45me6ts7jn3kf0vfr.apps.googleusercontent.com";
var SERVICE_EMAIL = "xxxxxxx-0h21osagsg02eqk45me6ts7jn3kf0vfr@developer.gserviceaccount.com"
var claim_set = {
"iss": SERVICE_EMAIL,
"scope": 'https://www.googleapis.com/auth/analytics.readonly',
"aud": 'https://www.googleapis.com/oauth2/v3/token',
"exp":seconds,
"iat":seconds
};
var algorithm = {"alg":"RS256","typ":"JWT"};
var private_key = fs.readFileSync('privatekey.pem');
var signature = jwt.sign(claim_set, private_key, { algorithm: algorithm.alg});
var post_obj = {
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: signature
};
request.post({
url:'https://www.googleapis.com/oauth2/v3/token',
form: post_obj
}, function(err, data) {
if (err) throw err;
var body = JSON.parse(data.body);
var token = body.access_token;
// console.log(token);
console.log("Token: ",token);
var auth_obj = {
'auth': {
'bearer': token
}
};
// THIS CODE DOES RETURN INFORMATION
// request.get('https://www.googleapis.com/plus/v1/people/me', auth_obj, function(err, data) {
// if (err) throw err;
// console.log(JSON.parse(data.body));
// });
var report = {
'ids': 'ga:78624107',
'start-date': '2014-10-01',
'end-date': '2014-12-31',
'metrics': 'ga:sessions,ga:bounces'
};
var report2 = 'metrics=ga%253Ausers&start-date=2015-02-24&end-date=2015-03-10&max-results=50'
var report3 = 'ids=ga:78624107&start-date=2015-02-24&end-date=2015-03-10&metrics=ga:users'
request.get('https://www.googleapis.com/analytics/v3/data/ga?'+report3, auth_obj, function(err, data) {
if (err) throw err;
console.log(JSON.parse(data.body));
});
});