jm874327
jm874327

Reputation: 158

Refresh Tokens Google OAuth 2.0 PHP

Using the Google OAuth 2.0 code from this site https://github.com/google/google-api-php-client

I need help coding the refresh token into the following code, I am not sure on how to do it, there are a lot of resources out there, but I can't find any that helps me incorporate it into my code. Current problem now is if I let the token expire, it gives me an error saying I don't have a refresh token and I need it because I don't want to use the force option for the accesstype. I am using the php client:

    //include google api files
    require_once 'src/Google/Client.php';
    require_once 'src/Google/Service/Oauth2.php';

    //start session
    $client_id = 'xxxx';
    $client_secret = 'xxxx';
    $redirect_uri = 'xxxxx';

    $client = new Google_Client();
    $client->setApplicationName("Backpack Em");
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
    $client->setAccessType('offline');
    $service = new Google_Service_Oauth2 ($client);

 if (isset($_REQUEST['logout'])) {
  unset($_SESSION['upload_token']);
  $client->revokeToken();   //added
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));     //redirect user back to page
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['upload_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];       header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
  $client->setAccessToken($_SESSION['upload_token']);
  if ($client->isAccessTokenExpired()) {
    unset($_SESSION['upload_token']);
  }
}

if ($client->getAccessToken()) 
  {
    //For logged in user, get details from google using access token
    $user           = $service->userinfo->get($params);
    //$user_id          = filter_var($user['id'],FILTER_SANITIZE_SPECIAL_CHARS);
    $user_name          = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
    $first_name         = filter_var($user['given_name'], FILTER_SANITIZE_SPECIAL_CHARS);
    $last_name          = filter_var($user['family_name'], FILTER_SANITIZE_SPECIAL_CHARS);
    $email          = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
    $profile_url        = filter_var($user['link'], FILTER_VALIDATE_URL);
    $profile_image_url      = filter_var($user['picture'], FILTER_VALIDATE_URL);
    $gender         = filter_var($user['gender'], FILTER_SANITIZE_SPECIAL_CHARS);
    $personMarkup       = "$email<div><img src='$profile_image_url?sz=50'></div>";
    $_SESSION['upload_token']   = $client->getAccessToken();
    $_SESSION['upload_token']   = $client->getRefreshToken();

  }

else
  {
  $authUrl = $client->createAuthUrl();
  }
?>

Upvotes: 3

Views: 4027

Answers (2)

Sir_Faenor
Sir_Faenor

Reputation: 897

Old question but I hope this can still help somebody. These are the steps I followed for a server side token refresh (no need for user to log in).

  1. In a Google Developer Console app, create a new client id for OAuth, using 'https://developers.google.com/oauthplayground' as redirect uri. ( you need this for the authentication in the playground)
  2. In https://developers.google.com/oauthplayground/, click on the settings icon in the top right corner and check "Use your own OAuth credentials". You have to insert valid credentials( client id and client secret) as generated at point 1.
  3. Select and authorize your Api in the left column ("Step 1")
  4. Once you got the Authorization Code, exchange it for tokens ("Step 2")
  5. Now, you can use client id, client secret (the same you used at point 2) and the refresh token (the one you got at point 4 ) in your script.

This is the working code I am using (for Analytics e.g):

$clientId = 'xxxxxxxxxxxxxxxxx'; // from google developer console
$clientSecret = 'xxxxxxxxxxxxxx'; // from google developer console
$refreshToken = 'xxxxxxxxxx'; // from https://developers.google.com/oauthplayground/
$client = new Google_Client();
$client->setClientId($clientId);
$client->setClientSecret($clientSecret);
$client->refreshToken($refreshToken);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);
$analytics = new Google_Service_Analytics($client);
$response = $analytics->data_ga->get(
   'ga:' . xxxxxxx, 
   '7daysAgo',
   'today',
   'ga:sessions');

Upvotes: 0

Hans Z.
Hans Z.

Reputation: 54088

Store the refresh token in the session as in:

$refresh_token = $client->getRefreshToken();
$_SESSION['refresh_token'] = $refresh_token;

And when you want to get a new access token you can call:

$refresh_token = $_SESSION['refresh_token'];
$client->refreshToken($refreshToken);
$access_token = $client->getAccessToken();
$_SESSION['upload_token'] = $access_token;

You can call $client>isAccessTokenExpired() to see if an access token has expired and you would need to trigger the refresh flow.

To print/access the expires_in value, you can use:

$json = json_decode($client->getAccessToken());
echo $json['expires_in'];

but be aware that expires_in is relative to the time that the token was created, so to check if a token has expired you'd use:

$expired = ($json['created'] + $json['expires_in']) < time();

Upvotes: 2

Related Questions