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

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

PHP

Composer

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.

Composer.json

"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');

Logic

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';

            if(!\File::exists($path))
            {
                throw new \Exception("Can't find .p12 certificate: " . $path);
            }

            $client = new Google_Client();
            $client->setClientId('123456789-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com');
            $client->setApplicationName('Dash');

            $auth = new Google_Auth_AssertionCredentials(
                '123456789-abcdefghijklmnopqrstuvwxyz@developer.gserviceaccount.com',
                array(
                    'https://www.googleapis.com/auth/analytics.readonly'
                ),
                file_get_contents($path)
            );

            $client->setAssertionCredentials($auth);

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

1 comment to Calling Google Analytics Realtime API from PHP

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>