google 驱动器 api 即使我使用刷新令牌,访问令牌也会在 ~12 小时内过期

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

我正在使用 php 库 google-api-php-client-2.2.0

我正在尝试通过 crontab

执行 php 脚本,每小时自动更新一个 google 驱动器电子表格的值

这是我如何让我的客户使用 google 驱动器服务

function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $client->setIncludeGrantedScopes(true);

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

    return $client;
}

以下是搜索正确的 google 驱动器文件并在找到后更新它的代码

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";
}else{
    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')
            );
        }
    }
}

我希望当我从 CLIENT_SECRET_PATH 文件中获取的访问令牌过期时 - 我将从同一文件中的刷新令牌中获取(因为我对此进行了适当的检查)新的访问令牌。 我用已获取的内容覆盖文件并进一步更新和例程。

然而,这会工作约 12 小时(我 运行 每小时一次),然后停止工作。 如果您能提供帮助,我将不胜感激

我想通了,下面几行是通过文件查找:

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

默认 pageSize 值 10 太小了。一段时间后,您正在寻找的文档 ID 将不会在前 10 个结果中返回。变量可在 [1;1000] 范围内配置 我输入了 1000,它已经解决了我的问题。