Send event to Google Analytics using API server sided

Hello Analytics API: PHP quickstart for service accounts is not going to help you at all. That code uses the core reporting API the core reporting API is for requesting data from Google Analytics not sending data to Google Analytics.

To send data to Google Analytics we use the Measurement Protocol. The measurement protocol is used to send information to Google analytics the JS snippet you posted also uses the measurement protocol.

You can use the measurement protocol from any language that supports HTTP post or Http Get. That being said there is no PHP specific library for sending information to Google analytics you are going to have to format your post yourself. A tip would be to use Validating hits to check it before you send it to Google while you are developing this.

It will probably look something like this

http://www.google-analytics.com/collect?v=1&tid=UA-XXX-Y&cid=35009a79-1a05-49d7-b876-2b884d0f825b&an=My%20Awesom%20APP&aid=com.daimto.awesom.app&av=1.0.0&aiid=come.daimto.awesom.installer &t=event&ec=list&ea=accounts&userclicked&ev=10

Here is an example of how to do it with PHP.

First build your request with Google Analytics Hit Builder, test it with https://google-analytics.com/debug/collect?_query_here, and then send it with file_get_contents (see here).

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => 'v=1&t=transaction&tid=UA-xxxxxxx-x&cid=xxxxxx&ti=abcdef&tr=100&in=productname'
    )
);
$context  = stream_context_create($options);
$result = file_get_contents('https://www.google-analytics.com/collect', false, $context);

There is a PHP library php-ga-measurement-protocol by theiconic on github which can be used to send data using Measurement Protocal.

use TheIconic\Tracking\GoogleAnalytics\Analytics;

// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);

// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-26293728-11')
    ->setClientId('12345678')
    ->setDocumentPath('/mypage')
    ->setIpOverride("202.126.106.175");

// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();