Search code examples
oauth-2.0access-tokengoogle-analytics-api

Refresh Token for Google Api Php Client


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?


Solution

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