Server-Side Tracking for PrestaShop with GTM and GA4

Standard

Contents:

  1. Introduction to Server-Side Tracking
  2. Required Tools and Setup
  3. Step-by-Step Setup
    • 3.1. Configure GA4
    • 3.2. Set Up GTM Server-Side Container
    • 3.3. Deploy the GTM Server-Side Tagging Server
    • 3.4. Configure PrestaShop to Send Events
    • 3.5. Configure GTM Client and Tags
    • 3.6. Testing and Debugging
  4. Security and Best Practices
  5. Final Thoughts

🔍 Introduction to Server-Side Tracking

Server-side tracking moves data collection from the client (user’s browser) to a secure server environment. Benefits include:

  • Bypassing ad blockers and browser limitations (e.g., Safari ITP).
  • Enhanced data security and control.
  • Improved site performance.

🧰 Required Tools and Setup

Before you start, make sure you have:

  • A PrestaShop site (v1.7+ recommended).
  • A Google Analytics 4 property.
  • A Google Tag Manager (GTM) account.
  • A server environment for GTM server container, either:
  • Basic knowledge of PHP and server configur

🚀 Step-by-Step Setup

3.1. Create and Configure GA4

  1. Go to Google Analytics.
  2. Create a GA4 property.
  3. Set up a Web Data Stream.
  4. Copy the Measurement ID (G-XXXXXXXXXX) for later use.

3.2. Set Up GTM Server-Side Container

  1. In GTM, create a new Server container.
    • Go to GTM Dashboard > Admin > Create Container > Choose “Server”.
  2. Choose a deployment method:
    • App Engine (default and easiest to maintain).
    • Or export the container for manual deployment.
  3. Deploy using Google Cloud:
    • Accept defaults in App Engine setup.
    • Choose a billing account and project.
    • It will provide a server endpoint: https://<your-server>.appspot.com.

3.3. Deploy GTM Server-Side Tagging Server (Alternative: Custom Hosting)
If hosting manually:

Example: Deploying with Docker on VPS

# Clone GTM server image
git clone https://github.com/GoogleCloudPlatform/terraform-google-tag-manager-server.git
cd terraform-google-tag-manager-server

# Configure Docker
docker build -t gtm-server .
docker run -d -p 8080:8080 --name gtm-server gtm-server

Then reverse proxy via Nginx or Apache:

server {
  listen 443 ssl;
  server_name sgtm.example.com;

  location / {
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

Ensure HTTPS with Let’s Encrypt.

3.4. Configure PrestaShop to Send Events to Server GTM

Here’s how to send server-side events from PrestaShop using PHP and cURL.

3.4.1. Create a PHP class for GA4 Event Transmission
Create modules/yourmodule/classes/Ga4ServerEvent.php

class Ga4ServerEvent
{
    private $endpoint = 'https://<your-gtm-server>/collect';
    private $measurementId = 'G-XXXXXXXXXX';
    private $apiSecret = 'YOUR_API_SECRET'; // from GA4 Admin > Data Streams > Measurement Protocol

    public function sendEvent($client_id, $event_name, $params = [])
    {
        $payload = [
            'client_id' => $client_id,
            'events' => [
                [
                    'name' => $event_name,
                    'params' => $params
                ]
            ]
        ];

        $url = "https://www.google-analytics.com/mp/collect?measurement_id={$this->measurementId}&api_secret={$this->apiSecret}";

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }
}

3.4.2. Hook Into PrestaShop Events

In your module’s main file:

public function hookActionOrderStatusPostUpdate($params)
{
    $order = new Order($params['id_order']);
    $customer = new Customer($order->id_customer);
    $client_id = $this->getClientIdFromCookie();

    $eventSender = new Ga4ServerEvent();
    $eventSender->sendEvent($client_id, 'purchase', [
        'currency' => $order->id_currency,
        'value' => $order->total_paid,
        'transaction_id' => $order->reference,
        // Add items array if needed
    ]);
}

private function getClientIdFromCookie()
{
    if (isset($_COOKIE['_ga'])) {
        if (preg_match('/GA\d\.\d\.(\d+\.\d+)/', $_COOKIE['_ga'], $matches)) {
            return $matches[1];
        }
    }
    return uniqid(); // fallback
}

3.5. Configure GTM Server Container

In your Server GTM Container, create a GA4 Client.

  • This processes requests sent from your PrestaShop server.

Add a GA4 Tag to forward data to GA4:

  • Trigger: All requests from the GA4 Client
  • Configure with your GA4 Measurement ID

Optional: Add Filters for Different Events

You can customize by creating triggers for purchase, view_item, etc., and send event data accordingly.

3.6. Test and Debug

  1. Enable Preview Mode in GTM Server container.
  2. Test events by completing a purchase or viewing a product.
  3. Use GA4 DebugView (available in GA4 Admin) to verify events.
  4. Check real-time data in your GA4 dashboard.

4.🛡️ Security and Best Practices

Restrict Public Access: Use CORS policies or header whitelisting to prevent abuse of your server endpoint.

Log Events: Log requests and responses for troubleshooting.

Use HTTPS: Always encrypt your data in transit.

Set up custom domain: e.g., track.yourdomain.com to improve trust and bypass blockers.

5. 📘 Final Thoughts

Server-side tracking with PrestaShop and GA4 ensures data accuracy and long-term resilience. While setup is more complex, the benefits in terms of data integrity, user privacy, and tracking continuity far outweigh the initial configuration overhead.

Leave a Reply

Your email address will not be published. Required fields are marked *