PHP code example of schenke-io / laravel-ga4-marketing

1. Go to this page and download the library: Download schenke-io/laravel-ga4-marketing 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/ */

    

schenke-io / laravel-ga4-marketing example snippets


return [
    /*
     * Full path to the service account credentials JSON file.
     * This is          * Your Google Analytics 4 Measurement ID (e.g., G-XXXXXXXXXX).
         * Found in GA4 Admin > Data Streams > [Your Stream].
         */
        'measurement_id' => env('GA4_MEASUREMENT_ID', config('services.google.ga4.measurement_id')),

        /*
         * The Measurement Protocol API Secret.
         * Created in GA4 Admin > Data Streams > [Your Stream] > Measurement Protocol API secrets.
         */
        'api_secret' => env('GA4_API_SECRET', config('services.google.ga4.api_secret')),

        /*
         * When enabled, events    /*
             * The maximum number of events allowed per client within
             * the specified decay period.
             */
            'max_attempts' => env('GA4_RATE_LIMIT_MAX_ATTEMPTS', 30),

            /*
             * The time window (in seconds) for rate limiting. After this period,
             * the attempt count for a client is reset.
             */
            'decay_seconds' => env('GA4_RATE_LIMIT_DECAY_SECONDS', 60),
        ],

        /*
         * The duration (in seconds) of inactivity before a new session is started.
         * Defaults to 1800 seconds (30 minutes).
         */
        'session_lifetime' => env('GA4_SESSION_LIFETIME', 1800),

        /*
         * How events are processed: 'api' for immediate sending or 'job' to
         * queue them for background processing.
         */
        'event_handling' => env('GA4_EVENT_HANDLING', 'api'),

        /*
         * When enabled, the client ID is automatically set to a hashed
         * version of the authenticated user's ID.
         */
        'client_from_user_id' => env('GA4_CLIENT_FROM_USER_ID', false),

        /*
         * The name of the cookie used to store the visitor ID.
         */
        'cookie_name' => env('GA4_COOKIE_NAME', 'visitor'),

        /*
         * The lifetime of the visitor cookie in minutes (144000 = 100 days).
         */
        'cookie_lifetime' => env('GA4_COOKIE_LIFETIME', 144000),
    ],

    /*
     * Add additional bot user-agent fragments here to be excluded from tracking.
     * Useful for filtering out custom crawlers or internal monitoring tools.
     */
    'extra_bots' => [
        // 'custom-bot',
    ],
];

Route::middleware(['track-page-view'])->group(function () {
    // your routes
});

Route::middleware(['capture-ad-parameters'])->group(function () {
    // your routes
});

Route::middleware(['track-page-view'])->group(function () {
    // your routes
});

Route::middleware(['track-outbound-link'])->group(function () {
    Route::get('/external-redirect', function () {
        return redirect('https://external-site.com');
    });
});

use SchenkeIo\LaravelGa4Marketing\Services\AnalyticsService;

public function someAction(AnalyticsService $ga4Service)
{
    $clientId = $ga4Service->getClientId();

    $ga4Service->sendEvent($clientId, 'button_click', [
        'button_name' => 'subscribe',
        'location' => 'footer'
    ]);
}

// E-commerce events
$ga4Service->viewItem($items, 'USD', 10.0);
$ga4Service->addToCart($items, 'USD', 10.0);
$ga4Service->beginCheckout($items, 'USD', 10.0, 'COUPON');
$ga4Service->purchase($transactionId, $items, 99.99, 'USD');

// Other recommended events
$ga4Service->login('google');
$ga4Service->signUp('email');
$ga4Service->search('query');
$ga4Service->share('social', 'article', '123');
$ga4Service->scroll(90);
$ga4Service->fileDownload('report.pdf', 'pdf', 'https://example.com/report.pdf');
$ga4Service->calculatorUsed(['type' => 'mortgage']);

'extra_bots' => [
    'custom-bot-fragment',
    // ... add more as needed
],

$this->dispatch('ga4-event', 'button_click', [
    'button_name' => 'subscribe'
]);

$ga4Service->setUserId('user-123');

$response = $ga4Service->setDebugMode(true)
    ->sendEvent($clientId, 'test_event', ['value' => 123]);

if ($response && $response->successful()) {
    $debugInfo = $response->json();
    // inspect validationMessages
}
bash
php artisan vendor:publish --tag="ga4-marketing-config"
bash
php artisan ga4-marketing:verify-ga4