我有一个 Google+ 应用程序正在为某些测试帐户成功编写应用程序活动,但其他应用程序返回 401 Unauthorized 错误:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "unauthorized",
"message": "Unauthorized"
}
],
"code": 401,
"message": "Unauthorized"
}
}
我还在响应标头中注意到了这一点:
WWW-AuthenticateBearer realm="https://www.google.com/accounts/AuthSubRequest", error=invalid_token
这似乎表明令牌无效,但我不确定我是如何错误地使用 gapi.auth.authorize 的......特别是因为该脚本使用某些测试帐户可以完美运行,并且可以毫无问题地向 G+ 写入时刻。如果有人可以提出任何原因,某些测试帐户可能无法为编写应用程序活动进行身份验证(或下面的代码有任何问题),请告诉我!
// first call gapi.auth.authorize with immediate:true:
_checkAuth = function _checkAuth(){
gapi.auth.authorize({
client_id : 'XXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
scope : 'https://www.googleapis.com/auth/plus.login',
request_visible_actions : 'http://schemas.google.com/CreateActivity',
immediate : true
}, function(authResult){
if(!authResult || authResult.error){
_signIn();
}else{
_performAction();
}
});
},
// if not logged in, call gapi.auth.authorize with immediate:false:
_signIn = function _signIn(){
gapi.auth.authorize({
client_id : 'XXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
scope : 'https://www.googleapis.com/auth/plus.login',
request_visible_actions : 'http://schemas.google.com/CreateActivity',
immediate : false
}, function(token){
gapi.auth.setToken(token);
_performAction();
});
},
// create activity
_performAction = function _performAction(){
gapi.client.load('plus','v1', function(){
gapi.client.setApiKey('XXXXXXXXXXXXXXXXXXXXXXX');
var payload = {
"type" : 'http://schemas.google.com/CreateActivity'
};
payload.target = {
"id" : "myappid",
"image" : "http://www.example.com/xxxxxxxxxxx.jpg",
"type" : 'http://schema.org/CreativeWork',
"description" : "description of activity",
"name" : "name of activity"
};
var args = {
'path' : '/plus/v1/people/me/moments/vault',
'method' : 'POST',
'body' : JSON.stringify(payload),
'callback' : function(response) {
console.log(response); // error
}
};
// triggers 401 error for some accounts
gapi.client.request(args);
});
},