theiconic / php-ga-measurement-protocol
使用PHP从服务器发送数据到Google Analytics。这个库完全实现了GA测量协议。
Requires
- php: >=5.5
- guzzlehttp/guzzle: ^6.0 || ^7.0
Requires (Dev)
- phpunit/phpunit: 4.7.*
- satooshi/php-coveralls: 1.0.1
README
描述
使用PHP从服务器发送数据到Google Analytics。这个库完全实现了GA测量协议,因此可以发送通常在客户端使用analytics.js发送的任何数据。您可以发送有关以下参数类别的数据:(完整列表)
- 通用
- 用户
- 会话
- 流量来源
- 系统信息
- 击
- 内容信息
- 应用跟踪
- 事件跟踪
- 电子商务
- 增强型电子商务
- 社交互动
- 计时
- 异常
- 自定义维度/度量
- 内容实验
- 内容分组
安装
使用Composer安装此包。
如果您正在使用PHP 5.5或更高版本
和Guzzle 6
,则
{ "require": { "theiconic/php-ga-measurement-protocol": "^2.0" } }
或者如果您正在使用PHP 5.4或更高版本
和Guzzle 5
,则
{ "require": { "theiconic/php-ga-measurement-protocol": "^1.1" } }
请注意,v1不再维护且缺少新功能(如调试和击验证),建议您更新到v2。
集成
您可以使用此包单独使用,或者使用方便的框架集成
- Laravel 4/5 - https://github.com/irazasyed/laravel-gamp
- Yii 2 - https://github.com/baibaratsky/yii2-ga-measurement-protocol
- Symfony2 - https://github.com/fourlabsldn/GampBundle
请随意为您的框架创建集成,让我们知道,我们将在此列出。
用法
所有击的必要参数为协议版本、跟踪ID以及以下之一:客户端ID或用户ID。如果您不希望所有击都看起来像是从您的服务器发出的,则建议使用一些可选参数,如IP覆盖。
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();
击应该已到达GA属性UA-26293728-11。您可以在实时仪表板中验证此信息。请注意,如果您需要将GA报告与之前用户行为相关联,则必须获取并设置ClientId以与GA Cookie相同。请参阅(此处)。
库已完成100%,完整文档正在制作中,但基本上所有参数都可以以相同的方式设置。
// Look at the parameter names in Google official docs at // https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters $analytics->set<ParameterName>('my_value');
// Get any parameter by its name // Look at the parameter names in Google official docs at // https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters $analytics->get<ParameterName>();
如果您使用的是IDE(如PHPStorm),则设置参数的所有方法都应该自动完成,这使得构建Analytics对象变得非常容易。
用例
简单电子商务的订单跟踪
use TheIconic\Tracking\GoogleAnalytics\Analytics; $analytics = new Analytics(); // Build the order data programmatically, including each order product in the payload // Take notice, if you want GA reports to tie this event with previous user actions // you must get and set the same ClientId from the GA Cookie // First, general and required hit data $analytics->setProtocolVersion('1') ->setTrackingId('UA-26293624-12') ->setClientId('2133506694.1448249699'); // To report an order we need to make single hit of type 'transaction' and a hit of // type 'item' for every item purchased. Just like analytics.js would do when // tracking e-commerce from JavaScript $analytics->setTransactionId(1667) // transaction id. required ->setRevenue(65.00) ->setShipping(5.00) ->setTax(10.83) // make the 'transaction' hit ->sendTransaction(); foreach ($cartProducts as $cartProduct) { $response = $analytics->setTransactionId(1667) // transaction id. required, same value as above ->setItemName($cartProduct->name) // required ->setItemCode($cartProduct->code) // SKU or id ->setItemCategory($cartProduct->category) // item variation: category, size, color etc. ->setItemPrice($cartProduct->price) ->setItemQuantity($cartProduct->qty) // make the 'item' hit ->sendItem(); }
增强型电子商务的订单跟踪
use TheIconic\Tracking\GoogleAnalytics\Analytics; $analytics = new Analytics(); // Build the order data programmatically, including each order product in the payload // Take notice, if you want GA reports to tie this event with previous user actions // you must get and set the same ClientId from the GA Cookie // First, general and required hit data $analytics->setProtocolVersion('1') ->setTrackingId('UA-26293624-12') ->setClientId('2133506694.1448249699') ->setUserId('123'); // Then, include the transaction data $analytics->setTransactionId('7778922') ->setAffiliation('THE ICONIC') ->setRevenue(250.0) ->setTax(25.0) ->setShipping(15.0) ->setCouponCode('MY_COUPON'); // Include a product $productData1 = [ 'sku' => 'AAAA-6666', 'name' => 'Test Product 2', 'brand' => 'Test Brand 2', 'category' => 'Test Category 3/Test Category 4', 'variant' => 'yellow', 'price' => 50.00, 'quantity' => 1, 'coupon_code' => 'TEST 2', 'position' => 2 ]; $analytics->addProduct($productData1); // You can include as many products as you need this way $productData2 = [ 'sku' => 'AAAA-5555', 'name' => 'Test Product', 'brand' => 'Test Brand', 'category' => 'Test Category 1/Test Category 2', 'variant' => 'blue', 'price' => 85.00, 'quantity' => 2, 'coupon_code' => 'TEST', 'position' => 4 ]; $analytics->addProduct($productData2); // Don't forget to set the product action, in this case to PURCHASE $analytics->setProductActionToPurchase(); // Finally, you must send a hit, in this case we send an Event $analytics->setEventCategory('Checkout') ->setEventAction('Purchase') ->sendEvent();
批量击
GA有一个端点,您可以一次性注册多个击,限制为20个击。要在构建Analytics对象时发送的击可以放置在队列中。
以下是一个示例,发送两个击,然后清空队列。
$analytics = new Analytics(false, false); $analytics ->setProtocolVersion('1') ->setTrackingId('UA-xxxxxx-x') ->setClientId('xxxxxx.xxxxxx'); foreach(range(0, 19) as $i) { $analytics = $analytics ->setDocumentPath("/mypage$i") ->enqueuePageview(); //enqueue url without pushing } $analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empties the queue
当发送点击事件时队列会被清空,也可以通过emptyQueue
方法手动清空队列。
$analytics = new Analytics(false, false); $analytics ->setProtocolVersion('1') ->setTrackingId('UA-xxxxxx-x') ->setClientId('xxxxxx.xxxxxx'); foreach(range(0, 5) as $i) { $analytics = $analytics ->setDocumentPath("/mypage$i") ->enqueuePageview(); //enqueue url without pushing } $analytics->emptyQueue(); // empty queue, allows to enqueue 20 hits again foreach(range(1, 20) as $i) { $analytics = $analytics ->setDocumentPath("/mypage$i") ->enqueuePageview(); //enqueue url without pushing } $analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empties the queue
如果尝试入队超过20个点击事件,库将抛出EnqueueUrlsOverflowException
异常。
点击事件的验证
来自Google开发者指南
Google Analytics度量协议不返回HTTP错误代码,即使度量协议的点击事件格式错误或缺少必需的参数。为了确保您的点击事件格式正确且包含所有必需的参数,您可以在部署到生产之前使用验证服务器进行测试。
要发送验证点击事件,请开启调试模式,如下所示
// Make sure AsyncRequest is set to false (it defaults to false) $response = $analytics ->setDebug(true) ->sendPageview(); $debugResponse = $response->getDebugResponse(); // The debug response is an associative array, you could use print_r to view its contents print_r($debugResponse);
GA实际上返回一个JSON,该JSON被解析为关联数组。阅读(这里)了解如何解释响应。
禁用库点击事件以用于测试/开发环境
在您的应用程序配置中,您可以有一个标志用于启用或禁用库,这样就不实际向GA发送点击事件,在这种情况下,库返回一个返回空值的AnalyticsResponseInterface对象。
这在开发或测试环境中特别有用。
// Instantiate the Analytics object by passing the second parameter in the constructor as TRUE $analytics = new Analytics(true, true);
贡献者
- Jorge A. Borges - 主开发者 (http://jorgeborges.me)
- Juan Falcón - arcticfalcon
- Syed Irfaq R. - irazasyed
- Andrei Baibaratsky - baibaratsky
- Martín Palombo - lombo
- Amit Rana - amit0rana
- Stefan Zweifel - stefanzweifel
- Titouan Benoit - nightbr
- Hayashi Ryo - ryo88c
- Radek Hřebeček - http://www.hrebecek.cz/
- edim24 - ryo88c
- venyii - venyii
- Peter Jaap Blaakmeer - peterjaap
- Alberto Bottarini - alberto-bottarini
许可证
PHP版的Google Analytics度量协议库THE ICONIC发布在MIT许可证下。