Tutorial: Implementing Google+ API using OAuth 2.0 in PHP

On September 15, 2011 Google released Google+ APIs to public. Google+ API is a programming interface to Google+. With the help of this API users can integrate apps or websites with Google+. Currently, Google+ API is in the initial stages of its development. It is not yet a full-fledged API that can support almost anything like Facebook API. Even Google+ itself is not full-fledged Social Network like its rival Facebook. Google engineers are adding more and more features to it, day by day. Recently Google+ Pages was launched which helps to build relationships with your users, encouraging them to spend more time engaging with your content. 25 labs have set up a Google+ Page for itself. You can check it out at https://plus.google.com/100978449713779879158/. Many such features that are on Facebook are being implemented into Google+. The access provided by Google+ API is currently limited. As of now, Google+ API provides only read-only access to public data. All API calls require either an OAuth 2.0 token or an API key.

This tutorial will give you the basic idea of implementing Google+ API. Google has released many Client Libraries for easy implementation of the API. In this tutorial we will be using Google APIs Client Library for PHP which is currently in beta.

 

Registering your application

Google+ APISteps 1 to 7 will explain the procedure of registering the application at Google. You need to register and obtain Client ID, Client secret, Redirect URIs and API key for the application to work.

Step 1:

You need to register your product at Google to use Google+ API. To start the registration process, head to Google API Console.
Create a new project by clicking ‘Create…’ which will be located under the drop down menu that is located at the top left corner of the page, if you have created a project earlier. If you entirely new to Google API console, then ‘Create project…’ button will be right in the middle of the page.

Project drop down menu

Project drop down menu

Create in the drop down menu

Create in the drop down menu

Step 2:

You will be taken to the ‘Services’ tab. If not navigate to ‘Services’ tab.

Toggle the Status button next to ‘Google+ API’ to ‘ON’

Services tab

Services tab

Google+ API toggle button

Google+ API toggle button

Step 3:

Click ‘API Access’ from the left menu.

API access

API access

Step 4:

In the page that opens up, click on the ‘Create an OAuth 2.0 client ID…’ button.

Create OAuth client ID

Create OAuth client ID

Step 5:

Fill in a name for the project. You can optional give a product logo. The maximum allowed size for the logo is 120 x 60 pixels. This logo will also be displayed on the user’s confirmation page.

Enter the details

Enter the details

After you fill in the details click ‘Next’ button.

Step 6:

Now you will be taken to Client ID settings page.

Choose ‘Web application’ radio button for the Application type.

In ‘Your site or hostname’ section, choose ‘http://’ or ‘https://’ as per your requirement. Please note that some servers do not support secure protocol (https://) by default. You may need to acquire an SSL certificate to enable https on your server. Authoritatively signed certificates may be free or cost between US$13 and $1,500 per year. So, if you are comfortable with http, then feel free to proceed with it.

Now, enter your domain for the web application. You can also provide ‘localhost’. If you are trying it on localhost, then there is chance that you get a SSL certificate error when the user grants permission to access his details. I have given a possible solution to this problem at the end of this tutorial.

Client ID settings hostname

Client ID settings hostname

Now, click ‘more options’ which lies next to ‘Your site or hostname’. Enter the URL that you wish your user to get redirected to, after logging in as the ‘Authorized Redirect URIs’. In my case it is ‘http://localhost/googleplus’. You will automatically have your host address as ‘Authorized JavaScript Origins’.

Client ID settings Redirect URIs

Client ID settings Redirect URIs

Click ‘Create client ID’ button.

Step 7:

If everything had gone well, you can view the API credentials for your web application.

Note down the Client ID, Client secret and Redirect URIs which will be under ‘Client ID for web applications’ section. Also note ‘API key’ which comes under the section ‘Simple API Access’. You will need them in Step 9.

API credentials

API Credentials

Step 8: (Downloading Client Library)

Download Google APIs Client Library for PHP. Head to http://code.google.com/p/google-api-php-client/downloads/list and download the latest version of the Client Library. Extract the compressed file. Inside you will find a folder named ‘google-api-php-client’. Copy the folder to the place where you wish to host the webpage. In my case it is ‘localhost/googleplus’. Please note that this is the ‘Authorized Redirect URIs’ that you provided in Step 6.

At the time of writing this tutorial, the client library version available for download is 0.4.6
I am not sure whether the script will work for future versions. If you find the script broken, please feel free to comment on the post so that I can try and fix the script.

Step 9: (Creating the access file)

Now we will start the coding for the implementation of Google+ API. Create a file ‘google-plus-access.php’ in the same place where you copied the folder ‘google-api-php-client’ in the previous step. I will divide the script into various sections and explain each of them.

First we need to include the required files from the API Client that we downloaded in the previous step.

require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';

When a user authenticates, an access token will be returned with which we retrieve the details. We store this access token as a session variable. So we start a session.

session_start();

Then we need to initialize the API client object. Also set a name for the application.

$client = new apiClient();
$client->setApplicationName("Google+ PHP Starter Application");

Now we need to set the API credentials. Replace the arguments with those you created in Step 7.

$client->setClientId('Your Client ID');
$client->setClientSecret('Your Client Secret');
$client->setRedirectUri('Your Redirect URI');
$client->setDeveloperKey('Your API key');

We use setScopes() function to tell Google what we want to access from the user. In our case we need to access Google+ data. So we provide scope specific to Google+ as argument. You can optionally include scopes for more Google services if you wish.

$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));

Initialize the plus API service which takes the API client object as argument.

$plus = new apiPlusService($client);

Before getting into the authentication part we need to check whether the user has requested to clear the login information. That is, check whether the user reached the page by clicking the logout button.

We pass a ‘logout’ parameter to the URL to indicate that the user has directed to logout. So we check for ‘logout’ parameter in local URL. If the ‘logout’ parameter is found then we clear the access token from the session.

if(isset($_REQUEST['logout']))
{
    unset($_SESSION['access_token']);
}

Now we check whether the user clicked allow when the permission for accessing the data was asked for. If the user clicked allow, then there will be ‘code’ parameter in the URL. We check for it and if found, we need to authenticate the user and also store the access token returned by Google in session. We use functions authenticate() and getAccessToken() respectively to achieve them. Then we need to reload the page, but without the code parameter in the URL.

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

We check whether access token is set in the session. If yes, we can conclude that we have valid access token and so we can pass it to the client.

if(isset($_SESSION['access_token']))
{
    $client->setAccessToken($_SESSION['access_token']);
}

getAccessToken() method will return the access token if a valid access token is set to the client and otherwise it will return FALSE. If getAccessToken() returns FALSE, then we need to create the login URL with which the user can login. We use createAuthUrl() method for it.

If an access token is returned, it means that the user is logged in and so we can retrieve the details of the user. We use methods people->get() and activities->listActivities() to request for people details and activity details respectively. The only argument for people->get() is ‘userID’. We pass special value ‘me’ to indicate authenticated user. activities->listActivities() has two required parameters, ‘userID’ and ‘collection’. Collection specifies the collection of activities to list. Currently ‘public’ is the only acceptable value. We pass an optional parameter to the listActivities() method to set the maximum number of results to be returned. The acceptable values are 1 to 100 and the default value is 20. Then we use the method getAccessToken() to retrieve the access token and update the access token that is stored in session. This is done because the access token may have been updated lazily.

if ($client->getAccessToken()) {
  $me = $plus->people->get('me');
 
  $optParams = array('maxResults' => 100);
  $activities = $plus->activities->listActivities('me', 'public', $optParams);
 
  $_SESSION['access_token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}

This is the end of ’google-plus-access.php’. We will have the variables $me and $activities set once a user is authenticated. We will use these variables to display the data in ‘index.php’ that we are about to create in next step. We will also use variable $authUrl that has the login URL.

Step 10: (Creating the index file)

Create ‘index.php’ in same location where you created ’google-plus-access.php’. We must include the file ’google-plus-access.php’ to ‘index.php’.

To find out whether the user is logged in we check whether both $me and $activities are set. If not, we display the login button with the login URL.

$me and $activities are arrays and you can check which all fields are needed for your application by printing them. I have used only few of the available fields for this demo. A point to note is that you can get the profile picture of a user in custom sizes just by appending a GET parameter ‘sz’ which stands for size.

Example:

<img src="<?php echo($me['image']['url']) ; ?>?sz=200" />

UPDATE: On 15th November 2011, Google has made a minor change because of which the above line of code will fail to render the image. Earlier $me['image']['url'] used to return the URL to the profile picture at full resolution. But now, by default it returns a thumbnail (of size 50pixel). That is, a GET parameter ‘sz’ with value 50 is appended to URL. So inorder to get the URL to the picture at full resolution we need to strip off the ‘sz’ parameter. So the above code need to be rewritten as:

<img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" />

With this the coding is complete and you can try it out. You can download the complete source of the demo from here.

User Authentication

When a user clicks the login URL he will be taken to a permission screen similar to the one shown below. If the user clicks ‘allow access’ he will be redirected to your webpage as an authenticated user.

User Authentication

User Authentication

Issue you may face

If you are using localhost on windows to try this code, you may get an SSL certificate error. Once the user grants permission you may see something similar to:

Fatal error: Uncaught exception ‘apiIOException’ with message ‘HTTP Error: (0) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed’ in C:\xampp\htdocs\googleplus\google-api-php-client\src\io\apiCurlIO.php:127 Stack trace: #0 C:\xampp\htdocs\googleplus\google-api-php-client\src\auth\apiOAuth2.php(87): apiCurlIO->makeRequest(Object(apiHttpRequest)) #1 C:\xampp\htdocs\googleplus\google-api-php-client\src\apiClient.php(132): apiOAuth2->authenticate(Array) #2 C:\xampp\htdocs\googleplus\google-plus-access.php(24): apiClient->authenticate() #3 C:\xampp\htdocs\googleplus\index.php(2): include_once(‘C:\xampp\htdocs…’) #4 {main} thrown in C:\xampp\htdocs\googleplus\google-api-php-client\src\io\apiCurlIO.php on line 127

This means that the server is unable to perform peer SSL certificate verification. The Windows version of PHP doesn’t come bundled with a Certificate Authority bundle. So you need to add it yourself.

Solution 1:

In ‘google-api-php-client\src\io\’ folder, open ‘apiCurlIO.php’

Replace

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

with

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

UPDATE : As on Jan 17, 2012 the latest version of Google API PHP Client is 0.4.8.3 (Beta) and it has an array $DEFAULT_CURL_PARAMS which sets all the parameters for CURL. And so you won’t be able to see the above mentioned line of code. I have update the demo source bundle with version 0.4.8.3 (Beta). In the case of new version :

Replace

CURLOPT_SSL_VERIFYPEER => true

with

CURLOPT_SSL_VERIFYPEER => false

Solution 2:

Download the .pem file from the cURL site and rename the extension to .crt

Save the renamed file to your web server.

Add the following line to ‘google-api-php-client/src/io/apiCurlIO.php’ right before the ‘curl_exec()’ method call. As per the current version of Google APIs Client Library for PHP, the line of code (‘curl_exec’ method call) is $respData = curl_exec($ch);

curl_setopt($ch, CURLOPT_CAINFO, 'c:/path/to/ca-bundle.crt');

Remember to replace ‘c:/path/to/ca-bundle.crt’ to with the path for your saved .crt file.

Hope everything worked well. Comment below if you face any problems or find any improvements to the script.