I have a Google+ app that is successfully writing app activity for certain test accounts, yet others return a 401 Unauthorized error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "unauthorized",
"message": "Unauthorized"
}
],
"code": 401,
"message": "Unauthorized"
}
}
I also noticed this in the response header:
WWW-AuthenticateBearer realm="https://www.google.com/accounts/AuthSubRequest", error=invalid_token
This seems to indicate an invalid token, but I'm not sure how I'm using gapi.auth.authorize incorrectly... especially because the script works perfectly using certain test accounts and writes moments to G+ without issue. If anyone could suggest any reasons certain test accounts might be unable to authenticate for writing app activity (or anything wrong with the code below), please let me know!
// 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);
});
},