Thursday 14 June 2018

Get the access token with OAuth 2.0 for Google API


Follow Below 4 steps to get the access token with OAuth 2.0 for Google API


1. Obtain OAuth 2.0 credentials ("Client ID" and "Secret Key") from the Google Developers Console.
  • Go to https://console.developers.google.com/
  • Select your project (create new project, If not have created before).
  • Click on "APIs & auth"
  • Click to "APIs", Now you have all the list of Google APIs  .
  • Select OR Search the APIs from search box, the one which you want to use.
  • Select API and Click on "Enable API". (I enable "Google Webmaster Tools API")
  • Now, click on "Credentials", Click on "Create new Client ID" under OAuth tab.
  • Popup will come. click on "Configure consent screen".
  • New form will appear. Fill the details and click on "Save".
  • Confirmation page appear, Click on "Create Client ID"
  • Now you will see the screen simpilar to below:

 Obtain OAuth 2.0 credentials
 Obtain OAuth 2.0 credentials
  • m. Get the "client Id" and "Client secret". (DON'T SHARE IT).


2. Create a new page in PHP like http://www.domain.com/auth-url.php
Add this URL in "Authorized redirect URIs" in your project (in Edit setting) above created.


3. Get the GET Access token from google using "Client ID" and "Secret Key"
Add the below code in "auth-url.php"
  define(YOUR_CLIENT_ID,'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
  define(YOUR_CLIENT_SECRET,'xxxxxxxxxxxxxxx');
if (isset($_GET['code'])) {    
    $code = $_GET['code'];
    //Set the Auth URL
    $url = 'https://accounts.google.com/o/oauth2/token';
    
    //Set the Auth Parameter
    $redirectUri='http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"];
    $params = array(
        "client_id" => YOUR_CLIENT_ID,
        "client_secret" => YOUR_CLIENT_SECRET,
        "redirect_uri" => $redirectUri,
        "grant_type" => "authorization_code",
        "code" => $code,
    );

    /** Init the curl */
    $ch = curl_init();
    curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
    curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
    curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] === 200) {
        header('Content-Type: ' . $info['content_type']);
        return $output;
    } else {
        die('An error occured');
    }
    /** Init the curl */
    
} else {

    $url = "https://accounts.google.com/o/oauth2/auth";

    //Set the Auth Parameter
    $params = array(
        "response_type" => "code",
        "client_id" => YOUR_CLIENT_ID,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],        
        "scope" => "https://www.googleapis.com/auth/webmasters.readonly" //I have added scope for webmaster tool
        
    );

    $requestTo = $url . '?' . http_build_query($params);

    //Redirect the page
    header("Location: " . $requestTo);
} 



4. You will get result simpliar to below.
{ "access_token" : "ya29.kgGOtdWEj32NOSxLWkZXAaXAagmkP-4WgHEd8gpUfuelHD_lslquKzHMVV2OnnNc5h1BKWkY8aeCrA", "token_type" : "Bearer", "expires_in" : 3600 }

Here you got access_token, token_type and expires_in (in Seconds).


If this code does not work and need any assistance, Please feel free to comment.