Category Archives: PHP

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 https://console.developers.google.com 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 …@developer.gserviceaccount.com ) 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 ...googleusercontent.com] ';
$email_address = ' [add your long ass string ...@developer.gserviceaccount.com]';
$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 ="https://www.googleapis.com/auth/analytics.readonly";
//server side auth
$cred = new Google_Auth_AssertionCredentials(
$email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$client->setClientId($client_id);

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).


createService($client);
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){
getViews($service,$ga_account_id,$ga_property['id']);
}
}
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
'ga:sessions',
$optParams
);
printDataTable($cr_results);
} 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.

https://github.com/google/google-api-php-client
https://console.developers.google.com/start/appengine
https://developers.google.com/analytics/solutions/articles/hello-analytics-api OLD
https://console.developers.google.com/start/appengine
https://developers.google.com/api-client-library/php/start/get_started **
http://www.sitepoint.com/using-google-analytics-api-php-logging/
http://www.sitepoint.com/using-google-analytics-api-v3-php-fetching-data/
http://www.daimto.com/google-oauth2-php/
https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/analytics/demo/helloAnalyticsApi.php

after auth,
management
https://developers.google.com/analytics/devguides/config/mgmt/v3/

core reporting
https://developers.google.com/analytics/devguides/reporting/core/v3/

links for getting and parsing data:
https://developers.google.com/analytics/devguides/reporting/core/v3/reference#q_details
https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=event_tracking&jump=ga_eventcategory

serverside auth
http://stackoverflow.com/questions/26590159/google-analytics-embed-api-authentication
https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth
http://stackoverflow.com/questions/9863509/service-applications-and-google-analytics-api-v3-server-to-server-oauth2-authen
http://stackoverflow.com/questions/25376791/fatal-error-uncaught-exception-google-auth-exception-with-message-error-refr
http://stackoverflow.com/questions/12837748/analytics-google-api-error-403-user-does-not-have-any-google-analytics-account
https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts#googleAccounts
https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php

embed api
https://developers.google.com/analytics/devguides/reporting/embed/v1/