devpro/laravel-ga4-event-tracking

此包已被弃用且不再维护。作者建议使用luketowers/laravel-ga4-event-tracking包。

简化了在Laravel应用程序中使用Google Analytics 4的测量协议来跟踪事件。

v2.0.0 2024-09-19 20:48 UTC

This package is auto-updated.

Last update: 2024-09-19 20:51:56 UTC


README

Version Tests License

简化了使用Google Analytics 4的测量协议来跟踪Laravel应用程序中的事件。

安装

  1. 通过Composer安装包
composer require luketowers/laravel-ga4-event-tracking
  1. 在.env文件中设置GA4_MEASUREMENT_IDGA4_MEASUREMENT_PROTOCOL_API_SECRET

分别从Google Analytics > Admin > Data Streams > [选择网站] > Measurement IDGoogle Analytics > Admin > Data Streams > [选择网站] > Measurement Protocol API secrets复制。

  1. 可选:通过在终端运行此命令发布配置/视图文件
php artisan vendor:publish --tag=ga4-event-tracking.config --tag=ga4-event-tracking.views
  1. 在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

安全

如果您发现任何与安全相关的问题,请使用 报告漏洞 按钮,而不是使用问题跟踪器。

致谢

本包是基于以下项目分叉的

许可证

本包是开源软件,受 MIT 许可证 许可。