Refresh Token for Google Api Php Client

2019-02-05 05:47发布

问题:

I am using the Google API Client to access Google Analytics. I want to access the data in offline mode, so I need a refresh token. How do I get a refresh_token?

回答1:

try using the following code:

    <?php
        require_once 'apiClient.php';

        const REDIRECT_URL = 'INSERT YOUR REDIRECT URL HERE';
        const CLIENT_ID = 'INSERT YOUR CLIENT ID HERE';
        const CLIENT_SECRET = 'INSERT YOUR CLIENT SECRET';
        const ANALYTICS_SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';

        // Build a new client object to work with authorization.
        $client = new apiClient();
        $client->setClientId(CLIENT_ID);
        $client->setClientSecret(CLIENT_SECRET);
        $client->setRedirectUri(REDIRECT_URL);
        $client->setScopes(array(ANALYTICS_SCOPE));
        $client->setAccessType('offline');
        $auth = $client->authenticate();


        if ($client->getAccessToken()) {
           $token = $client->getAccessToken();
           $authObj = json_decode($token);
           $refreshToken = $authObj->refresh_token;
        }
        ?>


回答2:

For PHP SDK of Google Client v2:

php composer.phar require google/apiclient:^2.0

You can try the PHP code to refresh accessToken as following:

<?php

require_once __DIR__ . '/vendor/autoload.php';

define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Analytics::ANALYTICS_READONLY)
));

$client = new Google_Client();
$client->setApplicationName('YOUR APPLICATION NAME');
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

// Input AccessToken from such as session or database 
$accessToken = json_decode('YOUR CURRENT ACEESS TOKEN');

$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    // Get RefreshToken as json which can be reused
    $refreshToken = json_encode($client->getAccessToken());
}

Offline access issue

In addition, if you want to keep the existing behavior in your server-side applications, you need to set approval_prompt to force, otherwise you may get NULL returned from getRefreshToken(), which Google document doesn't mention:

$client->setApprovalPrompt('force');

Referring Upcoming changes to OAuth 2.0 endpoint