PHP code example of freema / ga4-measurement-protocol-bundle

1. Go to this page and download the library: Download freema/ga4-measurement-protocol-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

freema / ga4-measurement-protocol-bundle example snippets


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

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();

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

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();
    }
}

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();

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);

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();

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

   $analytics->setClientId('your-client-id');
   

   class MyClientIdHandler implements CustomClientIdHandler
   {
       public function buildClientId(): ?string
       {
           // Your custom logic to get client ID
       }
   }
   

   $analytics->setUserId($user->getId());
   

   class MyUserIdHandler implements CustomUserIdHandler
   {
       public function buildUserId(): ?string
       {
           // Your custom logic to get user ID
       }
   }
   

   $analytics->setSessionId('your-session-id');
   

   class MySessionIdHandler implements CustomSessionIdHandler
   {
       public function buildSessionId(): ?string
       {
           // Your custom logic to get session ID
       }
   }
   

   $analytics->setDebugMode(true);