I make many different api calls to google api using access_token
so I need to handle case when access_token
is expired and exchange refresh_token
to get new one.
What is the best way to do this?
I guess turn every API call with try{}catch(){}
block.
If an exception rise, in catch()
block I will make another API call to validate access_token
through https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
endpoint.
This is probably not a good idea to turn every API call to try() catch(){}
block and duplicate catch () logic.
How can i do it better?
P.S. I am using guzzle library for making API calls.
If you're using a library provided by Google to make your calls, then I suggest you check if the library does not already handle the retry for you. The Java library does this and I suspect the Python library also does.
If you're not using a library, check if there would not be one available for your language. If will greatly help you.
If you really don't have a choice and can't use Google's libraries, then I suggest you mimic their behavior in your own code. This would mean creating a kind of GoogleRequest
behavior (a class, a module or something similar depending on your language). This behavior would provide an execute()
method that would handle the authentication error, refresh the token and retry the request.
By the way the URL used to refresh a token is not the one you listed in your question. You must send a POST
request to the URL https://www.googleapis.com/oauth2/v3/token
with this body :
client_secret=YOUR_CLIENT_SECRET&grant_type=refresh_token&refresh_token=YOUR_REFRESH_TOKEN&client_id=YOUR-CLIENT_ID
Wrapping it in a try catch is a very bad idea, because then you are going to make a request and boom its down so you need to get another one. This is probably going to up your quota. There is no reason to send a request to the API to find out if your access token is expired.
An access token is good for 1 hour. You can use that to decided if you need to refresh your access token. It's how the Google-api-php-client library does it.
I really do recommend you use Google's Client lib it will make things much easer for you.
I'm the anti-library guy, so I'd say read https://developers.google.com/accounts/docs/OAuth2WebServer#refresh and just make a simple POST and parse the JSON response. It doesn't get much simpler.
PHP code exchange is easy if you just use the Google API Client library for PHP. From the Google+ Quickstart sample:
$client = new Google_Client();
$client->setApplicationName('YOUR_APP_NAME';);
$client->setClientId('YOUR_CLIENT_ID';);
$client->setClientSecret('YOUR_CLIENT_SECRET';);
$client->setRedirectUri('postmessage');
// Code came from a POST
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());