Automatically Refresh Token Using Google Drive API with PHP Script

Automatically refresh token using google drive api with php script

You don't have to periodically ask for an access token. If you have a refresh_token, PHP client will automatically acquire a new access token for you.

In order to retrieve an refresh_token, you need to set access_type to "offline" and ask for offline access permissions:

$drive->setAccessType('offline');

Once you get a code,

$_GET['code']= 'X/XXX';
$drive->authenticate();

// persist refresh token encrypted
$refreshToken = $drive->getAccessToken()["refreshToken"];

For future requests, make sure that refreshed token is always set:

$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);

If you want a force access token refresh, you can do it by calling refreshToken:

$drive->refreshToken($refreshToken);

Beware, refresh_token will be returned only on the first $drive->authenticate(), you need to permanently store it. In order to get a new refresh_token, you need to revoke your existing token and start auth process again.

Offline access is explained in detail on Google's OAuth 2.0 documentation.

How to get Google drive refresh token automatically

in Step 1 when Click “Authorize APIs” and allow access to your account when prompted. There will be a few warning prompts, just proceed.

When you get to step 2, check “Auto-refresh the token before it expires” and click “Exchange authorization code for tokens”.

Sample Image

When you get to step 3, click on step 2 again and you should see your refresh token.

Sample Image

Now, All you need to do is a post request like below :-

POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json

{
"client_id": <client_id>,
"client_secret": <client_secret>,
"refresh_token": <refresh_token>,
"grant_type": "refresh_token"
}

google drive api access token expires in ~12h even when i use refresh token

i figured this out, below lines are to look up thru the files:

$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);

default pageSize value which is 10 is way too little. after some time doc ID you're looking for won't be returned within first 10 results. variable is configurable within range [1;1000]
i put 1000 and it has solved the issue for me.



Related Topics



Leave a reply



Submit