使用 API 服务器端将事件发送到 Google Analytics

Send event to Google Analytics using API server sided

我有一个网站,我使用 javascript 函数将事件发送到 Google Analytics:

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

但是我还需要使用 PHP 从 server-side 发送一些类似的事件。我尝试了这个快速入门教程:Hello Analytics API: PHP quickstart for service accounts 并且报告非常有效,但我不知道如何发送事件。

你能一步一步地告诉我我应该编写什么代码来发送与上面提到的完全相同的事件吗?

Hello Analytics API: PHP quickstart for service accounts 根本帮不了你。该代码使用核心报告 API 核心报告 API 用于请求数据 from Google Analytics 不发送数据 to Google 分析。

要将数据发送到 Google Analytics,我们使用 Measurement Protocol。测量协议用于向 Google 分析您 post 编辑的 JS 片段也使用测量协议。

您可以使用支持 HTTP post 或 Http Get 的任何语言的测量协议。也就是说,没有 PHP 特定的库可以将信息发送到 Google 分析,您将不得不自己格式化 post。一个小窍门是在你开发它之前使用 Validating hits 检查它,然后再将它发送到 Google。

它可能看起来像这样

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

有一个 PHP 库 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();

这里有一个如何使用 PHP 的例子。

首先使用 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);