0

I am currently working on google docs API with PHP code. I am following this but with this case When my token get expires, I need to delete the token.json file and again run the PHP quickstart.php command on the terminal to generate a new token.json file. By this method, I am able to continue with my work. But this method is not appropriate.

I did code like this-

<?php
ini_set('display_errors', 1);
require __DIR__ . '/vendor/autoload.php';

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Docs API PHP Quickstart');
    $client->setScopes([
                        "https://www.googleapis.com/auth/documents",
                        "https://www.googleapis.com/auth/drive.file",
                        "https://www.googleapis.com/auth/drive",
                        Google_Service_Drive::DRIVE_READONLY,
                        ]);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory('token.json');
    
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {

        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        
        $authCode = trim(fgets(STDIN));
        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }

        file_put_contents($credentialsPath, json_encode($accessToken));
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($accessToken);       
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }

    return $client;
}

from this above code, I am not able to get the refresh token from my file. Then why this function is used!

if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($accessToken);       
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }

Although I researched a lot and gone through this links- Google API Client "refresh token must be passed in or set as part of setAccessToken"

But, I didn't get what I wanted. Can anybody tell me what am I missing or doing wrong in fetching the refresh token from the file? It also won't give us any kind of notification that the token is expired, It just simply throws an error. I cannot do this in my project.

Please tell me how we can achieve this. It would be a great help.

TBA
  • 1,921
  • 4
  • 13
  • 26
Taniya Halder
  • 185
  • 1
  • 12
  • 1
    You can get the refresh token using `$client->getRefreshToken()`. You cannot refresh a token with an access token. So you should use `$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());` – Ron van der Heijden Mar 01 '22 at 15:55
  • @RonvanderHeijden, Thanks for replying but when I am using this it shows me the same error- 'error] => invalid_grant [error_description] => Token has been expired or revoked.' This is not helping me. Can you tell me some other way? FYI - I am getting the refresh token but From this line unable to get the new access token from this refresh token. – Taniya Halder Mar 01 '22 at 16:01
  • So your refresh token is also expired. You should request new ones using the `authUrl`. – Ron van der Heijden Mar 01 '22 at 16:03
  • @RonvanderHeijden, I thought refresh token never gets expire. – Taniya Halder Mar 01 '22 at 16:06
  • You should be able to read the tokens and check their expirations. – Ron van der Heijden Mar 01 '22 at 16:13
  • You may as well want to check this [Refresh token thread](https://stackoverflow.com/questions/8953983/do-google-refresh-tokens-expire) as you may be getting an expired token due to exceeding a maximum amount of granted live refresh tokens – Gabriel Carballo Mar 02 '22 at 00:59

0 Answers0