Author Archives: jamie

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/

Raspberry Pi Time Lapse via node

Fourth try:

Third try: (best one yet with the clouds)

Second try: (not much going on that day)

First try:

based off of http://designspark.com/blog/time-lapse-photography-with-the-raspberry-pi-camera.

I pushed everything up to my dropbox with http://www.andreafabrizi.it/?dropbox_uploader via niltoid. Then compiled to video with http://en.wikipedia.org/wiki/MEncoder on my ubuntu machine (apt-get install mencoder). Still need to find a free mac compiler.

my code (so far) here: https://github.com/jamiegilmartin/RPiNodeTimeLapse

The Nature of Code – Tornado

I received my The Nature of Code book by Daniel Shiffman a few weeks ago and, even though I’ve already been lacking in sleep, I’ve been staying up way late imbibing it’s priceless code examples. This book definitely lives up to it’s reputation and I would include it on my stranded-on-a-desert-island wish list (providing the island had power & computers that ran Processing etc). Anyway, I’ve started a playful tornado sketch and will trying to incorporate more concepts from the book into it in the future. Check back for updates.

Screenshot from 2013-08-14 08:32:45

Linux on Macbook 2,1

So my RaspberryPi is locked up in my desk at work and besides it’s just a little slow but I suppose I was needing a Linux fix so I started retracing my steps and installing a similar set up on my new old Macbook 2,1 circa. 2006. I installed Ubuntu 12.04 LTS and it runs AMAZINGLY fast and the mac is now no longer a paper weight that could barely handle OSX Leopard. It has been a fun trip getting things up and running and I definitely see that there is a time to .dmg and a time to create aliases to java libraries in some obscure file system folder. Dev wise, this 2gig dirty old machine is surely becoming my preferred device – LAMP is so sweet and node and mongo are a breeze and yes, it’s helped me to make the switch to SublimeText over Textmate (though still a user while in OSX ). Now if I can just get openCV to work with Processing…

Robot: Solar Tracker on wheels – here we go

IMG_2004

Ah birthdays… I’ve received a bunch of amazon gift cards for my birthday and I think I’ve finally spent all the money. Besides a seat post bike rack, all I bought was electronics stuff; my first robot chassis as well as a bunch of other random stuff… (inductors for trying to do that Disney Touche singing plant project which radioshack does not carry). I’ll mostly be following niltoid as usual but I’m mounting my old solar tracker on top. My Raspberry pi looks pretty good mounted on there, hopefully it will become some super AI brain. I also, like niltoid, bought a HC-SR04 Ultra-sonic sensor (data sheet) which should be fun to try and use. I’m presently looking at this tutorial and this library. Should be fun.

Now onto motor driver:
Ahmad (niltoid’s) code
also looking at this tutorial.

Update: 5.15.2013
IMG_2028

All the parts are hooked up and working. I still need to figure out the power situation as well as re-intergrating the solar charging part but the components are there though the code is rudimentary at the moment, pretty much just a loop to test each component. Now the really fun part begins.