I am new to Google API and trying to follow quick start guide. I have configured My PHP file for same like below
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig('ddc.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$client->setApprovalPrompt('force');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} 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));
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
And using For Update Sheet Like below
$client = getClient();
$service = new Google_Service_Sheets($client);
During ENABLE API, I have choose https://example.com/sheet/oauth2callback
as callback URL but there no any file related in this directory like oauth2callback , May be that issue?
I am generating token in My Window 10 PC using CMD and generating token. Then I am using that token in my hosting which run my file in Browser. Its working fine but After about hour token getting expired and asking me again for generate token with message like
Open the following link in your browser:.....
I have read that its refresh token automatically and we do not need do anything but in my case its not getting new token automatically or may be I am missing something. Let me know if someone here can help me for same.
Access tokens are short lived tokens, they will expire after an hour and then the user will need to either reauthenticate or you should request offline access and store the refresh token in your code so that you can use that in the future to request a new access token when ever your current access token is due to expire.
Assuming that you have a refresh token and it has been set on your client the following code would refresh as needed.
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
Code ripped from Oauth2Authentication.php