PHP Gmail API access' token expired without login

46 Views Asked by At

I am using Google Client class to get access to Gmail API using with the tokens that I have stored in the tokens.json file.

When the access token is expired, I have tried this:

if ($client->isAccessTokenExpired() == true) {
    $tokens = json_decode(file_get_contents($tokenPath), true);
    $refresh_token_key = $tokens['refresh_token'];
    $access_token = $refresh_token_key;

    // Update the access token and save it to the file
    $client->setAccessToken($refresh_token_key);

    $refreshToken = $client->getRefreshToken();
    //$accessToken = $client->fetchAccessTokenWithRefreshToken($refreshToken);
}

It will not let me to get access to Gmail API as it will give me an error:

"error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Invalid Credentials",
        "domain": "global",
        "reason": "authError",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "UNAUTHENTICATED"
  }
}

So I have to use this instead:

if ($client->isAccessTokenExpired() == true) {
    $tokens = json_decode(file_get_contents($tokenPath), true);
    $refresh_token_key = $tokens['access_token'];
    $access_token = $refresh_token_key;

    // Update the access token and save it to the file
    $client->setAccessToken($refresh_token_key);

    $refreshToken = $client->getRefreshToken();
    //$accessToken = $client->fetchAccessTokenWithRefreshToken($refreshToken);
}

It works fine, but how I can get access to Gmail API when my token is expired?

Here is the full code:

<?php
   
require_once('googleapi2/google/vendor/autoload.php');

//json file from your api
$CLIENT_SECRET_PATH = __DIR__ . '/tokens.json';
$client = new Google_Client();
$client->setAuthConfigFile('tokens.json');
$client->setDeveloperKey("AIzaSyBdawagXmS4cM7nMCaRn01_V3taY06uo5c");
$client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);
$client->addScope('https://www.googleapis.com/auth/userinfo.email');
$client->addScope('https://www.googleapis.com/auth/gmail.readonly');
$client->setAccessType('offline'); //not sure this is necessary for this type of call
//$client->setIncludeGrantedScopes(true);   // incremental auth


// Load previously authorized token from a file, if it exists.
$tokenPath = 'tokens.json';



if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    
    if ($client->isAccessTokenExpired() == true) {
        $tokens = json_decode(file_get_contents($tokenPath), true);
        $refresh_token_key = $tokens['access_token'];
        $access_token = $refresh_token_key;

        // Update the access token and save it to the file
        $client->setAccessToken($refresh_token_key);

        $refreshToken = $client->getRefreshToken();
        //$accessToken = $client->fetchAccessTokenWithRefreshToken($refreshToken);
    }
    
    


    // Refresh the token if it's expired
    /*if ($client->isAccessTokenExpired() == true) {
        $accessToken = $client->getRefreshToken();
        echo $accessToken;
        echo "<br>";
        exit;

        // Update the access token and save it to the file
        //$client->setAccessToken($accessToken);
        //file_put_contents($tokenPath, json_encode($accessToken));
    }*/

}

//$client->addScope('https://www.googleapis.com/auth/gmail.readonly');

$gmailService = new Google_Service_Gmail($client);
$users = $gmailService->users->getProfile('me');

print_r($gmailService);
exit;

?>

When the access token is expired, I am pretty sure there is a way to get access to Gmail API without login if I have to use refresh token. I have tried it and it doesn't work. I have been searching for the answers and none of them does helps.

If I have to use the refresh token, how I can use it to update the access token or how I can use the refresh token to get access to Gmail API?

Any advice would be much appreciated.

0

There are 0 best solutions below