bel*_*cea 8 authentication api google-analytics node.js
我很难使用Node.js客户端库对Google Analytics Reporting API v4进行身份验证.我尝试了所有方法,从JWT(服务令牌:JSON和P12),API密钥和OAuth 2.0开始,但我从未成功通过身份验证.
我在开发人员控制台中激活了API,创建了ID并授予了我的Google Analytics(分析)属性和视图的权限.我成功获得了服务帐户的授权和访问令牌,但我不知道如何使用它来对Analytics Reporting API v4进行身份验证.
我被困在401错误消息前面:"请求没有有效的身份验证凭据".我尝试使用JWT模仿用户,但随后服务帐户未经授权.
使用Node.js客户端库和JWT身份验证:
var google = require('googleapis.js');
var viewID = 'XXXXXXXXX'; // Google Analytics view ID
var key = require('service_account.json'); // Service account
var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/analytics.readonly'], null);
var oauth2Client = new google.auth.OAuth2();
jwtClient.authorize(function(err, result) {
if (err) {
console.log('Unauthorize');
console.log(err);
return;
}
oauth2Client.setCredentials({
access_token: result.access_token
});
//Need to authenticate somewhere near here
var analytics = google.analyticsreporting('v4');
//Or here
var req = {
reportRequests: [
{
viewId: viewID,
dateRanges: [
{
startDate: '2016-05-01',
endDate: '2016-06-30',
},],
metrics: [
{
expression: 'ga:users',
}, {
expression: 'ga:sessions',
},],
},],
};
//Maybe here
analytics.reports.batchGet(req,
function(err, response) {
if (err) {
console.log('Fail');
console.log(err);
return;
}
console.log('Success');
console.log(response);
}
);
});
Run Code Online (Sandbox Code Playgroud)
以前版本的Node.js客户端库似乎有一个方法来指定客户端,但它消失了,可能已弃用.
withAuthClient(oauth2Client)
Run Code Online (Sandbox Code Playgroud)
我试图在API调用或请求中传递客户端或令牌,但没有一个工作.
google.analyticsreporting({ version: 'v4', auth: oauth2Client });
google.analyticsreporting({ version: 'v4', access_token: result.access_token });
Run Code Online (Sandbox Code Playgroud)
也许这是一个noob问题,但我不知道该怎么做,我没有在Google API或客户端库文档中看到与Analytics Reporting v4身份验证相关的任何内容,我找到的大多数示例都使用了Google AnalyticsAPI v3.
如果有人成功通过Google Analytics Reporting API v4进行身份验证,请帮助:/
找出我遗漏的东西:
Google API客户端库"选项":
google.options({ auth: oauth2Client }); //this one is not very optional
Run Code Online (Sandbox Code Playgroud)与Google Analytics Reporting API v4文档不同,使用客户端库的查询必须具有标头,以便为每个请求指定客户端(感谢CVarisco注意到,客户端库文档并不真正准确..):
var request ={
'headers': {'Content-Type': 'application/json'},
'auth': oauth2Client,
'resource': req,
};
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
3274 次 |
| 最近记录: |