刷新Google Calendar API的访问令牌

时间:2018-11-21 11:09:21

标签: php google-api google-calendar-api google-oauth google-api-php-client

当前,我正在使用https://developers.google.com/calendar/quickstart/php这个API,但令牌会在3-4小时后过期,如何自动刷新Google Calendar API的访问令牌

当前代码为:

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Calendar API PHP Quickstart');
    $client->setScopes(Google_Service_Calendar::CALENDAR);
    $client->setAuthConfig(__DIR__ . '/google-calender/credentials.json');
    $client->setAccessType('offline');
    $client ->setApprovalPrompt ('force');

    // Load previously authorized token from a file, if it exists.
    $tokenPath =__DIR__ . '/google-calender/token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // 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());
        } 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);
            $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; }

1 个答案:

答案 0 :(得分:0)

您需要在请求新的访问令牌后在客户端上设置新的访问令牌。

if ($client->isAccessTokenExpired()) {              
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->setAccessToken($client->getAccessToken()); 
            $_SESSION['access_token'] = $client->getAccessToken();              
        }   

我的sample