使用API服务器端发送事件到谷歌分析


Send event to Google Analytics using API server sided

我有一个网站,我发送事件到谷歌分析使用javascript函数:

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

然而,我还需要使用PHP从server-side发送一些类似的事件。我尝试了这个快速入门教程:Hello Analytics API: PHP快速入门服务帐户和报告工作像一个魅力,但我不知道如何发送事件。

你能告诉我一步一步我应该编码发送完全相同的事件像上面提到的

Hello Analytics API:服务帐户的PHP快速入门根本不会帮到你。该代码使用核心报告API,核心报告API用于从 Google Analytics请求数据而不是将数据发送到 Google Analytics。

向Google Analytics发送数据时,我们使用Measurement Protocol。度量协议用于向Google分析发送信息,您发布的JS片段也使用度量协议。

您可以使用来自任何支持HTTP post或HTTP Get的语言的度量协议。也就是说,没有特定的PHP库来发送信息到谷歌分析,你将不得不自己格式化你的帖子。一个小技巧是,当你在开发这个时,在你把它发送给谷歌之前,使用验证点击来检查它。

它可能看起来像这样

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

github上有一个由theiconic编写的PHP库PHP -ga- Measurement -protocol,可用于使用Measurement protocol发送数据。

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();

下面是一个如何在PHP中做到这一点的例子。

首先用Google Analytics Hit Builder构建您的请求,用https://google-analytics.com/debug/collect?_query_here测试它,然后用file_get_contents发送(见这里)。

$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);