Jan 082012
 

This is the second part of a three part series on how to embed a Google Calendar into a web page and use it to accept online bookings/appointments from other online users.

The Series:

  1. Part 1: Setting up Google Calendar
  2. Part 2: OAuth2 and Configuring Your ‘Application’ With Google <- You Are Here
  3. Part 3: A Sample Web Page For Bookings

Background

This was by far the hardest part of the whole exercise. I had worked with version 1 of the Google API for PHP a few years back. This allowed you to code your username and password into your script, and it would handle authentication for your application. Now that we are on to version 3 of the API, that method is no longer available. Instead OAuth2 is used for authentication and token management.

I downloaded code samples, and went about building my application, however, I quickly realized that the OAuth2 code samples are designed to allow you to interact with a visitors calendar. In the case of taking online bookings, I need to work with a single calendar, namely my calendar, not theirs.

After a lot of trial and error, and then reading, I realized that it could be done, and relied on what is called a ‘Refresh Token’ in OAuth2. This token allows you to get a new valid authentication token when the initial grant from your end user expires. Since the refresh token doesn’t expire, you can always use it to get a new authentication token, and therefore people can continue to use your application after you have initially configured it. I spent a while trying to implement it myself with no success, but then I came across this page: http://www.ericnagel.com/how-to-tips/google-affiliate-network-api.html This explains in some detail how to configure the application and token. It is written for the Google Affiliate Network API, but I made a few tweaks to make it work for Calendar. I will now take you through the steps of setting up your application with Google, and generating your Refresh Token.

Create Your Application

Log into your Google Account, and then visit https://code.google.com/apis/console/. This will take you to a page that invites you to create a project with the Google API. Click on Create project….

You are now asked to activate the services you wish to use. Click the button next to Calendar API to enable the calendar. You will be redirected to a page with a Terms of Service. Read and accept this.

Now click on API Access. Here we will configure the IDs needed for your application to authenticate with Google. Click on Create an OAuth2 client ID…. You will be offered to create Branding Information. You should add your project/product name. The rest won’t be necessary as you will not be asking users directly for access to their resources, but you can complete it if you like.

Then click Next. Here you will want to select Installed application. Click Create client ID.

You will be taken back to the API Access screen, with your new Client ID and Client secret. You will need this information to generate your Refresh Token, and to configure your application.

This page will also have your API key for ‘Simple API Access’. You will also need this API Key for your final calendar application.

Get Your Application Information

Now that you have your application information, it is time to generate your refresh token. I’ve modified the script available from http://www.ericnagel.com/how-to-tips/google-affiliate-network-api.html to just get us our refresh token for our calendar application. Here is the code for the script. Download this and save it as oauth-setup.php:

<?php
$cScope         =   'https://www.googleapis.com/auth/calendar';
$cClientID      =   '';
$cClientSecret  =   '';
$cRedirectURI   =   'urn:ietf:wg:oauth:2.0:oob';
 
$cAuthCode      =   '';

if (empty($cAuthCode)) {
    $rsParams = array(
                        'response_type' => 'code',
                        'client_id' => $cClientID,
                        'redirect_uri' => $cRedirectURI,
                        'access_type' => 'offline',
                        'scope' => $cScope,
                        'approval_prompt' => 'force'
                     );

    $cOauthURL = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($rsParams);
    echo("Go to\n$cOauthURL\nand enter the given value into this script under \$cAuthCode\n");
    exit();
} // ends if (empty($cAuthCode))
elseif (empty($cRefreshToken)) {
    $cTokenURL = 'https://accounts.google.com/o/oauth2/token';
    $rsPostData = array(
                        'code'          =>   $cAuthCode,
                        'client_id'     =>   $cClientID,
                        'client_secret' =>   $cClientSecret,
                        'redirect_uri'  =>   $cRedirectURI,
                        'grant_type'    =>   'authorization_code',
                        );
    $ch = curl_init();
 
    curl_setopt($ch, CURLOPT_URL, $cTokenURL);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    $cTokenReturn = curl_exec($ch);
    $oToken = json_decode($cTokenReturn);
    echo("Here is your Refresh Token for your application.  Do not loose this!\n\n");
    echo("Refresh Token = '" . $oToken->refresh_token . "';\n");
} // ends
?>

Before running this script, you will need to enter your Client ID ($cClientID) and Client Secret ($cClientSecret) as we found on the API page with Google. Once these values are added, run this script from the command line like this: php oauth-setup.php. You should see output like this:

thomas@thomas-desktop:~/code$ php oauth-setup.php 
Go to
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=##########################&redirect_uri=###############&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar
and enter the given value into this script under $cAuthCode

Visit the website, grant permission to access your resources, and then copy the code on this page. This is your auth code, and is normally good for 3600 seconds or so.

Enter this code into the oauth-setup.php script in the $cAuthCode variable. Then run the script again: php oauth-setup.php. You should see output like this:

thomas@thomas-desktop:~/code$ php oauth-setup.php 
Here is your Refresh Token for your application.  Do not loose this!

Refresh Token = '#####################################';

Now, copy down the Refresh Token and save it for later. You will need it to make subsequent requests to Google to get a valid Auth Code for a transaction.

Stay tuned for Part 3 of the tutorial, which will use the above information to make calendar requests to Google. And allow us to create a web application that uses Google Calendar as a backend for a scheduling application.