I'm looking at using php-ga (https://packagist.org/packages/unitedprototype/php-ga) to send simple analytics to GA - basically capturing when an API endpoint is hit.
I'm using the code below and it's working well, but GA is treating every endpoint hit (tested by refreshing a test page) as a unique visitor. Has anyone out there seen this before? The API knows 'who' is contacting it, thanks to authentication.
Can anyone show me how to tell GA that each refresh is actually a single user session, rather than a brand new visit?
use UnitedPrototype\GoogleAnalytics;
$ga = new GoogleAnalytics\Tracker('UA-12345678-1', 'mysite.com');
$visitor = new GoogleAnalytics\Visitor();
$visitor->setIpAddress($_SERVER['REMOTE_ADDR']);
$visitor->setUserAgent($_SERVER['HTTP_USER_AGENT']);
$session = new GoogleAnalytics\Session();
// Assemble Page information
$page = new GoogleAnalytics\Page('/api/v1/test-ga-thingy');
$page->setTitle('Testing the API Thingy');
// Track page view
$ga->trackPageview($page, $session, $visitor);
I had the same problem, to solve this you need to get PHP to check if the analytics cookie is set, if it is then it shouldn't create a new one, if it isn't it should. Open the file
GoogleAnalytics/Session.php
and go to line number72
. Over there you'll find this code:Once you create a new instance of Session, it'll go through these lines. But over here it gives every instance a newly generated sessionid, gives it a new trackcount and a new generated startTime. Well that's not what we want, so you'll need to change it to see if there allready are any cookies from google analytics and if there are, it should use those. Change these lines to this:
That solves 1 problem, but theres another one, each time you create a new instance of the class "Visitor" theres the same problem. Open the file
GoogleAnalytics/Visitor.php
and go to line number150
. Over there you'll find this code:You'll need to change it into: