Using Google-API-PHP-Client with Google Analytics Core Reporting

Heads up! This post was written when Metric Marketing was known as Canada's Web Shop.
headshot

Google's PHP client library for their GData API hasn't received as much love as their client libraries for other languages. Despite the lack of high level service classes for Google Analytics' Core Reporting API it is possible to work with it using google-api-php-client.

The below is a quick and dirty self contained example based on a Google+ example to get a report. Before you get started go to the API Console and enable access to the Analytics API and generate a client id, client secret, and to register your redirect uri.

As a bonus, this example also shows you how to get page views per day over the last two weeks. I spent the better part of a day finding this incantation, so Merry Christmas PHP Developers!

<?php

$ga_ua = 'UA-XXXXXXX-X'; // This is the ID from your GA snippet.
$client_id = 'your client id'; // From the API Console
$client_secret = 'your client secret'; // From the API Console
$redirect_url = 'http://yourdomain.com/ga-gdata.php'; // The address of this script

require_once 'path/to/google-api-php-client/src/apiClient.php';

session_start();

$client = new apiClient();
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GA Report");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_url);

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die("The session state ({$_SESSION['state']}) didn't match the state parameter ({$_GET['state']})");
  }
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

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

if ($client->getAccessToken()) {
	$url = 'https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles';

	$request = $client->getIo()->authenticatedRequest(new apiHttpRequest($url));

	if ($request->getResponseHttpCode() != 200) {
		throw new apiException("http code: " . $request->getResponseHttpCode() . ", response body: " . $request->getResponseBody());
	}

	$json = json_decode($request->getResponseBody(), true);

	foreach ($json['items'] as $item) {
		if ($item['webPropertyId'] == $ga_ua) {
			$web_property_id = $item['id'];
		}			
	}

	$yesterday = strtotime('-1 day');
	$two_weeks_ago = strtotime('-2 weeks', $yesterday);	

	$search_config = array(
		'ids' => 'ga:'.$web_property_id,
		'start-date' => date('Y-m-d', $two_weeks_ago),
		'end-date' => date('Y-m-d', $yesterday),
		'dimensions' => 'ga:year,ga:month,ga:day',
		'metrics' => 'ga:pageviews'
	);

	$url = 'https://www.googleapis.com/analytics/v3/data/ga?'.http_build_query($search_config);

	$request = $client->getIo()->authenticatedRequest(new apiHttpRequest($url));

	if ($request->getResponseHttpCode() != 200) {
		throw new apiException("http code: " . $request->getResponseHttpCode() . ", response body: " . $request->getResponseBody());
	}
	var_dump(json_decode($request->getResponseBody(), true));

	// The access token may have been updated lazily.
	$_SESSION['token'] = $client->getAccessToken();
} else {
	$state = mt_rand();
	$client->setState($state);
	$_SESSION['state'] = $state;

	$authUrl = $client->createAuthUrl();
	print "<a class="login" href="$authUrl">Connect Me!</a>";
}

Like what you read? Sign up for our Newsletter.