Google API check access token expires

Assume you know how to request access token. In this example we store access token on $_SESSION.

Follow docs https://developers.google.com/accounts/docs/OAuth2UserAgent#validatetoken in example below implement with

PHP

$_SESSION['token'] = $client->getAccessToken();
if(isset($_SESSION["token"]))
{
$accessToken = $_SESSION['token'];
$tokenArray = json_decode($accessToken,true);

$urlCheckToken = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=".$tokenArray["access_token"];

$tokenInfo = json_decode(file_get_contents($urlCheckToken),true);
/** if not expires then return
{
"issued_to": "312061235759.apps.googleusercontent.com",
"audience": "312061235759.apps.googleusercontent.com",
"user_id": "111780638437171864416",
"scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/drive",
"expires_in": 3287,
"email": "emeeting.ktb@gmail.com",
"verified_email": true,
"access_type": "offline"
}
*/

//accesss token expires
if(isset($tokenInfo["error"]) || $tokenInfo == "")
{
session_unregister("token");
$flashMsg->add('w', 'Login expired. Please login again.');
echo '<script type="text/javascript">// <![CDATA[
'
;
                echo 'window.location = "'.$config['baseUrl'].'login.php"';
                echo '
// ]]></script>'
;
}

}

Related posts:

This entry was posted in Google API Oauth2.0. Bookmark the permalink.