I’m using the latest version of the Google API Client PHP SDK (v2.11) to request an OAuth2 access token.
While retrieving an access token, I can see that the expires_in
value is missing from the response, which leads to a PHP error when calling isAccessTokenExpired()
later on:
Step 1 – Retrieve an access and refresh token
...
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
var_dump($client->getAccessToken());
...
Result
array(1) { ["access_token"]=> string(163) "xxxxxxxxxxxxxxxxxxx" }
It seems that both the expires_in
and created
columns are missing from this answer.
Step 2 – Let’s check if the Access token has expired and needs to be refreshed
$client->setAccessToken($_SESSION['access_token']);
if ($client->isAccessTokenExpired())
{
$client->refreshToken($_SESSION['refresh_token']);
$_SESSION['access_token'] = $client->getAccessToken();
}
Result
Warning: Undefined array key "expires_in" in
/var/www/admin/vendor/google/apiclient/src/Client.php on line 554
2
Answers
My API response was missing
expires_in
due to retrieving the tokens twice in my redirect.php script (called after the user has been authenticated).As described here, the OAuth refresh token as well as
expires_in
value are provided to you only during the first authorization. Adding aconsent
prompt also helped to address this issue.If you are doing some testing and need to reset the authorization you gave, you can do it here: https://myaccount.google.com/permissions
Here's the full script, which is now working:
It includes a domain check (i.e. replace mydomain.com by your own domain) as well as a referrer callback (i.e. populate
state
on your login page with the referrer first).This is the code I use. The library should be handling this for you.
Oauth2Callback.php
Oauth2Authentication.php