I have an API on my webserver that accesses the data in the website's database. I am trying to figure out how to use google analytics to track the API usage. The clients accessing the API response will not be able to execute javascript.
I have tried https://developers.google.com/analytics/devguides/collection/other/mobileWebsites to do server side, but since MY API cannot open any images, it will not work. Any Idea out there?
API example is http://www.serviidb.com/api/video .
If you have updated to Universal Analytics (the new Google Analytics) you can generate events or pageviews directly from PHP.
Google has created the Measurement protocol that is basically a set of http requests with some parameters contatining what you want to track. I will paste here the code I use in my own site to track downloads.
To track anything you just have to call AnalyticsDoHit() with your own parameters:
// Create a page view directly from PHP. No javascript.
function AnalyticsDoHit($tid, $slug, $title)
{
// Standard params
$v = 1;
$cid = ParseOrCreateAnalyticsCookie();
// Send PageView hit
$data = array(
'v' => $v,
'tid' => $tid,
'cid' => $cid,
't' => 'pageview',
'dt' => $title,
'dp' => $slug
);
$getString = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
file_get_contents($getString); // do the https request
}
// Gets the current Analytics session identifier or create a new one
// if it does not exist
function ParseOrCreateAnalyticsCookie()
{
if (isset($_COOKIE['_ga']))
{
// An analytics cookie is found
list($version, $domainDepth, $cid1, $cid2) = preg_split('[\.]', $_COOKIE["_ga"], 4);
$contents = array(
'version' => $version,
'domainDepth' => $domainDepth,
'cid' => $cid1 . '.' . $cid2
);
$cid = $contents['cid'];
}
else
{
// no analytics cookie is found. Create a new one
$cid1 = mt_rand(0, 2147483647);
$cid2 = mt_rand(0, 2147483647);
$cid = $cid1 . '.' . $cid2;
setcookie('_ga', 'GA1.2.' . $cid, time() + 60 * 60 * 24 * 365 * 2, '/');
}
return $cid;
}
Use it as follows:
AnalyticsDoHit("UA-XXXXXX-X", "http://www.AutomatedEmailParser.com/EmailAndParser_setup.msi", "EmailAndParser_setup.msi");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With