8ctopus / php-ga-measurement-protocol
使用PHP从服务器发送数据到Google Analytics。此库完全实现了GA测量协议。
Requires
- php: >=7.3
- guzzlehttp/guzzle: ^6.0 || ^7.0
Requires (Dev)
- php-coveralls/php-coveralls: ^1.0.1
- phpunit/phpunit: ^9
Replaces
README
这是对原始已不再维护的项目 https://github.com/theiconic/php-ga-measurement-protocol.git 的分支。没有计划添加对Google Analytics 4的支持,此包仅用于维护php 8.x支持。
描述
使用PHP从服务器发送数据到Google Analytics。此库完全实现了GA测量协议,因此可以发送您通常在客户端侧通过analytics.js发送的任何数据。您可以发送以下参数类别的数据:用户、会话、流量来源、系统信息、点击、内容信息、应用跟踪、事件跟踪、电子商务、增强电子商务、社交互动、计时、异常、自定义维度/指标、内容实验、内容分组。
- 通用
- 用户
- 会话
- 流量来源
- 系统信息
- 点击
- 内容信息
- 应用跟踪
- 事件跟踪
- 电子商务
- 增强电子商务
- 社交互动
- 计时
- 异常
- 自定义维度/指标
- 内容实验
- 内容分组
安装
使用Composer安装此包。
composer require 8ctopus/php-ga-measurement-protocol
集成
您可以使用此包独立使用,或者使用方便的框架集成
- Laravel 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报告与之前用户操作关联,您必须获取并设置与GA Cookie相同的ClientId。阅读 (这里)。
库已完成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>();
如果您使用PHPStorm等IDE,所有设置参数的方法都应自动完成,这使得构建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);
贡献者
- 豪尔赫·A·博尔赫斯 - 首席开发者(《http://jorgeborges.me》)
- 胡安·法尔孔 - (arcticfalcon)
- 赛义德·艾拉法·R. - (irazasyed)
- 安德烈·拜巴茨基 - (baibaratsky)
- 马丁·帕洛莫 - (lombo)
- 阿米特·拉纳 - (amit0rana)
- 斯特凡·齐维费尔 - (stefanzweifel)
- 蒂图安·贝诺伊 - (nightbr)
- 林遥 - (ryo88c)
- 拉德克·赫雷贝切克 - (http://www.hrebecek.cz/)
- edim24 - (ryo88c)
- venyii - (venyii)
- 皮特·雅普·布拉克梅尔 - (peterjaap)
- 阿尔贝托·博塔里尼 - (alberto-bottarini)
许可协议
PHP的Google Analytics测量协议库THE ICONIC发布于MIT许可协议下。