google-auth-library-php
google-auth-library-php copied to clipboard
How to refresh an expired token?
I used the steps from this page to get the access token. Now I have the access token and refresh token.
How can you refresh the access_token using the refresh token?
https://github.com/googleapis/php-analytics-data/pull/2/commits/175f05d8026adfba4ae44f0001337a2522a65cfc#top
$oauth = new OAuth2([
'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
'tokenCredentialUri' => 'https://oauth2.googleapis.com/token',
'authorizationUri' => $keys->{'web'}->{'auth_uri'},
'clientId' => $keys->{'web'}->{'client_id'},
'clientSecret' => $keys->{'web'}->{'client_secret'},
'redirectUri' => 'http://' . $_SERVER['HTTP_HOST'] . '/',
]);
$auth_url = $oauth->buildFullAuthorizationUri();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
// If an OAuth2 authorization code is present in the URL, exchange it for
// an access token.
$oauth->setCode($_GET['code']);
$oauth->fetchAuthToken();
// Persist the acquired access token in a session.
$_SESSION['access_token'] = $oauth->getAccessToken();
// Refresh the current page.
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
Any suggestion?
If you use the AuthTokenMiddleware, which you can see an example in the README, you will not need to handle manually refreshing the token, as it will happen automatically with the middleware.