kitbrennan90/php-ga-measurement-protocol

PHP 包,用于与 Google Analytics 测量协议交互(例如,使用您的服务器端发送页面浏览和事件到 Google Analytics)。

v1.0.3 2019-03-14 16:35 UTC

This package is auto-updated.

Last update: 2024-09-15 05:49:42 UTC


README

这个简单的库可以让您发送服务器端跟踪事件到 Google Analytics。

安装

建议通过 composer 安装此库。在命令行中: composer require kitbrennan90/php-ga-measurement-protocol

如果您使用 PSR-4(或现代框架),只需在脚本顶部导入客户端

use GaMeasurementProtocol\Client;

如果您不使用 PSR-4,则应要求 composer 自动加载: require_once('vendor/autoload.php');

使用此库

初始化客户端

$trackingId = 'GA-123456-1'; // Take the tracking/property ID from your Google Analytics account
$client = new Client($trackingId);

发送页面浏览

该库默认触发页面浏览。

$trackingId = 'GA-123456-1'; // Take the tracking/property ID from your Google Analytics account
$client = new Client($trackingId);

$params = [
    'dl' => 'http://foo.com/home?a=b' // Document location, required for a 'pageview' type
];

$client->request()
   ->setParameters($params)
   ->send();

不工作? 默认情况下,测量协议不会引发任何错误,如果您的结果未在 Google Analytics 中显示,请探索下面的调试部分以解决问题。

发送其他 hit 类型(例如,事件,屏幕视图)

该库支持每种跟踪类型(作为常量可用)

  • GaMeasurementProtocol\Enums\HitType::PAGEVIEW
  • GaMeasurementProtocol\Enums\HitType::SCREENVIEW
  • GaMeasurementProtocol\Enums\HitType::EVENT
  • GaMeasurementProtocol\Enums\HitType::TRANSACTION
  • GaMeasurementProtocol\Enums\HitType::ITEM
  • GaMeasurementProtocol\Enums\HitType::SOCIAL
  • GaMeasurementProtocol\Enums\HitType::EXCEPTION
  • GaMeasurementProtocol\Enums\HitType::TIMING

只需在请求上调用 setHitType($type)

$trackingId = 'GA-123456-1'; // Take the tracking/property ID from your Google Analytics account
$client = new Client($trackingId);

$params = [
    'dl' => 'http://foo.com/home?a=b' // Document location, required for a 'pageview' type
];

$client->request()
   ->setParameters($params)
   ->setHitType(GaMeasurementProtocol\Enums\HitType::EVENT)
   ->send();

发送附加参数

完整支持的参数列表可以在此处找到: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters

将所有可选参数添加到数组中,并在请求对象上调用 setParameters($params)

$trackingId = 'GA-123456-1'; // Take the tracking/property ID from your Google Analytics account
$client = new Client($trackingId);

$params = [
    'dl' => 'http://foo.com/home?a=b', // Document location, required for a 'pageview' type
    'ul' => 'en-us' // User language
];

$client->request()
   ->setParameters($params)
   ->send();

调试

测量协议始终返回 200,即使参数无效。您需要启用调试模式,这将 var_dump 调试结果到您的视图。

注意 如果启用调试模式,结果将不会出现在您的 Google Analytics 中。

一旦调试模式表明您的 hit 是有效的,您应该关闭调试模式并再次发送请求。

$trackingId = 'GA-123456-1'; // Take the tracking/property ID from your Google Analytics account
$client = new Client($trackingId);

$params = [
    'dl' => 'http://foo.com/home?a=b' // Document location, required for a 'pageview' type
];

$client->setDebug(true)
   ->request()
   ->setParameters($params)
   ->send();