0

我遇到了谷歌驱动 API 令牌的问题,真的需要一些帮助,拜托。只是为了让您知道这是我第一次处理谷歌 API 和令牌。

所以我做的步骤是我从谷歌驱动API页面 https://developers.google.com/drive/api/v3/quickstart/php获取PHP快速入门代码

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    $client->setAuthConfig('/my path to/ credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = '/my path to/ token.json';
    if (file_exists($tokenPath)) {
        $check = file_get_contents($tokenPath); <---- Just added this line and the next one to test it from an article i read but no success
        $client->setAccessToken($check);
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->refreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            echo "Open the following link in your browser:\n%s\n", $authUrl;
            echo 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

我通过使用 google oauth2 游乐场作为 URI 并安装了我使用的 token.json 文件来使用 credentials.json 运行它。

所以效果很好,我根据需要创建和删除了我的文件,但昨天突然(在使用它大约 10 天并且工作良好之后)它都停止给我一个错误,说令牌已过期:

An error occured{ "error": "invalid_grant", "error_description": "Token has been expired or revoked." }

在线阅读我看到很多线程提到它不应该过期,因为有这条线

$client->refreshToken($client->getRefreshToken());

在那里,但我的情况并非如此,它仍然过期。

我很确定我错过了一些东西,请赐教,谢谢。

4

0 回答 0