Giter Site home page Giter Site logo

droidlabour / laravel-ga4-event-tracking Goto Github PK

View Code? Open in Web Editor NEW

This project forked from devproca/laravel-ga4-event-tracking

0.0 0.0 0.0 49 KB

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

License: MIT License

PHP 95.00% Blade 5.00%

laravel-ga4-event-tracking's Introduction

Laravel Google Analytics 4 Measurement Protocol Event Tracking

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 devpro/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 DevPro\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 two additional methods that lets you customize the call sent to GA4.

With the broadcastGA4EventAs 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.

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

<?php

namespace App\Events;

use App\Order;
use DevPro\GA4EventTracking\ShouldBroadcastToAnalytics;
use DevPro\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 DevPro\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

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.

laravel-ga4-event-tracking's People

Contributors

luketowers avatar droidlabour avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.