v1ncent
v1ncent

Reputation: 11

Google Oauth refresh Token

I'm trying to use Google Oauth to access Google Analytics Datas. It's works fine except with token. The token expires after an hour and I don't know how to refresh it. There a line where there's "For simplicity of the example we only store the accessToken. If it expires use the refreshToken to get a fresh one" but I don't know how to… Here's my code

$client_id = 'xxxxxxxxxx.apps.googleusercontent.com';

// From the APIs console
$client_secret = 'xxxxxxxxxxxxx';

 // Url to your this page, must match the one in the APIs console
$redirect_uri = 'mylocalurl.php';


session_start();
include('GoogleAnalyticsAPI.class.php');

$ga = new GoogleAnalyticsAPI(); 
$ga->auth->setClientId($client_id);
$ga->auth->setClientSecret($client_secret);
$ga->auth->setRedirectUri($redirect_uri);

if (isset($_GET['force_oauth'])) {
    $_SESSION['oauth_access_token'] = null;
}


/*
 *  Step 1: Check if we have an oAuth access token in our session
 *          If we've got $_GET['code'], move to the next step
 */
if (!isset($_SESSION['oauth_access_token']) && !isset($_GET['code'])) {
    // Go get the url of the authentication page, redirect the client and go get that token!
    $url = $ga->auth->buildAuthUrl();
    header("Location: ".$url);
} 

/*
 *  Step 2: Returning from the Google oAuth page, the access token should be in $_GET['code']
 */
if (!isset($_SESSION['oauth_access_token']) && isset($_GET['code'])) {
    $auth = $ga->auth->getAccessToken($_GET['code']);
    if ($auth['http_code'] == 200) {
        $accessToken    = $auth['access_token'];
        $refreshToken   = $auth['refresh_token'];
        $tokenExpires   = $auth['expires_in'];
        $tokenCreated   = time();

        // For simplicity of the example we only store the accessToken
        // If it expires use the refreshToken to get a fresh one
        $_SESSION['oauth_access_token'] = $accessToken;
    } else {
        die("Sorry, something wend wrong retrieving the oAuth tokens");
    }
}

Thanks

Upvotes: 1

Views: 472

Answers (1)

lambderp
lambderp

Reputation: 11

I am not sure of the details of doing this in PHP but there is an end point to request against for refreshing the access token.

The API end point is https://accounts.google.com/o/oauth2/token and the body of request should be something like

{
   'refresh_token' => your_stored_refresh_token,
   'client_id' => ENV['CLIENT_ID'],
   'client_secret' => ENV['CLIENT_SECRET'],
   'grant_type' => 'refresh_token'
}

If successful that request will return a fresh access token.

Upvotes: 1

Related Questions