The new and improved guide to using an oAuth2 service account with Google Analytics

This has been a long time coming! Since my last Google Analytics guide the PHP version of Google's API Client has had a significant update and has moved over to Git, it doesn't have proper namespacing as yet but you can install the package via Composer which will sort that issue out for you.

The goal of this article is to show you how to use the Analytics API in offline mode without requiring an active login from a user. Most of the examples that I have seen are 'online' and require user interaction in the form of logins details and a button click, this is no use at all if you are trying to pull down Analytics data for use in an automated task such as building a list of most read articles on your site

Setting up your project

The first step is to grab Google's PHP API Client, you can clone/download the library directly if you wish but by far the easiest way to handle this is to use Composer (and this guide will assume that you are). If you haven't used Composer before there is a handy guide on how to get started with it on the Composer website.

Once you've got composer create a folder for your project and create a composer.json file like this:

{
    "require": {
        "google/apiclient": "dev-master"
    }
}

Run a composer update (which will probably entail running "php composer.phar update" and the API client will get pulled down for you into your projects vendor directory.

With the API in place it's time to get everything else set up.

Create an application

OK so now you should have the client downloaded, the next step is to setup 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.
  • Click on APIs under APIs & Auth in the left hand nav, click on the off button next to the Analytics API entry to turn it on.
  • Next select Credentials under APIs & Auth and click Ceate New Client ID, select service account from the dialog and click Create Client ID.
  • You will be offered a download, this is your private key. Save it somewhere on disk, later on you will need to move into your project so it can be used to access the API.

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 Credentials 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, the link is on the top of the page of the accounts overview page.
  • Click on User Management under the Account section, you should see a form with a text field under the heading Add permissions for.
  • Pop the email that was generated by the Google Developer Consoler (it will look something like [ID]@developer.gserviceaccount.com) into the text field.
  • Make sure that Read & Analyse is selected in the drop down to the right of the text field and click add.

Before we leave Google Analytics we need just one more piece of information and that's the View ID for the site that you want to access via the API, to get this click on View Settings under the View section of the admin page, making sure to select the desired site from the drop down. Make a note of the View ID as you will need this later on.

Working with the API client

OK you are ready to start writing a PHP script to interact with the Analytics API, so let’s write a little Hello World style intro script that will connect to the Analytics API and retrieve some basic account information. Make sure that you place the key that you got from the developer console into a folder that can be included by your script, for instance 'project_root/keys'.

So here is the basic Hello World style Analytics script, note that we are including Composers autoload classes so the Google API Clients classes are loaded automatically:

<?php
// api dependencies
require 'vendor/autoload.php';

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

// set assertion credentials
$client->setAssertionCredentials(
    new Google_Auth_AssertionCredentials(
        '[ID]@developer.gserviceaccount.com', // email you added to GA
        array('https://www.googleapis.com/auth/analytics.readonly'),
       	file_get_contents('keys/[YOUR-KEY-FILE]') // keyfile you downloaded
    )
);

// other settings
$client->setClientId('[CLIENT-ID].apps.googleusercontent.com'); // from API console

// create service and get data
$service = new Google_Service_Analytics($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 setup your oAuth account properly and that you have entered all the details correctly into the script.

Grabbing Analytics data

Let's try a more complex example. Say for instance that you wanted to grab a list of the most read Content on your site, here's an example script that shows how this can be achieved:

<?php
// api dependencies
require 'vendor/autoload.php';

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

// set assertion credentials
$client->setAssertionCredentials(
    new Google_Auth_AssertionCredentials(
        '[ID]@developer.gserviceaccount.com', // email you added to GA
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents('keys/[YOUR-KEY-FILE]') // keyfile you downloaded
    )
);

// other settings
$client->setClientId('[CLIENT-ID].apps.googleusercontent.com'); // from API console

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

$response = $service->data_ga->get(
        'ga:[VIEW-ID]]', // profile id
        '2014-01-01', // start date
        '2014-02-01', // end date
        'ga:uniquePageviews',
        array(
            'dimensions' => 'ga:pagePath',
            'sort' => '-ga:uniquePageviews',
            'filters' => 'ga:pagePath=~/[a-zA-Z0-9-]+/[a-zA-Z0-9-]+', // example url regex filter
            'max-results' => '25'));
var_dump($response);
?>

You can find the code for these examples on Github.