How to use oAuth2 with a Google Analytics API service account in PHP

In a previous post I detailed how to use the GAPI PHP interface to request data from the analytics API. In this post I will detail how to use a newer PHP interface that uses Google’s v3 API over oAuth2.

NOTE: This guide is out of date, plese use my new and improved Google Analytics API oAuth guide.

You can read my previous post on using the Google Export API here, unfortunately the code in this old article uses antiquated techniques for retrieving data from Google. The new way to connect is to use Google’s new oAuth2 interface which offer’s a token based authentication system for enhanced security.

As in my previous article I am going to use a nice pre-built PHP interface to handle the connection to Google so we won’t have to worry about the low level stuff, just the fun stuff. The PHP interface we are going to use is Google’s official PHP interface, don’t download the version that is available from this link however, you need to get the latest version of the code which contains some features that are currently in beta. Hence you will need to do an SVN checkout from Google’s repository to get the latest version of their API interface. At the time of writing the latest publicly available version of the interface does not support retrieving data offline (as in no user interaction) from the Analytic’s API.

Create an application

OK so now you should have the interface downloaded, the next step is to set-up your an application in Google’s API Console, setting up your application will give you the various tokens needed to connect using oAuth2, it also gives you some usage data about your app and some control over usage limits.

Anywho, here’s how to register your new oAuth2 app:

  • Head over to the Google API Console.
  • Create a new app using the drop down on the top left.
  • Click on the Services tab and turn the Analytics API on.
  • Then click on the API Access tab and click on the create oAuth2 client ID button.
  • Type in a Product Name (can be anything you like) and click next.
  • Select Service Account in the next dialog and click the Create Client ID button.
  • Download your private key by clicking the button, save the key somewhere on your disk, later on it will need to be moved into your project so it can be used to access the API.
  • Close the download key dialog.

Google Analytics setup

The Google API console should have generated a Client ID and Email address for your application, these should be listed under the Service account section. Before you can connect to the API you need to do one more thing, and that is associate the email generated by the API console with the Google Analytics account that you want to connect too.

  • Head over to your Google Analytics account.
  • Go to the Admin page (link is on the top right of the page).
  • Click on the Users tab.
  • Click New user and enter the email address generated by the Google API console, make this user an Administrator and create the user.

Write your script

OK now that everything has been set up you are ready to start writing some PHP to interact with your new oAuth2 application. So let’s write ourselves a little Hello World style intro script that will connect to the Analytics API and retrieve some basic account information. The script we are going to create will work on both command line and webserver contexts, so place the script wherever you want depending on how you wish to execute it. Just make sure that you place the Google API PHP Client and the key that you got from the developer console into folders that can be included by your script.

So here is the basic, Hello World style Analytics script, modify it with your own paths and oAuth2 settings where neseccary:

<?php
// api dependencies
require_once('google-api-php-client-read-only/src/Google_Client.php');
require_once('google-api-php-client-read-only/src/contrib/Google_AnalyticsService.php');

// create client object and set app name
$client = new Google_Client();
$client->setApplicationName(''); // name of your app

// set assertion credentials
$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        '', // email you added to GA
        array('https://www.googleapis.com/auth/analytics.readonly'),
       file_get_contents('') // keyfile you downloaded
    )
);

// other settings
$client->setClientId(''); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?

// create service and get data
$service = new Google_AnalyticsService($client);

var_dump($service->management_accounts->listManagementAccounts());
?>

If you execute this script you should see a dump of some information about your Analytics account. If you see any errors or the data does not appear then check that you have set up your oAuth account properly and that you have entered all the details correctly into the script.

You can see more Google oAuth 2 examples here.

Note: If you get errors about a function called openssl_sign then you might need to update your version of PHP to 5.3.