devpro / laravel-ga4-event-tracking
简化了在Laravel应用程序中使用Google Analytics 4的测量协议来跟踪事件。
Requires
- php: ^8.1 || ^8.2 || ^8.3
- guzzlehttp/guzzle: ^7.5
- illuminate/bus: ^8.0 || ^9.0 || ^10.0 || ^11.0
- illuminate/http: ^8.74 || ^9.0 || ^10.0 || ^11.0
- illuminate/queue: ^8.0 || ^9.0 || ^10.0 || ^11.0
- illuminate/validation: ^8.0 || ^9.0 || ^10.0 || ^11.0
Requires (Dev)
- mockery/mockery: ^1.4.4
- nesbot/carbon: ^2.66
- orchestra/testbench: ^6.20 || ^7.0 || ^8.0
- phpunit/phpunit: ^9.5
README
简化了使用Google Analytics 4的测量协议来跟踪Laravel应用程序中的事件。
安装
- 通过Composer安装包
composer require luketowers/laravel-ga4-event-tracking
- 在.env文件中设置
GA4_MEASUREMENT_ID
和GA4_MEASUREMENT_PROTOCOL_API_SECRET
。
分别从
Google Analytics > Admin > Data Streams > [选择网站] > Measurement ID
和Google Analytics > Admin > Data Streams > [选择网站] > Measurement Protocol API secrets
复制。
- 可选:通过在终端运行此命令发布配置/视图文件
php artisan vendor:publish --tag=ga4-event-tracking.config --tag=ga4-event-tracking.views
- 在Google Analytics跟踪代码后,在布局文件中包含
sendGA4ClientID
指令。
<!-- Google Analytics Code --> @sendGA4ClientID <!-- </head> -->
client_id
是向Google Analytics发送事件所必需的。此包提供了一个Blade指令,您可以在布局文件中将它放在Google Analytics代码跟踪代码之后。它从Google Analytics注入的ga()
或gtag()
辅助函数中获取当前用户的GA client_id
,并向您的应用程序发送POST请求以将client_id
存储在会话中,然后在发送事件到GA4时,由DispatchAnalyticsJob
使用。
如果您不使用此blade指令,您将必须自行处理检索、存储和发送client_id
。您可以使用GA$::setClientId($clientId)
手动设置client_id
。
用法
此包提供了两种向Google Analytics 4发送事件的方式
通过GA4
外观直接发送
直接发送事件就像在您的后端任何地方调用GA4
外观上的sendEvent($eventData)
方法一样简单,以便将事件发布到Google Analytics 4。$eventData
包含事件名称和参数,如本参考页面所示。例如
GA4::sendEvent([ 'name' => 'login', 'params' => [ 'method' => 'Google', ], ]);
sendEvent()
方法将返回一个包含请求状态的数组。
通过Laravel事件系统向GA4广播事件
只需将ShouldBroadcastToAnalytics
接口添加到您的事件中,您就准备好了!您不需要手动绑定任何监听器。
<?php namespace App\Events; use App\Order; use LukeTowers\GA4EventTracking\ShouldBroadcastToAnalytics; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class OrderWasCreated implements ShouldBroadcastToAnalytics { use Dispatchable, SerializesModels; public $order; public function __construct(Order $order) { $this->order = $order; } }
还有一些其他方法可以自定义发送给GA4的调用。
broadcastGA4EventAs
使用此方法,您可以自定义事件动作的名称。默认情况下,我们使用带有命名空间的类名。此方法还允许您访问底层的GA4
类实例。
eventOccurredAt
使用此方法,您可以自定义事件发生的时间。这将用于发送到测量协议的timestamp_micros
参数。默认情况下,我们使用当前时间。您必须返回一个Carbon\Carbon
实例,以便它可以被使用。
use Carbon\Carbon; use LukeTowers\GA4EventTracking\GA4; use LukeTowers\GA4EventTracking\ShouldBroadcastToAnalytics; use Illuminate\Queue\SerializesModels; class OrderSubmitted extends Event implements ShouldBroadcastToAnalytics { use SerializesModels; protected Carbon $submittedAt; public function __construct( public Order $order ) { $this->submittedAt = now(); } public function eventOccurredAt(): Carbon { return $this->submittedAt; } }
withGA4Parameters
使用此方法,您可以设置发送事件参数。
<?php namespace App\Events; use App\Order; use LukeTowers\GA4EventTracking\ShouldBroadcastToAnalytics; use LukeTowers\GA4EventTracking\GA4; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class OrderWasCreated implements ShouldBroadcastToAnalytics { use Dispatchable, SerializesModels; public $order; public function __construct(Order $order) { $this->order = $order; } public function withGA4Parameters(GA4 $ga4): array { $eventData = [ 'transaction_id' => $order->id, 'value' => $order->amount_total, 'currency' => 'USD', 'tax' => $order->amount_tax, 'shipping' => $order->amount_shipping, 'items' => [], 'event_category' => config('app.name'), 'event_label' => 'Order Created', ]; foreach ($order->items as $item) { $eventData['items'][] = [ 'id' => $item->sku ?: 'p-' . $item->product->id, 'name' => $item->title, 'brand' => $item->product->brand->name ?? '', 'category' => $item->product->category->title ?? '', 'quantity' => $item->quantity, 'price' => $item->price, 'variant' => $item->variant->title ?? '', ]; } return $eventData; } public function broadcastGA4EventAs(GA4 $ga4): string { return 'purchase'; } }
处理框架和第三方事件
如果您要处理无法添加 ShouldBroadcastToAnalytics
接口的事件,您可以使用 EventServiceProvider
手动注册它们,并使用 DispatchAnalyticsJob
监听器。
<?php namespace App\Providers; use LukeTowers\GA4EventTracking\Listeners\DispatchAnalyticsJob; use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, DispatchAnalyticsJob::class, ], ]; }
调试模式
您还可以通过在调用 sendEvent()
方法之前调用 enableDebugging()
方法来启用 调试模式。例如 - GA4::enableDebugging()->sendEvent($eventData)
。在这种情况下,sendEvent()
方法将返回 Google Analytics 请求的响应(数组)。
测试
composer test
或
./vendor/bin/phpunit
安全
如果您发现任何与安全相关的问题,请使用 报告漏洞 按钮,而不是使用问题跟踪器。
致谢
本包是基于以下项目分叉的
- protonemedia/laravel-analytics-event-tracking:原始包,但仅支持通用分析。
- daikazu/laravel-ga4-event-tracking:从原始包分叉以支持 Google Analytics 4,但该包未得到维护,且与 Laravel 10 不兼容。
- accexs/laravel-ga4-event-tracking:从
daikazu
的包分叉,但缺少一些功能,并且没有干净地分叉。
许可证
本包是开源软件,受 MIT 许可证 许可。