🤯 50% Off! 700+ courses, assessments, and books

Using the Google Analytics API with PHP: Logging In

Younes Rafie
Share

In this series, we’re going to see how we can use the Google Analytics API to interact with our Google Analytics data via PHP. We’ll be using Laravel on Homestead Improved, but you can follow along with any framework on any development environment – Laravel + HI is simply the fastest and recommended starting point.

Requirements

To be able to follow along, you need to have a Google Analytics account which you can get from the Google Analytics page.

You also need to be familiar with the basic usage of the Google Analytics dashboard.

Google Analytics Dashboard

What are we going to build?

In this article we’re going to build an app that looks like Google Analytics Explorer, but to make it short, we’re going to limit the functionality and discuss how we can extend our demo.

Google Analytics API

Overview

The Google Analytics API is divided into a number of APIs. We use each API depending on our needs:

  • Management API:
    Provides access to Google Analytics configuration data like accounts, properties, views, goals…

  • Metadata API:
    Provides access to the list of columns (Dimensions, Metrics) so that we don’t need to hard code them inside our app.

  • Core Reporting API:
    Provides access to dashboard data, and most of the tasks are available through this API.

  • Real Time Reporting API:
    Gives you access to real time data, like the one on your Google Analytics dashboard. At the time of this writing, this API is in beta.

Real Time Dashboard

  • Embed API:
    This API allows you to create and embed dashboards in your website using javascript.

  • MCF Reporting API:
    Multi-Channel Funnels Reporting API enables you to request Multi-Channel Funnels data for an authenticated user, which means you can query data from multiple sources and use it for your own statistics.

In this article, we’re going to be focused on the Management API, Metadata API and Core reporting API. First, let’s start with some basic usage.

Basic Usage

To start using the API, we need to create a new project on the Google Developers Console.
Google Developers Console

You project dashboard should look like this:
Google Console Project Dashboard

Now we have a project ready to use any of the provided Google services. Because we intend to use Google Analytics API, we need to activate it.

When you want to use a Google API you need to provide two things:

1) Your API credentials.
2) Your developer keys.

Go to menu, API & AUTH, select “APIs” and enable Analytics API
Google Console APIs

Under the API & AUTH menu, select the Credentials link, and select Create new client ID.

Select Web Application for our app, then enter your website URL and your login redirect page URL. Because we will be using Laravel in our demo, you can use localhost:8000 for the development phase, and don’t forget to change https to http in your URL.

Google Console Credentials

At the bottom of the page, you have the Public API access. We need to create a new access key.

1) choose the Browser Key option for our demo.
2) on the http referrers box, you can leave the value empty to accept requests from anywhere, or specify your domain address.

Now we are ready to start playing around with the API.

Limits and Quotas

When working with Google Analytics API, we are limited to a number of requests per day, per second, etc. You can read the full doc page for more information.

Project Configuration

I will assume that you already know how to set up a new Laravel project on Homestead Improved.

We need to require "google/api-client": "dev-master" in our composer.json and update the dependencies.

In my app/config/, I will create a file called analytics.php where I can put my configuration.

return [
    'app_name'          => 'Your app name', //Can be anything
    'client_id'         => 'Your ID',//can be found on the credentials page
    'client_secret'     => 'Your secret ID',//on the credentials page
    'api_key'           => 'Your key'//can be found at the bottom of your credentials page
];

To keep things separated, i will create a folder named src inside my app directory and create a file called GA_Service.php where I can put all request logic.

// app/src/GA_Service.php

class GA_Service{
    //...
}

Trying to access this class somewhere in our code will result in a Class not found exception, so we can take advantage of composer autoloading feature.

In the composer.json file, go to the autoload classmap section and add our path to the list.

// composer.json

...
"autoload":{
    "classmap": [
        ...
        ,
		"app/src"
    ]
}

Don’t forget to run composer dump-autoload after saving the changes.

By default, Laravel includes a file called HomeController.php in the app/controllers directory. We will use it as our main app controller.

Back to the GA_Service class; to communicate with Google APIs we use a class called Google_Client. In our constructor, we will create a new instance and start filling the necessary parameters.

public function __construct( Google_Client $client ){
	$this->client = $client;
	$this->init();
}

private function init(){
		$this->client->setClientId(Config::get('analytics.client_id') );
		$this->client->setClientSecret(Config::get('analytics.client_secret'));
		$this->client->setDeveloperKey(Config::get('analytics.api_key'));
		$this->client->setRedirectUri('http://localhost:8000/login');
		$this->client->setScopes(array('https://www.googleapis.com/auth/analytics'));
}

Instead of instantiating the class inside the constructor, we pass it as a parameter and let Laravel’s IoC resolve it for us. For more details, be sure to check this article out.

The first three lines of the init method are self explanatory; the Config::get method grabs the configuration from the analytics.php file.

The redirect URI method is the redirection URL to be used after Google verification and it should match the one registered previously on the Google Console Dashboard.

The setScope method is where we specify the access level needed for our app:

After setting up our google client we’re going to set our login process:

// app/src/GA_Service.php
public function isLoggedIn(){
	if (isset($_SESSION['token'])) {
	  $this->client->setAccessToken($_SESSION['token']);
	  return true;
	}

	return $this->client->getAccessToken();
}//authenticate

public function login( $code ){ 	$this->client->authenticate($code);
 	$token = $this->client->getAccessToken();
  	$_SESSION['token'] = $token;
  			
	return token;
}//login

public function getLoginUrl(){
	$authUrl = $this->client->createAuthUrl();
	return $authUrl;
}//getLoginUrl
  • isLoggedIn: return true if the user has an access token to be used.
  • getLoginUrl: if the user is not logged in, we get an authentication URL.
  • login: we have already set a redirect URL on the Google API Dashboard, we receive back a $_GET['code'] parameter that we can use to get a token for our requests.

Let’s use what we’ve got for now. Inside our controller:

// app/controllers/HomeController.php

class HomeController extends BaseController {
	private $ga;

	public function __construct( GA_Service $ga ){
		$this->ga = $ga;
	}

	public function index()
	{
		if( $this->ga->isLoggedIn() ){
			return 'Show home page';
		}
		else{
            $url = $this->ga->getLoginUrl();
			return View::make('login', [ 'url' => $url ]);

		}

	}//index
}//class


// app/routes.php

Route::get('/', 'HomeController@index');
Route::get('/login', 'HomeController@login');

We inject GA_Service into our controller, and when the user hits our index route, we check if he’s logged in. If not, we generate the authentication URL.

App permission request

After accepting the request permission, you will be redirected to the login page with the code parameter.

// app/controllers/HomeController.php
public function login(){
	if( Input::has('code') ){
		$code = Input::get('code');
		$this->ga->login($code);
        
		return "Go to the home <a href='/'>page</a>";
	}
	else{
		return "Invalide request parameters";
	}//else
}//login

In our login function, we test if the code exists. If so, we pass it to our GA_Service::login function so we can authenticate and get a token for the user.

Wrapping up

In this part we discussed the basic usage of Google Analytics API. At this point, we have a token that we can use to query the list of APIs, and in the next part, we’re going to continue building our demo app using the Google Analytics API.