PHPackages                             freema/ga4-measurement-protocol-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. freema/ga4-measurement-protocol-bundle

ActiveSymfony-bundle[API Development](/categories/api)

freema/ga4-measurement-protocol-bundle
======================================

Google Analytics 4 Measurement Protocol Bundle for Symfony applications

1.1(8mo ago)0213↓50%MITPHPPHP &gt;=8.1CI passing

Since Mar 21Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/freema/ga4-measurement-protocol-bundle)[ Packagist](https://packagist.org/packages/freema/ga4-measurement-protocol-bundle)[ RSS](/packages/freema-ga4-measurement-protocol-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (18)Versions (11)Used By (0)

Google Analytics 4 Measurement Protocol Bundle
==============================================

[](#google-analytics-4-measurement-protocol-bundle)

[![CI](https://github.com/freema/ga4-measurement-protocol-bundle/workflows/CI/badge.svg)](https://github.com/freema/ga4-measurement-protocol-bundle/workflows/CI/badge.svg)[![Coverage](https://camo.githubusercontent.com/b45b5445399b90c51119a783a00cca22c896a52315bca737b300d91e05e55710/68747470733a2f2f636f6465636f762e696f2f67682f667265656d612f6761342d6d6561737572656d656e742d70726f746f636f6c2d62756e646c652f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://camo.githubusercontent.com/b45b5445399b90c51119a783a00cca22c896a52315bca737b300d91e05e55710/68747470733a2f2f636f6465636f762e696f2f67682f667265656d612f6761342d6d6561737572656d656e742d70726f746f636f6c2d62756e646c652f6272616e63682f6d61696e2f67726170682f62616467652e737667)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)[![PHP](https://camo.githubusercontent.com/3e41095f4ad1c6ad78f988bd1c107f87972f334143c3ba814165a03e1f43a63c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d3737374242343f6c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://camo.githubusercontent.com/3e41095f4ad1c6ad78f988bd1c107f87972f334143c3ba814165a03e1f43a63c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d3737374242343f6c6f676f3d706870266c6f676f436f6c6f723d7768697465)[![Symfony](https://camo.githubusercontent.com/c7b438fa05847d8a632da0ceb68da991eae650a68a3077a315716f3f450f3c37/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53796d666f6e792d352e342532422d3030303030303f6c6f676f3d73796d666f6e79266c6f676f436f6c6f723d7768697465)](https://camo.githubusercontent.com/c7b438fa05847d8a632da0ceb68da991eae650a68a3077a315716f3f450f3c37/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53796d666f6e792d352e342532422d3030303030303f6c6f676f3d73796d666f6e79266c6f676f436f6c6f723d7768697465)[![code style: prettier](https://camo.githubusercontent.com/0e3c7d7b2a558f52e1c6110956e5c4fef2af1f3219192707e6ec0d7f84d081ff/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f64655f7374796c652d5053522d2d31322d6666363962342e737667)](https://camo.githubusercontent.com/0e3c7d7b2a558f52e1c6110956e5c4fef2af1f3219192707e6ec0d7f84d081ff/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f64655f7374796c652d5053522d2d31322d6666363962342e737667)

This bundle provides a clean, object-oriented integration with Google Analytics 4 Measurement Protocol for Symfony applications. It uses an event-based approach to track page views, purchases, and custom events in GA4.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Symfony 5.4 or 6.4, 7.1 +

Installation
------------

[](#installation)

```
composer require freema/ga4-measurement-protocol-bundle
```

Configuration
-------------

[](#configuration)

Add the bundle to your `config/bundles.php`:

```
return [
    // ...
    Freema\GA4MeasurementProtocolBundle\GA4MeasurementProtocolBundle::class => ['all' => true],
    // ...
];
```

Create a configuration file `config/packages/ga4_measurement_protocol.yaml`:

```
# config/packages/ga4_measurement_protocol.yaml
ga4_measurement_protocol:
  clients:
    front:
      tracking_id: 'G-XXXXXXXXXX'  # Your GA4 Measurement ID
      api_secret: 'YOUR_SECRET'    # Your GA4 API Secret
```

Full Configuration Reference
----------------------------

[](#full-configuration-reference)

```
ga4_measurement_protocol:
    # HTTP client configuration
    http_client:
        config:
            # Proxy configuration (Symfony HTTP client format)
            proxy: 'http://proxy.example.com:3128'
            no_proxy: ['localhost', '.example.com']
            # Other HTTP client options
            timeout: 5.0
            max_redirects: 5

    # Required: Define your analytics clients
    clients:
        front:
            # Required: Your GA4 Measurement ID
            tracking_id: 'G-XXXXXXXXXX'

            # Required: Your GA4 API Secret
            api_secret: 'YOUR_SECRET'

            # Optional: Fixed client ID to use for all requests
            client_id: '555.123456789'

            # Optional: Enable debug mode
            debug_mode: true

            # Optional: Custom handlers
            custom_client_id_handler: 'App\Handler\MyClientIdHandler'
            custom_user_id_handler: 'App\Handler\MyUserIdHandler'
            custom_session_id_handler: 'App\Handler\MySessionIdHandler'
```

Using the Bundle
----------------

[](#using-the-bundle)

The bundle uses an event-based approach where you create specific event objects, add them to the client, and then send them. This makes the code cleaner and easier to understand.

### Basic Usage

[](#basic-usage)

```
use Freema\GA4MeasurementProtocolBundle\Client\AnalyticsRegistryInterface;
use Freema\GA4MeasurementProtocolBundle\Event\PageViewEvent;

// Get the analytics client
$analytics = $analyticsRegistry->getClient('front');

// Create an event
$pageViewEvent = new PageViewEvent();
$pageViewEvent->setDocumentPath('/your-page-path');
$pageViewEvent->setDocumentTitle('Your Page Title');

// Add the event and send
$analytics->addEvent($pageViewEvent);
$result = $analytics->send();
```

### Page View Example

[](#page-view-example)

```
use Freema\GA4MeasurementProtocolBundle\Client\AnalyticsRegistryInterface;
use Freema\GA4MeasurementProtocolBundle\Event\PageViewEvent;

class YourController
{
    public function pageViewAction(AnalyticsRegistryInterface $analyticsRegistry)
    {
        // Get the analytics client
        $analytics = $analyticsRegistry->getClient('front');

        // Create a page view event
        $pageViewEvent = new PageViewEvent();
        $pageViewEvent->setDocumentPath('/your-page-path');
        $pageViewEvent->setDocumentTitle('Your Page Title');

        // Add the event and send
        $analytics->addEvent($pageViewEvent);
        $result = $analytics->send();

        // Result contains URL and parameters sent
    }
}
```

### Purchase Event Example

[](#purchase-event-example)

```
use Freema\GA4MeasurementProtocolBundle\Client\AnalyticsRegistryInterface;
use Freema\GA4MeasurementProtocolBundle\Event\PurchaseEvent;
use Freema\GA4MeasurementProtocolBundle\Event\Item;

class YourController
{
    public function purchaseAction(AnalyticsRegistryInterface $analyticsRegistry, $order)
    {
        // Get the analytics client
        $analytics = $analyticsRegistry->getClient('front');

        // Create a purchase event
        $purchaseEvent = new PurchaseEvent();
        $purchaseEvent->setTransactionId($order->getOrderNumber());
        $purchaseEvent->setValue($order->getTotal());
        $purchaseEvent->setTax($order->getTax());
        $purchaseEvent->setShipping($order->getShippingCost());

        // Add products as items
        foreach ($order->getItems() as $orderItem) {
            $item = new Item();
            $item->setItemId($orderItem->getSku());
            $item->setItemName($orderItem->getName());
            $item->setPrice($orderItem->getPrice());
            $item->setQuantity($orderItem->getQuantity());
            $item->setItemBrand($orderItem->getBrand());

            $purchaseEvent->addItem($item);
        }

        // Add the event and send
        $analytics->addEvent($purchaseEvent);
        $result = $analytics->send();
    }
}
```

Event Types
-----------

[](#event-types)

The bundle provides a variety of pre-defined event types that match GA4's standard events.

### E-commerce Events

[](#e-commerce-events)

```
use Freema\GA4MeasurementProtocolBundle\Event\Ecommerce\ViewItemEvent;
use Freema\GA4MeasurementProtocolBundle\Event\Ecommerce\AddToCartEvent;
use Freema\GA4MeasurementProtocolBundle\Event\Ecommerce\BeginCheckoutEvent;
use Freema\GA4MeasurementProtocolBundle\Event\PurchaseEvent;
use Freema\GA4MeasurementProtocolBundle\Event\Item;

// Create item
$item = new Item();
$item->setItemId('SKU123');
$item->setItemName('Product Name');
$item->setPrice(29.99);
$item->setQuantity(1);
$item->setItemBrand('Brand Name');
$item->setItemCategory('Category');

// View item
$viewItemEvent = new ViewItemEvent();
$viewItemEvent->setValue(29.99);
$viewItemEvent->addItem($item);
$analytics->addEvent($viewItemEvent);

// Add to cart
$addToCartEvent = new AddToCartEvent();
$addToCartEvent->setValue(29.99);
$addToCartEvent->addItem($item);
$analytics->addEvent($addToCartEvent);

// Begin checkout
$beginCheckoutEvent = new BeginCheckoutEvent();
$beginCheckoutEvent->setValue(29.99);
$beginCheckoutEvent->addItem($item);
$analytics->addEvent($beginCheckoutEvent);

// Purchase
$purchaseEvent = new PurchaseEvent();
$purchaseEvent->setTransactionId('ORDER123');
$purchaseEvent->setValue(29.99);
$purchaseEvent->setTax(6.00);
$purchaseEvent->addItem($item);
$analytics->addEvent($purchaseEvent);

// Send all events at once
$analytics->send();
```

### Engagement Events

[](#engagement-events)

```
use Freema\GA4MeasurementProtocolBundle\Event\Engagement\LoginEvent;
use Freema\GA4MeasurementProtocolBundle\Event\Engagement\SignUpEvent;

// Login
$loginEvent = new LoginEvent();
$loginEvent->setMethod('email');
$analytics->addEvent($loginEvent);

// Sign up
$signUpEvent = new SignUpEvent();
$signUpEvent->setMethod('email');
$analytics->addEvent($signUpEvent);
```

### Custom Event

[](#custom-event)

```
use Freema\GA4MeasurementProtocolBundle\Event\CustomEvent;

// Create a custom event
$customEvent = new CustomEvent('your_custom_event_name');
$customEvent->addParameter('event_category', 'user_engagement');
$customEvent->addParameter('event_action', 'click');
$customEvent->addParameter('custom_dimension1', 'value1');

// Add the event and send
$analytics->addEvent($customEvent);
$result = $analytics->send();
```

Creating Your Own Event Classes
-------------------------------

[](#creating-your-own-event-classes)

You can easily create your own event classes for specific events:

```
namespace App\Analytics\Event;

use Freema\GA4MeasurementProtocolBundle\Event\AbstractEvent;

class SpecialOfferViewEvent extends AbstractEvent
{
    public function getName(): string
    {
        return 'view_special_offer';
    }

    public function setOfferId(string $offerId): self
    {
        $this->parameters['offer_id'] = $offerId;
        return $this;
    }

    public function setOfferName(string $offerName): self
    {
        $this->parameters['offer_name'] = $offerName;
        return $this;
    }
}
```

ID Management
-------------

[](#id-management)

### Client ID

[](#client-id)

Client ID is required by GA4 to identify unique users. The bundle will:

1. Try to get it from the `_ga` cookie
2. Use a fixed value if configured: ```
    client_id: '555.123456789'
    ```
3. Accept a programmatic value: ```
    $analytics->setClientId('your-client-id');
    ```
4. Use a custom handler: ```
    class MyClientIdHandler implements CustomClientIdHandler
    {
        public function buildClientId(): ?string
        {
            // Your custom logic to get client ID
        }
    }
    ```

### User ID

[](#user-id)

User ID helps identify logged-in users across devices. You can:

1. Set it programmatically: ```
    $analytics->setUserId($user->getId());
    ```
2. Use a custom handler: ```
    class MyUserIdHandler implements CustomUserIdHandler
    {
        public function buildUserId(): ?string
        {
            // Your custom logic to get user ID
        }
    }
    ```

### Session ID

[](#session-id)

Session ID helps GA4 group events that happen in the same session. The bundle can:

1. Extract it from the GA4 cookie for your property: ```
    // For trackingId G-NX8H4907NJ
    // Cookie format: _ga_NX8H4907NJ=GS1.1.1743566249.16.0.1743566249.60.0.181542193
    // The session ID is 1743566249 in this example

    ```
2. Accept a programmatic value: ```
    $analytics->setSessionId('your-session-id');
    ```
3. Use a custom handler: ```
    class MySessionIdHandler implements CustomSessionIdHandler
    {
        public function buildSessionId(): ?string
        {
            // Your custom logic to get session ID
        }
    }
    ```

Debug Mode
----------

[](#debug-mode)

Debug mode enables detailed validation of your events from GA4:

1. Configure it globally: ```
    debug_mode: true
    ```
2. Set it programmatically: ```
    $analytics->setDebugMode(true);
    ```

When debug mode is enabled:

- Events are sent to GA4's debug endpoint
- A `debug_mode` parameter is added to each event
- More detailed validation messages are returned

License
-------

[](#license)

This bundle is available under the MIT License. See the [LICENSE](LICENSE) file for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance62

Regular maintenance activity

Popularity14

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~43 days

Total

5

Last Release

241d ago

Major Versions

0.9 → 1.02025-04-04

### Community

Maintainers

![](https://www.gravatar.com/avatar/1feadbd856db0d9578f7e3c5221c76bd76d4cdfa745bd748be918b2cd10de70c?d=identicon)[Freema](/maintainers/Freema)

---

Top Contributors

[![freema](https://avatars.githubusercontent.com/u/2912985?v=4)](https://github.com/freema "freema (25 commits)")

---

Tags

analyticsbundlephpsymfonysymfony-bundle

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/freema-ga4-measurement-protocol-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/freema-ga4-measurement-protocol-bundle/health.svg)](https://phpackages.com/packages/freema-ga4-measurement-protocol-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M650](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
