Generate Google API Refresh and Access Tokens in PHP

You are able to access private user information through Google API by means of an access token which expires after 3600s. So what happens when you want to retrieve information offline like what most web applications do? Here comes the refresh token. This guy does not expire and you are able to generate a new access token using REST.

A. OAuth API Parameters

  • Access Token - Grants your tool access to use a Google account with the AdWords API for a limited period of time.
  • Access Type (online/offline) - Indicates whether your application needs to access a Google API when the user is not present at the browser.
  • Refresh Token - Enables your software to generate a new access token once the access token has expired.
  • Client ID - Informs the OAuth API which application is making requests to it.
  • Client Secret - Provides an additional layer of security when identifying your tool.
  • Redirect URI - Specifies the URL that you would like users to be sent to once they've given consent-or not-for your application to access their account.
  • Authorization Code - Gives your tool permission to request access and refresh tokens once the user has approved your request.
  • Error Code - Indicates that the user rejected your authorization request.
  • Response Type (code) - Requests an authorization code instead of just generating an access token.
  • State - Passes a value-such as a user ID-back to your application, so it can continue the sign up process.
  • Scope - Determines which services-AdWords, Google Analytics, GMail etc-within in a Google account that your tool is allowed to access.
  • Approval Prompt (auto/force) - Changes the default behaviour of automatically approving your application if the OAuth sequence is run multiple times.

B. Create Project

First of all you need to go to Google API Console and create a new project MyProject. Enter MyProject.

C. Create New Client ID

In MyProject, go to APIs & auth > Credentials and click Create new Client ID button:

  • Choose Application type is Web application
  • Empty Authorized JavaScript origins is you don't use
  • Set Authorized redirect URI to retrive Tokens, you can set many URI

    http://localhost:8080/coloza/oauth2callback

    http://localhost/coloza/oauth2callback.php

When New Client Id created, you can get Client ID, Email address, Client secret, Redirect URIs. You can remove and add more redirect uri after New Client Id created. And you can download JSON for more information.

D. PHP Code to get Tokens

$access_type = "offline";

This line tells Google API that we want it to generate a refresh token.

$approval_prompt = "force";

This line asks Google to prompt us again for approval even if we have previously approved it. I use this in testing scenarios when I have run the script a number of times and end up with a blank refresh token.

$scope = "https://www.google.com/apis/ads/publisher";

This is an important line of code. This defines the access scope of the application. So if our application is only interested in accessing the DFP API, put that in the scope. If you want to access more APIs, place the URIs separated by a space.

Finally note that the response we get from Google is JSON encoded and therefore needs to be decoded to extract the refresh and access tokens.

E. Code Example (oauth2callback.php)

<?php
$url = "https://accounts.google.com/o/oauth2/auth";
$client_id = "INSERT_CLIENT_ID_HERE";
$client_secret = "INSERT_CLIENT_SECRET_HERE";
$redirect_uri = "http://localhost/coloza/oauth2callback.php";
$access_type = "offline";
$approval_prompt = "force";
$grant_type = "authorization_code";
$scope = "https://www.google.com/apis/ads/publisher";
$params_request = array(
  "response_type" => "code",
  "client_id" => "$client_id",
  "redirect_uri" => "$redirect_uri",
  "access_type" => "$access_type",
  "approval_prompt" => "$approval_prompt",
  "scope" => "$scope"
  );
$request_to = $url . '?' . http_build_query($params_request);
if(isset($_GET['code'])) {
  // try to get an access token
  $code = $_GET['code'];
  $url = 'https://accounts.google.com/o/oauth2/token';
  $params = array(
    "code" => $code,
    "client_id" => "$client_id",
    "client_secret" => "$client_secret",
    "redirect_uri" => "$redirect_uri",
    "grant_type" => "$grant_type"
  );
  $curl = curl_init($url);
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
  $json_response = curl_exec($curl);
  curl_close($curl);
  $authObj = json_decode($json_response);
  echo "Refresh token: " . $authObj->refresh_token;
  echo "\nAccess token: " . $authObj->access_token;
}
header("Location: " . $request_to);
?>

Comments

Popular posts from this blog

Reduce TIME_WAIT Socket Connections