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.