Google Analytics API with PHP Tutorial

Perhaps I’m spoiled, but dealing with Google’s documentation always leaves me frustrated. Often a changed interface leaves information outdated.  Other times the Google engineers leave steps out because they don’t need to hold the hands of dummies like me. Well other dummies, I’m here to sort that out (at least when it comes to a very very specific use case!)

Most tutorials focus on a use case that requires some kind of user authentication. However, I want to use the API to grab data from Google at regular intervals with no human interaction, so that’s why I’m writing this up.

Why use the Google Analytics API?

You can see all of your data in the Google Analytics dashboard, right? Why do you need to access it programmatically? Here’s one reason: It can be powerful if you want to feed information about your sites traffic back into the site content itself! For example, if you want to promote your most popular pages you need to be able to query traffic information.

A rookie might think to herself, “Why use Google Analytics? I could just add a +1 to the database every time the page is viewed and not mess with this API nonsense!” Don’t do this! Writing to the database with that frequency is extremely bad practice. Google Analytics is great at storing traffic data, so we’re going to offload that part to the big G.

Let’s Do It

Creating our API keys

Create a project through the Developers Console here: https://console.developers.google.com

Screen Shot 2014-06-01 at 11.13.52 AM

First we need to switch on the Analytics API. On the left hand menu go to “APIs  & auth” and click the “off” button to switch on the Analytics API.

Screen Shot 2014-06-01 at 11.14.42 AM

Next, we need to create the keys. On the left hand menu: APIs & auth > Credentials. Click “Create new Client ID”

Screen Shot 2014-06-01 at 11.15.23 AM

Create a new “Service Account”

Screen Shot 2014-06-01 at 11.15.41 AM

Your browser will automatically download a .p12 file, you will need this later. Google has also generated a Client ID, Email address, and a Public key for your service account.

Screen Shot 2014-06-01 at 11.59.03 AM

You’ll need to go to your Google Analytics account and add the email address (@developer.gserviceaccount.com). Go to admin dashboard and navigate to User Management under the Account level.

Screen Shot 2014-06-01 at 11.58.03 AM

Here is where you need to add the email address.

Screen Shot 2014-06-01 at 11.58.33 AM

Connecting to Google Analytics API

The first step is to get the Google Analytics API Client from github. You can find it here: https://github.com/google/google-api-php-client

If you want to avoid using git you can use the “download zip” button on the right hand side.

Unzip it, name the folder something friendly and put it on your server (you only really need SRC). You also need to put the .p12 file on your server.

Now we need to create a .php file to interact with the client. Place this file in the /examples directory alongside the other .php files. You can name it whatever you like. There are two parts to this file, first configuring all of the Google generated details with our client.

<?php
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once ('Google/Client.php');
require_once ('Google/Service/Analytics.php');
// Initialize the Google Client object  $client = new Google_Client();
$client->setApplicationName('YOUR PRODUCT NAME'); //doesn't seem to be important

$client->setAssertionCredentials(
    new Google_Auth_AssertionCredentials(
        'EMAIL_ADDRESS@developer.gserviceaccount.com',
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents("http://yourdomain.com/privatekey.p12")
    )
);

// Get this from the Google Console, API Access page
$client->setClientId('YOUR_CLIENT_ID.apps.googleusercontent.com');
$client->setAccessType('offline_access');

The second, is to write the API call. You need the Analytics ID to replace 1111111 below. The pieces you need to make a successful query are the ID, a date range for the traffic data (start date and end date),  “metrics”, and then any optional parameters. One great way to help build the proper query is to use http://ga-dev-tools.appspot.com/explorer/

// Create the Analytics object, build the query and make a call ot the API
$analytics = new Google_Service_Analytics($client);
$analytics_id   = 'ga:11111111';
$lastWeek       = date('Y-m-d', strtotime('-52 week'));
$today          = date('Y-m-d');
	try {
		$optParams = array();
                // Uncomment any of the optional parameters to include them in your query
		//$optParams['dimensions'] = "";
		//$optParams['sort'] = "";
		//$optParams['filters'] = "";
		//$optParams['max-results'] = "";
		$metrics = 'ga:visits';
	    $results = $analytics->data_ga->get($analytics_id,
	                        $lastWeek,
	                        $today,$metrics,$optParams);
	    print_r($results);
	} catch(Exception $e) {
	    echo 'There was an error : - ' . $e->getMessage();
	}

Special thanks to Terry Seidler who’s answer on Stack Overflow helped me immensely. It just needed a few updates on the class names and adjusting of the client file structure.

Here is test.php as one file that you can copy and paste:

<?php set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once ('Google/Client.php');
require_once ('Google/Service/Analytics.php');
// Initialise the Google Client object $client = new Google_Client();
$client->setApplicationName('Your product name');

$client->setAssertionCredentials(
    new Google_Auth_AssertionCredentials(
        'your_service_account_email@developer.gserviceaccount.com',
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents("YOUR_P12_FILE_LOCATION.p12")
    )
);

// Get this from the Google Console, API Access page
$client->setClientId('YOUR_CLIENT_ID.apps.googleusercontent.com');
$client->setAccessType('offline_access');

// Create the Analytics object, build the query and make a call ot the API
$analytics = new Google_Service_Analytics($client);
$analytics_id   = 'ga:11111111';
$lastWeek       = date('Y-m-d', strtotime('-52 week'));
$today          = date('Y-m-d');
	try {
		$optParams = array();
		//Uncomment any of the optional parameters to include them in your query
		#$optParams['dimensions'] = "";
		#$optParams['sort'] = "";
		#$optParams['filters'] = "";
		#$optParams['max-results'] = "";
		$metrics = 'ga:visits';
	    $results = $analytics->data_ga->get($analytics_id,
	                        $lastWeek,
	                        $today,$metrics,$optParams);
	    print_r($results);
	} catch(Exception $e) {
	    echo 'There was an error : - ' . $e->getMessage();
	}

Leave a Reply

Your email address will not be published. Required fields are marked *