PHPackages                             guillaumevar/php-ga4-mp - 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. guillaumevar/php-ga4-mp

ActiveLibrary[API Development](/categories/api)

guillaumevar/php-ga4-mp
=======================

PHP GoogleAnalytics4 Measurement Protocol Library

v1.0.0(3y ago)032MITPHPPHP &gt;=7.1

Since Jun 25Pushed 3y agoCompare

[ Source](https://github.com/guillaume-var/php-GA4-Measurement-Protocol)[ Packagist](https://packagist.org/packages/guillaumevar/php-ga4-mp)[ RSS](/packages/guillaumevar-php-ga4-mp/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (1)Dependencies (4)Versions (3)Used By (0)

Google Analytics 4 Measurement Protocol PHP Library
===================================================

[](#google-analytics-4-measurement-protocol-php-library)

[![Coverage Status](https://camo.githubusercontent.com/c709864138bb970bc59024826ff77e727a2619654e59fcc33e125c0c35e36f7e/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f62723333662f7068702d4741342d4d6561737572656d656e742d50726f746f636f6c2f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/br33f/php-GA4-Measurement-Protocol?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/a63f97c05f8582e2554766ff16f36872c2a41b23d65fa1f223d5b3f7a40d1075/68747470733a2f2f706f7365722e707567782e6f72672f62723333662f7068702d6761342d6d702f762f737461626c652e706e67)](https://packagist.org/packages/br33f/php-ga4-mp)[![Total Downloads](https://camo.githubusercontent.com/af328bc2c1c59132c368d59e44f98c0ce9797347e46f3ba2238b892b9c6faa62/68747470733a2f2f706f7365722e707567782e6f72672f62723333662f7068702d6761342d6d702f646f776e6c6f6164732e706e67)](https://packagist.org/packages/br33f/php-ga4-mp)

Overview
--------

[](#overview)

This is a PHP Library facilitating the use of Google Analytics 4 (GA4) Measurement Protocol. Measurement Protocol allows developers to send events directly from server-side PHP to Google Analytics.

Please note that GA4 Measurement Protocol is in alpha and might encounter breaking changes. Full documentation is available here:

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

[](#requirements)

- PHP &gt;= 7.1
- ext-json
- guzzlehttp/guzzle: ^6.5.5

dev:

- phpunit/phpunit: "^9.5"
- fakerphp/faker: "^1.14"

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

[](#installation)

The recommended way to install this library is via [Composer](https://getcomposer.org/ "Composer") (packagist package: [br33f/php-ga4-mp](https://packagist.org/packages/br33f/php-ga4-mp "br33f/php-ga4-mp")).

Install by composer command:

```
composer require br33f/php-ga4-mp

```

or `package.json`

```
{
    "require": {
        "br33f/php-ga4-mp": "^0.1.0"
    }
}

```

Usage
-----

[](#usage)

### Send View Item Event

[](#send-view-item-event)

```
use Br33f\Ga4\MeasurementProtocol\Service;
use Br33f\Ga4\MeasurementProtocol\Dto\Request\BaseRequest;
use Br33f\Ga4\MeasurementProtocol\Dto\Event\ViewItemEvent;
use Br33f\Ga4\MeasurementProtocol\Dto\Parameter\ItemParameter;

// Create service instance
$ga4Service = new Service('MEASUREMENT_PROTOCOL_API_SECRET', 'MEASUREMENT_ID');

// Create base request with required client_id
$baseRequest = new BaseRequest('CLIENT_ID');

// Create Event Data
$viewItemEventData = new ViewItemEvent();
$viewItemEventData
    ->setValue(51.10)
    ->setCurrency('EUR');

// Create Item
$viewedItem = new ItemParameter();
$viewedItem
    ->setItemId('ITEM_ID')
    ->setItemName('ITEM_NAME')
    ->setPrice(25.55)
    ->setQuantity(2);

// Add this item to viewItemEventData
$viewItemEventData->addItem($viewedItem)

// Add event to base request (you can add up to 25 events to single request)
$baseRequest->addEvent($viewItemEventData);

// We have all the data we need. Just send the request.
$ga4Service->send($baseRequest);
```

### Send Purchase Event

[](#send-purchase-event)

```
use Br33f\Ga4\MeasurementProtocol\Service;
use Br33f\Ga4\MeasurementProtocol\Dto\Request\BaseRequest;
use Br33f\Ga4\MeasurementProtocol\Dto\Event\PurchaseEvent;
use Br33f\Ga4\MeasurementProtocol\Dto\Parameter\ItemParameter;

// Create service instance
$ga4Service = new Service('MEASUREMENT_PROTOCOL_API_SECRET', 'MEASUREMENT_ID');

// Create base request with required client_id
$baseRequest = new BaseRequest('CLIENT_ID');

// Create Event Data
$purchaseEventData = new PurchaseEvent();
$purchaseEventData
    ->setValue(250.00)
    ->setCurrency('USD');

// Create Item
$purchasedItem1 = new ItemParameter();
$purchasedItem1
    ->setItemId('FIRST_ITEM_ID')
    ->setItemName('FIRST_ITEM_NAME')
    ->setPrice(100.00)
    ->setQuantity(2);

// Add this item to purchaseEventData
$purchaseEventData->addItem($purchasedItem1)

// You can also fill item data via constructor
$purchaseEventData->addItem(new ItemParameter([
    'item_id' => 'SECOND_ITEM_ID',
    'item_name' => 'SECOND_ITEM_NAME',
    'price' => 50.00,
    'quantity' => 1
]));

// Add event to base request (you can add up to 25 events to single request)
$baseRequest->addEvent($purchaseEventData);

// We have all the data we need. Just send the request.
$ga4Service->send($baseRequest);
```

At the moment, the library contains the defined structures of the following events:

Event nameStructureDocumentationadd\_payment\_infoAddPaymentInfoEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#add_payment_info)add\_shipping\_infoAddShippingInfoEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#add_shipping_info)add\_to\_cartAddToCartEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#add_to_cart)begin\_checkoutBeginCheckoutEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#begin_checkout)loginLoginEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#login)purchasePurchaseEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#purchase)refundRefundEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#refund)remove\_from\_cartRemoveFromCartEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#remove_from_cart)searchSearchEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#search)select\_itemSelectItemEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#select_item)sign\_upSignUpEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#sign_up)view\_cartViewCartEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#view_cart)view\_itemViewItemEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#view_item)view\_search\_resultsViewSearchResultsEvent[see documentation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#view_search_results)These events are sent analogously to the examples presented above.

### Other events

[](#other-events)

In order to send any event one can use `BaseEvent` structure and add any data. Please note that specific event structure should be used instead if already defined, since BaseEvent does not force any structure or provide data validation.

```
use Br33f\Ga4\MeasurementProtocol\Service;
use Br33f\Ga4\MeasurementProtocol\Dto\Request\BaseRequest;
use Br33f\Ga4\MeasurementProtocol\Dto\Event\BaseEvent;

// Create Service and request same as above
// ...

// Create Base Event Data (for example: 'share' event - https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#share)
$eventName = 'share';
$anyEventData = new BaseEvent($eventName);
$purchaseEventData
    ->setMethod('Twitter')
    ->setContentType('Post')
    ->setItemId('example_item_id')
    ->setAnyParamYouWish('test'); // means 'any_param_you_wish' is set

// Add event to base request (you can add up to 25 events to single request) and send, same as above
// ...
```

Debug event data and requests
-----------------------------

[](#debug-event-data-and-requests)

Debuging event data is possible by sending them to debug endpoint (Measurement Protocol Validation Server), since default endpoint for Google Analytics 4 Measurement Protocol does not return any HTTP error codes or messages. In order to validate event one should use `sendDebug($request)` method instead of `send($request)`.

Method `sendDebug($request)` returns `DebugResponse` object, which is hydrated with response data such as: `status_code` and `validation_messages`.

### Example:

[](#example)

```
use Br33f\Ga4\MeasurementProtocol\Service;
use Br33f\Ga4\MeasurementProtocol\Dto\Request\BaseRequest;
use Br33f\Ga4\MeasurementProtocol\Dto\Event\AddToCartEvent;
use Br33f\Ga4\MeasurementProtocol\Dto\Parameter\ItemParameter;

// Create service instance
$ga4Service = new Service('MEASUREMENT_PROTOCOL_API_SECRET', 'MEASUREMENT_ID");

// Create base request with required client_id
$baseRequest = new BaseRequest('CLIENT_ID');

// Create Invalid Event Data
$addToCartEventData = new AddToCartEvent();
$addToCartEventData
    ->setValue(99.99)
    ->setCurrency('SOME_INVALID_CURRENCY_CODE'); // invalid currency code

// addItem
$addToCartEventData->addItem(new ItemParameter([
    'item_id' => 'ITEM_ID',
    'item_name' => 'ITEM_NAME',
    'price' => 99.99,
    'quantity' => 1
]));

// Add event to base request (you can add up to 25 events to single request)
$baseRequest->addEvent($addToCartEventData);

// Instead of sending data to production Measurement Protocol endpoint
// $ga4Service->send($baseRequest);
// Send data to validation endpoint, which responds with status cude and validation messages.
$debugResponse = $ga4Service->sendDebug($baseRequest);

// Now debug response contains status code, and validation messages if request is invalid
var_dump($debugResponse->getStatusCode());
var_dump($debugResponse->getValidationMessages());
```

Unit Testing
------------

[](#unit-testing)

Unit Testing for this module is done using PHPUnit 9.

Running unit tests:

```
composer install
php vendor/bin/phpunit

```

License
-------

[](#license)

This library is released under the MIT License.

###  Health Score

23

—

LowBetter than 26% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% 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 ~367 days

Total

2

Last Release

1457d ago

Major Versions

v0.1.0 → v1.0.02022-06-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/fb2f2b0b36c8316695f5ad788d70a55673fefcb51ae123949e944e8c79f2e53f?d=identicon)[guillaume-var](/maintainers/guillaume-var)

---

Top Contributors

[![br33f](https://avatars.githubusercontent.com/u/14214995?v=4)](https://github.com/br33f "br33f (12 commits)")[![guillaume-var](https://avatars.githubusercontent.com/u/108343531?v=4)](https://github.com/guillaume-var "guillaume-var (3 commits)")[![denisdulici](https://avatars.githubusercontent.com/u/5254835?v=4)](https://github.com/denisdulici "denisdulici (1 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![uncle-roma](https://avatars.githubusercontent.com/u/84439111?v=4)](https://github.com/uncle-roma "uncle-roma (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/guillaumevar-php-ga4-mp/health.svg)

```
[![Health](https://phpackages.com/badges/guillaumevar-php-ga4-mp/health.svg)](https://phpackages.com/packages/guillaumevar-php-ga4-mp)
```

###  Alternatives

[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3661.2M46](/packages/tencentcloud-tencentcloud-sdk-php)[neuron-core/neuron-ai

The PHP Agentic Framework.

2.0k496.1k33](/packages/neuron-core-neuron-ai)[avalara/avataxclient

Client library for Avalara's AvaTax suite of business tax calculation and processing services. Uses the REST v2 API.

528.3M7](/packages/avalara-avataxclient)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

252.5k](/packages/eslazarev-wildberries-sdk)[files.com/files-php-sdk

Files.com PHP SDK

2478.1k](/packages/filescom-files-php-sdk)[aimeos/prisma

A powerful PHP package for integrating media related Large Language Models (LLMs) into your applications

1772.4k4](/packages/aimeos-prisma)

PHPackages © 2026

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