定制 luketowers/laravel-ga4-event-tracking 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

luketowers/laravel-ga4-event-tracking

Composer 安装命令:

composer require luketowers/laravel-ga4-event-tracking

包简介

Simplifies using the Measurement Protocol for Google Analytics 4 to track events in Laravel applications.

README 文档

README

Version Tests License

Simplifies using the Measurement Protocol for Google Analytics 4 to track events in Laravel applications.

Installation

  1. Install package via Composer
composer require luketowers/laravel-ga4-event-tracking
  1. Set GA4_MEASUREMENT_ID and GA4_MEASUREMENT_PROTOCOL_API_SECRET in your .env file.

Copy from Google Analytics > Admin > Data Streams > [Select Site] > Measurement ID & Google Analytics > Admin > Data Streams > [Select Site] > Measurement Protocol API secrets respectively.

  1. Optional: Publish the config / view files by running this command in your terminal:
php artisan vendor:publish --tag=ga4-event-tracking.config --tag=ga4-event-tracking.views
  1. Include the sendGA4ClientID directive in your layout file after the Google Analytics Code tracking code.
<!-- Google Analytics Code -->
@sendGA4ClientID
<!-- </head> -->

The client_id is required to send an event to Google Analytics. This package provides a Blade directive which you can put in your layout file after the Google Analytics Code tracking code. It grabs the current user's GA client_id from either the ga() or gtag() helper functions injected by Google Analytics and makes a POST request to your application to store the client_id in the session, which is later used by the DispatchAnalyticsJob when sending events to GA4.

If you do not use this blade directive, you will have to handle retrieving, storing, and sending the client_id yourself. You can use GA$::setClientId($clientId) to set the client_id manually.

Usage

This package provides two ways to send events to Google Analytics 4:

Directly via the GA4 facade:

Sending event directly is as simple as calling the sendEvent($eventData) method on the GA4 facade from anywhere in your backend to post event to Google Analytics 4. $eventData contains the name and params of the event as per this reference page. For example:

GA4::sendEvent([
    'name' => 'login',
    'params' => [
        'method' => 'Google',
    ],
]);

The sendEvent() method will return an array with the status of the request.

Broadcast events to GA4 via the Laravel Event System

Just add the ShouldBroadcastToAnalytics interface to your event, and you're ready! You don't have to manually bind any listeners.

<?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;
    }
}

There are additional methods that let you customize the call sent to GA4.

broadcastGA4EventAs

With this method you can customize the name of the Event Action. By default, we use the class name with the class's namespace removed. This method gives you access to the underlying GA4 class instance as well.

eventOccurredAt

With this method you can customize the time that the event occurred at. This will be used in the timestamp_micros parameter sent to the Measurement Protocol. By default, we use the current time. You must return an instance of Carbon\Carbon in order for it to be used.

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

With this method you can set the parameters of the event being sent.

<?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';
    }
}

Handle framework and 3rd-party events

If you want to handle events where you can't add the ShouldBroadcastToAnalytics interface, you can manually register them in your EventServiceProvider using the DispatchAnalyticsJob listener.

<?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,
        ],
    ];
}

Debugging Mode

You can also enable debugging mode by calling enableDebugging() method before calling the sendEvent() method. Like so - GA4::enableDebugging()->sendEvent($eventData). The sendEvent() method will return the response (array) from Google Analytics request in that case.

Testing

composer test

or

./vendor/bin/phpunit

Security

If you discover any security related issues, please use the Report a vulnerability button instead of using the issue tracker.

Credits:

This package is a fork of the following projects:

License

This package is open-sourced software licensed under the MIT License.

luketowers/laravel-ga4-event-tracking 适用场景与选型建议

luketowers/laravel-ga4-event-tracking 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 19.02k 次下载、GitHub Stars 达 21, 最近一次更新时间为 2024 年 09 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「analytics」 「laravel」 「laravel-analytics」 「analytics-event-tracking」 「ga4」 「google-analytics-4」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 luketowers/laravel-ga4-event-tracking 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 luketowers/laravel-ga4-event-tracking 我们能提供哪些服务?
定制开发 / 二次开发

基于 luketowers/laravel-ga4-event-tracking 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 19.02k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 21
  • 点击次数: 23
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 21
  • Watchers: 4
  • Forks: 10
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-09-19