Refresh Token for Google Api Php Client

Sanganabasu picture Sanganabasu · Jun 23, 2012 · Viewed 9.8k times · Source

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?

Answer

Aymen Mouelhi picture Aymen Mouelhi · Jul 3, 2012

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;
        }
        ?>