0

I am using the Google API Client to access the Directory API. My code is as follows:

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('G Suite Directory API');
    $client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');

    $client->setApprovalPrompt('force');

    // 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 = '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 {
            .....
            //this is where google creates the initial token
        }

    }
}

My problem revolves around this line:

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

When I initially authorise the client, I get a token.json that contains a refresh token. After an hour, the token expires and it creates a new token. This new token however does not include a refresh token. So it will only ever refresh once and then stop working after 2 hours.

Is there a setting I'm missing? I had to add $client->setApprovalPrompt('force'); in order for the initial token to include a refresh token.

4

1 回答 1

0

您应该继续重复使用最初获得的刷新令牌,以每小时获取新的访问令牌(然后您将在每个 API 请求中使用该令牌)。刷新令牌通常不会过期。

于 2019-07-12T16:38:58.993 回答