alvadi-it/php-ga-measurement-protocol

使用PHP从服务器发送数据到Google Analytics。这个库完全实现了GA测量协议。

dev-master 2023-07-04 13:13 UTC

This package is not auto-updated.

Last update: 2024-09-25 17:05:32 UTC


README

Build Status Coverage Status Scrutinizer Code Quality Latest Stable Version Total Downloads License Documentation Status

描述

使用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。

集成

您可以使用此包单独使用,或者使用方便的框架集成

您可以自由地为您喜欢的框架创建集成,并让我们知道,以便我们在这里列出它。

用法

所有击打所需参数为协议版本、跟踪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

验证击

来自谷歌开发者指南

谷歌分析测量协议不返回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);

贡献者

许可证

PHP版谷歌分析测量协议库由MIT许可证发布。