8
votes

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?

2
Note: If your response from getAccessToken does not contain a refresh token even though you do it just as in smartcodes' example code you may need to revoke your application's access and start authentication (as a user) all over again because Google remembers earlier attempts and if you didn't give "offline" access earlier, you won't get it automatically later on. -> security.google.com/settings/security/permissionsBlaM
This comment is what saved my day ^^^ During local development, I couldn't find the refresh token anywhere and all I had to do was revoke the app and try again.SaltedBlowfish

2 Answers

7
votes

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
votes

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