Send event to Google Analytics using API server sided

aokozlov picture aokozlov · Aug 25, 2015 · Viewed 31.2k times · Source

I have a website where I send events to Google Analytics using javascript function:

ga('send', 'event', 'showphone', 'feedback', 'result');

However I also need to send some similar events from server-side using PHP. I tried this quick start tutorial: Hello Analytics API: PHP quickstart for service accounts and reporting works like a charm, but I have no idea how to send event.

Could you please show me step-by-step what I should code to send exactly same event like mentioned above.

Answer

DaImTo picture DaImTo · Aug 25, 2015

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