I have a problem with google api and oauth2 token.
There is an app which allows to synchronize contacts / calendar with your google account by oauth2 token.
When first time user wants to connect with his google account, he needs to grant access , then app is receiving code/token which is saved and will be used for offline synchronization later.
function getClient($app)
{
$client = new Google_Client();
$client->setAuthConfig("path_to_secret.json");
switch($app)
{
case 'contacts':
$client->addScope(Google_Service_Script::WWW_GOOGLE_COM_M8_FEEDS);
$client->addScope(Google_Service_People::USERINFO_EMAIL);
break;
case 'calendar':
$client->addScope(Google_Service_Calendar::CALENDAR);
break;
default:
throw new Exception('API Callback not defined in setup');
}
$client->setAccessType('offline'); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setRedirectUri(GOOGLE_APP_URL . $app.'/callback.php');
return $client;
}
(there are different tokens for contacts and calendar)
The synchronization script:
...
try
{
$client = getClient('calendar');
$client->setAccessToken(unserialize($accessToken));
$http = $client->authorize();
$service = new Google_Service_Calendar($client);
...
}
$accessToken is a serialized string like:
a:5:{s:12:"access_token";s:131:"******token_here********";s:10:"token_type";s:6:"Bearer";s:10:"expires_in";i:3598;s:8:"id_token";s:902:"***id_token****";s:7:"created";i:1505178047;}
This is working for first time and couple more times but after some time(hours) there is an error:
Error: {"error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }}
What I am doing wrong?
What is interesting that for contacts synchronization works fine all the time (access token has the same attributes as in calendar synchronization )
access_token
, if it's needed. When you authorizing any user by code – you might haverefresh_token
, which allows you to get newaccess_token
, when last is expired (just with access type == 'offline'). What changes did you make before you get this error? – Sergey Chizhik