Google Analytics API with PHP using a service account

Google APIs are great. You can do almost everything with them: data reporting, file upload, everything. Unfortunately the documentation isn’t that good because same very important informations are not reported there! So you try the examples and they don’t work because of a hidden step you didn’t done.

So, talking about Google Analytics API we have the opportunity to get reports from your Google Analytics account using a offline script. That’s very useful if you want to use the data for some purpose and you create a cron job that grabs the data from Analytics and stores it somewhere. To do this (with API V3) you have to follow this steps:

  • First of all access the Google Developer Console and create a project if you don’t have already one
  • From APIs & Auth > APIs activate the APIs you need, in our case the Analytics API
  • From APIs & Auth > Credentials create a new “Client ID” of type “Service Account”
  • Download the p12 file, this is the private key that will be used in communication between your script and che Google Analytics API server
  • In the Developer Console a new entry has appeared. Copy the eMail address and access your Google Analytics account. Add a new user using the copied address. This is a very important step.

Now you’re ready to code. You will need the Google API PHP library from GitHub. Download it and unzip it where needed.

Ok, we’re ready to code. Here’s a simple example:

<?php
setApplicationName('My Project');

$client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
	SERVICE_ACCOUNT_EMAIL_ADDRESS,
	array('https://www.googleapis.com/auth/analytics.readonly'),
	file_get_contents(PATH_TO_YOUR_P12_FILE)
));

$client->setClientId(SERVICE_ACCOUNT_CLIENT_ID);
$client->setAccessType('offline_access');

$service = new Google_Service_Analytics($client);

// Connection ok, now you can use the API
$results = $service->data_ga->get(
 'ga:1234',
 '2014-09-01',
 '2014-09-07',
 'ga:pageviews'
);
?>

If you get a invalid_grant error check all the steps again.

An other possible issue is that your local time is not synced with the real time. Check this too.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *