- VolkomenJuist.nl - http://www.volkomenjuist.nl/blog -

Calling Google Analytics Realtime API from PHP

This article describes how to call the Google Analytics API via PHP.

1. Create a new project in the Google Developers Console (https://console.developers.google.com) and make sure the (realtime) analytics API is turned on. At the credentials page, create a new Client ID. This will generate a Client ID, Email address and a public key fingerprints. Afterwards generate a P12 key. This will also download the key file. I stored in the root of my Laravel project.

Developers console [1]

2. Go to your analytics page and add the email address (which is generated before) as a user to have read/analyze rights.



I am using Laravel (5) for this project. This framework uses composer to get all dependencies, so we need to add the Google dependency to the composer.json file. Run ‘composer update’. This will download/autoload the apiclient [2].


"google/apiclient": "1.0.*@beta"

Route (optional)

I created a route to access the api (e.g. http://localhost/google). Therefore I added the following line to routes.php.

$router->get('/google', 'DashboardController@google');


All the magic is located in the  dashboard controller

use Google_Client;
use Google_Service_Analytics;
use Google_Auth_AssertionCredentials;

class DashboardController extends Controller {
    public function google() {

        try {

            $path = base_path() . '/Dash-abcdedgh3f74c.p12';

                throw new \Exception("Can't find .p12 certificate: " . $path);

            $client = new Google_Client();

            $auth = new Google_Auth_AssertionCredentials(


            $service = new Google_Service_Analytics($client);

            $params = array(
                'dimensions' => 'ga:date, ga:hour'
            $results = $service->data_ga->get('ga:12345678', 'yesterday', 'today', 'ga:users, ga:pageviews, ga:sessions', $params); // - OK

//$realtime = $service->data_realtime->get('ga:12345678', 'rt:activeUsers');
 return Response::json($results);

 } catch (\Google_Exception $e) {
 //Proper exception handling

Note: the ga:xxxxxx number is the id of the report.

Buffer [3]