How can I get an updated access token, using stored refresh token

mattpark22 picture mattpark22 · Apr 2, 2013 · Viewed 12.3k times · Source

I'm building an application that allows the admin to authenticate access to their analytics account for offline usage, and stores the refresh token in the database.

Now when I try to use the API on the frontend, it returns the following error:

"Access Token Expired. There wan a general error : The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved."

Here's my code that generates this error so far:

require_once "lib/google/Google_Client.php";
require_once "lib/google/contrib/Google_AnalyticsService.php";

$_analytics = new analytics();
$_googleClient = new Google_Client();
$_googleClient->setClientId($_analytics->gaClientId);
$_googleClient->setClientSecret($_analytics->gaClientSecret);
$_googleClient->setRedirectUri($_analytics->gaRedirectUri);
$_googleClient->setScopes($_analytics->gaScope);
$_googleClient->setAccessType($_analytics->gaAccessType);

// Returns last access token from the database (this works)
$_tokenArray['access_token'] = $_analytics->dbAccessToken($_agencyId);
$_googleClient->setAccessToken(json_encode($_tokenArray));

if($_googleClient->isAccessTokenExpired()) {
    // Don't think this is required for Analytics API V3
    //$_googleClient->refreshToken($_analytics->dbRefreshToken($_agencyId));
    echo 'Access Token Expired'; // Debug
}

if (!$_googleClient->getAccessToken()) {
    echo '<h2>Error - Admin has not setup analytics correct yet</h2>';
}

I'm after a function to run something like setRefreshToken - entering the value from the database, from the admin previously authenticating it online.

Answer

Gareth Luckett picture Gareth Luckett · Apr 3, 2013

You could try the following, you would need to add in the code to store the new token in your database.

if($_googleClient->isAccessTokenExpired()) {
    // Don't think this is required for Analytics API V3
    //$_googleClient->refreshToken($_analytics->dbRefreshToken($_agencyId));
    echo 'Access Token Expired'; // Debug

    $_googleClient->authenticate();
    $NewAccessToken = json_decode($_googleClient->getAccessToken());
    $_googleClient->refreshToken($NewAccessToken->refresh_token);
}