Category Archives: Tutorial

Google API service application php authentication

In case you are currently trying to get some Google Analytics data (or data from another one of their APIs) and you’re feeling a bit like this, here’s a quick sketch of the map of my first journey through the swamp of sadness.

I’m sure you’ve already gone here and created an account and a project and maybe you’ve already gone to the APIs & Auth tab and enabled the API you wanted to use (Analytics in my case).  And maybe you’ve even gone to the tab under that one, Credentials, and created a new Service Account and downloaded your p12 key. Great, so before any coding starts, take that long Service Account Email you see (ends in … ) and go into your Google Analytics account and give that email permissions. (Admin>Account>User Management and add to Admin>Property>User Management too just to be safe).

Ok, now download some stuff.  I installed the Google App Engine and did most of my development there but you don’t really need to.  My code worked using MAMP too.   You’ll need the latest Google API PHP Client from github, there are older versions of the API referenced in the docs and some of the many many sites and stackoverflow queries I visited, but they don’t work.

ok, code.  Let’s start with the basic config stuff.

require_once 'google-api-php-client/src/Google/autoload.php';
$client_id = ' [add your long ass string] ';
$email_address = ' [add your long ass string]';
$key_file_location = ' [ref your .p12 file] ';
$key = file_get_contents($key_file_location);

ok, now let’s create the google client.

$client = new Google_Client();
$client->setApplicationName('GA Analytics API Sample');
//separate additional scopes with a comma
$scopes ="";
//server side auth
$cred = new Google_Auth_AssertionCredentials(
if($client->getAuth()->isAccessTokenExpired()) {

So far so good?  Next, let’s create a new Google Service instance (again, in my case, I’m using the Google Analytics Service – if you’re using a different service, I hope some of the code below helps you).

function createService(&$client){
$service = new Google_Service_Analytics($client);
$man_accounts = $service->management_accounts->listManagementAccounts();
foreach($man_accounts['items'] as $ga_account){
getProperties( $service, $ga_account['id']);

Now let’s get the Property or site whose analytics data we want to get. And for each property we will call the ‘getViews’ method.

function getProperties(&$service,&$ga_account_id){
$man_properties = $service->management_webproperties->listManagementWebproperties($ga_account_id);
foreach($man_properties as $ga_property){
function getViews(&$service,&$ga_account_id,$ga_property_id){
$man_views = $service->management_profiles->listManagementProfiles( $ga_account_id, $ga_property_id );
foreach($man_views['items'] as $ga_view){
startCoreReprorting($service, $ga_view['id']);

And now for the Core Reporting which is where we query for analytics data using ‘dimensions’ and ‘metrics’  which you can go read about somewhere else.  This post is about just getting something to work.

function startCoreReprorting(&$service, $ga_view_id){
try {
$optParams = array(
'dimensions' => 'ga:eventCategory', //required
'metrics' => 'ga:uniqueEvents'
//'sort' => '-ga:sessions,ga:source', //optional
//'filters' => 'ga:medium==organic',
//'max-results' => '25'
$cr_results = $service->data_ga->get(
'ga:' . $ga_view_id,
'2010-01-01',//start date
'today', //end date
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();

And now to format the results a little. (Note: all html tags below are stripped of their brackets because it breaks WP)

function printDataTable(&$cr_results) {
if(count($cr_results->getRows()) > 0) {
$table .= 'table';
// Print headers.
$table .= 'tr';
foreach ($cr_results->getColumnHeaders() as $header) {
$table .= 'th' . $header->name . '/th';
$table .= '/tr';
// Print table rows.
foreach ($cr_results->getRows() as $row) {
$table .= 'tr';
foreach ($row as $cell) {
$table .= 'td'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '/td';
$table .= '/tr';
$table .= '/table';
}else {
$table .= 'p No Results Found./p';
print $table;

And here are a bunch of the links I went to get this up and running. So thanks to everyone below. OLD **

after auth,

core reporting

links for getting and parsing data:

serverside auth

embed api