yko_ yko_ - 3 years ago 207
PHP Question

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

i'm using php library google-api-php-client-2.2.0

i'm trying to automate update of a google drive spreadsheet with values each hour by executing php script via crontab

here is how i get my client to work with google drive service

function getClient() {
$client = new Google_Client();

// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
if ($client->isAccessTokenExpired()) {
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
$accessToken = json_decode(file_get_contents($credentialsPath), true);

return $client;

and below is a code which searches for the correct google drive file and updates it once found

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', __DIR__ . '/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(Google_Service_Drive::DRIVE)));

$client = getClient();
$service = new Google_Service_Drive($client);

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

$data = get_results_as_string($all); // this is data to be updated with

if (count($results->getFiles()) == 0) {
print "No files found.\n";
foreach ($results->getFiles() as $file) {
if ($file->getName() == $GOOGLE_SPREADSHEET_NAME){
$fileId = $file->getId();
$emptyFile = new Google_Service_Drive_DriveFile();
$service->files->update($fileId, $emptyFile, array(
'data' => $data,
'mimeType' => 'text/csv',
'uploadType' => 'media',
'fields' => 'id')

i expect that when access token i grab from CLIENT_SECRET_PATH file expires - i will fetch (since i have appropriate check for this) new access token from refresh token i have in the same file.
i overwrite the file with what has been fetched and go further with updates and routine.

however this works for around of ~12 hours (i'm running this once per hour) and then stops to be working.
appreciate if you could help on this please

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download