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:

setApplicationName('My Project');

$client->setAssertionCredentials(new Google_Auth_AssertionCredentials(


$service = new Google_Service_Analytics($client);

// Connection ok, now you can use the API
$results = $service->data_ga->get(

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.

Leave a Reply

Your email address will not be published. Required fields are marked *