PHP Classes

Tracking PHP API Accesses using Google Analytics Part 2: Recording API Accesses - PHP Google Analytics API Metrics Tracker package blog

Recommend this page to a friend!
  All package blogs All package blogs   PHP Google Analytics API Metrics Tracker PHP Google Analytics API Metrics Tracker   Blog PHP Google Analytics API Metrics Tracker package blog   RSS 1.0 feed RSS 2.0 feed   Blog Tracking PHP API Acce...  
  Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  

Author:

Viewers: 408

Last month viewers: 2

Package: PHP Google Analytics API Metrics Tracker

In the first part of this article it was presented a solution to retrieve statistics data from Google Analytics API using PHP but this API also allows recording events.

This can be useful to record accesses to a PHP API that you are providing in your site.

Read this article to learn how to use Google Analytics PHP to track the accesses to a PHP API of your own.




Loaded Article

Contents

Introduction

Description of the Problem and the Proposed Solution

Advantages and Disadvantages of using the Google Analytics API

Implementation

Conclusion


Introduction

Many Web applications provide an API, so other applications can access and interact with your Web application. So it may be useful to your project to keep track of the accesses to your server-side API usage data in Google Analytics.

Description of the Problem and the Proposed Solution

Given: clients call the server API of your application.

Task: monitoring the number of API calls.

Proposed solution: using Google Analytics.

How: by calling Google Analytics API. Actually, I have borrowed the solution that Google suggested for monitoring in mobile applications.

Advantages and Disadvantages of using the Google Analytics API

What is this useful for? If you have been already using Google Analytics for monitoring your Web site, why not to collect API statistics in the same interface?

The advantages of such approach:

  • Ability to get statistics about general API loads (investors like it)
  • Minimal efforts for obtaining statistics by calling the already available Google Analytics API (see below for details)
  • A single statistics interface both for the Web site part and the API
  • Ready to use Google Analytics tools: analysis, reports, history review, comparing data in different time periods
  • In Google Analytics interface you can track the usage of your resource in the real-time mode.
Google Analytics Interface Look

Disadvantages are:

  • Any Google Analytics parameters will be missing due to making sense in the API call context, like for instance browser type, cookies enabled or disabled, etc.
  • Without additional efforts all your customers will be considered as new visitors

As for the disadvantages, some of the parameters are possible to defined by using data received from the client calling the API and configuring Google Analytics API for using this. For instance, you can try to analyze the geography of your API users by their IP addresses. You can also try to translate ‘user agent' value of your client.

In order to distinguish different API clients from each other, you need to assign each client a unique identifier that they will pass in the call. This is a ‘partner-id' parameter in the sample below.

Implementation

I will show Zend Framework based plugin as a sample solution, but it can be ported to any project with minimum fuss.

First of all create a new tracker in Google Analytics, get its code and enter it in the configuration file: application/configs/application.ini

google.analytics.tracking.code = UA-44444444-44

My code will automatically replace standard “UA” prefix by the prefix for using it in mobile applications - “MO”.

Then set the API call in application/Bootstrap.php:

protected function _initPlugins() {
     $front = Zend_Controller_Front :: getInstance();
     $front->registerPlugin(new XXX_Controller_Plugin_Integration_Google_Analytics_Mobile_Tracker);
 } 
And finally, the plugin code itself. Do not forget to replace XXX with your prefix.
<?php
/**
* Calls Google Analytics to track usage, e.g. of our API
* done for http://yasno.tv/ project
* @author Alexander Skakunov <alex.skakunov@gmail.com>
*/
class Yasno_Controller_Plugin_Integration_Google_Analytics_Mobile_Tracker extends Zend_Controller_Plugin_Abstract {

const G_VERSION = '4.4sh';
const COOKIE_NAME = '__utmmobile';
const COOKIE_PATH = '/';
const COOKIE_USER_PERSISTENCE = 63072000; // Two years in seconds.
const UTM_GIF_LOCATION = 'http://www.google-analytics.com/__utm.gif';
/**
* @var Zend_Http_Client
*/
protected $_httpClient;
public function __construct() {
$this->setHttpClient(new Zend_Http_Client);
}
/**
* @return Zend_Http_Client $httpClient
*/
public function getHttpClient() {
return $this->_httpClient;
}
/**
* @param Zend_Http_Client
* @return this
*/
public function setHttpClient(Zend_Http_Client $httpClient) {
$this->_httpClient = $httpClient;
return $this;
}
/**
* form URL with params and call Google backend to send these params
* @param Zend_Controller_Request_Abstract $request
*/
public function preDispatch(Zend_Controller_Request_Abstract $request) {
if (is_null($request->getServer('SERVER_NAME'))) {
return;
}
$config = Zend_Registry::get('config');
if (empty($config->google->analytics->tracking->code)) {
return;
}
$visitorId = $this->_getVisitorId($request);

$this->_buildUtmUrl($visitorId, $request);
$this->_setCookie($visitorId);
$httpClient = $this->getHttpClient();

if ('' != $request->getServer('HTTP_USER_AGENT')) {
$httpClient->setConfig(array('useragent', $request->getServer('HTTP_USER_AGENT')));
}
if ('' != $request->getServer('HTTP_ACCEPT_LANGUAGE')) {
$httpClient->setHeaders('Accept-Language: ' . $request->getServer('HTTP_ACCEPT_LANGUAGE'));
}
$httpClient->request();
}

/**
* sets params of HTTP client to build the URL to call Google backend
* @param string $visitorId
*/
protected function _buildUtmUrl($visitorId, $request) {
$config = Zend_Registry::get('config');
$trackingCode = $config->google->analytics->tracking->code;
$trackingCode = 'MO' . substr($trackingCode, 2);
$client = $this->getHttpClient();
$client->setMethod(Zend_Http_Client::GET);
$client->setUri(self::UTM_GIF_LOCATION);
$client->setParameterGet(
array(
'utmwv' => self::G_VERSION,
'utmn' => rand(0, 0x7fffffff),
'utmhn' => $request->getServer('SERVER_NAME'),
'utmr' => $request->getServer('HTTP_REFERER'),
'utmp' => $request->getServer('REQUEST_URI'),
'utmac' => $trackingCode,
'utmcc' => '__utma%3D999.999.999.999.999.1%3B',
'utmvid' => $visitorId,
'utmip' => $this->_getIP($request),
)
);
}
/**
* The last octect of the IP address is removed to anonymize the user.
* @param Zend_Controller_Request_Abstract $request
* @return string
*/
protected function _getIP($request) {
$realIp = !is_null($request->getServer('HTTP_X_REAL_IP'))
? $request->getServer('HTTP_X_REAL_IP')
: $request->getServer('REMOTE_ADDR');
if (empty($realIp)) {
return '';
}
// Capture the first three octects of the IP address and replace the forth
// with 0, e.g. 124.455.3.123 becomes 124.455.3.0
$regex = '/^([^.]+\.[^.]+\.[^.]+\.).*/';
if (preg_match($regex, $realIp, $matches)) {
return $matches[1] . '0';
}
return '';
}
/**
* set visitor ID by one of 3 rules, required for proper tracking
* @param Zend_Controller_Request_Abstract $request
* @return string
*/
protected function _getVisitorId(Zend_Controller_Request_Abstract $request) {
// If there is a value in the cookie, don't change it.
if (!empty($_COOKIE[self::COOKIE_NAME])) {
return $_COOKIE[self::COOKIE_NAME];
}

if (null != $request->getParam('partner-id')) {
return $request->getParam('partner-id');
}
return '0x' . substr(md5($request->getServer('HTTP_USER_AGENT') . uniqid(rand(0, 0x7fffffff), true)), 0, 16);
}
/**
* Add visitor ID cookie to the response.
* @param string $visitorId
*/
protected function _setCookie($visitorId) {
$cookie = new Zend_Http_Cookie(
self::COOKIE_NAME,
$visitorId,
$_SERVER['SERVER_NAME'],
time()+self::COOKIE_USER_PERSISTENCE,
self::COOKIE_PATH
);
$this->getHttpClient()->setCookie($cookie);
}
}

If this code is to track your application API usage, you can tell your API's clients to provide unique value for the 'partner-id' variable. That will allow to count different users.

The code also tries to detect the IP address and the accepted language for every call.

Conclusion

As you have seen, using Google Analytics to track the accesses to PHP based APIs is not hard at all. You just need to be careful and forward some values taken from the API call request.

If you liked this article or have questions about using Google Analytics API from PHP to track your Web API accesses, post a comment here.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

No comments were submitted yet.



  Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  
  All package blogs All package blogs   PHP Google Analytics API Metrics Tracker PHP Google Analytics API Metrics Tracker   Blog PHP Google Analytics API Metrics Tracker package blog   RSS 1.0 feed RSS 2.0 feed   Blog Tracking PHP API Acce...