PHP code example of bluepsyduck / ga4-measurement-protocol

1. Go to this page and download the library: Download bluepsyduck/ga4-measurement-protocol 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/ */

    

bluepsyduck / ga4-measurement-protocol example snippets




use BluePsyduck\Ga4MeasurementProtocol\Config;
use BluePsyduck\Ga4MeasurementProtocol\Client;
use BluePsyduck\Ga4MeasurementProtocol\Serializer\Serializer;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory;
use Psr\Http\Client\ClientExceptionInterface;

// Create the ent
$client = new Client(
    $guzzleClient, // Implementation of the PSR-18 ClientInterface 
    $httpFactory,  // Implementation of the PSR-17 RequestFactoryInterface
    $httpFactory,  // Implementation of the PSR-17 StreamFactoryInterface
    $serializer,   // Shipped with the library
    $config,
);

// Send a payload to GA4
try {
    $client->send($payload);
} catch (ClientExceptionInterface $e) {
    // Handle the exception, or ignore it
}


use BluePsyduck\Ga4MeasurementProtocol\Request\Payload;
use BluePsyduck\Ga4MeasurementProtocol\Request\Event\EarnVirtualCurrencyEvent;
use Psr\Http\Client\ClientExceptionInterface;

// Create the first simple event
$event1 = new EarnVirtualCurrencyEvent();
$event1->virtualCurrencyName = 'Gems';
$event1->value = 42;

// Create the second event, containing an item
$item = new Item();
$item->quantity = 4;
$item->itemId = 'I_12345';

$event2 = new AddPaymentInfoEvent();
$event2->value = 13.37;
$event2->currency = 'EUR';
$event2->items[] = $item;

// Create the actual payload
$payload = new Payload();
$payload->clientId = 'foo';
$payload->events = [$event1, $event2];

// Send the payload to GA4
try {
    $client->send($payload);
} catch (ClientExceptionInterface $e) {
    // Handle the exception, or ignore it
}



use BluePsyduck\Ga4MeasurementProtocol\Attribute\Event;
use BluePsyduck\Ga4MeasurementProtocol\Attribute\Parameter;
use BluePsyduck\Ga4MeasurementProtocol\Request\Event\EventInterface;

#[Event('fancy_event')] // Expects the name of the event to be used in the payload to Google Analytics. 
class FancyEvent implements EventInterface
{
    /**
     * A fancy value for the fancy event.
     * @var string|null 
     */
    #[Parameter('fancy_value')] // Expects the name of the parameter to be used in the payload. Please pay attention
                                // to the limitations of parameter names, such as their maximum length.
    public ?string $fancyValue = null;
}

// Create your custom event
$fancyEvent = new FancyEvent();
$fancyEvent->fancyValue = 'fancy';

// Add the event to the payload
$payload->events[] = $fancyEvent;