> This is part 1 of 2 of the full documentation (pages 1–100 of 167).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.adpage.io/llms-full.txt/1
> Page index: https://docs.adpage.io/llms.txt

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.adpage.io/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# All you need for the best data insights

Everything you need to build, deploy, and manage your data collection for the best insights.

***

### Where to start

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><i class="fa-rocket-launch" style="color:$primary;">:rocket-launch:</i></td><td><strong>Getting started</strong></td><td>Set up your AdPage container, connect GTM, and get your tagging pixel and Data Assistant running in minutes.</td><td><a href="/getting-started/setup-adpage-container">Getting Started</a></td></tr><tr><td><i class="fa-puzzle-piece" style="color:$primary;">:puzzle-piece:</i></td><td><strong>Optimize your setup</strong></td><td>Step-by-step tracking setup guides for Shopify, WooCommerce, WordPress, Magento, Lightspeed, and custom platforms.</td><td><a href="/optimize-your-setup/consent-management">Optimize your setup</a></td></tr><tr><td><i class="fa-book-open" style="color:$primary;">:book-open:</i></td><td><strong>Integrations websites</strong></td><td>API reference, configuration options, and a glossary of terms used across the platform.</td><td><a href="/integrations-websites/shopify">Integrations websites</a></td></tr><tr><td><i class="fa-bullhorn" style="color:$primary;">:bullhorn:</i></td><td><strong>Integrations marketingtools</strong></td><td>Connect your marketing platforms like Google Ads, Meta, and TikTok for full-funnel reporting.</td><td><a href="/integrations-marketingtools/meta-ads">Integrations marketingtools</a></td></tr><tr><td><i class="fa-bug" style="color:$primary;">:bug:</i></td><td><strong>Debugging and monitoring</strong></td><td>Troubleshoot tracking issues and monitor your container's health with real-time alerts.</td><td><a href="broken://pages/rVS25xMLel7VVKYFVvrU">Broken link</a></td></tr><tr><td><i class="fa-user-gear" style="color:$primary;">:user-gear:</i></td><td><strong>Account management</strong></td><td>Manage invoices, billing details, and team access for your account.</td><td><a href="broken://pages/7nERTCIjwxRhrmcXy1FX">Broken link</a></td></tr></tbody></table>


# Setup AdPage container

Go from sign-up to your first deploy in under five minutes.

This quickstart is about getting you to your first deploy fast. We're going to skip most of the setup for now, since you can always go back and tweak things once you've got something up and running.

{% hint style="success" %}
**Estimated time: 5 minutes.** All you need is access to a Google Tag Manager account, your site's DNS settings and the website's backend.
{% endhint %}

## Create your AdPage Container

{% stepper %}
{% step %}

### Register and create your account

Go to [AdPage](https://data.adpage.io/) and register or log in. Follow the steps to set up your account and fill in the info it asks for. You'll need to pick whether you're a client or an agency. The difference comes down to who you're setting up containers for. Go with **client** if it's for your own website or websites, and **agency** if you're setting them up for your clients.
{% endstep %}

{% step %}

### Create a container

Start by adding your first client, or just add a container right away. If you add a client's company first, you can then add a container under that company.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FEHPdixyIQFruy4pPdfEr%2Faccount-containers-eigen-volledig-en.webp?alt=media" alt="Containers overview in AdPage with the Add container button"><figcaption><p>The Containers page: add a container or open an existing one.</p></figcaption></figure>
{% endstep %}
{% endstepper %}

## Server container configuration

To get your AdPage server container going, you'll need to hook it up to a Google Tag Manager server container. After that, connect it to the root domain using CNAME cloaking. The last step is swapping out the standard Google Tag Manager script on the website for a Tagging Pixel.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FUUzOEKx1pn8M46GCdn4u%2Fsetup-wizard-step1-server-container-en.webp?alt=media" alt="Set up your container wizard at step 1 of 3, Server container"><figcaption><p>The setup wizard takes you through the server container, domain and pixel.</p></figcaption></figure>

{% stepper %}
{% step %}

### Connect your AdPage container with your Google Tag Manager server container

You can connect your AdPage server container to a Google Tag Manager server container with Google's base64 configuration code. That way you can set up your tracking rules on the Google Tag Manager server container.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F8IJgy9hY1eqZCGjHdITL%2Fcontainer-instellingen-servercontainer-detail-en.webp?alt=media" alt="Server container (sGTM) section in the container settings"><figcaption><p>Paste the provisioning code of your Google Tag Manager server container.</p></figcaption></figure>

<details>

<summary>Manually retreive the base64 configuration code</summary>

If you'd rather set up the Google Tag Manager server container connection by hand, you'll need to grab the base64 code yourself.\
\
Go to [Google Tag Manager](https://tagmanager.google.com/) and open your server container, or make a new one if you don't have one yet.\
\
You'll find the configuration code in the **Container settings** inside the server container admin. It shows up once you click the **"Set up your tagging server"** button.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FuTr0ldchhskPWoXDEPi7%2Fimage.png?alt=media&amp;token=47de3d9c-2fae-49df-8dde-666c2a022fb6" alt=""><figcaption></figcaption></figure>

</details>
{% endstep %}

{% step %}

### Configure DNS records

To use AdPage server-side tagging, you'll need to set up a custom domain. This is also called a custom tagging server URL, and it's what lets you set first-party cookies and use the AdPage Tagging Pixel. Make sure the URL uses the same root domain as your website.

Log in to wherever you manage your domain and create a new DNS record for the subdomain you want to use. It's a CNAME record, and you'll find the Host and Target values in the registration instructions.

{% hint style="info" %}
You can edit the Host of this CNAME record in your AdPage container settings. The Target is always `projects.trytagging.com`
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FomE863k9LjhhjH5lqdkY%2Fcontainer-instellingen-domeinen-detail-en.webp?alt=media" alt="Domains and SSL section with DNS and SSL status"><figcaption><p>Domains and SSL: your subdomain with its DNS and SSL status.</p></figcaption></figure>
{% endstep %}

{% step %}

### Tagging Pixel

Step 3 of the container registration is to replace the Google Tag Manager script on the website with an AdPage Tagging Pixel. This Tagging Pixel has the same functionality as a Google Tag Manager script, it sets up the connection between the website and your Google Tag Manager web container.

{% hint style="info" %}
The Tagging Pixel replaces the regular Google Tag Manager script in the site code. When adding the Tagging Pixel, make sure to delete the regular Google Tag Manager script.
{% endhint %}

Add your **Website URL**, add the **Google Tag Manager Web Container ID**. These two inputs are needed to generate the Tagging Pixel script and set up the Tagging Pixel verification.

Once you've added those two, you can generate the Tagging Pixel instructions. You'll get different instructions depending on which Content Management System (CMS) you use. AdPage has an App for Shopify, a Plugin for Wordpress and WooCommerce, a Module for Magento, and its own set of instructions for Lightspeed, which also add an e-commerce dataLayer to the front end of the website. If all you need is the Tagging Pixel script, pick the custom CMS option to get the code for the `<head>` and `<body>`.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FCanPj0PTX5oJhn8KUKjr%2Fcontainer-instellingen-taggingpixel-detail-en.webp?alt=media" alt="Tagging pixel section with platform choice and installation code"><figcaption><p>Choose your platform and copy the Tagging Pixel installation code.</p></figcaption></figure>

{% hint style="info" %}
If you don't have access to the website's backend, you can also copy and share these instuctions by using the **Copy the installation link** at the top of these instructions.
{% endhint %}
{% endstep %}

{% step %}

### Finalizing the configuration

Once you've finished those three steps, you can go into the server container's dashboard. Your AdPage server container is ready to use. From here you can move on to setting up the tracking rules in your Google Tag Manager web and server containers.

{% hint style="info" %}
You can skip Step 2 and Step 3 during registration if you want. Both are things you can set up later from your server container's dashboard.
{% endhint %}
{% endstep %}
{% endstepper %}

## What's next?

Once you've added your first client or container, you can move on to setting up the tracking rules in your Google Tag Manager web and server containers. The next step goes over what you need to set up in your Google Tag Manager server container.

If you are setting up server-side tagging for a Shopify, WooCommerce, Magento or Lightspeed webshop. You can skip ahead to these steps: [Using AdPage Templates](/getting-started/using-adpage-templates).


# Setup GTM server container

Go from sign-up to your first deploy in under five minutes.

## GA4 configuration

Let's start with the GA4 configuration. Your AdPage server container is going to receive GA4-formatted requests sent from the client, so we'll set up a Google Analytics 4 client and tag to handle those incoming requests. These Google Tag Manager server container settings will ensure that the incoming GA4 requests get sent on to your Google Analytics 4 property as GA4 events.

{% stepper %}
{% step %}

### GA4 Client

To begin with, let’s focus on the Client part of the Google Tag Manager server container. A Client on a Google Tag Manager server container is responsible for receiving incoming data on the server. The GA4 Client enables the server to receive and understand data in GA4 format.

By default, a GA4 Client should already exist on your server container. If you go to the **Clients** section, you should find this client. There are no changes needed to this Client for a regular server-side tagging setup.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FiF8bf8cvXqCmCT7TYGyk%2Fimage.png?alt=media&amp;token=c189e564-5c76-4c7e-959e-814e0308a8fb" alt=""><figcaption></figcaption></figure>

<details>

<summary>Edit the GA4 Client</summary>

By default the GA4 client uses the JavaScript managed client ID, which means it reads the `_ga` cookie that the Google tag sets in the browser. That works fine for a standard server-side setup, so you can leave this section alone.

If you'd rather let the server handle identification, set Client ID source to Server Managed. The server container then writes its own first-party cookie called `FPID` in the HTTP response, with the HttpOnly flag, so browser JavaScript can't read it. Since it isn't set by JavaScript, it keeps its full lifespan, because Safari's ITP only shortens cookies that JavaScript sets. That's the main reason to switch. Returning visitors stay recognisable for longer, and your user and attribution data holds up better.

If you make this change on a property that already gets traffic, also check Migrate from JavaScript Managed Client ID. Visitors who already have a `_ga` cookie will keep their current ID, and `FPID` only takes over once that cookie is gone. Without it, all your existing visitors get a new ID at the same time, which shows up in GA4 as a spike in new users. On a brand new property there's nothing to migrate, so you don't need the option.

Two things worth checking before you switch. First, the client ID that GA4 receives comes from the `FPID` value, so it no longer matches the `_ga` value that client-side scripts can read. If other tools or integrations rely on that value, test them first. Second, with Server Managed turned on, the FPID cookie gets generated on every request the client claims, no matter what the consent state is, unless you blank out the cookie name conditionally.

</details>
{% endstep %}

{% step %}

### GA4 Tag configuration

Now that the GA4 client is configured, the server can receive and process GA4 web tracking requests. Now we need to a create a Tag to dispatch these requests to the correct GA4 property.

Go to the **Tags** tab of your server container and create a new tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F28xP5GbQutC86XZZBmG2%2Fimage.png?alt=media&amp;token=bfb7b7e7-8d78-482d-9e48-1058426f3f77" alt=""><figcaption></figcaption></figure>

Select **Google Analytics: GA4** as the tag configuration.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FxyAAxut7ciLlqmmtjrbW%2Fimage.png?alt=media&amp;token=78f698e3-526c-47e2-909a-afbde1075c0b" alt=""><figcaption></figcaption></figure>

In this GA4 tag, several configurations are possible. Here are the 2 most commonly used fields:

**Measurement ID**\
This measurement ID decides which GA4 property your data goes to. If you fill it in, everything gets sent to that property. If you leave it empty, it uses whichever measurement ID your web container sends along.

**Event name**\
This field lets you force the tag to send one specific event name to GA4. Leave it empty and the event names coming in from your web container get passed along as they are.
{% endstep %}

{% step %}

### GA4 trigger configuration

To forward all GA4 events arriving on your server to your GA4 property, configure the tag to trigger when the `Client Name` equals `GA4`.

If **Client Name** doesn’t appear in the dropdown for the trigger condition, enable it by clicking on **Choose Built-in variable**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Ft0VSqIaf3mNegHNklYfr%2Fimage.png?alt=media&amp;token=663bbe17-7c6e-424b-bfa6-1ef7a3320ce5" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

Preview url configuration

To be able to use the preview mode in your Google Tag Manager server container, you have to input the server which tracking subdomain you're using. Without this step you won't be able to launch the preview on the server side.

Go to the **Admin** section of your Google Tag Manager server container and open **Container settings**. On that page, add the tracking subdomain you set up earlier in the **Server container URLs** input field.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fza21RSIbeMXuH6VZXnaC%2Fimage.png?alt=media&amp;token=c8781749-26ec-49c6-a190-dc10dc1da7b5" alt=""><figcaption></figcaption></figure>

## What's next?

You've just set up your first server-side tagging setup for Google Analytics 4. With your GA4 Client and Tag configured, head on to the next step, where you'll set up the Google Tag Manager web container so it can send GA4 requests to your server container based on website-interactions.


# Setup GTM web container

Go from sign-up to your first deploy in under five minutes.

## GA4 configuration

In your Google Tag Manager web container, you'll set up GA4 event tags based on site-interactions. These tags turn those interactions into events and send them to your server container URL. Once GA4 tracking is set up properly on the client side, sending those events out to the different platforms from the server becomes pretty simple.

{% stepper %}
{% step %}

### Overwrite the GA4 endpoint in the Google Tag

If you use server-side tagging, your GA4 hits should be sent to your own tracking domain instead of directly to Google. The easiest way to do this is in one place: the Google Tag.&#x20;

The Google tag (`gtag.js` outside of Google Tag Manager) is not a tag that measures something by itself. It loads the Google measurement library and sets up the shared configuration that all your GA4 hits use.

A GA4 Event tag contains almost nothing on its own. It adds the event name and its event parameters, and inherits everything else from the Google tag that carries the same Measurement ID. That is exactly why the endpoint override belongs on the Google tag: set it once, and every event tag follows.

Open the Google Tag in the Google Tag Manager web container used for the GA4 configuration. Ensure that the following three parameters are added:

* server\_container\_url = your AdPage server container URL
* send\_page\_view = false
* first\_party\_collection = true

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FgwZVhk3GEr90cGwMqpzo%2Fimage.png?alt=media&amp;token=876d52dd-e733-458e-91ab-4931cd6a5f6b" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### GA4 page\_view event tag

Because we've just set the 'send\_page\_view' configuration parameter to false in the Google Tag, we will need a separate GA4 event tag.&#x20;

{% hint style="info" %}
You set the `send_page_view` parameter to `false` in the Google tag. The reason is that the `page_view` event would otherwise be created automatically the moment the Google tag fires. If that happens, you cannot add any extra parameters to that `page_view` event. The `event_id` parameter in particular matters a great deal, because the tracking setup of marketing platforms relies on it for deduplication.
{% endhint %}

Go to **Tags** and create new tag. Select **Google Analytics: GA4 Event** as the tag configuration. In the **Measurement ID** input field you fill in your GA4 property's Measurement ID, and in the **Event Name** field you fill in 'page\_view'.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0xnNJd76US1NfvQ6U0jM%2Fimage.png?alt=media&amp;token=3e2da1fe-239e-4d79-a838-75b83b2c7a4b" alt=""><figcaption></figcaption></figure>

Give this tag the correct **Trigger**. If you are using a Consent Management Platform with a dataLayer event push on every page, you set up the trigger based on that dataLayer event. Otherwise choose the **All Pages** trigger.
{% endstep %}
{% endstepper %}

Every other GA4 event tag in your web container that uses the same Measurement ID picks up its configuration from the Google tag. From this point on, all of them get sent to your `server_container_url` instead of straight to Google Analytics. That includes purchases, form submissions, custom events, and everything else you built earlier. This is exactly what's supposed to happen, but it does mean your whole GA4 measurement now runs through the server container.

So test it before you publish. Open preview mode in your web container, click through the pages and interactions that fire your GA4 event tags, and check that each request goes to your tracking domain. Keep the preview of your server container open next to it so you can confirm the events show up there, get claimed by the GA4 Client, and go out to GA4 with the parameters you expect. Don't publish until you've seen every important event make it through from start to finish.

## What's next?

You’ve finished configuring the Google Tag Manager web container to send GA4 event requests towards your server container. Before you start testing the configuration so far and setting up your marketing platform tracking, let's first set up the Data Assistent Tag for events monitoring so that you can monitor what’s happening on the website's dataLayer.


# Tagging Pixel verification

Why the check can report a missing pixel that is actually there, and the two things that fix it.

Once the Tagging Pixel is installed, AdPage checks whether it really loads on your website. This page explains what that check does, and what to do when it reports a missing pixel that you know is there.

## How the check works

The check opens your shop page in a real Chromium browser from Amsterdam, waits for the page to finish loading, and looks for two things: scripts loading from your tagging domain, and the hits those scripts send.

{% hint style="info" %}
Loading the page in a real browser matters. A check that only reads the page source cannot see a script that is added while the page loads, and would report a working pixel as missing.
{% endhint %}

The check runs when you press **Verify pixel** in your container settings, and once a day on its own.

## When the check reports a missing pixel

Two causes are common, and neither of them means something is wrong with your pixel.

### 1. No website URL for this domain

The check needs to know which page to open. If the **Website URL** is empty for this tagging domain, AdPage derives it from the tagging domain itself: `tagging.example.com` becomes `example.com`.

That guess is right for most shops, but not all. If your shop lives somewhere else, the check opens the wrong page, finds nothing, and says so. You will recognise this case by the wording: the result mentions that the URL was derived.

Fill in the website in **Settings → Tagging Pixel** and verify again.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FCanPj0PTX5oJhn8KUKjr%2Fcontainer-instellingen-taggingpixel-detail-en.webp?alt=media" alt="Tagging Pixel section in the container settings with website field and verification status"><figcaption><p>Fill in your website and verify the Tagging Pixel again.</p></figcaption></figure>

{% hint style="info" %}
A container can have several tagging domains, and each one has its own Website URL. Filling it in for one domain does nothing for the others — check each domain you use.
{% endhint %}

### 2. Your firewall or bot protection blocks the check

A firewall, WAF or bot protection in front of your shop can refuse visitors it does not recognise. Our check is then turned away before it ever sees your page, and the result looks the same as a missing pixel.

The fix is to allow our check through. Your container dashboard shows the IP addresses it comes from, with a button to copy them.

{% hint style="warning" %}
Copy the addresses from your dashboard, not from this page. The list is kept up to date automatically, and the dashboard always shows the current one. If verification starts failing again later, open the dashboard and compare the list.
{% endhint %}

{% stepper %}
{% step %}

### Open your container dashboard

The list appears under **Automatic verification still pending**, or under the pixel status when a check has failed.
{% endstep %}

{% step %}

### Copy the addresses

Use **Copy list** to put all of them on your clipboard at once.
{% endstep %}

{% step %}

### Allow them through

Send the list to whoever manages your hosting, firewall or bot protection, and ask them to allow these addresses. In Cloudflare this is a WAF rule; in other setups it may be an IP allowlist or an exception for a security rule.
{% endstep %}

{% step %}

### Verify again

Press **Verify pixel** in your container settings. The check should now reach your page.
{% endstep %}
{% endstepper %}

## Confirming the pixel manually

If you cannot change the firewall, you can confirm the pixel yourself with **Confirm manually**. Your container then stops warning about an unfinished setup.

Be clear about what this does and does not do:

* It records that **you** checked the pixel. It does not verify anything on our side.
* AdPage keeps checking in the background. As soon as a check sees your pixel load, your manual confirmation is replaced by a real verification.
* It does not make tracking work. If the pixel genuinely is not installed, confirming it manually only hides the warning — you will still see no data coming in.

{% hint style="info" %}
To check the pixel yourself, open your website, press F12 to open the developer tools, go to the **Network** tab and filter on your tagging domain. Reload the page. If you see requests to that domain, the pixel is loading.
{% endhint %}

## What's next?

With the pixel verified, your container is collecting data. From here you can move on to the tracking rules in your Google Tag Manager containers, or check the data quality of your setup under **Monitoring**.


# Setup Data Assistent

The AdPage Data Assistent tag can be configured to provide additional insights into the quality of the setup as ongoing activity

The AdPage Data Assistant tag monitors everything that happens in the dataLayer of your website. These dataLayer events will get temporarily saved so our in-software Data Assistent chatbot can help you find and fix issues quickly.

{% hint style="warning" %}
Make sure trytagging\_user data is in the datalayer. You can check this via \
\
![](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FANHa17pyA88xZciVFtf7%2Fimage.png?alt=media\&token=b5b0c748-a4e8-449a-b4d6-5d8defe11fbd)
{% endhint %}

## Setup steps

{% stepper %}
{% step %}

### Add the tag template to your workspace

Open your Google Tag Manager web container. Go to **Tags** and create a new tag. As the **Tag Configuration**, select **Discover more tag types in the Community Template Gallery**. In the template gallery look for the AdPage Data Assistant configuration. Add this tag configuration to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FiJVirynleP6wdqXzUVnw%2Fimage.png?alt=media&amp;token=978bdc18-a385-4af8-8b7b-a366b4fbca92" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Configure the tag

In the **Tagging URL** input field, enter your server container URL. Expand **Advanced Settings**, then **Consent Settings**. Enable **Require additional consent for tag to fire**. Enter `analytics_storage` as the required consent. For example "[https://tagging.domain.nl](https://tagging.martvisser.nl)"

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FHqvscCxInn5BfIX6AbOX%2Fimage.png?alt=media&amp;token=02d7ec1b-d1a9-41f5-904e-6a5fe5d8a55f" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Add the trigger

Add a **Trigger** to your Data Assistant tag. Open **Triggering** and select the blue plus icon to create a new trigger. Select **Custom Event** as the trigger type. Enter `.*` as the event name. Enable **Use regex matching**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FvKBV5iUiR7nHWPtbqCBe%2Fimage.png?alt=media&amp;token=b393486a-9424-4d75-8dcd-ba3a324b314c" alt=""><figcaption></figcaption></figure>

Save the trigger, then save the tag.
{% endstep %}
{% endstepper %}

## What's next?

Events Monitoring is now active for your server-side tracking. Continue with the Tagging pixel setup to track funnel interactions.


# Using the GTM Preview Mode

How to use the Google Tag Manager preview mode in the web and server container to debug and test

Google Tag Manager's Preview Mode is a valuable tool that helps you test tags and triggers before you publish your changes. But it is also needed to debug your trackings setup. Let's take a look at when and how to use it.

### What is GTM's preview mode?

Preview mode (also called preview and debug mode) in Google Tag Manager is a built-in feature that lets you test tags, triggers and variables in real time on your website or in your server container. You use this mode before you publish your changes, but also to debug in a test environment, so real visitors don't notice anything.

In a server-side tagging setup you work with two containers in Google Tag Manager: a web container and a server container. Both containers have their own preview mode, and each one works slightly differently. In this article we explain when and how to use the preview mode of the GTM web container, and when and how to use the preview mode of the GTM server container.

Let's start with the web container.

{% stepper %}
{% step %}

#### Web container preview mode

There are three key moments where you use preview mode in the Google Tag Manager web container:

* After setting up new tags and triggers.
* To check whether your existing tags and triggers still fire correctly.
* After making changes to your website.

#### 1. Creating new tags and triggers

After setting up new tags and triggers, it's essential to use preview mode before you publish your container. To test them, click 'Preview' in the top right of the container you're working in. In the popup of the preview window, enter the URL of the website that is connected to this container. Your site now opens in a new tab in a test environment.

Say you've set up a tag and trigger for a specific button on a certain page of your site. In the test environment, navigate to that page and perform the action, for example clicking the button. In the preview tab you can then see which tags fired and which didn't. You can also review this per page and per site-interaction in the vertical menu on the left.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FEz4x8RVzjTaRGzwqhmKV%2Fimage.png?alt=media&amp;token=918a6c28-9641-4dc6-9bdb-2de688ea2d7f" alt=""><figcaption></figcaption></figure>

#### 2. Check whether your existing tags and triggers still fire

If you notice that certain events aren't coming in, or aren't coming in correctly, in platforms such as Meta Ads or Google Analytics, the first thing to check is whether the tags and triggers in Google Tag Manager still fire correctly.&#x20;

Start by performing the action that should make the tag fire. Select that session event in the vertical menu on the left. In the list of tags that didn't fire (Tags not fired), select the tag that should have fired. Under **Firing Triggers** you'll then see an overview explaining why that tag didn't fire.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0XmHsriTwHsbKESyMHgO%2Fimage.png?alt=media&amp;token=44b61a90-c8ab-4e3d-8d15-29b21d94093c" alt=""><figcaption></figcaption></figure>

#### 3. Changes made to your site

When you make changes to your site, such as changing URLs, updating button and link texts, or adjusting the checkout flow, it's important to make sure those changes don't break your measurement. If you open your site in the preview mode, you can walk through all of your changes and perform the relevant events. Preview mode lets you keep track of which tags do and don't fire.

#### Troubleshooting tags that didn't fire

If tags didn't fire that should have, click the event where you expected the tag to fire in the vertical menu on the left. Select the event, then click the tag that didn't fire to see what's wrong with the trigger. Inside that tag you can find out why the trigger didn't work in the **Firing Triggers** section, and make changes based on that information.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FcFdFswuFLkMBIqpKdidE%2Fimage.png?alt=media&amp;token=782fe899-0680-4740-862e-bbd755713226" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Server container preview mode

There are two key moments where you use preview mode in the Google Tag Manager server container:

* When you create new server-side tags and triggers.
* When you make changes to your server-side tagging setup, or when the incoming requests from your web container change.

#### 1. Testing new tags and triggers

Preview mode in the server container works differently from the web container, because it waits for incoming events from your website instead of you clicking through your site directly. When you open preview mode, your website doesn't open automatically. You'll only see an overview of incoming requests in the preview mode interface once you start sending events to the server container URL when you have opened the website within the same browser.

So a requirement for using the GTM server container preview mode is that you've made the necessary Google tag configuration settings in your GTM web container.

In the overview on the left you'll see the incoming requests in chronological order, where the GA4 client turns them into a readable event. In the overview on the right you can see the tags that are triggered when the event arrives.&#x20;

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FxjSBxLOJINc8Lg2NdNrF%2Fimage%20(50).png?alt=media&amp;token=032271a4-328d-4e73-bbb5-dfc9b1d1bab2" alt=""><figcaption></figcaption></figure>

#### 2. Testing changes to your web container

When you make changes in the GTM web container and want to know whether this affects your GTM server container tags, you can check this in preview mode as well. When an event comes in, you expect specific tags to be triggered or you want specific parameters to be sent towards your marketing platforms. If that doesn't happen, you know something is wrongly set up in the GTM web container or in the server container.

If you make changes to the parameters of an event tag, you can easily review them in the Event Data tab of the incoming request. The Event Data tab shows you which client processed the incoming request and which event data you can work with in your server tags, triggers and variables.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fw8TdQJC33TSFl5WEye3v%2Fimage.png?alt=media&amp;token=ece15494-4472-4094-b104-f0816e8e098e" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

***

### No requests coming into your GTM server container preview mode?

If you are testing your server-side tagging setup and no event requests show up in the server container preview mode? Don't worry. We'll explain the most common causes step by step so you can get back to testing quickly.

{% stepper %}
{% step %}

#### Check the basics

Before you dig deeper, confirm that your server container is live and responding.

* **Health check:** open a new tab, go to your server container URL and add `/healthy` to it. You should see `ok`.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FiMw3coNsBq74Hwx1CszA%2Fimage.png?alt=media&amp;token=7b89344d-2329-44c5-b62b-56be4d71d0ce" alt=""><figcaption></figcaption></figure>

* **Test endpoint:** open a new tab, go to your server container URL and add `/test`. A `400` error is expected and fine. What matters is that you see this request arrive in your preview mode. If it does, your container and preview session are working.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F4h6bqxNc8OzLLSJd4v39%2Fimage.png?alt=media&amp;token=3eebbdfe-975e-4848-9a19-c9c95c21cdc1" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Verify the server container URL

Using the wrong server container URL in your Google tag is one of the most common causes. Make sure the server container URL in your Google tag configuration (in your GTM web container) matches exactly the URL where you are running the sGTM preview. Double-check for typos, a missing subdomain, or `http` instead of `https`.
{% endstep %}

{% step %}

#### Check whether your Google tag configuration is being overwritten

Another frequent cause is a second source on the website overwriting your Google tag configuration, usually a hardcoded gtag.js script.

**How to check:**

1. Open the **Network** tab in your browser developer tools.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FZRB3XReVlPcd6gXnqM01%2Fimage.png?alt=media&amp;token=45bde7f2-d593-4b55-aba8-001903fd462c" alt=""><figcaption></figcaption></figure>

2. Enable **Preserve log** so events are kept when the page changes.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fvcu613SHxIVCAZlizATz%2Fimage.png?alt=media&amp;token=6a828b0b-9d2d-43e4-9af8-39221262de5e" alt=""><figcaption></figcaption></figure>

3. Filter on your GA4 measurement ID.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FxIlpGqfi9nDHtXZ6W7Ej%2Fimage.png?alt=media&amp;token=23da506b-4ae2-4225-b117-48b59bf55d68" alt=""><figcaption></figcaption></figure>

4. Look at where the requests are going. If they go to `googletagmanager.com` or `region1.google-analytics.com` instead of your server container URL, your Google tag configuration in the GTM web container is being overwritten by a gtag.js script on the website.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FFibfEEsWJhoMHjPzq7kv%2Fimage.png?alt=media&amp;token=3965d0eb-7005-4069-aa39-7561993360ee" alt=""><figcaption></figcaption></figure>

**Possible causes:**

* A gtag.js script in the website source.
* Multiple Google tags using the same measurement ID.
* The standard Google Tag Manager script running alongside the tagging pixel script.
  {% endstep %}

{% step %}

#### Still nothing?

A few less obvious things worth checking:

* **Same browser, same session.** Preview mode only captures traffic from the browser session that was started from the preview window. Opening the site in another browser, another profile, or in incognito breaks that link. Use the preview window itself, or the "Send requests to..." tab it opens.
* **Ad blockers and privacy extensions.** These can block requests before they ever leave the browser. Test with extensions disabled or in a clean profile.
* **Consent state.** With Consent Mode active, tags may be waiting for consent and simply never fire. Accept consent on the page and check again.
* **Web container preview.** Check whether the tag fires at all in the web container preview. If the tag doesn't fire there, the problem is in the web container, not on the server side.
  {% endstep %}
  {% endstepper %}


# Using AdPage Templates

Import ready-made web and server container templates

To get the right tags, triggers and variables into your Google Tag Manager containers, we've built ready-made templates for both the web and the server container. These templates cover the following webshop platforms: WooCommerce, Shopify, Magento and Lightspeed.

You can find them in the template library on our platform: <https://data.adpage.io/template-library>

{% hint style="info" %}
Do not use these templates for websites or webshops that don't run on Shopify, WooCommerce, Magento or Lightspeed.
{% endhint %}

### Before you start: the AdPage e-commerce dataLayer

For webshops on WooCommerce, Shopify, Magento or Lightspeed, you install the Tagging Pixel to replace the Google Tag Manager script, and along with it you install the AdPage e-commerce dataLayer.

These dataLayer events use a `trytagging_` prefix. That prefix exists so our events never collide with events that are already being pushed by your theme, another plugin or an existing GTM setup. No duplicate events, no double conversions.

Our templates are built entirely on these `trytagging_` events. So the templates only work if the Tagging Pixel and the e-commerce dataLayer have been installed correctly first. If you haven't done that yet, follow the Tagging Pixel instructions for your platform before importing anything.

### Generating the templates

In the template library you'll find two things:

**Individual templates.**\
Web and server container templates per marketing platform, so you can pick exactly what you need.

**The container template generator.**\
Here you select the marketing platforms you want to set up and the Consent Management Platform you're using. The generator then builds complete, ready-to-import container templates for both your GTM web container and your GTM server container, already wired up for your consent setup.

Either way, you end up with JSON files: one for the web container, one for the server container.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FICnzw0tJsO0nsXbEsKQX%2Ftemplate-library-per-platform-en.webp?alt=media" alt="Template library in AdPage with GTM templates per platform"><figcaption><p>The template library: download templates per platform or for the whole container.</p></figcaption></figure>

## Importing the web container template

{% stepper %}
{% step %}

### GTM web container

1. Go to **Admin** and click **Import Container**.
2. Click **Choose container file** and upload the JSON file for your web container.
3. Choose your **existing workspace**.
4. Select **Merge** and then **Rename conflicting tags, triggers and variables**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FANcP3sboOjc0JILIvZ3e%2Fimage.png?alt=media&amp;token=b9df38ea-76a0-4236-b64f-802167f4bdef" alt=""><figcaption></figcaption></figure>

5. Go to **Variables** and edit every user-defined variable whose name starts with `@`. These are the constants that hold your the IDs for your platforms, and the `@` is there so you can spot them at a glance. Nothing works until they're filled in.
6. Check for a duplicate Google Tag. If you already had a Google Tag for the GA4 Measurement ID you're now configuring, delete or pause it. Your web container should only ever contain one Google Tag per endpoint (one per Google Ads ID, one per GA4 ID).
7. Pause or remove overlapping tags. You're now generating GA4 events based on the AdPage dataLayer, so any older tags function on the former e-commerce dataLayer need to be paused or removed.
   {% endstep %}

{% step %}

### GTM server container

1. Go to **Admin** and click **Import Container**.
2. Click **Choose container file** and upload the JSON file for your web container.
3. Choose your **existing workspace**.
4. Select **Merge** and then **Rename conflicting tags, triggers and variables**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Ft1Ibnp88tTxO36oiDE86%2Fimage.png?alt=media&amp;token=05d5db20-4542-433e-883d-598098e0417b" alt=""><figcaption></figcaption></figure>

5. Go to **Clients** and check whether an extra GA4 client has been added. If it has, delete the new imported GA4 client.
6. Go to **Variables** and edit every user-defined variable whose name starts with `@`. These are the constants that hold your the IDs, Labels and Tokens for your platforms, and the `@` is there so you can spot them at a glance. Nothing works until they're filled in.
   {% endstep %}
   {% endstepper %}

These templates are the starting point of your tracking setup, not the finished product. If you publish your GTM containers straight after importing the JSON files, you will run into problems: unfilled variables, duplicate tags and events firing twice.

{% hint style="info" %}
Never ever publish a Google Tag Manager container after importing a template without validating using the Google Tag Manager preview mode.
{% endhint %}


# Consent Management

Consent management isn't technically part of your server-side tagging setup, but it affects it a lot. But your tracking setup and your consent management are tied together whether you like it or not. Since the GDPR rulings, every website and webshop needs a Consent Management Platform that correctly handles visitors' choice in your cookiebanner. Your tracking setup then has to respect those choices. Besides GDPR, Google has its own requirements. If you want to keep using their advertising and measurement products in Europe, you need to send the right consent signals for Consent Mode v2.

### What is Consent Mode v2?

Consent Mode v2 is Google's framework for adjusting tag behavior based on a visitor's cookie choices, without you having to fully block every Google tag by hand. Instead of an all-or-nothing switch, your CMP passes four consent signals into the Google tag:

| Signal               | Controls                                                         |
| -------------------- | ---------------------------------------------------------------- |
| `analytics_storage`  | Whether measurement data (e.g. GA4) can be stored                |
| `ad_storage`         | Whether advertising cookies/identifiers can be stored            |
| `ad_user_data`       | Whether user data can be sent to Google for advertising purposes |
| `ad_personalization` | Whether the visitor can be used for personalized/remarketing ads |

{% hint style="info" %}
Consent Mode v2 only governs **Google's own tags** (Google Tag, GA4, Google Ads, Floodlight). Every other platform (Meta, Pinterest, LinkedIn, TikTok, etc.) needs to be gated separately, which is covered in step 2 below.
{% endhint %}

**Basic vs. Advanced mode**

* **Basic mode** \
  If a visitor denies consent, the relevant Google tags simply don't fire at all. No data reaches Google for that category. This requires you to add blocking triggers on the server so the tag can't fire without consent.
* **Advanced mode** \
  Google's tags fire either way, no matter the visitor's choice in your cookiebanner. The difference is what data actually goes out the door. If consent is denied, the request gets stripped of anything that could identify the person and goes out as a plain, cookieless ping instead. Google then fills in the missing pieces with modeling, basically making an educated guess about the traffic it couldn't measure properly.

With Advanced mode, an extra parameter is added to outgoing requests indicating what was and wasn't consented to:

| Code | Marketing consent | Analytics consent |
| ---- | ----------------- | ----------------- |
| G100 | No                | No                |
| G101 | No                | Yes               |
| G110 | Yes               | No                |
| G111 | Yes               | Yes               |

Most setups should default to **Advanced mode** unless there's a specific compliance reason to hard-block Google tags, it preserves far more usable data while still respecting the visitor's choice.

### Step 1: Configure Consent Mode v2 in web GTM

{% stepper %}
{% step %}

#### Load your CMP on the Consent Initialization trigger

Your CMP (Cookiebot, Consent Studio, etc) needs to load before anything else on the page. GTM has a dedicated **Consent Initialization** trigger reserved exactly for this, it fires before any other tag, so nothing else can activate until a consent state exists.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F7UUILSdf6T4vyvCAxmBP%2Fimage.png?alt=media&amp;token=172b64f0-ff36-42a0-a73a-e735c32a3a89" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Set the default consent state

Before a visitor makes a choice, all four signals (ad\_storage, ad\_user\_data, ad\_personalization, analytics\_storage) should default to "denied." Set this as the default state on your Google tag / consent settings.
{% endstep %}

{% step %}

#### Turn on Consent Overview in GTM Web

Enable the Consent Overview settings in your web container. This is what lets you require specific consent signals per tag rather than relying on a single global switch.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FYzPcbOri5ti2RMlwGPaW%2Fimage.png?alt=media&amp;token=12407103-d4e3-4b24-a72b-280bb12c7d55" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Assign consent requirements to each Google tag

For tags without built-in consent checks, specify which consent signal is required. The Google Tag, GA4 event tags, Conversion Linker, and Google Ads conversion tags already have built-in consent checks, so they don't need manual configuration, they read the consent state automatically.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FnjAjKa7iPCaJOnw2D5aH%2Fimage.png?alt=media&amp;token=901ece80-7e85-4b63-a578-edc45284c441" alt=""><figcaption></figcaption></figure>

In the Consent Overview you are able to bulk select tags to select the Additional Consent required to fire these tags.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fu1YGy8UTAXiiBTuYBgyl%2Fimage.png?alt=media&amp;token=f85dde37-7999-4e2c-bd62-694dd2fa21a3" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### Step 2: Send consent to your server container

Google tags carry their consent signals to GTM Server automatically as part of the request. There's nothing extra to build for those requests. Every other platform (Meta, Pinterest, LinkedIn, TikTok, etc.) needs its consent status forwarded manually, since those tags don't understand Consent Mode v2 at all.

{% stepper %}
{% step %}

#### Find where your CMP stores accepted vendors

Most CMPs store the list of vendors/categories a visitor accepted, either in a first-party cookie or as a dataLayer variable. Check your CMP's documentation to confirm which one applies, the exact cookie or variable name differs per CMP.
{% endstep %}

{% step %}

#### Create a variable in GTM Web to read it

Add a First-Party Cookie variable (or a Data Layer Variable, depending on your CMP) that captures the accepted vendors or categories.
{% endstep %}

{% step %}

#### Add it as a parameter on your Google tag

Add an extra event parameter (for example `consent_status`) to your Google tag configuration, using the variable from the previous step as its value. This is what carries the consent information from the browser into the request sent to your server container.
{% endstep %}
{% endstepper %}

### Step 3: Configure server-side triggers based on consent

Once `consent_status` (or whatever you named it) arrives at your GTM Server container, each non-Google tag needs a trigger condition that checks it before firing.

{% stepper %}
{% step %}

#### Create an Event Data variable

In GTM Server, create a variable that reads the incoming `consent_status` parameter from the event data.
{% endstep %}

{% step %}

#### Add a consent condition to each platform tag

For each platform tag (Meta CAPI, Pinterest CAPI, LinkedIn CAPI, etc.), add an extra trigger condition checking that the Event Data variable contains that platform's identifier, e.g. the Meta tag only fires if the value contains "facebook", the Pinterest tag only if it contains "pinterest".
{% endstep %}

{% step %}

#### Repeat for every non-Google platform

Apply the same pattern to every remaining server-side tag. Any tag without a consent condition will fire regardless of the visitor's choice, so double-check nothing is left unguarded.
{% endstep %}
{% endstepper %}

### Step 4: Validate that it's actually working

{% stepper %}
{% step %}

#### Test the "deny" path

Open your site in an incognito window with GTM Web preview mode running, and reject all cookies. Confirm only the CMP/Consent Initialization tag fires, no Google or platform tags should activate yet.
{% endstep %}

{% step %}

#### Check the Google tag's request in Basic mode

If you're running Basic mode, confirm in GTM Server preview that the Google tags are blocked from firing while consent is denied, and that no request reaches Google Ads or GA4 for that visit.
{% endstep %}

{% step %}

#### Check the anonymized ping in Advanced mode

If you're running Advanced mode, confirm the Google tag still fires but the outgoing request carries a `gcs` parameter matching a denied state (e.g. `G100`) and contains no identifying cookie values.
{% endstep %}

{% step %}

#### Test the "accept" path

Accept all cookies and reload. Confirm the CMP's consent-update event or cookie now reflects full consent, and that your Google tags fire with the `gcs` parameter matching full consent (e.g. `G111`).
{% endstep %}

{% step %}

#### Confirm consent reaches the server for non-Google tags

In GTM Server preview mode, inspect an incoming request and confirm the `consent_status` parameter is present and contains the vendors the visitor accepted.
{% endstep %}

{% step %}

#### Confirm platform tags only fire when consented

Still in Server preview, accept only some categories (e.g. accept Meta but reject Pinterest) and confirm the Meta CAPI tag fires while the Pinterest CAPI tag does not — and vice versa when you flip the choice.
{% endstep %}
{% endstepper %}

If any of these checks fail, head back to the matching step. Usually the problem is one of two things. Either the Google tag is missing a consent parameter, or one of your platform tags on the server never got its trigger condition set up.


# Add Cookiebot to GTM

This guide explains step by step how to integrate the Cookiebot template into your Google Tag Manager web container, so your website complies with privacy regulations and visitors give proper consent for cookie use.

{% stepper %}
{% step %}

#### Open your GTM web container

Go to **Templates** and click **Search Gallery** under Tag Templates. Use the search function to find the Cookiebot template, then add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F4vQVUTUXN5QQp1Rgz1Mb%2Fimage.png?alt=media&amp;token=01ac4f54-48b4-4cfe-a852-daebca8e6801" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Create the Cookiebot CMP tag

Go to **Tags** and create a new tag. As the tag configuration, choose **Cookiebot CMP**.
{% endstep %}

{% step %}

#### Enter your Cookiebot ID

In the **Cookiebot ID** field, enter your Cookiebot ID. You can find this by copying the Domain Group ID from the **Your Scripts** tab in your Cookiebot account.
{% endstep %}

{% step %}

#### Configure language and region

For **Language**, let Cookiebot determine it automatically, or set it via a GTM variable so you control which language is shown and when. Specify the **CDN Region** where Cookiebot is active — EU or COM. For sites active in Europe, choose .eu.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FtuXc2CzteaJEVAx4ZKpR%2Fimage.png?alt=media&amp;token=19fcb50b-2d97-4486-ac0d-8acfb0357c1b" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Set the default consent state (optional)

If you want to adjust the **Default Consent State** (everything denied for new visitors), create a new Region and enter the default consent a new user has before they accept or reject cookies.
{% endstep %}

{% step %}

#### Set the trigger and save

As the trigger, choose **Consent Initialisation** and save the tag.
{% endstep %}
{% endstepper %}

Next, make sure your consent overview settings are configured correctly within Google Tag Manager. Follow [the 'Consent Management' article](/optimize-your-setup/consent-management) for these settings.

Since you don't want to measure events before the visitor has given consent, you'll also need to adjust the triggers of specific tags, such as the page\_view event tags, see [the 'Trigger sequence for consent processing' article](/optimize-your-setup/consent-management/trigger-sequence-for-consent-processing) to learn how to set this up.


# Add Consent Studio to GTM

This guide explains step by step how to integrate the Consent Studio template into your Google Tag Manager web container, so your website complies with privacy regulations and visitors give proper consent for cookie use.

{% stepper %}
{% step %}
**Add the Consent Studio tag template**

Open your GTM web container, go to **Templates**, and click **Search Gallery** under Tag Templates. Search for **Consent Studio CMP** and add it to your workspace.
{% endstep %}

{% step %}
**Create the Consent Studio CMP tag**

Go to **Tags** and create a new tag. As the tag configuration, choose **Consent Studio CMP**.
{% endstep %}

{% step %}
**Confirm your domain is registered**

Unlike some other CMPs, Consent Studio doesn't need a manual ID pasted into the tag — it matches based on the domain you registered in your Consent Studio dashboard. Just make sure the site you're tagging is added there first.
{% endstep %}

{% step %}
**Set the trigger and save**

As the trigger, choose **Consent Initialization – All Pages**. This is required for Consent Studio to support Google Consent Mode v2 correctly. Save the tag.
{% endstep %}

{% step %}
**Choose Basic or Advanced consent mode**

* **Advanced** — the simpler option. Let tags load on their normal trigger (e.g. All Pages), and Consent Studio adjusts their behavior automatically based on the visitor's consent state. This works well for official Google tags, which respect consent signals natively.
* **Basic** — tags are only allowed to load once consent for a specific category has been given. To set this up, create a **Custom Event** trigger using one of Consent Studio's built-in dataLayer events — `cookie_consent_granted_functional`, `cookie_consent_granted_analytics`, or `cookie_consent_granted_marketing` — and attach it to any tag that shouldn't fire until that category is accepted.

If you're not sure whether a particular tag respects consent signals on its own, Basic mode is the safer default for it.
{% endstep %}

{% step %}
**Enable or disable Google Consent Mode (optional)**

Google Consent Mode is on by default. If you need to turn it off, open the Consent Studio CMP tag's **General Settings** and set the Google Consent Mode toggle to **No**.
{% endstep %}
{% endstepper %}

Next, make sure your consent overview settings are configured correctly within Google Tag Manager. Follow [the 'Consent Management' article](/optimize-your-setup/consent-management) for these settings.

Since you don't want to measure events before the visitor has given consent, you'll also need to adjust the triggers of specific tags, such as the page\_view event tags, see [the 'Trigger sequence for consent processing' article](/optimize-your-setup/consent-management/trigger-sequence-for-consent-processing) to learn how to set this up.


# Trigger sequence for consent processing

How do you ensure the tags that have to fire on every page, fire after the given consent has been processed?

## Setting up the triggering order for consent processing

In this article we cover how to make sure your tags that have to fire on every page (page\_view event tags, Hotjar or Clarity, etc) fire correctly to ensure the given consent has been processed.

### Why does consent processing matter?

When someone visits your website for the first time, they haven't given consent for cookies and tracking yet. That means tags like the page\_view event tags won't fire with all data (GA4 event tags will send cookieless pings) or won't fire at all (Meta Ads tag with additional consent checks set up). So in your tracking setup, you'll need to wait until consent has been fully processed before you try to fire your page\_view tags.

***

### A trigger for the consent update on every page

Google Tag Manager offers 5 standard triggers for a page load. But none of those 5 wait for the consent signals to fully process. That's why you'll want to set up tags that are reliant on the given consent with a trigger that ensures all given consent has been processed.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fovj9AMYRDWE9KUjevlK4%2FServer-side%20tagging%20met%20webhooks%20(4).png?alt=media&amp;token=d753a316-e6ca-4708-9af8-c99cabeb9b09" alt=""><figcaption></figcaption></figure>

Depending on the Consent Management Platform (CMP) you use, a specific dataLayer event push may take place the moment consent is updated.&#x20;

#### Consent Studio, CookieYes and Cookiebot

After a visitor gives consent through a Cookiebot or Consent Studio banner, a dataLayer event called `cookie_consent_update` appears on every page. You can set all your triggers on this for a complete setup, including the Google Tag and the page\_view event tags. Make sure all other event tags never fire before `cookie_consent_update`, but always after it.

**Steps for setting up the trigger**

1. Create a Custom Event trigger with the name `cookie_consent_update`.

<figure><img src="https://euw1.frontkb-cdn.com/attachments/9808087/547522/9f26c895-41d6-44e3-9db6-71d5355f9cb8.png" alt=""><figcaption></figcaption></figure>

2. Replace the triggers on all tags that need to fire on every page with this trigger.

<figure><img src="https://euw1.frontkb-cdn.com/attachments/9808087/547522/6de014ed-69c0-4a02-8760-c1e9ba4fcecc.png" alt=""><figcaption></figcaption></figure>

3. Replace the triggers on all tags that could fire before `cookie_consent_update` lands in the dataLayer, as follows:
   * Triggering based on thank you pages: use a dedicated `cookie_consent_update` trigger.
   * Triggering based on a dataLayer event that can fire earlier than `cookie_consent_update`: add it to a trigger group.

**Trigger adjustment:**

You can change all your thank you page triggers into Custom Event triggers that listen for the event name `cookie_consent_update`.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FwZmkaOEO2oBL5wSfcTJZ%2Fimage.png?alt=media&amp;token=030d1209-ceed-40cd-ae20-64f215447983" alt=""><figcaption></figcaption></figure>

**Trigger group:**

If a trigger can fire before `cookie_consent_update`, you can place it in a trigger group together with `cookie_consent_update`. A trigger group waits until every trigger in the group has fired on a page before it can activate.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FlHpYAmlHW6YT7ch5L1uM%2Fimage.png?alt=media&amp;token=80d67bb8-86cf-4ae7-9611-199fcc2904fd" alt=""><figcaption></figcaption></figure>

#### Other Consent Management Platforms

Not every CMP pushes a dataLayer event when consent is updated, and the ones that do don't always name it `cookie_consent_update`. So if you're not using Cookiebot, CookieYes or Consent Studio, you'll need to find out for yourself what your CMP makes available. The only reliable way to do that is to watch it happen in Google Tag Manager preview mode.

1. Open the Google Tag Manager web container's preview mode on your site and clear all cookies for the domain, so you're treated as a brand new visitor.
2. Accept all cookies in the banner.
3. Look at the event stream in the left-hand column and find the gtag **Consent Update** call.
4. Check whether a dataLayer event push appears **after** that consent update call.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FBCJSTPJZUVBJEqK5GWTc%2Fimage.png?alt=media&amp;token=72f725c2-6f6a-46c8-a519-3254488e3dcd" alt=""><figcaption></figcaption></figure>

If you find one, the next question is whether it repeats. Reload the page a few times and click through to a second page without clearing your cookies. An event that only appears once, at the moment someone interacts with the banner, isn't the one you're looking for here. What you need is an event that fires on every page load once consent is already stored, because that's what lets you hang your page\_view tags on it the same way you would with `cookie_consent_update`. If the event only shows up on that first interaction, the approach in the next section is the one to use instead.

And if there's no dataLayer event push after the consent update at all, then your CMP simply doesn't give you anything to trigger on. In that case you can't reliably control the order in which your tags fire, which means you'll keep losing the campaign parameters and referrer data from the first page of a session. That's the point at which we'd suggest moving to a CMP that does push a consent update event. Cookiebot and Consent Studio both do, and both integrate cleanly with the setup described above.


# Ideal cookiebanner setup

As a marketer, you want the highest possible percentage of accepted cookies. A cookie banner that's big and hard to ignore gives you the best shot at getting a yes right away, so you don't lose that data from a session that often decides everything.

Here's the thing about asking for explicit consent. You can't track anyone until they actually click accept. So if your banner is easy to brush off, visitors will happily wander around your site while you sit there measuring nothing. And once they click through to the second page, that referrer and those campaign parameters are gone for good. Getting your marketing scripts to load on that first page, and starting to measure the journey right there, matters a lot more than most people realize.

#### **Cookiebot Manager**

1. Select **Explicit Consent** so you ask for opt-in consent.
2. Select **Overlay** or **Pop-up** so the cookie banner can't be ignored on the first page for new site visitors.
3. Select **Multilevel** so visitors can give or refuse consent for different categories.
4. Select **Allow all / Selection** if you don't want a button to reject all cookies in one simple click. But you are required to have a "deny all" or "reject all" button on your cookie banner.
5. Leave the **Close icon** option unchecked, so visitors can't close the banner without giving or refusing consent.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FdcUgcijDmnSdTUCfgGWD%2Fimage.png?alt=media&amp;token=94b2583b-9e7b-4fc0-be22-505f350dbc80" alt="" width="563"><figcaption></figcaption></figure>

#### **Cookiebot Admin**

* Under **Layout**, choose **Dialog** to make the banner as hard to ignore as possible.&#x20;
* For **Style effect**, choose **Overlay**. That way the rest of the page is blocked off and visitors can't click around the banner.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fd45abtntGjLo1cxoQNP3%2Fimage.png?alt=media&amp;token=a1ec88a7-991a-44bc-a2ce-2281a6532d12" alt=""><figcaption></figcaption></figure>

* Under **Compliance**, choose **Explicit Consent** as the **Method**, so you ask visitors for opt-in consent.
* Under **Type**, choose **Inline multilevel** to give visitors a choice between consent categories.
* Under **Buttons**, choose **Allow All / Selection** if you don't want a button that lets visitors reject everything in a single click. But you are required to have a "deny all" or "reject all" button on your cookie banner.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FkwXa1RldqSLA6xq61k8l%2Fimage.png?alt=media&amp;token=e53bcdf8-cf06-464d-82f6-0ecbc3ee1784" alt=""><figcaption></figcaption></figure>

#### **Consent Studio**

* In your Consent Studio account, go to the **Styling** options under **Web CMP**.
* Make sure the **Position** is **Centered**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FDF72hgdwrPfv6cDHrkLm%2Fimage.png?alt=media&amp;token=091de5c6-f04d-4ac1-84cb-a015f9c2e30c" alt=""><figcaption></figcaption></figure>

* Enable the option **Enable Overlay Behind Banner** in the **Overlay** options to make the cookiebanner unignorable.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F6044GC3zmcfwcWzgbuDD%2Fimage.png?alt=media&amp;token=e673099a-2e9a-462a-acef-f5b508211178" alt=""><figcaption></figcaption></figure>


# Webhook Matching

Ensure AdPage's webhook functionality always sends purchase events towards GA4 and marketing platforms with the correct consent signals and marketing data

### What does Webhook Matching do?

Purchase events that fire in the browser are fragile. Ad blockers can stop them, cookie restrictions can strip them, and Safari's ITP can cut the data short before it ever reaches you. Server-side tagging fixes these issues, but there are still three scenarios where the browser-side purchase tracking won't work.

1. Visitors who never come back to your thank-you page. They pay in their banking app, see the confirmation there, and close it. Job done in their eyes. If they don't land on your thank-you page, the browser event never fires.
2. Visitors who do land on the thank-you page but leave too quickly. Your tracking scripts need a moment to load and send. Close the tab before that and the event tracking dies with it.
3. Someone starts their journey in an in-app browser, maybe inside an LLM app or a social app, then gets sent off to their payment app. On the way back, the payment app hands them over to whatever browser their phone has set as default. Now they're in a totally different browser with a different session and no cookies from the original visit, so even a perfectly loaded thank-you page reports it as something other than what it is.

Backend webhooks from your shop platform (Shopify, WooCommerce, Magento) don't have that problem because they get sent straight from the server. The trade-off is that they can show up without any browser context, so no `gclid`, no user-agent, and no items array. AdPage's Webhook Matching links the browser data and the webhook data together using a shared match identifier, merges the payloads, and forwards a single validated event downstream. The result: no duplicate conversions, and no missed ones either.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F3TFREPT1hh29haoO8acq%2FWebhook%20Notifier%20(7).png?alt=media&amp;token=25d9be4a-5492-427d-bb88-e12ccd8b21d8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F4kSU4XBsHmHgBawhABCC%2FWebhook%20Notifier%20(6).png?alt=media&amp;token=3ae3419f-fc23-4bfc-95ac-9c9ccfb3c86e" alt=""><figcaption></figcaption></figure>

### Setting up Webhook Matching

There are two steps to setting up Webhook Matching.

**Step 1** is processing the incoming webhook (Trigger) and a begin\_checkout event (Prepare) to ensure that those can be matched.

After the Matching rate is at a high enough percentage (>90%) these matched webhooks can be sent towards Google Analytics and your marketingplatforms, setting that up is **Step 2**.

{% stepper %}
{% step %}

#### Step 1: Setting up the Webhook Matching Rate

1. Open the server container in Google Tag Manager
2. Go to Templates → Tag Templates → New
3. Click the three dots in the top right → Import → select `adpage-event-notifier.tpl`. You can download it here: <https://adpage.b-cdn.net/GTM-Templates/adpage-event-notifier.tpl>
4. Click Save. The "AdPage Event Notifier" template now appears in the templates list
5. Create two tags using this template:

**Tag 1 — Prepare (event received from client-side):**

* Mode: `Prepare`
* Container ID: found in the URL of your AdPage server container\
  \
  ![](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyXQZwDv6XjwyRSFU2uoD%2Fimage.png?alt=media\&token=fbb5ae48-6167-4976-b3fb-49b778752b9f)<br>
* Platform preset: choose whichever applies (see below)
* Event name: `purchase`
* Trigger: a browser event just before completing the checkout (e.g. `begin_checkout`)
* Give it a correct name: "AdPage Event Notifier - Prepare"

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FzDelZYkvyynWS7DIIjGV%2Fimage.png?alt=media&amp;token=deb4f40f-4270-4d46-b453-700276884be6" alt=""><figcaption></figcaption></figure>

**Tag 2 — Trigger (server-side webhook):**

* Mode: `Trigger`
* Container ID: found in the URL of your AdPage server container
* Platform preset: same as above (see below)
* Transaction ID: an Event Data variable with `transaction_id` as the Key Path
* Trigger: the webhook event from your commerce platform (the webhook that gets processed by [the AdPage Webhook Client](/extensions/google-tag-manager-templates/adpage-webhook-client))
* Give it a "AdPage Event Notifier - trigger"

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FrYzzeYqJgg3oxVBb3xk0%2Fimage.png?alt=media&amp;token=b8f963c1-217b-484a-9441-7c209a62a95f" alt=""><figcaption></figcaption></figure>

**Platform Preset**

The platform preset option is the BasketKey you want to use to link the Prepare and Trigger sides together, both must send the same value, or they won't match.

| Setup                                                 | Preset                       | BasketKey                                        |
| ----------------------------------------------------- | ---------------------------- | ------------------------------------------------ |
| Client has the AdPage Tagging plugin/script installed | AdPage Tagging (universal) ⭐ | `user_id` (from the `trytagging_user_id` cookie) |
| Native Shopify (no Tagging plugin)                    | Shopify                      | `cart_token`                                     |
| Native Magento                                        | Magento                      | `quote_id`                                       |
| Native Lightspeed C-Series                            | Lightspeed                   | `quote_id`                                       |
| Native Shopware 6                                     | Shopware                     | `cart_token`                                     |
| Something else / custom integration                   | Custom                       | define your own                                  |

{% hint style="info" icon="webhook" %}
For around 95% of clients, **AdPage Tagging (universal)** is the right choice, it works across any platform because the AdPage tagging stack uses the same `user_id` UUID everywhere: in the browser (`trytagging_user_id` cookie) and in the webhook (`marketing.user_id`).
{% endhint %}

{% hint style="danger" %}
**Never forward the BasketKey `user_id` as GA4's own `user_id` parameter.**

The `user_id` used here is AdPage's own matching identifier — it only exists to link Prepare and Trigger together and has nothing to do with GA4's reserved, top-level `user_id` field from GA4's User-ID feature.

If this BasketKey value gets mapped into the outgoing Measurement Protocol payload as GA4's `user_id` (for example through a custom field override on the MP client/tag), GA4 starts treating it as a persistent, cross-session identity even though it isn't one. Under **Observed** or **Blended** Reporting Identity, GA4 gives User-ID priority over Client ID when deciding whose journey a hit belongs to. Because the forwarded `user_id` on a webhook-matched purchase usually doesn't carry the same `ga_session_id` as the visitor's browser session, GA4 can no longer recognise the webhook hit as the same order as the client-side hit — instead of being deduplicated on `transaction_id` within one identity, it gets counted as a second, separate purchase under a different "Effective User ID".

\
Only forward `user_id` to GA4 if it's a real, stable GA4 User-ID that the client already sets consistently on login (client-side, via `gtag('config', ...)`, per Google's own User-ID requirements) — never the BasketKey matching value.
{% endhint %}

Step 1 result would be:<br>

<img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fi4dnXCJ70tSEnMFpyDSO%2Fimage.png?alt=media&amp;token=d66c6bdc-0447-4a56-8bbe-567b478833bc" alt="" data-size="original">\
\
\
Publish the Google Tag Manager server container with these 2 new tags. The incoming begin\_checkout events and webhooks will be automatically matched in your AdPage server container. Check back in a couple of days to check on the Webhook Matching Rate.
{% endstep %}

{% step %}

### Step 2: Validate the webhook matching rate

A couple of days after publishing step 1 you are able to check the webhook matching rate within your AdPage server container.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FFve4wkkcN3HQjIHI9tkO%2Fimage.png?alt=media&amp;token=89e74b41-c781-4b96-813c-500db2c648f5" alt=""><figcaption></figcaption></figure>

If the match rate is above 90% you can continue with Step 3 below.

If the match rate is below 90% you should alter the webhook matching configuration. Alter the configuration in the top right behind the **Configuration** button. Here you'll find the following configuration settings:

**Extra identifier (fallback)**\
Pick a field present in both prepare and trigger (`user_id`, `cart_token`). It's the only deterministic option, takes precedence over the others, and keeps the normal Matched status. Usually the biggest single gain.

**Transaction ID prefix**\
Only needed when the same order arrives via two sources with different ID formats. Fill in the prefix and tick the "ignore" checkbox so the bare duplicate is dropped. Leave empty if there's one source.

**Probabilistic matching**\
Off by default. Links missed orders to a recent prepare based on items, value, identity and timing. Status becomes Probable. Enable when no fallback field is available; be careful on shops with many near-identical low-value orders.

**Trigger-only**\
Off by default. Sends the order on the `_ga` client\_id alone, without a prepare. Recovers orders where the prepare never fired. Weaker attribution, but the conversion is preserved. Status: Trigger-only.

**Unconsented conversions**\
On by default, leave it on. Sends a cookieless, PII-free ping for denied-consent orders so GA4 can model them. Only switch off after checking the client's privacy policy.
{% endstep %}

{% step %}

#### Step 3: Utilizing the matched Webhooks

To be able to utilize the matched webhooks, you'll have to create a GA4 Measurement Protocol client. The Webhook Matching callback arrives on your sGTM `/mp` endpoint. A client needs to be in place there to claim the incoming Measurement Protocol request and convert it into an event that your downstream tags (GA4, Google Ads, Meta CAPI, etc.) can pick up.

1. Create the client: In your server container, go to **Clients → New**, choose client type **Measurement Protocol (GA4)**, and give it a recognizable name such as "AdPage MP" Set **Path / Activation** to your callback URL, `/mp`.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Ftn1AU94XTkykQUEgCtcT%2Fimage.png?alt=media&amp;token=c1d683c7-8868-4e34-84b5-9b56de6ab9f4" alt=""><figcaption></figcaption></figure>

2. Block the purchase events in your regular GA4 trigger: add the condition to your regular GA4 trigger that 'Event Name' does not equal 'purchase'.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FsMHv1jOOQqyXpbhan7El%2Fimage.png?alt=media&amp;token=23ed5e72-c417-4b6f-8266-3c8feeefdb81" alt=""><figcaption></figcaption></figure>

3. Add a new Measurement Protocol Client trigger: create a new trigger that fires on all incoming requests in your Measurement Protocol Client. After creating this trigger, add it to your Google Analytics 4 tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FVALr883pzWJhvOyvBrU9%2Fimage.png?alt=media&amp;token=b8fd9b75-f6c1-402c-bbaa-325aedccff6e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FinkOI4Qvfvni7WVFgrqu%2Fimage.png?alt=media&amp;token=f3eb56ba-90e4-4bce-acfb-fe9efe0b6891" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### Testing and debugging

Before publishing the changes made for **Step 2**, confirm that Prepare and Trigger are actually matching.

{% stepper %}
{% step %}

#### Use the Webhook Replay functionality to test the matched webhooks

To test the matched webhook without placing a new order,

1. Go to your AdPage container's **Webhook Logs**
2. Find a Matched Webhook and open it by clicking on it
3. Find the **Replay** button at the bottom

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FdzhKmFGiC8jw81vO7GoI%2Fimage.png?alt=media&amp;token=699f0716-6b8c-4ffc-b5ad-1501b630bd4e" alt=""><figcaption></figcaption></figure>

4. Go to your Google Tag Manager server container and start the preview mode
5. Click on the 3 dots in the top right and select the option **Send requests manually**, copy the X-Gtm-Server-Preview HTTP header.
6. Paste the X-Gtm-Server-Preview HTTP header in the Matched Webhook replay input field
7. The webhook replays in the Google Tag Manager preview mode so you can see exactly which tags fire and what the outgoing payloads of these tags are.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FAd2oSHV7tCPYiDAD5GRN%2Fimage.png?alt=media&amp;token=7117972d-a068-4e10-a63b-7b4827331743" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### Reading the Webhook Matching dashboard

Under **Webhook Matching → Match health**, you can see at a glance how well Prepare and Trigger have matched over the selected period (7 days by default), and where things are going wrong.

The percentage at the top is the share of orders processed successfully — matched, handled via in-app browsers, or cookieless — against the total number of incoming orders.

* **Matched** — Prepare and Trigger were linked on the Basket ID. This is the healthy path.
* **In-app browsers** — orders from in-app browsers (Instagram/Facebook app, etc.) where cookies work in a limited way.
* **Cookieless** — orders with no trackable cookie (see "Sending unconsented conversions" under Advanced options below).
* **Not reached** — orders that weren't matched. Hover over this segment for a breakdown by cause: **stale cookies** (the Prepare cookie had already expired by the time the Trigger arrived — too much time between checkout start and order confirmation), or **other/unclear** (a catch-all, usually incidental).

Below the bar you'll see the number of orders without consent — orders that are (partly) not tracked in GA4 because the visitor declined tracking.

Use **Analyze missed** to run an analysis on "not reached" orders and see whether probabilistic matching or trigger-only forwarding (see Advanced options) could have recovered them.

* Click **Details** on any row under Recent events to inspect an individual event: status, source (transaction ID), and callback time appear at the top.
* The **payload check** flags data mismatches, such as "value ≠ sum of items" when the order total doesn't match the sum of line items within tax/shipping tolerance — this is a warning, not a block; the event still goes through, but it's worth checking whether the client's integration is sending the right fields.
* **Tracking consent** shows whether consent was granted or denied, along with the underlying Consent Mode flags (`analytics_storage`, `ad_storage`, `gcs`).
* **Browser** shows the user-agent, useful for spotting patterns (e.g. a lot of "not reached" events from one browser/OS combination).
* **Prepare buffered** and **Trigger processed** show the exact timestamps of both events — the gap between them matters for stale-cookie issues. Further down you'll find four tabs — outgoing payload, Prepare data, order data, and raw Trigger body — useful for seeing exactly what came in before processing, plus options to copy the payload or replay the event.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FRAu5x6WmZPeQMJjga7pu%2Fimage.png?alt=media&amp;token=ec3702df-3e82-44df-a399-922b175df4ea" alt=""><figcaption></figcaption></figure>

### What's in the outgoing payload

The Event Notifier's callback to sGTM carries a complete payload, ready to use across all major ad platforms. The template automatically forwards:

**GA4 (Measurement Protocol)**

```
event_name:           "purchase"
client_id:            (from browser or webhook marketing.ga4_client_id)
transaction_id:       (from order)
value, tax, shipping: (from order)
currency:             EUR / USD / more.
items[]:              (complete array with item_id, item_name, price, quantity, item_brand, item_category, etc.)
engagement_time_msec: 100 (default)
page_location:        real thank-you URL (Shopify Web Pixel sandbox-URLs are automatisch cleaned)
gcs, gcd:             Consent state
ip_override:          server-side geocoding
```

**Meta CAPI (Facebook + Instagram)**

{% hint style="warning" %}

### How deduplication works

Meta deduplicates the browser Pixel event and the server-side CAPI event for the same purchase when both have the **same** `event_id` and **same** `event_name` (`Purchase`). Meta keeps one event within a \~48-hour window and ignores the other.

The `event_id` is therefore the key. It must meet two requirements:

1. **Identical** in the browser Pixel and CAPI event for the same purchase.
2. **Unique per purchase** — otherwise, separate orders may be incorrectly merged.

The only value that meets both requirements is the `transaction_id` **(order ID)**. Use:

> ⚠️ Do **not** use `user_id` as the `event_id`. It remains stable per customer, not per order. A second purchase by the same customer within 48 hours would be incorrectly discarded as a duplicate. Use `user_id` as the BasketKey and `external_id`, not as the deduplication key.

> ⚠️ The `event_id` must be **exactly the same string** in both events. Watch for prefixes or formatting differences. If the browser sends `12345` and the server sends `order_12345`, Meta sees two separate events and does not deduplicate them.

> 💡 Ensure the CAPI `event_id` comes from the **Trigger/order side** (`transaction_id`). Do not use a random `event_id` generated during the Prepare/`begin_checkout` step. It never matches the browser `Purchase` event.
> {% endhint %}

|              | **Source**                                                       | `event_id`                    |
| ------------ | ---------------------------------------------------------------- | ----------------------------- |
| Browser-side | Meta Pixel `Purchase` thankyou page                              | `transaction_id`              |
| Server-side  | AdPage - Meta Conversion API on  the Measurement Protocol Client | `transaction_id` from payload |

```
bp:                  _fbp cookie (Facebook browser ID)
fbc:                  _fbc cookie (Facebook click ID)
em:                   email (SHA256 via FB CAPI tag)
fn, ln, ph:           first_name, last_name, phone (SHA256 also)
zp, ct, st, country:  zip, city, state, country
external_id:          customer.id (cross-order stable)
client_ip_address:    IP for IP-matching
client_user_agent:    UA for browser-fingerprinting
event_id:             for browser-pixel deduplication
```

**Google Ads (conversion + remarketing)**

```
_gcl_aw, _gcl_dc, _gcl_gb:  gclid cookies (set by Conversion Linker)
FPGCLAW, FPGCLDC:            first-party gclid variants
gclid, gbraid, wbraid:        URL-parameters (iOS app campaigns)
client_id, ga_session_id:     for stiching with page_view events
value, currency:              conversion value
```

**TikTok Events API**

```
_ttp, ttp:            TikTok pixel cookie
ttclid:               TikTok click ID (from URL ?ttclid=)
email, phone_number:  (TikTok uses complete fields instead of FB's shorts)
first_name, last_name, city, state, zip_code, country_code: idem
external_id:          customer.id
ip, user_agent:       for matching
```

**Pinterest Conversions API**

```
_epik, epik:          Pinterest click ID cookie + URL param
em, fn, ln, ph, zp:   (same conversion as FB CAPI)
ct, st, country:      adres-velden
external_id:          customer.id
client_ip_address:    IP
client_user_agent:    UA
```

**Consent, across every platform**

```
ad_storage, ad_user_data, ad_personalization, analytics_storage: "granted"/"denied"
consent.ad_storage, consent.ad_user_data, …: aslo (nested object)
gcs, gcd: Google Consent strings (forGA4 / Google Ads)
```

### Troubleshooting

* **"Match identifier value could not be resolved"** — The BasketKey wasn't found in the event data. Check the error log in the sGTM console, find where the UUID actually lives in the EventDataSnapshot, and set that path via **Identifier value override** in the tag config.<br>
* **Trigger returns a 308 redirect** — The URL ends with `/trigger/` and no value. Same root cause as above — recheck BasketKey resolution.<br>
* **Trigger returns a 400** — Body validation failed, usually because `transaction_id` or `value` is empty. With the AdPage Tagging plugin (WooCommerce/PrestaShop) this lives at `ecommerce.transaction_id` — confirm the webhook is sending it.<br>
* **`missed` status in Event Notifier logs** — A Trigger arrived with no matching Prepare. The browser-side Prepare likely failed (ad blocker, ITP, or no browser event right before checkout) — check sGTM preview on the storefront.<br>
* **`callback_failed`** — sGTM isn't receiving the Event Notifier's callback. Check the callback URL in AdPage's tenant config — usually a missing `/data` suffix or the wrong subdomain.

### Advanced options

* **Multi-market setups** (Shopify Markets or multi-locale shops) — enter all GA4 property IDs comma-separated in the GA4 Measurement IDs field (e.g. `G-NL123, G-BE456, G-DE789`). Event Notifier then forwards the matching `_ga_<MID>` cookie per property so sGTM can route downstream.
* **WooCommerce without the Tagging plugin** — enter the exact `wp_woocommerce_session_<hash>` cookie name in the WooCommerce session cookie field.
* **Custom event identifiers** — choose the Custom preset and define your own identifier name and variable reference.
* **Duplicate-identifier prevention** — if an order arrives with both a canonical identifier (e.g. `vtnl-...`) and a bare variant (e.g. just the order number), the bare variant is ignored and only the canonical one proceeds.
* **Probabilistic matching** — attempts to link an otherwise-missed order to a recent Prepare event based on items, amount, customer identity, and timing. When confidence is high enough, the event is sent to GA4 with status **Probable** instead of **Matched**. Off by default — only enable this if you trust it for a given client.
* **Trigger-only forwarding** — sends an otherwise-missed order (no Prepare, not even via probabilistic matching) to GA4 anyway, using the GA4 `client_id` from the Trigger's own `ga` cookie. Only works if that client ID is present; otherwise the order stays missed. Status becomes **Trigger-only**. Off by default.
* **Sending unconsented conversions** — forwards an order where tracking consent was declined (so no GA4 client ID) as a privacy-safe, cookieless ping: a disposable client ID with "denied" consent flags and no PII, so GA4 can still model the conversion. Status becomes **Unconsented**. Off by default — only enable this after discussing consent implications with the client, since it forwards data even without tracking consent.

### Need help?

If a client's setup doesn't fit anything covered here, ask our support at <support@adpage.io> with the container ID and a screenshot of the sGTM console log.


# Reporting Identity in GA4

What the Reporting Identity setting in GA4 does, the three available options, and the pros and cons of each for reading your data.

### What is Reporting Identity?

Under **Admin → Data display → Reporting Identity**, GA4 decides how it stitches individual events — from the same visitor, on the same or a different device — into a single user/session before they land in your reports. This setting doesn't change which events come in, but it does change how GA4 assigns them to users and sessions — which directly affects the numbers you see in Reports, Explorations, and conversions.

There are three options, in decreasing order of "how many identification methods GA4 is allowed to use":

| Option       | Uses                                                |
| ------------ | --------------------------------------------------- |
| Blended      | User-ID → Google signals → device ID → **modeling** |
| Observed     | User-ID → Google signals → device ID (no modeling)  |
| Device-based | Device ID only (`client_id`)                        |

Important to remember: as soon as a User-ID is available, both **Blended** and **Observed** give it priority over the device ID (`client_id`) when deciding who caused an event. That makes these two options stronger for cross-device recognition, but also more sensitive to mistakes in how User-ID is sent — see the caveat at the bottom of this page.

### Option 1 — Blended

Blended is the default setting for new GA4 properties. Besides User-ID, Google signals and device ID, GA4 also applies **modeling** here: for visitors who did not consent to `analytics_storage` (denied consent), Google uses machine learning to estimate their behavior based on the behavior of similar visitors who did consent. Google calls this *behavioral modeling for consent mode*.

This modeling only happens once a property has enough volume: at least 1,000 events per day with `analytics_storage=denied` over a 7-day period, and at least 1,000 daily users with granted consent on at least 7 of the last 28 days. Below those thresholds GA4 shows no modeled data and the result stays the same as Observed.

**Pros for reading your data**

* Fills the gap left by cookie banners/consent refusal, so sessions, users and conversions sit closer to reality than the other two options — especially relevant with a low consent rate.
* Best cross-device coverage: links visits across multiple devices to a single user whenever a User-ID or Google signals are available.

**Cons for reading your data**

* Modeled data is a statistical estimate, not a count — reports show a data-quality icon once estimated data is included, but beyond that most standard reports don't show which part of a number is modeled.
* Modeled behavioral data isn't used in: audiences, some Exploration types, sequenced segments, Loyalty reports, predictive metrics, and BigQuery export — there you only see the observed portion.
* Yesterday's data is often not (fully) modeled yet — day-over-day comparisons can look different on day one versus a few days later.
* Because User-ID takes priority over `client_id` here, this option is the most sensitive to mistakes in how User-ID is supplied (see the caveat below).

### Option 2 — Observed

Observed uses the same hierarchy as Blended (User-ID → Google signals → device ID), but without the modeling step for consent gaps. Whatever wasn't observed simply stays missing instead of being estimated.

**Pros for reading your data**

* Still has cross-device recognition via User-ID/Google signals, so it's better than Device-based for clients with logged-in accounts or Google signals.
* All numbers are purely observed — no modeling, so no uncertainty about "is this number partly estimated".

**Cons for reading your data**

* No compensation for consent refusal: with a low consent rate this can come out noticeably lower than Blended, purely from visitors who aren't counted.
* Same sensitivity to User-ID mistakes as Blended, because User-ID also takes priority over `client_id` here.

### Option 3 — Device-based

Device-based uses only `client_id` (the cookie/device ID). User-ID and Google signals are ignored entirely, even if they are being sent.

**Pros for reading your data**

* Simplest, most predictable count: one `client_id` equals one "user", always based on what actually comes in.
* Immune to mistakes in the User-ID implementation, since User-ID simply isn't taken into account — a wrong or inconsistent User-ID can't do any damage here.

**Cons for reading your data**

* No cross-device linking: the same person on phone and laptop counts as two users.
* No compensation for consent refusal — usually the lowest numbers of the three, especially with a lot of cookie refusals.

### Caveat: User-ID mistakes can throw off counts under Blended/Observed

Because Blended and Observed give User-ID priority over `client_id`, how you supply User-ID determines whether switching to one of these two options improves your data or distorts it.

GA4's User-ID is a reserved, top-level field, meant only for a stable identifier of logged-in users, set consistently (for example via `gtag('config', ...)` before other events, and reset to `null` on logout). If a User-ID value doesn't meet those requirements — for example because it doesn't belong to the same session/`ga_session_id` as the rest of the visit, or because it's actually an internal matching ID that happens to also be called `user_id` — GA4 can end up counting events that actually belong to the same visit separately, under a different "Effective User ID". Concretely: purchase events that normally get deduplicated on `transaction_id` within one session can get double-counted as soon as you switch from Device-based to Blended/Observed — purely because of how User-ID was supplied, not because of any change in actual visitor behavior.

See the **Webhook Matching** article for a concrete example of this: accidentally forwarding AdPage's internal BasketKey matching ID as GA4's `user_id`.

### Which option should you pick?

* **Default advice:** leave Blended (the GA4 default) in place as long as User-ID is used correctly and consistently — or not sent at all. This gives the most complete numbers.
* **When in doubt about the User-ID implementation** (for example while investigating a measurement discrepancy): temporarily switch to Device-based to check whether a discrepancy disappears. If it does, the problem is in the User-ID mapping, not in the underlying tracking data.
* **No User-ID used or wanted at all** (e.g. a purely anonymous B2C shop without accounts): Observed and Device-based then give the same result as Blended without modeling — choose based on whether or not you want the consent modeling.

### Source

Based on [\[GA4\] Behavioral modeling for consent mode](https://support.google.com/analytics/answer/11161109?hl=nl\&utm_id=ad) (Google Analytics Help).


# Conversion recovery

Let AdPage send the purchases your Google Ads tag missed to Google Ads after all, through Google's Data Manager API, without an extra tag in your server container.

Your Google Ads tag does not see every purchase. A visitor pays in their banking app and never returns to the thank-you page, closes the tab too early, or comes back in a different browser. [Webhook Matching](/optimize-your-setup/webhook-matching) already links those orders to the visit they belong to. Conversion recovery sends them on to Google Ads.

AdPage sends each purchase itself, through Google's Data Manager API, with the order's click id and hashed customer data. You do not build or import a tag for it in your server container.

Google deduplicates on the order number. A purchase your tag already sent counts once, so keep your conversion tag: Conversion recovery is an extra source on the same conversion action.

## What you need

* **Webhook Matching** is on. Conversion recovery runs on the matched order webhooks.
* A **conversion action** in the Google Ads account, usually your primary purchase action. See [Where to find the Google Ads Conversion ID and Conversion Labels](/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels) if you still need to create one.
* A way for AdPage to reach the Google Ads account: the account is linked to AdPage's manager account (MCC), or Google Ads is connected for the container under **Integrations**.
* The **Performance** plan or higher. On a lower plan the page shows **From Performance**. AdPage support can open it for your account.

## Set it up

You find it in your container under **Data boosts**, on the **Boosts** tab, at **Conversion recovery**.

1. Under **Settings**, choose the **Google Ads account**.
2. Choose the **conversion action**. Pick the action Smart Bidding optimises for, and use the same action in the tag on your site. With two different actions Google does not deduplicate the two. The action your tag already sends to is marked **your tag**.
3. Choose **which Google login** AdPage delivers with, see below.
4. Click **Test connection**. Google checks a test conversion without anything landing in your account. **View the latest order** shows what AdPage would send for the latest order.
5. Switch on **Send to Google Ads**. The status changes to **Active**.

There is no Save button: a change is stored right away. If you choose another account, the conversion action is cleared and sending switches off, so you choose it again.

{% hint style="warning" %}
**Does your tag send the order number without a prefix?** If Webhook Matching uses a transaction ID prefix, switch on **Remove order prefix**. Google only recognises the same order when both sources send the same order number.
{% endhint %}

{% hint style="info" %}
If AdPage's MCC shows an account whose conversion actions do not match the conversion ID your tag sends to, AdPage warns you. Check that the account belongs to this customer before you click **Use this account anyway**.
{% endhint %}

## What is sent

Per purchase: the order number, value and currency, the time of the purchase, the click id (`gclid`, `gbraid` or `wbraid`), hashed customer data (email address, name and address), device and IP, and whether it is a new or returning customer when your webshop knows it.

* Only purchases are sent. Other events are skipped.
* Only with consent for advertising. Without it nothing goes to Google.
* Email address, name and street leave AdPage hashed with SHA-256 only.
* An order with neither a click id nor customer data is not sent: Google would have nothing to match it with.

## Which Google login

| Choice                        | When                                                                                                                                                                                                 |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Through AdPage's MCC**      | The default. The Google Ads account is under AdPage's manager account.                                                                                                                               |
| **With the own Google login** | The account is under your agency's manager account (MCC), not under AdPage's. AdPage then delivers with the Google login connected for this container under Integrations. No link request is needed. |

If Google refuses the test through AdPage's MCC with a 403, the account is not under that MCC. The test then shows what you can do:

* **Send link request from AdPage**, and accept it in Google Ads under **Admin → Access and security → Managers**. Then test again.
* **Deliver with the own Google login**, for an account under your agency's manager account.

The own Google login needs the permission to send conversions. If it does not have it, a notice with **Reconnect** appears. Click it, sign in with **the same Google account** and tick every box. Your account choice under Integrations stays.

## A separate account per domain

Does your webshop have several domains, each with its own Google Ads account, for example one domain per country? Then link each domain to its own account under **Per domain**. That section appears once the account and conversion action above are chosen.

* An order goes to the account of the domain it checked out on in the browser. A subdomain falls under its domain: an order on `m.shop.com` goes to the account of `shop.com`.
* A domain without its own line, or an order without a domain, goes to the account above.
* All domains use the same Google login.

1. Click **Add the domains of your tag**. AdPage lists the domains your Google Ads tag sent purchases from, with the account named after the domain when there is exactly one. Add a single line with **Add domain**.
2. Choose the **account** and the **conversion action** for each domain. AdPage picks the action your tag on that domain already sends to.
3. A domain is saved as soon as it has an account and an action. Below the list you see how many domains are not done yet.
4. Click **Test all domains**. An error shows next to its domain, and below the list how many domains are OK.

## Read the results

The top of the page measures the last 7 days. It matches the orders from your webshop, by order number, to the conversions your server container sent to Google Ads.

| Tile                        | What it tells you                                                                                                              |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| **Recovered by AdPage**     | The share of your orders that your tag missed, Conversion recovery sent and Google processed, with the number and the revenue. |
| **Processed by Google**     | What Google processed of everything that reached Conversion recovery.                                                          |
| **Attributed to campaigns** | What Google Ads counts on the conversion action, on the day of the purchase, with the conversion value.                        |

Click a tile to see what is behind it: the orders per outcome, the campaigns and a table per day.

An order ends up in one of these rows:

* **Your tag sent the conversion**. Nothing to recover.
* **Recovered by AdPage**. Your tag missed it, AdPage sent it and Google processed it.
* **Waiting for Google**. Google took the request but has not given a final status yet.
* **Missed, not recovered**, with the reason below.
* **Missed, unknown**. From before AdPage kept track of this.

{% hint style="info" %}
A conversion your site fires directly with gtag.js, outside the server container, is invisible to AdPage and counts as missed here.
{% endhint %}

### Why an order was not recovered

| Reason                                | What it means                                                                                            |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| **No consent for ads**                | The visitor did not consent to advertising. Nothing is sent.                                             |
| **No click id and no customer data**  | Google would have nothing to match the purchase with.                                                    |
| **Match not certain enough**          | Webhook Matching linked the order to a visit as a probable match only. Those are not sent to Google Ads. |
| **Rejected by Google**                | Google refused the purchase, see the reasons below.                                                      |
| **Failed at AdPage**                  | Sending did not work, for example because the Google login was not available.                            |
| **Never reached Conversion recovery** | Webhook Matching did not match the order, or Conversion recovery was off at the time.                    |

When Google refuses a purchase, the page gives Google's reason:

| Google's reason                                    | What it means                                                                                     |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| **Click id not valid for this account**            | The click belongs to another Google Ads account. Check the account, or set an account per domain. |
| **Google already had this order number**           | Another source sent the same order first. It counts once.                                         |
| **Google already had this click for this action**  | Google already counted a conversion for this click on this action.                                |
| **Too old for Google**                             | The click or the purchase is too old for Google to accept.                                        |
| **No consent according to Google**                 | Google has no consent for this user.                                                              |
| **Customer data terms not accepted in Google Ads** | Accept the customer data terms in the Google Ads account.                                         |
| **No final status from Google within 48 hours**    | Google never confirmed the request. If this happens often, contact support.                       |

{% hint style="warning" %}
**Does Google Ads count more than AdPage sent?** Then other sources send to the same action too, for example an older upload tag in your server container. If that source uses a different order number, a purchase counts twice. Remove the old tag or point it at another action.
{% endhint %}

### An import action

If the chosen conversion action is an import action, your tag cannot send to it. Everything the action gets comes from AdPage. The page then shows what AdPage sent and what Google did with it, not what it recovered.

## Coming from the AdPage Google Ads tag

Older setups upload purchases with the **AdPage Google Ads tag** in the server container. That tag takes a conversion action ID and a Tagging API key, and sends through the Google Ads API (`UploadClickConversions`).

Since June 2026 Google only allows that call for accounts that already used it, and points new integrations to the Data Manager API. For a new setup, use Conversion recovery instead. A `400` with **Customer ID not found** in Preview means the upload was never switched on for the container. The tag has no field for it.

1. Set up [Webhook Matching](/optimize-your-setup/webhook-matching), so the order webhook is matched to the visit and its click id.
2. Set up Conversion recovery as described above, with the same conversion action.
3. Pause the AdPage Google Ads tag in your server container. Left on, it keeps failing, or it counts purchases twice if it sends a different order number.

## Need help?

Contact support at <support@adpage.io> with the container ID and the order number of a purchase that did not arrive.


# Profit on Ad Spend

Optimize your advertising platforms based on your profit margin instead of your revenue.

Most webshops let their ad platforms bid on revenue. But an order of € 200 with a € 20 margin is worth less to you than an order of € 80 with a € 40 margin, and your ad platform cannot tell the difference unless you tell it.

Profit on Ad Spend sends the profit on every order along with the purchase, so you can optimize on what you actually keep.

## What you need

One thing: a purchase price per product. There are three ways to give us that, and they can be used together.

|            | Shopify cost per item                       | Magento catalogue                    | XML purchase-price feed               |
| ---------- | ------------------------------------------- | ------------------------------------ | ------------------------------------- |
| Works on   | Shopify only                                | Magento only                         | Any platform                          |
| Comes from | the **Cost per item** field on each variant | the `cost` attribute on each product | a feed you generate yourself          |
| Setup      | connect Shopify, fill in cost per item      | connect Magento, fill in `cost`      | generate a feed, fill in three fields |

None is better in general. A shop platform you have already connected is the least work; a feed works everywhere. Use several and they add up.

Everything you set up in AdPage for this lives on one screen: **Data boosts → Profit on Adspend** in your container.

## How the profit reaches your tags

|                           | The AdPage variable                                                                            | The existing setup                 |
| ------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------- |
| Cost source               | Shopify, Magento, feed, or a combination                                                       | feed only                          |
| Parameters                | `cost_of_goods`, `shipping_cost`, `payment_cost`, `other_cost`, `gross_profit`, `profit_value` | `purchase_price`, `profit_margin`  |
| VAT                       | calculated excluding VAT for you                                                               | you build the subtraction yourself |
| Shipping and payment cost | included                                                                                       | not included                       |

The existing setup keeps working and you do not have to change anything. Setting up a new container, or running on Shopify or Magento? Use the variable.

Google Ads can also get the profit without a tag: AdPage then sends it itself, see [Profit straight to Google Ads](/optimize-your-setup/profit-on-ad-spend/profit-straight-to-google-ads).

## Set it up

1. Choose your cost source — Shopify, catalogue, feed, or a combination
2. The variables — what each parameter means and which setup fills it
3. Cost Items — shipping, payment and other costs per order
4. Set up the server container — the variable, and checking it in preview
5. GA4 and Google Ads — register the metrics and bid on profit
6. Profit straight to Google Ads — or let AdPage send the profit to Google Ads itself, also per domain
7. Troubleshooting — when the number looks wrong

Using the dashboard in Dutch? The Dutch glossary lists every label these pages quote, with its Dutch name.

{% hint style="info" %}
Step 2 is worth reading even if you are in a hurry. Profit on Ad Spend can produce a perfectly plausible number that rests on an estimate rather than on your cost prices, and that page tells you how to spot the difference.
{% endhint %}


# Choose your cost source

Profit on Ad Spend needs a purchase price per product. It can come from Shopify, from your Magento catalogue, from an XML feed, or from a combination.

Everything else on this page depends on one thing: we need to know what a product cost you. There are three ways to tell us, they can be used together, and none is better in general — it depends on your platform.

{% hint style="info" %}
This page quotes the dashboard in English. Using it in Dutch? See the [Dutch glossary](/optimize-your-setup/profit-on-ad-spend/dutch-glossary) for every label.
{% endhint %}

|                       | Shopify cost per item                       | Magento catalogue                    | XML purchase-price feed               |
| --------------------- | ------------------------------------------- | ------------------------------------ | ------------------------------------- |
| Works on              | Shopify only                                | Magento only                         | Any platform                          |
| Comes from            | the **Cost per item** field on each variant | the `cost` attribute on each product | a feed you generate yourself          |
| You change a price in | Shopify                                     | Magento                              | the tool that generates the feed      |
| How fresh             | re-read nightly                             | re-read on every sync                | re-read once per hour                 |
| Setup                 | connect Shopify, fill in cost per item      | connect Magento, fill in `cost`      | generate a feed, fill in three fields |

{% hint style="info" %}
**AdPage does not store a price you type in.** The purchase price always comes from one of the sources above, so to change a cost price you change it at the source. AdPage picks it up on the next sync — or straight away with **Sync now** on the Profit on Adspend screen.
{% endhint %}

Use several and they add up: a product id known in both a shop platform and the feed takes the shop figure, because that is your own bookkeeping rather than an export of it. Ids that only exist in the feed — variants, EANs, products from another shop — are added on top.

{% hint style="info" %}
No cost source at all? Then Profit on Ad Spend has nothing to work with. A fallback margin can stand in for products whose cost we do not know, but a margin is an estimate, not a measurement. See The variables for how to tell the two apart.
{% endhint %}

## The Profit on Adspend screen

Everything you set up in AdPage for Profit on Ad Spend is on one screen: open your container at [data.adpage.io](https://data.adpage.io), go to **Settings → Profit on Adspend** and click **Open Profit on Adspend**. Or go straight to `https://data.adpage.io/containers/<your container id>/profit-on-adspend`.

On that screen you find, top to bottom:

| Block                                                 | What it does                                                                                                                                                               |
| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **On / Off** switch                                   | Turns Profit on Ad Spend on or off for this container                                                                                                                      |
| **Mode**                                              | **Standard** reads the XML feed per order when the purchase webhook comes in. **Advanced** syncs your costs, and adds cost items, the GTM variable and Data Studio reports |
| **Product feed** (Advanced) / **XML feed** (Standard) | Feed URL and the two columns we read, plus the sync status: how many products have a cost price                                                                            |
| **Cost items**                                        | Shipping, payment and other costs per order — see Cost Items. Advanced only                                                                                                |
| **Set up in Google Tag Manager**                      | The lookup token and instructions for the GTM variable. Advanced only                                                                                                      |
| **Check on a real order**                             | Shows the profit calculated on a real order, so you can check the result. Advanced only                                                                                    |

## Shopify cost per item

Shopify already stores a purchase price per variant, so on Shopify there is nothing to generate and nothing to export.

{% stepper %}
{% step %}

#### Fill in Cost per item

In Shopify, open a product and scroll to the variant's **Inventory** section. **Cost per item** is the field we read. A variant without it has no known cost.

Shopify stores this **excluding VAT**, which is the basis Profit on Ad Spend calculates in. Include your import duties and other landed costs here — that is what makes it a purchase price rather than a supplier price.
{% endstep %}

{% step %}

#### Connect Shopify and approve the permissions

Connect the Shopify integration for this container. See [Shopify](https://docs.adpage.io/data-and-insights/marketing-integrations/shopify) for the connection itself.

Reading cost prices needs the **read\_inventory** permission. Stores that installed AdPage before that permission existed do not have it, and Shopify then answers with an access error rather than with zero costs.

If you connected a while ago, open the AdPage app once from your Shopify admin and approve the permissions it asks for. That one-off re-consent is all it takes.
{% endstep %}

{% step %}

#### Turn on Profit on Ad Spend

Open the [Profit on Adspend screen](#the-profit-on-adspend-screen), switch it **On** and choose **Advanced**. (The same switch is also on the **Send Profit on Adspend profit** card under **Webhook Matching**.)

You should end up with a line like "20565 products with a cost price". That number is the check: far below your catalogue size means most variants have an empty **Cost per item**.
{% endstep %}
{% endstepper %}

**Which keys a Shopify cost lands under.** Every priced variant is stored under both its SKU and its variant id, so an order line matches on whichever of the two it carries. A product id is added as well, but only when every variant of that product has the same cost — otherwise an order line carrying nothing but a product id would silently get one variant's price for all of them. Variant-priced products are the normal case, and there the product id is deliberately left out.

## Magento catalogue

{% stepper %}
{% step %}

#### Fill in the cost attribute

In Magento, every product has a `cost` field (Product → Advanced Pricing → Cost). Profit on Ad Spend reads that field, so a product without it has no known cost.

Costs here are **excluding VAT**, which is what Magento stores by default.
{% endstep %}

{% step %}

#### Connect Magento to AdPage

In your AdPage dashboard, connect the Magento integration for this container. No feed, no export, no extra tooling.
{% endstep %}

{% step %}

#### Turn on Profit on Ad Spend

Open the [Profit on Adspend screen](#the-profit-on-adspend-screen), switch it **On** and choose **Advanced**. Switching it on pulls the catalogue straight away. (The same switch is also on the **Send Profit on Adspend profit** card under **Webhook Matching**.)

You should end up with a line like "Active · 4274 products with a cost price from the Magento catalogue". That number is the check: if it is far below your catalogue size, most products have an empty `cost` field.
{% endstep %}
{% endstepper %}

## XML purchase-price feed

Works on any platform, and is the only option outside Shopify and Magento.

{% stepper %}
{% step %}

#### Generate an XML feed

An XML feed is a file containing information about a webshop's products, in a format different systems can read automatically. Change a price in your webshop and every connected system sees the change, without anyone updating it by hand.

You can generate one with Channable, a WooCommerce plugin, or a similar tool. It needs to contain at least a product id and a purchase price per product. The feed must be reachable without logging in.
{% endstep %}

{% step %}

#### Fill in the feed on the Profit on Adspend screen

Open the [Profit on Adspend screen](#the-profit-on-adspend-screen) and fill in the **Product feed** block (called **XML feed** in Standard mode):

* **Feed URL** — where the feed can be downloaded.
* **Product ID column** — the field holding the product id, for example `g:id`. This id must match the `item_id` in your incoming GA4 event requests. If you have not changed the `item_id` parameter in your GA4 event tags, that is the `item_id` from your dataLayer.
* **Cost price column** — the field in the feed holding the purchase price, for example `g:cost_of_goods_sold` or `g:custom_label_2`.

Click **Save feed**. In Advanced this syncs right away, so you immediately see how many products got a cost price.

**Finding the item\_id in the dataLayer.** Open your webshop and go to a product page. Inspect the page, go to the **Console** tab and type `window.dataLayer`. Find the `view_item` event and read the `item_id` of the product you are looking at.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FLGgKUgd6Xu3YIIwr9g3d%2Fimage.png?alt=media&#x26;token=e134c0de-b898-493d-ada3-ae77fdaa7c7f" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Tell us whether your feed prices include VAT

Purchase prices in a feed are sometimes listed including VAT and sometimes excluding it, and only you know which. Profit on Ad Spend calculates a pure ex-VAT margin, so if your feed lists prices including VAT, go to **Webhook Matching**, tick **The purchase prices in my feed include VAT** on the **Send Profit on Adspend profit** card, and fill in the **VAT percentage**.

Get this wrong and nothing breaks — your margin is simply off by the VAT rate. If the numbers look consistently too high or too low, check this setting first and re-sync.
{% endstep %}
{% endstepper %}

## Which ids have to match

Whichever source you use, a cost is only found when the product id we receive matches the id we have a cost for. We try every identifier an order line carries — `item_id`, variant id, `sku`, `item_sku` — and use the first one with a known cost, so a mismatch on one key can still resolve on another.

Whether that actually worked on a real order is visible in preview. See Set up the server container.

## What else comes off the margin

A cost source covers the products. Shipping, payment and packaging are set separately, on the same Profit on Adspend screen — see Cost Items.


# The variables

What each Profit on Ad Spend parameter means, which VAT basis it uses, and which setup fills it.

Profit on Ad Spend produces two sets of parameters. Which one you get depends on how you set up your server container — see Set up the server container.

## The recommended set

These come from the **AdPage Profit on Ad Spend** variable. All of them are order-level, in the event currency, and calculated **excluding VAT**.

| Parameter       | What it is                                                                       |
| --------------- | -------------------------------------------------------------------------------- |
| `cost_of_goods` | What the products on this order cost you                                         |
| `shipping_cost` | Shipping cost for this order, from your Cost Items settings                      |
| `payment_cost`  | Payment cost for this order, from your Cost Items settings                       |
| `other_cost`    | Your other per-order cost lines — packaging, returns handling, a marketplace fee |
| `gross_profit`  | Revenue excluding VAT, minus `cost_of_goods`                                     |
| `profit_value`  | `gross_profit`, minus shipping, payment and other cost                           |

Alongside them you get two fields that tell you how much to trust the numbers:

| Field      | What it tells you                                                                                                                             |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `coverage` | How many order lines had a real cost price (`matched`), how many fell back to your margin (`fallback`), and how many had neither (`unpriced`) |
| `source`   | Whether the figures come from the matched order webhook (`stash`) or were calculated from the event itself (`computed`)                       |

{% hint style="info" %}
**Why revenue is taken excluding VAT.** Your purchase prices are excluding VAT, so the revenue they are subtracted from has to be as well. We use `value` minus `tax`. An order of € 21.66 including 21% VAT is calculated against € 17.91.
{% endhint %}

**`profit_value` equal to `gross_profit`?** That is not a bug. It means Cost Items is switched off, so shipping, payment and other cost are all zero and there is nothing to subtract. See [Cost Items](/optimize-your-setup/profit-on-ad-spend/cost-items).

## The existing set

These come from the older manual setup and still work. They need an XML feed; a container whose costs come from the Shopify or Magento catalogue never gets them.

| Parameter        | What it is                                              |
| ---------------- | ------------------------------------------------------- |
| `purchase_price` | Total purchase price of the order, summed from the feed |
| `profit_margin`  | A value you build yourself in Google Tag Manager        |

{% hint style="warning" %}
Without a feed, `purchase_price` is **0.00** on every purchase. Not an error, and nothing in the interface points it out — the parameter is simply there with nothing in it. If you see zeroes everywhere, check whether a feed is configured at all.
{% endhint %}

## Which setup fills what

|                                   | Shopify cost per item | Magento catalogue | XML feed |
| --------------------------------- | --------------------- | ----------------- | -------- |
| `cost_of_goods` … `profit_value`  | yes                   | yes               | yes      |
| `purchase_price`, `profit_margin` | no                    | no                | yes      |

Running both sets at once is fine, as long as you do not send two of them to the same metric. See Troubleshooting.


# Cost Items

Shipping, payment and other per-order costs, subtracted from your margin so profit\_value is what you actually keep.

`cost_of_goods` covers what the products cost you. Everything else an order costs — the parcel, the payment provider, the packaging — is a **cost item**.

Switch cost items on and three parameters start filling: `shipping_cost`, `payment_cost` and `other_cost`. Leave them off and all three are zero, which is why `profit_value` would equal `gross_profit`.

{% hint style="info" %}
This page quotes the dashboard in English. Using it in Dutch? See the [Dutch glossary](/optimize-your-setup/profit-on-ad-spend/dutch-glossary) for every label.
{% endhint %}

## Where to find it

Cost items, the purchase-price feed and the on/off switch all live on one screen in the AdPage dashboard: **Profit on Adspend**.

{% stepper %}
{% step %}

#### Open your container

Log in at [data.adpage.io](https://data.adpage.io) and open the container you want to set up.
{% endstep %}

{% step %}

#### Go to Profit on Adspend

Open the container **Settings** and pick **Profit on Adspend** in the menu (*Feed, cost items and mode*). Click **Open Profit on Adspend**.

The screen lives at `https://data.adpage.io/containers/<your container id>/profit-on-adspend`, so you can also bookmark it.
{% endstep %}

{% step %}

#### Make sure the mode is Advanced

At the top, under **Mode**, choose **Advanced**. Cost items are only available in Advanced: in Standard mode the screen shows *Cost items are not available in this mode* and the margin stays at revenue minus purchase price.
{% endstep %}

{% step %}

#### Fill in the cost items

Scroll to the **Cost items** block, switch on **Subtract cost items**, fill in the blocks below and click **Save cost items**.
{% endstep %}
{% endstepper %}

{% hint style="info" %}
**Looking for the purchase price per product?** That is not a cost item. The purchase price (`cost_of_goods`) comes from your shop or a feed, and is managed there:

| Your cost source | Where you change the purchase price                                                                                                                 |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Shopify          | In Shopify: product → variant → **Cost per item**                                                                                                   |
| Magento          | In Magento: product → Advanced Pricing → **Cost**                                                                                                   |
| XML feed         | In the tool that generates your feed. The feed URL and column names are set on the same **Profit on Adspend** screen, in the **Product feed** block |

See Choose your cost source for the details.
{% endhint %}

## The three blocks

| Block                 | What belongs in it                                                                |
| --------------------- | --------------------------------------------------------------------------------- |
| **Shipping costs**    | What the carrier charges you. Fulfilment belongs here too — it is the same parcel |
| **Payment costs**     | What your payment provider charges per transaction                                |
| **Other order costs** | A free list: packaging, returns handling, a marketplace fee                       |

Each block is either **Flat + percentage**, or **Per method** (a table per method).

{% hint style="warning" %}
**Do not enter the same cost twice.** Fulfilment in *Shipping costs* and a € 5 "Fulfilment" line under *Other order costs* both get subtracted, and your margin is € 5 per order too low. Nothing errors — the number is simply wrong. The total at the bottom of the block is the only place this shows up, so check it.
{% endhint %}

## A table per method

A flat amount is an average, and an average is wrong on every individual order. If PostNL costs you € 4 and DHL € 8, a table charges each order what it really cost.

The method is looked up in one of two fields, depending on the block:

| Field             | Filled from                                                               |
| ----------------- | ------------------------------------------------------------------------- |
| `shipping_method` | Shopify's shipping line title, or `shipping_lines[].title` in the webhook |
| `payment_type`    | Shopify's payment gateway, or `payment_gateway_names` in the webhook      |

Using GA4's `shipping_tier` in your dataLayer? Then you are already covered: the AdPage variable sends `shipping_tier` as the shipping method when it is present, so a table on `shipping_method` matches your tiers.

## Get the spelling right

The method on the order is matched against your table as an exact string. `Mollie - iDEAL` typed by hand next to the real `mollie - ideal` silently gives you the fallback rate rather than the one you entered — no warning, just a different number.

So do not type them. With Shopify connected, the editor reads the methods your shop actually used over the last 30 days and lists them under **Found in Shopify**. Click those. Without Shopify, the same list comes from your own order webhooks (**Found in webhooks**).

A method missing from the list simply has not occurred recently; add it by hand and copy the spelling from an order.

## The fallback

Every table has a **Fallback**, used for a method that is not in it. Leave it at 0 and an unknown method costs you nothing in the calculation — which flatters the margin. A realistic average is the safer setting.

## Product without a cost price

Below the cost items you choose what happens to a product that is not in your feed or catalogue: **Count as free** (the order counts as full profit for that product) or **Estimate with a gross margin**. Count as free is only right when your cost source is complete.

## Per order, not per parcel

All of this is charged **per order**. An order that ships in two parcels is still one order, so it is charged one shipping cost. No source tells us the number of parcels, so a per-parcel rate is not expressible; if that difference matters to you, raise the flat amount to your real average per order.

## What it changes

```
gross_profit = revenue excluding VAT − cost_of_goods
profit_value = gross_profit − shipping_cost − payment_cost − other_cost
```

Both the Profit dashboard and the purchase event use the same settings, so the two agree. To see the result on a real order, use **Check on a real order** at the bottom of the Profit on Adspend screen and click **Check an order**.

See The variables for what each parameter contains, and Troubleshooting when a cost comes out as zero.


# Set up the server container

Add the variables to your Google Tag Manager server container and check, in preview, that they carry real cost prices.

Two routes. The first works with either cost source and does the maths for you; the second is the older setup, still supported, feed only.

## Recommended: the AdPage Profit on Ad Spend variable

{% stepper %}
{% step %}

#### Create a lookup token

In your AdPage dashboard, go to **Webhook Matching → Settings → Send Profit on Ad Spend** and click **Create token**.

![The Lookup token on the Profit on Ad Spend card](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F2LRHVZcuZjXHhENWnFw9%2Fpoas-token.png?alt=media)

Each container has its own token and it unlocks that container's cost prices, so it belongs in your **server** container only. Never in a web container, never on your site.
{% endstep %}

{% step %}

#### Import the template

Download [adpage-profit-on-adspend.tpl](https://adpage.b-cdn.net/GTM-Templates/adpage-profit-on-adspend.tpl) — the same download sits next to the token in the dashboard.

In your server container, go to **Templates**, click **New** under Variable Templates, then the three dots in the top right → **Import**. Import the file and save.
{% endstep %}

{% step %}

#### Create the variable

Create a new variable with the imported template as its configuration. Two fields to fill in:

* **Container ID** — your AdPage container UUID, the same one as on the Event Notifier tag. Not the GTM container id.
* **Lookup token** — the token from step 1.

![The AdPage Profit on Ad Spend variable configuration](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FvBAEPgrGnNNkTokSieCu%2Fpoas-variable.png?alt=media)

Everything else has a working default. *Return* decides which field the variable gives back; *Where the number comes from* can stay on **Auto**.
{% endstep %}

{% step %}

#### Add it to your GA4 purchase tag

Add the variable as an event parameter on the tag you want the profit on. Use the parameter name that matches what you selected under *Return* — `profit_value` for net profit, `gross_profit` for gross.
{% endstep %}
{% endstepper %}

## Existing setup: total purchase price and profit margin

Still supported and unchanged. Requires an XML feed.

{% stepper %}
{% step %}

#### Add the total purchase price variable

1. Download this variable template: [template](https://drive.google.com/file/d/1ksyCJc4jv2W7ldNGOPinSHIfMhKPCYSE/view).
2. Open your GTM server container and go to **Templates**. Click **New** under Variable Templates.
3. Click the three dots in the top right, then click **Import**. Import the template you just downloaded and save it.
4. Create a new variable. Choose the variable template you just imported as the variable configuration and save this variable.
   {% endstep %}

{% step %}

#### Add the profit margin variable

1. Go to **Templates** and add a new Variable Template by searching the template gallery. Look for the **Number & String Operations** template and add it to your workspace.\ <br>

   <figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fknywtmg8vdlU9HC64qTK%2Fimage.png?alt=media&#x26;token=ea3b2b22-b650-49e9-97dd-7012f07696f4" alt=""><figcaption></figcaption></figure>
2. Create a new variable with **Number & String Operations** as the variable configuration. Set the operation type to **Calculate** and the operation to **Subtract**. Parameter 1 is the eCommerce value (event data variable for `value`) and Parameter 2 is your total purchase price variable from the previous step. Save this variable as `profit_margin`.\ <br>

   <figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FbZMV2cWOpe0KvGL4Y39T%2Fimage.png?alt=media&#x26;token=15f2600f-88d5-4210-879e-41a5ff5c2ad1" alt=""><figcaption></figcaption></figure>

{% endstep %}

{% step %}

#### Add the variables to your GA4 (purchase) event tag

* `purchase_price`: value set to your total purchase price variable
* `profit_margin`: value set to your profit margin variable<br>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FX3G9T79Mdd1gDshatnpV%2Fimage.png?alt=media&#x26;token=b3f75e74-a9f0-4d3c-a3b3-975e9ed68bc1" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

## Validate in preview

Open your server container and turn on **preview mode**.

If you measure purchases through a webhook, replay one from the Webhook Logs. If you measure them from your web container through a GA4 event tag, complete a test purchase (this does not apply to Shopify).

**For the AdPage variable**, set *Return* to **all** for the duration of the test. You then see the whole object instead of a single number:

![The variable in preview, returning the full object](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fo5tIb3DkIcLn8ct8acBO%2Fpoas-preview.png?alt=media)

Look at **`coverage.matched`** before you look at the amount. It says how many order lines had a real cost price. If it is 0 while an amount still comes out, you are looking at the fallback margin rather than at your cost prices — an amount that looks right and is not. Set *Return* back afterwards.

**For the existing setup**, check that the `purchase_price` parameter is present on the **Event Data** tab and in the GA4 tag parameters.

{% hint style="info" %}
Nothing there? Work through [Troubleshooting](/optimize-your-setup/profit-on-ad-spend/troubleshooting).
{% endhint %}


# GA4 and Google Ads

Make the profit parameters visible in Google Analytics 4 and bid on them in Google Ads.

The parameters now reach your tags. Two more steps to make them usable.

## Google Analytics 4

GA4 drops parameters it does not know, so register them before you go looking for them in a report.

Go to **Admin → Custom Definitions** and add a **Custom Metric** for each parameter you send. Metric name and parameter name are the same.

| Parameter       | Unit of measurement |
| --------------- | ------------------- |
| `profit_value`  | Currency            |
| `gross_profit`  | Currency            |
| `cost_of_goods` | Currency            |
| `shipping_cost` | Currency            |
| `payment_cost`  | Currency            |

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FkoV6vBN3SY5CyxRwfFD0%2Fimage.png?alt=media&#x26;token=24874f6a-6f60-44ef-9a52-676614bb1c22" alt=""><figcaption></figcaption></figure>

Pick the right **Unit of measurement** and **Data Type** so GA4 can tell cost data and revenue data apart.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FbU7p1edlifLPPlQUuh0p%2Fimage.png?alt=media&#x26;token=4e901546-0836-4ca4-a68d-98291c10a324" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
On the existing setup the two metrics are `purchase_price` and `profit_margin` instead. Register whichever set you actually send — registering both is fine, but do not send both to the same metric.
{% endhint %}

Custom metrics only fill from the moment you create them. Yesterday's purchases stay empty, so give it a day before you judge the numbers.

## Google Ads

This is where Profit on Ad Spend earns its name: you let Google bid on profit instead of revenue.

{% hint style="info" %}
Rather not build a tag? AdPage can also send the profit to Google Ads itself, also with a separate account per domain: see [Profit straight to Google Ads](/optimize-your-setup/profit-on-ad-spend/profit-straight-to-google-ads).
{% endhint %}

Create a **new conversion action** in Google Ads, then a conversion tag that sends your profit variable as the conversion value instead of the order value.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FDctBiSX7ootPCWjMKKkS%2Fimage.png?alt=media&#x26;token=3ae79d44-6224-4cb1-a5f3-1d634990d183" alt=""><figcaption></figcaption></figure>

Use `profit_value` when you want the bid to account for shipping and payment cost, `gross_profit` when you only want product margin.

{% hint style="warning" %}
**Keep it as a separate conversion action.** Do not overwrite the value on your existing purchase conversion. You want to compare the two for a while before you hand your bidding over to the new one, and a separate action lets you switch back without losing history.
{% endhint %}

{% hint style="warning" %}
**Never send a profit of 0 as a conversion value.** A zero tells Google the conversion was worthless and it will bid away from whatever produced it. Leave the fallback value empty so the parameter is dropped when no profit is found, rather than sent as a zero.
{% endhint %}


# Profit straight to Google Ads

Let AdPage send the profit of every order to Google Ads itself, without a tag in your server container. Also with a separate Google Ads account per domain.

On [GA4 and Google Ads](/optimize-your-setup/profit-on-ad-spend/ga4-and-google-ads) you build a conversion tag yourself that sends the profit to Google Ads. It also works without a tag: AdPage then sends the profit of every order itself, as the conversion value of a dedicated conversion action in Google Ads.

It takes the same route as Conversion recovery: through Webhook Matching and Google's Data Manager API, with the order's click id and hashed customer data, and only with consent for advertising.

## What you need

* **Webhook Matching** is on. The profit per order comes along with the matched order webhook.
* **Profit** is on and cost prices are synced daily. Without profit on an order, AdPage sends nothing for that order.
* The **Performance** plan or higher.

## Set it up

You find it in your container under **Data boosts → Profit on Adspend**, at **Profit to Google Ads**.

1. Choose the **Google Ads account**.
2. Choose the **conversion action**. Use a dedicated action for profit: click **Create Profit (AdPage)**. AdPage creates an import action in the account that receives every order with its own profit. If that action already exists, the button reads **Choose Profit (AdPage)**.
3. Choose **which Google login** AdPage delivers with, see below.
4. Click **Test connection**. Google checks a test conversion without anything landing in your account. **View the latest order** shows what AdPage would send for the latest order.
5. Switch on **Send profit**.

The action is created as a secondary action, so it does not count in your bid strategy yet. When Smart Bidding should steer on profit, make **Profit (AdPage)** primary in Google Ads and your tag's purchase action secondary. Compare the two for a while first: with a separate action you can switch back without losing history.

{% hint style="warning" %}
**Do not choose an action your tag already sends purchases to.** The profit then stacks on top of revenue, and neither number is right. AdPage warns you when you pick such an action.
{% endhint %}

AdPage sends `profit_value`: the profit after cost price and after shipping, payment and other costs. A loss-making order counts with value 0, so Google learns it earned nothing. An order without any profit, because Profit was off or the order had no value, is not sent.

## Which Google login

| Choice                        | When                                                                                                                                                                                                 |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Through AdPage's MCC**      | The default. The Google Ads account is under AdPage's manager account.                                                                                                                               |
| **With the own Google login** | The account is under your agency's manager account (MCC), not under AdPage's. AdPage then delivers with the Google login connected for this container under Integrations. No link request is needed. |

If Google refuses the test through AdPage's MCC with a 403, the account is not under that MCC. The test then shows what you can do: send the account a link request, or switch to the own Google login.

The own Google login needs the permission to send conversions. If it does not have it, a notice with **Reconnect** appears. Click it, sign in with **the same Google account** and tick every box. Your account choice under Integrations stays.

{% hint style="info" %}
Reconnect for this permission with the button on this page. A connection made under Integrations does not ask for it if the login did not have it yet.
{% endhint %}

## A separate account per domain

Does your webshop have several domains, each with its own Google Ads account, for example one domain per country? Then link each domain to its own account under **Per domain**. That section appears once the account and conversion action above are chosen.

* An order goes to the account of the domain it checked out on in the browser. A subdomain falls under its domain: an order on `m.shop.com` goes to the account of `shop.com`.
* A domain without its own line, or an order without a domain, goes to the account above.
* All domains use the same Google login.

1. Click **Add the domains of your tag**. AdPage lists the domains your Google Ads tag sent purchases from, with the account named after the domain when there is exactly one. Add a single line with **Add domain**: choose the domain from the list, or **Another domain…** to type it yourself.
2. Choose the **account** and the **conversion action** for each domain. If **Profit (AdPage)** already exists in the account, AdPage picks it for you. Otherwise **New action: Profit (AdPage)** is at the bottom of the list of actions.
3. A domain is saved as soon as it has an account and an action. Below the list you see how many domains are not done yet.
4. Click **Test all domains**. An error shows next to its domain, and below the list how many domains are OK.

{% hint style="warning" %}
If your tag on a domain sends purchases to a conversion ID that is not in the chosen account, AdPage says so next to the domain. Usually the domain belongs to another account.
{% endhint %}

## What was sent

The page shows how many orders went to Google Ads with their profit in the last few days, and why the rest did not: no profit on the order, no consent for advertising, no click id and no customer data, an uncertain match, rejected by Google, or no own Google login with permission to send.

{% hint style="info" %}
Conversion recovery has the same choices for the Google login and per domain.
{% endhint %}


# Troubleshooting

What goes wrong with Profit on Ad Spend, and how to tell which one you have.

## Double counting

If you use webhook matching, the webhook route already puts `gross_profit` and `profit_value` on its own purchase event. Send the same parameter names from your browser purchase as well, both land in the same GA4 property, and your profit doubles.

Nothing warns you about this. The number is simply twice what it should be.

Decide per container which route delivers the profit — or give the browser variant different parameter names and keep them apart in your reporting.

## An amount that looks right but is not

A cost price is only found when the product id on the order matches an id we have a cost for. When no cost is found, the fallback margin fills the gap, and the result is an estimate wearing the same parameter name as a measurement.

Set *Return* to **all** in preview and read `coverage`:

```
coverage: {items: 3, matched: 3, fallback: 0, unpriced: 0}
```

`matched` is the number you want. If it is 0 while an amount still comes out, your ids do not line up — check the product id field of your feed, or whether the cost field is filled in Shopify or Magento.

## Shopify: zero cost prices, and nothing says why

Three different causes look identical from the outside, so check them in this order.

**The permission is missing.** Reading cost prices needs **read\_inventory**, which the app only started asking for once the feature existed. A store that installed AdPage before that does not grant it, and Shopify answers with an access error rather than with zero costs. Open the AdPage app once from your Shopify admin and approve the permissions it asks for.

**Cost per item is empty.** The permission is fine and Shopify simply has nothing to give. Open any product in Shopify, look at the variant's **Inventory** section, and check whether **Cost per item** is filled. This is the most common cause by far, and it is yours to fix in Shopify rather than in AdPage.

**The count is far below your catalogue size.** Some variants are priced and most are not. The line under the Profit on Ad Spend setting ("20565 products with a cost price from the Shopify catalogue") is the measurement; compare it with the number of variants you expect.

If all three look right and you still get nothing, contact <support@adpage.io> with the container and the myshopify domain — there is an admin check that walks these steps and reports which one failed.

## Shipping cost is the same on every order

You set up a table per shipping method, but every order is charged the fallback rate. That means no order is arriving with a shipping method on it, so nothing ever matches a row in your table.

The usual cause is a shop whose orders carry no shipping line at all — digital goods, local pickup, or a checkout that does not create one. Ask <support@adpage.io> to run the admin check on your container: it reports how many orders were read and which shipping and payment methods they actually carried. Zero methods against a positive order count settles it.

When your shop genuinely has no shipping methods to distinguish, a flat amount per order is the honest setting. A table that never matches is a fallback rate wearing a table's clothes.

## A method is in the table but is never charged

The lookup is an exact string match. `Mollie - iDEAL` typed by hand does not match the real `mollie - ideal`, so those orders quietly get the fallback rate instead.

Do not type method names. Click them from the **Found in Shopify** list in the Cost Items editor, which reads the methods your shop actually used.

## purchase\_price is 0.00 on every purchase

The existing setup needs an XML feed. Without one, the parameter is present and empty on every order, and nothing in the interface points it out.

Either connect a feed, or move to the AdPage Profit on Ad Spend variable, which also works from the Shopify or Magento catalogue.

## profit\_value equals gross\_profit

Cost Items is switched off, so shipping, payment and other cost are all 0 and there is nothing to subtract. Switch it on in your container settings.

## Nothing comes back at all on an order

The lookup answers `no_revenue` when the event carries no order value. Without revenue there is no margin to compute: only the cost side would be left, and that would come back as a negative number. A negative conversion value is worse in Google Ads than no value at all, so nothing is returned and your tag's own fallback stands.

Check that `value` is actually on the event. A genuine loss — revenue below cost — is not caught by this and does come through as a negative profit.

## A zero you cannot interpret

The fallback value of the variable is `0` by default, which you cannot tell apart from a genuine zero margin. Set *Value when nothing is found* to empty: the variable then returns nothing and the parameter is dropped instead of sent as a zero.

This matters most in Google Ads, where a zero conversion value is worse than no value at all.

A fallback the variable cannot read as a number — `0,5` with a comma, a stray letter — is treated the same as an empty one, so a typo there drops the parameter rather than sending something meaningless.

## 401 on the lookup

Two possible causes, and the answer deliberately does not say which: a wrong token, or Profit on Ad Spend switched off for this container. Check both.

Just created or replaced the token? Give it five minutes. The configuration is cached, so a new token needs a moment and an old one stays valid that bit longer.

## The margin is off by roughly the VAT rate

Purchase prices in a feed are sometimes listed including VAT. If you answered that question wrong when connecting the feed, every cost is off by the VAT rate and so is every margin.

Correct it in the feed settings and re-sync.

Costs from Shopify and Magento are read excluding VAT and have no such setting, so this one cannot happen to them.


# Dutch glossary

Using the AdPage dashboard in Dutch? Every Profit on Ad Spend label from these docs, with the Dutch label you see on screen.

These docs quote the AdPage dashboard in English. If your dashboard is set to Dutch, look up the label here. You can switch the language of the dashboard yourself under your account settings.

## Where to find it

| English                       | Nederlands                  |
| ----------------------------- | --------------------------- |
| Data boosts                   | Databoosts                  |
| Profit on Adspend (boost)     | Sturen op winstmarge        |
| Settings                      | Instellingen                |
| Profit on Adspend (menu item) | Profit on Adspend           |
| Feed, cost items and mode     | Feed, kostenposten en modus |
| Open Profit on Adspend        | Profit on Adspend openen    |
| Webhook Matching              | Webhook Matching            |
| Back to dashboard             | Terug naar dashboard        |

## The Profit on Adspend screen

| English                                   | Nederlands                                       |
| ----------------------------------------- | ------------------------------------------------ |
| On / Off                                  | Aan / Uit                                        |
| Mode                                      | Modus                                            |
| Standard                                  | Standaard                                        |
| Advanced                                  | Advanced                                         |
| Product feed                              | Productfeed                                      |
| XML feed                                  | XML-feed                                         |
| Feed URL                                  | Feed-URL                                         |
| Product ID column                         | Kolom met product-id                             |
| Cost price column                         | Kolom met kostprijs                              |
| Save feed                                 | Feed opslaan                                     |
| Sync now                                  | Nu synchroniseren                                |
| Last synced                               | Laatst gesynchroniseerd                          |
| products with a cost price                | producten met kostprijs                          |
| Cost items                                | Kostenposten                                     |
| Cost items are not available in this mode | Kostenposten zijn niet beschikbaar in deze modus |
| Switch to Advanced                        | Overstappen naar Advanced                        |
| Set up in Google Tag Manager              | Zetten in Google Tag Manager                     |
| GTM instructions and lookup token         | GTM-instructie en lookup token                   |
| Create lookup token                       | Lookup token aanmaken                            |
| Check on a real order                     | Controle op een echte order                      |
| Check an order                            | Controleer een order                             |
| Value sent                                | Meegestuurde waarde                              |

## Cost items

| English                                            | Nederlands                                         |
| -------------------------------------------------- | -------------------------------------------------- |
| Subtract cost items                                | Kostenposten aftrekken                             |
| Shipping costs                                     | Verzendkosten                                      |
| Payment costs                                      | Betaalkosten                                       |
| Other order costs                                  | Overige orderkosten                                |
| Flat + percentage                                  | Vast + percentage                                  |
| Per method                                         | Per methode                                        |
| Flat amount per order (€)                          | Vast bedrag per order (€)                          |
| Percentage of revenue (%)                          | Percentage van de omzet (%)                        |
| Field to look up the method in                     | Veld om de methode in op te zoeken                 |
| Found in Shopify                                   | Gevonden in Shopify                                |
| Found in webhooks                                  | Gevonden in webhooks                               |
| Fallback (used when the value is not in the table) | Fallback (gebruikt als waarde niet in tabel staat) |
| + Add cost line                                    | + Kostenregel toevoegen                            |
| Save cost items                                    | Kostenposten opslaan                               |
| Product without a cost price                       | Product zonder kostprijs                           |
| Count as free                                      | Tel als kosteloos                                  |
| Estimate with a gross margin                       | Schat met een brutomarge                           |
| Estimated gross margin (%)                         | Geschatte brutomarge (%)                           |

## The Profit on Adspend card under Webhook Matching

| English                                    | Nederlands                                        |
| ------------------------------------------ | ------------------------------------------------- |
| Send Profit on Adspend profit              | Profit on Adspend-winst meesturen                 |
| Open settings                              | Instellingen openen                               |
| The purchase prices in my feed include VAT | De inkoopprijzen in mijn feed staan inclusief btw |
| VAT percentage                             | Btw-percentage                                    |
| Lookup token                               | Lookup token                                      |
| Show token / Create token / Replace        | Token tonen / Token aanmaken / Vervangen          |
| Download template (.tpl)                   | Template downloaden (.tpl)                        |

## Profit to Google Ads

| English                     | Nederlands                    |
| --------------------------- | ----------------------------- |
| Profit to Google Ads        | Winst naar Google Ads         |
| Send profit                 | Winst sturen                  |
| Google Ads account          | Google Ads-account            |
| Conversion action           | Conversieactie                |
| Create Profit (AdPage)      | Winst (AdPage) aanmaken       |
| Choose Profit (AdPage)      | Winst (AdPage) kiezen         |
| Which Google login          | Langs welke Google-login      |
| Through AdPage's MCC        | Via de MCC van AdPage         |
| With the own Google login   | Via de eigen Google-login     |
| Reconnect                   | Opnieuw koppelen              |
| Test connection             | Test verbinding               |
| View the latest order       | Bekijk de laatste order       |
| Per domain                  | Per domein                    |
| Add the domains of your tag | Domeinen van je tag toevoegen |
| Add domain                  | Domein toevoegen              |
| Another domain…             | Ander domein…                 |
| New action: Profit (AdPage) | Nieuwe actie: Winst (AdPage)  |
| Test all domains            | Test alle domeinen            |

## Terms

| English        | Nederlands    |
| -------------- | ------------- |
| cost price     | kostprijs     |
| purchase price | inkoopprijs   |
| cost items     | kostenposten  |
| gross margin   | brutomarge    |
| revenue        | omzet         |
| excluding VAT  | exclusief btw |


# Google tag gateway (GTG)

What Google Tag Gateway does, how it compares to your AdPage server-side setup, and when to combine the two.

{% hint style="info" %}
**Google Tag Gateway (GTG)** is a Google product for loading Google tags in first-party. It's a different layer than your AdPage container — this article explains how the two fit together, and links to the setup guides below.
{% endhint %}

## Why first-party delivery matters

Two things are steadily eating into standard tag measurement:

* **Ad blockers.** A large share of visitors now run one. If a script like `gtm.js` is blocked because it's requested from a Google domain, the tags inside that container never fire — no page views, no add-to-cart, no purchase events.
* **Safari's ITP.** Safari treats cookies set by client-side JavaScript as tracking cookies once it decides they were set in a third-party context, and caps their lifetime at 7 days. A returning visitor after a week can look like a brand-new one, which quietly degrades attribution, remarketing audiences, and journey reporting.

## What Google Tag Gateway actually does

GTG puts a reverse proxy on your own domain. Instead of the browser requesting `googletagmanager.com/gtm.js`, it requests a path on your domain (e.g. `yourdomain.com/8kpl/gtm.js`), which is silently forwarded to Google and back.

That gets you:

* **Google scripts served first-party** — GTM, the Google tag, and Google Ads all load from your domain.
* **A partial reduction in ad-blocker impact** — blockers that key off the Google domain lose that signal. Blockers that key off the *shape* of the request (URL pattern, parameters) aren't affected.

What it does **not** get you:

* **No Safari fix.** GTG doesn't change *how* cookies are set — GA4 and GTM still write them via JavaScript, so Safari's 7-day cap still applies.
* **Google tags only.** GTG has no effect on Meta, TikTok, Snapchat, Pinterest, or LinkedIn.

## How this relates to your AdPage container

Your AdPage container already gives you a first-party tagging subdomain with a full server-side GTM environment behind it — that's what Setup AdPage container walks you through. GTG and AdPage solve overlapping but different problems:

|                                                      | GTG only                                                       | Your AdPage container          | GTG + AdPage |
| ---------------------------------------------------- | -------------------------------------------------------------- | ------------------------------ | ------------ |
| Google scripts served first-party                    | ✅                                                              | ✅ (via your tagging subdomain) | ✅            |
| Ad blocker reduction                                 | ⚠️ Partial                                                     | ✅                              | ⚠️ Partial+  |
| Safari 16.4+ resilience (cookies beyond 7 days)      | ❌                                                              | ✅ Server-set cookies           | ✅            |
| Meta / TikTok / Snapchat / Pinterest / LinkedIn CAPI | ❌                                                              | ✅                              | ✅            |
| Webhook matching & Data Assistant monitoring         | ❌                                                              | ✅                              | ✅            |
| Setup complexity                                     | <p>Low–medium<br><br>Depends on with or without claudflare</p> | Medium                         | Medium–high  |

{% hint style="success" %}
**In short:** GTG is a solid, low-effort first step for first-party delivery of Google's own scripts. It doesn't replace your AdPage container — for Safari resilience, non-Google platforms, data enrichment, and monitoring, you still need server-side tagging.
{% endhint %}

## Combining GTG with your AdPage setup

You don't have to choose one or the other. Two ways to combine them:

**Option A — GTG loads the tag, AdPage keeps its own endpoint (simplest).** GTG serves the Google tag/GTM script first-party via its measurement path. Events still flow to your existing AdPage tagging subdomain exactly as before — no changes to your webhook matching, consent setup, or server container.

**Option B — the measurement path as a single entry point (most "GTG-aligned").** The browser only ever talks to one path on your domain. Your reverse proxy then routes Google-bound traffic to GTG and everything else to your AdPage tagging subdomain. More routing work, but a cleaner single entry point.

For most setups, **Option A** is the practical choice — it adds first-party delivery for Google's scripts without touching anything in your existing AdPage configuration.

{% hint style="info" %}
**GTG and AdPage work better together.** Use GTG for Google’s first-party delivery, then use AdPage to activate your data across your marketing stack.

* **GTG** provides a **first-party delivery layer** for Google scripts and selected requests.
* **AdPage** provides a **server-side data layer** for collection, processing, and delivery to multiple destinations.

Together, GTG is the first-party **front door**. AdPage is the server-side **engine** that powers your marketing data.
{% endhint %}

## Benefits and limitations

**Partial reduction of ad blocker impact**

GTG serves scripts and some requests through your own domain. This can reduce blocks that only target Google domains.

This does not bypass every ad blocker. Some blockers inspect the request itself. They may block its URL, parameters, path, or type, even on your domain.

**Safari 16.4+: GTG does not bypass ITP**

Safari's Intelligent Tracking Prevention (ITP) limits JavaScript-set cookies to seven days. This applies even when the script loads from your domain.

Google Analytics 4 (GA4) and Google Tag Manager (GTM) set cookies in the browser with JavaScript. GTG serves these scripts through your domain, but does not change how they set cookies. Safari still limits them to seven days.

To keep cookies longer than seven days in Safari, set them **server-side** with an HTTP `Set-Cookie` header. GTG does not set cookies this way.

**Scope**

GTG works with **Google scripts and tags**, including Google tag and GTM. It does not change non-Google tags, such as Meta or TikTok.

## Setup guides

GTG itself is configured on your CDN or infrastructure, not inside AdPage. Pick the guide that matches your setup:

{% content-ref url="/pages/sLi12S5bnOrr52zl9YZP" %}
[Setup GTG via Cloudflare](/optimize-your-setup/google-tag-gateway-gtg/setup-gtg-via-cloudflare)
{% endcontent-ref %}

{% content-ref url="/pages/KC1GkiQPxhr3uRhwHGMA" %}
[Setup GTG without Cloudflare](/optimize-your-setup/google-tag-gateway-gtg/setup-gtg-without-cloudflare)
{% endcontent-ref %}

## What's next?

Once GTG is live, verify it with Tag Assistant or your browser's network tab (covered in both setup guides), then confirm events are still arriving correctly in your AdPage Data Assistant.


# Setup GTG via Cloudflare

Use the direct Cloudflare dashboard method when the GTM → Cloudflare OAuth connection fails with an "Access denied" error.

{% content-ref url="/pages/I26hhzVcMZdudkKjSP44" %}
[Google tag gateway (GTG)](/optimize-your-setup/google-tag-gateway-gtg)
{% endcontent-ref %}

*Category: Tracking setup · Reading level: Intermediate · Reading time: \~5 minutes*

Google Tag Gateway (GTG) loads your Google tags (GTM, GA4, Google Ads) from your own domain instead of directly from Google's servers. That gives you:

* Better data quality — fewer blocks by browser extensions
* First-party tracking — tags load as first-party content
* Higher conversion accuracy — Google reports \~11% more signal on average

## When do you use this method?

The standard way to set up GTG is via GTM → Sign in to Cloudflare. But this OAuth connection can fail with:

{% hint style="danger" %}
"Access denied. Check your sign-in information and permissions to update your Content Delivery Network."
{% endhint %}

This happens when:

* You were invited as a member on a client's Cloudflare account
* Account-wide API access is disabled (default on non-Enterprise accounts)
* The Cloudflare account owner can't complete the link themselves in GTM

In that case, use the direct Cloudflare dashboard method below — no GTM OAuth required.

### Requirements

| Requirement     | Details                                            |
| --------------- | -------------------------------------------------- |
| Cloudflare plan | Free or higher                                     |
| Cloudflare role | Super Administrator, Administrator, or Zaraz Admin |
| GTM container   | Installed on the website                           |
| Google Tag ID   | GTM-XXXXXXX (top-right in GTM)                     |

## Step-by-step setup

{% stepper %}
{% step %}

### Open Google Tag Gateway in Cloudflare

Log in to dash.cloudflare.com as the account owner (or as an invited member with sufficient rights). Select the domain you want to enable GTG on. In the left sidebar, scroll to **Web tag management → Google tag gateway**.

{% hint style="warning" %}
This needs to be done by someone with an account-level role. A domain-scoped role isn't enough.
{% endhint %}
{% endstep %}

{% step %}

### Configure Google Tag Gateway

Click **Configure** and fill in:

* **Google tag ID\*** — the website's GTM container ID, e.g. `GTM-AB123456`. Found top-right in the GTM interface.
* **Measurement path\*** — a path on the website that isn't in use yet, e.g. `/metrics`, `/gtm`, `/analytics`, or a random combination of letters/numbers (recommended).

{% hint style="success" %}
**Tip:** Use the default path Cloudflare suggests — it's a random combination that minimizes the chance of conflicts.
{% endhint %}

* **Set up tag** — leave off if the website already has a GTM snippet in the source code; turn on if Cloudflare should inject the tag automatically (no GTM snippet yet).

Click **Save**.
{% endstep %}

{% step %}

### Activate the toggle

After saving, a toggle appears on the Google Tag Gateway page. Turn it on.

Cloudflare now automatically injects the adjusted GTM snippet on the fly into every page on the domain — no source code changes needed.
{% endstep %}
{% endstepper %}

## Verifying your setup

**Method 1 — Check the page source** Go to the website → right-click → View Page Source (or Cmd+U / Ctrl+U) → search for the measurement path (e.g. `/metrics`). You should see a GTM snippet pointing to `yourdomain.com/[path]` instead of `googletagmanager.com`.

**Method 2 — Browser DevTools** Open DevTools (F12) → Network tab → reload the page → filter on your measurement path. Requests now run through your own domain ✅.

**Method 3 — Tag Assistant (most reliable)** Go to tagassistant.google.com → enter the website URL → Connect → navigate the site to trigger tags → Summary → Output → Hits Sent → confirm hits are sent via your measurement path.

## Common issues

**"Access denied" on the GTM OAuth link** Cause: Cloudflare API access is disabled for your member account — an Enterprise-only Cloudflare setting. Fix: Use the direct Cloudflare dashboard method described above.

**GTM status stays "Not started" after Cloudflare setup** Cause: GTM and Cloudflare aren't linked via OAuth, so GTM never receives a status update. Fix: This is expected with the direct Cloudflare method. Validate via Tag Assistant or DevTools instead — if requests run through your domain, it's working correctly.

**Tags load on admin pages (e.g. WordPress `/wp-admin`)** Cause: Cloudflare injects the snippet on every page on the domain. Fix: Set up a Cloudflare Configuration Rule to exclude the measurement path on admin URLs.

## GTM OAuth vs. Cloudflare dashboard method

|                                       | GTM OAuth    | Cloudflare dashboard      |
| ------------------------------------- | ------------ | ------------------------- |
| Automatic GTM configuration           | ✅ Yes        | ❌ No (not needed)         |
| Snippet injection by Cloudflare       | ✅ Automatic  | ✅ Automatic               |
| Website source code changes           | ❌ Not needed | ❌ Not needed              |
| Works as a member of a client account | ❌ Often not  | ✅ Yes                     |
| GTM status visible in the interface   | ✅ "Active"   | ⚠️ May show "Not started" |


# Setup GTG without Cloudflare

Configure GTG using Google Cloud Platform, Akamai, or a manual reverse proxy — for setups that don't run on Cloudflare.

{% content-ref url="/pages/I26hhzVcMZdudkKjSP44" %}
[Google tag gateway (GTG)](/optimize-your-setup/google-tag-gateway-gtg)
{% endcontent-ref %}

*Extended guide for alternative configurations.* This article covers setting up Google Tag Gateway (GTG) when you're not using Cloudflare: Google Cloud Platform, Akamai CDN, and manual configuration with other CDNs or web servers.

## 1. What is Google Tag Gateway?

Google Tag Gateway for advertisers lets you serve Google tags (GA4, Google Ads, or GTM) through your own first-party infrastructure. The tag loads from your domain instead of directly from Google's servers.

{% hint style="info" %}
**Important nuance**

Google Tag Gateway is not a replacement for server-side tagging — it's a lightweight addition. Your AdPage container gives you full data enrichment, server-set cookies for a longer lifetime, better privacy compliance, and integration with non-Google destinations. GTG is a solid first step for first-party delivery, but it doesn't offer the same functionality.
{% endhint %}

### 1.1 Benefits of Google Tag Gateway

* **Improved conversion data** — Google reports an average 11% improvement in conversion signal collection
* **First-party tag delivery** — tags load from your own domain, which can bypass some ad blockers
* **Simple implementation** — considerably less complex than a full server-side GTM setup
* **Lower cost** — no separate tagging servers required
* **Trusted Execution Environment** — improved privacy through TEE processing

### 1.2 Limitations of Tag Gateway (vs. server-side tagging)

* **No data enrichment** — you can't add server-side data to events
* **Limited cookie control** — cookies are still set client-side (ITP limitations remain)
* **Google tags only** — no support for Meta, TikTok, or other platforms
* **No custom transformations** — data passes through to Google unchanged
* **Limited debugging** — less visibility into what's actually happening

### 1.3 Do I need to change my nameservers?

Depends on the method:

| Method                | Change nameservers? | Notes                                                                                  |
| --------------------- | ------------------- | -------------------------------------------------------------------------------------- |
| Cloudflare            | ✅ Yes               | You need to move your nameservers to Cloudflare (unless you use a CNAME/partial setup) |
| Google Cloud Platform | ❌ No                | You only adjust your load balancer configuration. DNS stays where it is.               |
| Akamai                | ❌ No                | If you're already an Akamai customer, you just configure Property Manager rules.       |
| Manual (NGINX, etc.)  | ❌ No                | You only configure your own web server/proxy.                                          |

### 1.4 Available implementation options

| Option                | Complexity | Suited for         | Status               |
| --------------------- | ---------- | ------------------ | -------------------- |
| Google Cloud Platform | Low        | GCP users          | Available (Jan 2026) |
| Akamai CDN            | Low        | Akamai customers   | Available (Jan 2026) |
| Manual setup          | High       | Other CDNs/servers | Always available     |
| Fastly CDN            | Medium     | Fastly customers   | Planned              |

## 2. Google Cloud Platform (GCP) setup

Since January 2026, Google offers a one-click deployment option via Google Cloud Platform — the recommended method if you're already on GCP.

### 2.1 Requirements

* A Google Cloud project with billing configured
* Google Cloud administrator rights for resource management
* Access to Google tag settings via GTM, Google Ads, GA4, or Campaign Manager 360
* A working Google tag (GA4, Google Ads, or GTM) already installed on your site

### 2.2 Step-by-step configuration

{% stepper %}
{% step %}

### Open Google tag settings

**Via Google Ads:** go to your Google Ads account → Tools icon (wrench) → **Data manager** → under "Google tag", click **Manage** → **Admin**.

**Via Google Analytics:** go to **Admin** in your GA4 property → open **Data streams** → select your stream → **Configure tag settings** → **Admin**.
{% endstep %}

{% step %}

### Navigate to Tag Gateway settings

In Admin, click **Google tag gateway for advertisers** → **Continue** on the setup screen.
{% endstep %}

{% step %}

### Check compatibility

Enter a valid website URL → click **Scan** to check whether your site already uses a GCP load balancer → select **Google Cloud Load Balancer** from the list → **Continue**.
{% endstep %}

{% step %}

### Configure the gateway

The system automatically creates and configures:

* **External Application Load Balancer** — routes tag traffic through your first-party domain
* **Backend service** — handles gateway requests to Google's services
* **SSL certificates** — configured automatically for your domain
* **Routing rules** — direct traffic to the right backend
  {% endstep %}

{% step %}

### Adjust settings (optional)

You can override active domains via the edit icon. Adjust the measurement path (make sure it doesn't conflict with existing website routes).

{% hint style="success" %}
**Tip — measurement path:** use a neutral or random path instead of obvious names like `/metrics` or `/tracking` — for example `/v2ur` or `/5n8r`. This lowers the chance that ad blockers interfere with your tracking.
{% endhint %}
{% endstep %}
{% endstepper %}

## 3. Akamai CDN setup

Since January 2026, Google Tag Gateway also supports Akamai CDN — a good fit if you already use Akamai for content delivery.

### 3.1 Requirements

* An active Akamai account with Property Manager access
* One of the following Akamai products: Ion, Dynamic Site Accelerator, or API Acceleration
* A Google Tag ID (obtained via Google)

### 3.2 Configuration steps

{% stepper %}
{% step %}

### Create a new rule

Go to Akamai Property Manager → create a new rule named "Google Tag" → add at least a **Hostname match**.
{% endstep %}

{% step %}

### Configure the Google Tag Gateway behavior

Add the **Google Tag Gateway** behavior → specify your Google Tag ID (obtained via Google) → configure the **Serving Path** (e.g. `/gtag` or a unique path) → under Advanced options, choose whether Akamai or another platform injects the tag automatically.

{% hint style="warning" %}
**Incompatibilities:** The Google Tag Gateway behavior is incompatible with these Akamai behaviors: Brotli Support, Construct Response, and EdgeWorkers. Make sure they're not active in the same rule.
{% endhint %}
{% endstep %}
{% endstepper %}

## 4. Manual setup (NGINX, Fastly, other CDNs)

If you don't use Cloudflare, GCP, or Akamai, you can configure Google Tag Gateway manually with any CDN, load balancer, or web server that supports request forwarding.

### 4.1 Requirements for manual setup

* A working Google tag (GA4, Google Ads, or GTM) already installed on your site
* A CDN or server that supports request forwarding (e.g. Fastly, NGINX, Apache)
* Admin-level access to your domain's DNS
* SSL certificate configuration
* A dedicated path or subdomain (e.g. `/metrics` or `tags.yourdomain.com`)

### 4.2 NGINX proxy configuration

NGINX can act as a reverse proxy to load GTM as a first-party script. A minimal configuration:

```nginx
location /gtm-proxy/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://app-address;
}
```

* `Host` — sets the Host header on the request to the backend
* `X-Real-IP` — stores the client's original IP address
* `X-Forwarded-For` — carries the client IP plus any proxy server addresses

### 4.3 Docker + NGINX server-side setup

For a more robust implementation, you can run GTM server-side with Docker and NGINX as a proxy:

* Configure two separate subdomains: one for the preview server, one for the tagging server
* Make sure both services are reachable over HTTPS
* Configure the location block with the right proxy headers for client IP preservation

### 4.4 General manual configuration steps

1. Choose a URL path to act as the proxy to Google (e.g. `/v2ur` or `/5n8r`)
2. Configure your CDN/server to forward requests on this path to Google's endpoints
3. Preserve query parameters — make sure all URL parameters stay intact when forwarding
4. Configure SSL — a valid SSL certificate on your domain
5. Update your Google tag to point to the new first-party endpoint

## 5. Verifying your setup

### 5.1 Browser DevTools method

Open your website → right-click → **Inspect** (or F12) → **Network** tab → reload (F5/Ctrl+R) → filter on your URL path (e.g. `/v2ur`) → confirm the requests exist and include your website's domain.

### 5.2 What you should see

| Check              | Expected result                     |
| ------------------ | ----------------------------------- |
| HTTP status        | 200 OK                              |
| Request URL domain | Your own domain (not google.com)    |
| Request path       | Your configured path (e.g. `/v2ur`) |
| Response content   | JavaScript code from the Google tag |

## 6. Tag Gateway alongside your AdPage server-side tagging

Google Tag Gateway isn't a replacement for server-side tagging — it can be a valuable addition. Here's what each layer offers:

| Capability                          | Tag Gateway | AdPage server-side tagging |
| ----------------------------------- | ----------- | -------------------------- |
| First-party tag delivery            | ✅           | ✅                          |
| Server-set cookies                  | ❌           | ✅                          |
| Data enrichment                     | ❌           | ✅                          |
| Non-Google platforms (Meta, TikTok) | ❌           | ✅                          |
| Custom transformations              | ❌           | ✅                          |
| Privacy/data control                | Limited     | Full                       |
| Setup complexity                    | Low         | Higher                     |
| Ongoing cost                        | Low         | Higher                     |

### 6.1 When is GTG alone enough?

Tag Gateway can be sufficient if:

* You only use Google platforms (GA4, Google Ads)
* You don't need server-side data enrichment
* You have limited technical resources
* You want to get started quickly with first-party tracking

### 6.2 When do you need server-side tagging?

Server-side tagging (your AdPage container) is necessary if:

* You want to track Facebook, TikTok, or other non-Google platforms
* You want to set server-side cookies (longer lifetime, ITP-proof)
* You want to enrich data with CRM data or other server-side sources
* You want to remove or hash PII before data reaches vendors
* You want full control over what data goes where
* You need CAPI integrations (Conversions API)

### 6.3 Combining: Tag Gateway + your AdPage container

The most powerful setup is often a combination: use Tag Gateway for simple first-party delivery of Google tags, and your AdPage container for advanced use cases like CAPI integrations, data enrichment, and privacy compliance. That gives you the best of both.

## 7. FAQ

**Can I use Tag Gateway with TransIP nameservers?** Yes — you don't need to move to Cloudflare. Choose the GCP solution (recommended), Akamai (if you already use it), or a manual setup with your own web server/CDN. DNS stays with TransIP; you only configure the proxy/load balancer at the infrastructure level.

**Does Tag Gateway replace server-side tagging?** No, not at all. Tag Gateway is a lightweight solution for first-party tag delivery. Server-side tagging (your AdPage container) offers much more: data enrichment, server-set cookies, CAPI integrations, privacy control, and support for non-Google platforms. They work well together.

**Does Tag Gateway extend cookie lifetime?** No. Cookies are still set client-side, so Safari's ITP limitations still apply. For longer cookie lifetime, you need server-side tagging that can set cookies server-side — that's what your AdPage container does.

**What does Google Tag Gateway cost?** Depends on your chosen solution:

* GCP: charges for load balancer usage (relatively low)
* Akamai: included if you're already a customer
* Cloudflare: free on all plans (including the free tier)
* Manual: only your existing server/CDN costs

**Can I track Facebook/Meta with Tag Gateway?** No. Tag Gateway only supports Google tags (GA4, Google Ads, GTM). For Facebook, TikTok, Pinterest, and other platforms, you need server-side tagging with the matching CAPI integrations — already built into your AdPage container.

**Do I need to change my nameservers?** Only with Cloudflare do you typically need to move your nameservers. With GCP, Akamai, or a manual setup, your nameservers stay where they are — you only configure the proxy/load balancer.

## 8. Useful resources

* Google's official documentation
* Akamai TechDocs
* Google Ads Help
* Analytics Mania

{% hint style="info" %}
This article is meant as a guide and may change as Google rolls out new features.
{% endhint %}


# Server container monitoring

What you see on a container's Monitoring page: whether your tracking works, from the visit on your website to what your platforms accepted.

### Where to find it

Open your container and click **Monitoring** in the sidebar. At the top you see when the latest check ran and whether there are open alerts. Click **Refresh** to run the check again.

The page has five tabs: **Overview**, **Proactive monitoring**, **Raw requests**, **History** and **Sent alerts**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F6zugGFMnTh9OfVC3lVCV%2Fmonitoring-overview-performance-en.webp?alt=media" alt="The Overview tab of the Monitoring page"><figcaption><p>The Overview tab of the Monitoring page.</p></figcaption></figure>

{% hint style="info" %}
Monitoring shows whether your tracking works. What AdPage sends to your platforms on top of your server container is set up under **Data boosts**.
{% endhint %}

### Overview

The Overview follows your data in five steps. Each step shows its status at a glance, and the blocks below explain each step in more detail.

| Step                 | What it shows                                                                                                     |
| -------------------- | ----------------------------------------------------------------------------------------------------------------- |
| **Visit**            | Whether visits reach your server container: the CNAME record and the tagging pixel.                               |
| **Incoming**         | The events from your website, last 7 days.                                                                        |
| **Webhooks**         | Whether webhooks from your commerce platform come in, or *Not in use*.                                            |
| **Server container** | What your platforms accepted, last 7 days, with the acceptance percentage per platform.                           |
| **Boosts**           | How many of your boosts you use, for example *You use 3 of the 8 boosts*. **Go to Data boosts** opens the boosts. |

Under **Open alerts** you see what the latest check rejected. These are the issues we send alerts about. When everything is fine, it says *Nothing: everything from the latest check is fine.*

The column on the right links to the other tabs: **Go to Proactive monitoring ›**, **View history ›** and **View sent alerts ›**.

### Proactive monitoring

Here you choose which alerts you get by email: the **Purchase alert**, **Duplicate alert**, **Consent alert** and **Platform alert**, and who receives them. Proactive monitoring is part of the Performance package. See [Pro-active monitoring](/optimize-your-setup/pro-active-monitoring).

### Raw requests

A list of what your server container sent to your platforms in the last 7 days, newest first. Click a row to see the request and the response.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FkRT9N3AIT32ny8zK5NgG%2Fmonitoring-raw-requests-en.webp?alt=media" alt="The Raw requests tab with the Platform filter, Problems only and the list of requests"><figcaption><p>The Raw requests tab on the Monitoring page.</p></figcaption></figure>

* Use the **Platform** filter to show one platform, such as Google Analytics 4, Google Ads, Meta, TikTok, Pinterest, Snapchat, Microsoft Ads or LinkedIn.
* Tick **Problems only** to show only requests a platform did not accept.

There is no export. Missing a filter, column or export? Click **Request a feature ›** at the bottom of the tab.

{% hint style="info" %}
Raw requests are individual requests, not a total per day or week. For your request usage, see [Monthly Usage](https://docs.adpage.io/accountmanagement/container-management/monthly-usage).
{% endhint %}

### History

**Data quality per day** shows how your tracking scored on each day, together with the checks that were saved. Use it to see when a problem started, or whether a fix worked.

### Sent alerts

Every alert for this container, with whether it arrived and was read. Filter on channel (email or Slack), status and level. Sent alerts appear here automatically.


# Pro-active monitoring

How AdPage watches a client's tracking setup around the clock and alerts you the moment something breaks — instead of finding out weeks later.

### What does Pro-active Monitoring do?

Most tracking problems aren't discovered by looking at a dashboard — they're discovered when a client asks why their reported revenue looks wrong, sometimes weeks or months after a tag quietly stopped firing. Pro-active Monitoring closes that gap: AdPage continuously scans a container's tracking setup and automatically alerts the right people the moment something looks off, instead of waiting for someone to notice.

|                    | Without Pro-active Monitoring      | With Pro-active Monitoring            |
| ------------------ | ---------------------------------- | ------------------------------------- |
| **Checking**       | Manual, occasional                 | Automated, continuous                 |
| **Detection time** | Weeks to months                    | Within minutes                        |
| **Alerting**       | None — someone has to notice first | Automatic, sent straight to the inbox |

What gets scanned:

* Tag activity and status
* Incoming\_requests from platforms
* Platform delivery outgoing\_requests
* Webhook matching

{% hint style="info" %}
Pro-active Monitoring is a **Performance package** feature.
{% endhint %}

### Where to find it

Alerting is configured per container. Open your container, click **Monitoring** in the sidebar and open the **Proactive monitoring** tab (next to **Overview**, **Raw requests**, **History** and **Sent alerts**). For a tour of the other tabs, see [The Monitoring page](/optimize-your-setup/server-container-monitoring).

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FufYZLteSPKQvntQZuDRu%2Fmonitoring-proactive-performance-en.webp?alt=media" alt="The Proactive monitoring tab with the Purchase, Duplicate, Consent and Platform alerts"><figcaption><p>The Proactive monitoring tab on the Monitoring page.</p></figcaption></figure>

### The alerts

Under **Your alerts** you see which alerts are on, for example *0 of 4 on*. Turn each alert on or off with its switch, and click **Edit** to change it.

| Alert               | When you get an email                               |
| ------------------- | --------------------------------------------------- |
| **Purchase alert**  | No purchase has come in for 3 hours.                |
| **Duplicate alert** | An order comes in as a purchase 1.10 times or more. |
| **Consent alert**   | Fewer than 40% of your visitors give consent.       |
| **Platform alert**  | A platform accepts fewer than 90% of your events.   |

When you turn on an alert and there is no recipient yet, your own address is added. We only email when there is a new problem, not every hour again. Every alert that was sent is listed on the **Sent alerts** tab.

### Setting up Pro-active Monitoring

{% stepper %}
{% step %}

#### Turn on alerts

Flip **Alerts activate** to on. This is the master switch — with it off, none of the settings below send anything, no matter how they're configured.
{% endstep %}

{% step %}

#### Choose the alert frequency

| Frequency | What it sends    | Availability                                                                                  |
| --------- | ---------------- | --------------------------------------------------------------------------------------------- |
| Hourly    | A short summary  | Performance package only                                                                      |
| Daily     | A daily overview | Performance package only                                                                      |
| Weekly    | A weekly report  | Available on any package — an admin can enable this manually for a client without Performance |

Only one frequency is active at a time.
{% endstep %}

{% step %}

#### Choose which alert types to send

Two toggles, independent of each other:

* **Critical Alerts** — tracking has completely stopped, or there's a serious data issue.
* **Warnings** — potential problems that need attention but aren't (yet) breaking anything.

A client can be on Critical-only if they only want to hear about the fires, or have both on for earlier warnings too.
{% endstep %}

{% step %}

#### Manage email recipients

Under **Email receivers**, each recipient has an on/off toggle so you can pause someone's alerts without removing them. One recipient is marked **Primary** and can't be deleted, only toggled — every other recipient can be removed with the trash icon. Add someone new by typing their address in the field at the bottom and clicking **Add.**
{% endstep %}

{% step %}

#### Save

Click **save** to apply the configuration. A green **Alerts active** confirmation summarises what the client will now receive.
{% endstep %}
{% endstepper %}

### Testing your alert configuration

There are two ways to test, and they check different things:

* **Send test email** — fires an unconditional test email to the current recipient list, regardless of the container's actual tracking status. Use this to confirm the alert emails actually arrive and aren't landing in spam.
* **Full validation + alert test** — runs a real check against the container and only sends an alert if it actually finds an issue. Use this to confirm the detection logic itself is working, not just email delivery.

Run the full validation after any tracking change you'd expect Pro-active Monitoring to catch, to confirm it actually gets flagged.

{% hint style="warning" %}
You can also setup Slack and Teams as delivery channels in addition to email.
{% endhint %}

If a client's alerting needs don't fit contact <support@adpage.io> with the container ID.


# GEO headers

Use the location data (country, region, city, IP address and postal code) that AdPage automatically adds to every incoming request in your GTM server container.

### What are GEO headers?

Need better location information for advanced server-side logic? Use the GEO headers. AdPage server-side tagging automatically adds geographic information about the visitor as headers to every incoming request. This lets you identify where a visitor is accessing your site from, without relying on separate APIs or external services.

The following headers are added to the **Incoming HTTP Request** in your GTM server container:

| Header             | Contains                  |
| ------------------ | ------------------------- |
| `X-Geo-Country`    | The visitor's country     |
| `X-Geo-Region`     | The visitor's region      |
| `X-Geo-City`       | The visitor's city        |
| `X-Geo-Ipaddress`  | The visitor's IP address  |
| `X-Geo-PostalCode` | The visitor's postal code |

The values are looked up in a geolocation database based on the visitor's IP address and added to the headers.

{% hint style="info" %}
This product includes GeoLite2 data created by MaxMind, available from <https://www.maxmind.com>.
{% endhint %}

### Why use GEO headers?

* **Location-specific targeting** — recognise a user's country, region or city to enable more precise targeting and segmentation.
* **Region-specific settings and consent** — privacy rules (such as GDPR) differ per region, so adjusting tracking behaviour based on a user's location can be crucial. GEO headers help you collect user data in a lawful, compliant way without introducing an overly complex configuration.
* **Seamless integration with sGTM** — because the headers are added at server level, you don't need separate scripts or API calls to get location data.

### Do I need to set anything up?

No. The GEO headers are available automatically and are sent along with every request to your server container.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FPIrkSLHF8M7UFNA0PPLh%2Fimage.png?alt=media&amp;token=abb4b9fe-e144-447a-9cc7-d4baae622661" alt=""><figcaption></figcaption></figure>

### Using GEO headers in your tags

To use the location data in specific tags, create a **Request Header** variable in your GTM server container.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FJzNIjekIRR5EDcE9t3A9%2Fimage.png?alt=media&amp;token=c5a56fea-fb1c-45e3-97b9-2c1a886b8a51" alt=""><figcaption></figcaption></figure>

{% stepper %}
{% step %}

#### Create a new variable

In your GTM server container, go to **Variables** and click **New** under **User-Defined Variables**.
{% endstep %}

{% step %}

#### Choose Request Header

Select **Request Header** as the variable type and enter the header you need as the **Header Name**, for example `X-Geo-Country`.
{% endstep %}

{% step %}

#### Save and use the variable

Give the variable a clear name (for example `Request Header - X-Geo-Country`), save it, and use it in your tags, triggers or other variables wherever you need the location data.
{% endstep %}
{% endstepper %}

Repeat this for each GEO header you want to use.

{% hint style="success" %}
Use the [GTM Preview Mode](/getting-started/using-the-gtm-preview-mode) to check the values: open an incoming request and look at its request headers, or check the value of your new variable.
{% endhint %}


# Returns to Google Ads

Send returns from your returns platform to Google Ads, so Smart Bidding optimizes on the revenue you keep instead of revenue that comes back.

When a customer sends an order back, Google Ads keeps counting the full conversion. Smart Bidding then optimizes towards revenue you no longer have, and campaigns that bring in many returns look better than they are.

Returns to Google Ads corrects that. Every day, AdPage adjusts the conversions of returned orders in Google Ads:

* **Full return**: the conversion is retracted.
* **Partial return**: the conversion value is lowered to what the customer kept. This is optional.

It works with every returns platform you connect to AdPage. In AdPage you find it as **Returns as conversion adjustments** under **Data boosts**.

{% hint style="info" %}
Returns to Google Ads is part of the **Performance** plan, and is also included in **Ultimate**. On another plan, Data boosts shows it under **From Performance**, and the page says it comes with Performance and Ultimate, with a **View plans** button. No returns are sent to Google Ads until the container is on one of those plans.
{% endhint %}

## What you need

|                                         |                                                                                                                                                                                                                        |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The Performance plan                    | the container is on the Performance or Ultimate plan                                                                                                                                                                   |
| A returns platform                      | [Returnless](https://docs.adpage.io/data-and-insights/marketing-integrations/returnless) or [Returnista](https://docs.adpage.io/data-and-insights/marketing-integrations/returnista), connected under **Integrations** |
| Google Ads                              | connected to the container under **Integrations**, by a Google account with at least **Standard** access to the Google Ads account; Admin is not needed. Read-only access cannot adjust conversions                    |
| Order webhooks                          | your webshop sends its orders to AdPage, the same order webhooks [Webhook Matching](/optimize-your-setup/webhook-matching) uses                                                                                        |
| A purchase conversion with the order ID | the conversion action your purchases go to receives the order ID (`transaction_id`)                                                                                                                                    |

Google finds the conversion to adjust by its order ID. That works for website conversions (the Google tag or your server container) and for imported conversions such as the AdPage upload. Conversions imported from GA4, app conversions, store visits and call conversions cannot be adjusted, so AdPage does not offer them.

## Set it up

1. In your container, open **Data boosts**. On the **Boosts** tab, click **Set up** on the **Returns as conversion adjustments** tile. You can also reach it from the **Overview** tab, under **Boosts**.

   <figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F7fFzlTApxzguMivdHjgK%2Freturns-to-google-ads-data-streams.webp?alt=media" alt="The Overview tab of Data boosts in AdPage, with Returns as conversion adjustments under Boosts"><figcaption><p>Returns as conversion adjustments under Boosts on the Overview tab of Data boosts</p></figcaption></figure>

   If a returns platform or Google Ads is not connected yet, the page says **This needs two connections** and shows which one is missing. Click **Go to integrations** to connect it.
2. Under **Settings**, choose the **Google Ads account**. If you change the account later, the chosen conversion actions are cleared and **Send daily** switches off, so you choose them again.
3. Choose what happens **on a partial return**:
   * **Do nothing**: only full returns are retracted.
   * **Lower the value**: the conversion value becomes what the customer kept, including or excluding VAT, the same way your tag sends it. You do not have to tell AdPage which one: it works this out for each conversion action, see [What a conversion action gets as value](/optimize-your-setup/returns-to-google-ads#what-a-conversion-action-gets-as-value). Where it cannot tell, for example because the action gets profit, partial returns are left alone.
4. Tick the **conversion actions** your purchases go to, up to five. The action marked **Primary** is the one Smart Bidding uses. Page views, add to cart and similar actions are under **Show other conversions**; you rarely want those.

   <figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FkrMX9ESaqWKtSlhcEEcT%2Freturns-to-google-ads-settings.webp?alt=media" alt="The Settings panel with the Google Ads account, On a partial return set to Lower the value, and the Purchase conversion action ticked"><figcaption><p>Settings: the Google Ads account, what happens on a partial return, and the conversion actions</p></figcaption></figure>

   There is no Save button: a change saves right away once an account and at least one conversion action are chosen.
5. Click **Preview at Google** and check the result, see [Read the preview](/optimize-your-setup/returns-to-google-ads#read-the-preview).
6. Switch on **Send daily** at the top right of the page. The status under the switch changes to **On**, and from then on AdPage sends the adjustments every morning. You can only switch it on once an account and at least one conversion action are chosen. Switch it off to stop sending.

   <figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FJIOUCvq9ZqAugXerGOXE%2Freturns-to-google-ads-send-daily.webp?alt=media" alt="The Send daily switch at the top right of the Returns as conversion adjustments page, switched on"><figcaption><p>Send daily at the top right of the page, with the status under it</p></figcaption></figure>

{% hint style="warning" %}
A retraction is final: Google cannot restore a retracted conversion. The first run handles all completed returns on orders from the last 53 days at once, so always run the preview first.
{% endhint %}

## Read the preview

The preview is a dry run. Google checks the adjustments as if they were sent, including whether it can find the conversion, but nothing changes in your account. To keep it quick, Google checks at most 100 adjustments, for the newest returns, and the preview says when it checked such a sample. The daily run sends all of them.

You see how many adjustments Google would apply, how many orders have no Google Ads conversion, the first 25 orders by their name in your webshop, and what was skipped. With **Lower the value**, you also see what each conversion action gets as value.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyMTXQz7EScL62ukGK6IX%2Freturns-to-google-ads-preview.webp?alt=media" alt="A preview at Google: Google adjusts 13 of the 41 orders, the value per conversion action, and a table of orders with OK and No Google Ads conversion"><figcaption><p>A preview: nothing is changed in Google Ads</p></figcaption></figure>

| You see                                                                               | What it means                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **OK**                                                                                | Google found the conversion and would accept the adjustment                                                                                                                                                                                                                                                                                                                  |
| **No Google Ads conversion**                                                          | Google has no conversion with this order ID in this conversion action: the order did not come in through a Google Ads click (organic, social, email, direct, or an iOS click without a click ID), so there is nothing to retract. This is the normal outcome for most orders, not an error. Once the order is three days old, AdPage stops trying and lists it under skipped |
| **Order not found in webhook orders**                                                 | AdPage could not find the returned order among your order webhooks: the returns platform uses a different order number, or the order is older than 53 days                                                                                                                                                                                                                   |
| **Order number belongs to an order with a different order date**                      | The returns platform gives a different order date than the order with this number in your webshop. That is another order with the same number, for example #265638 from 2024 next to #2265638 from 2026, so AdPage leaves the return alone                                                                                                                                   |
| **Order number fits more than one order**                                             | Several orders have this number and the order date does not settle which one, so AdPage leaves the return alone                                                                                                                                                                                                                                                              |
| **Conversion older than 53 days**                                                     | Google no longer accepts adjustments this long after the conversion                                                                                                                                                                                                                                                                                                          |
| **Conversion less than 25 hours old**                                                 | Too early for Google; it goes out in a later run                                                                                                                                                                                                                                                                                                                             |
| **Return not completed yet**                                                          | The product is not back yet; it follows once the return is processed                                                                                                                                                                                                                                                                                                         |
| **Nothing refunded**                                                                  | The return has no refund amount, so there is nothing to adjust                                                                                                                                                                                                                                                                                                               |
| **Partial return, lowering the value is off**                                         | **On a partial return** is set to **Do nothing**, so partial returns are left alone                                                                                                                                                                                                                                                                                          |
| **Partial return, but the conversion action does not get a recognisable order value** | AdPage cannot tell what this conversion action gets as value, so it leaves the partial return alone there. Full returns are still retracted                                                                                                                                                                                                                                  |
| **Already sent**                                                                      | Adjusted in an earlier run                                                                                                                                                                                                                                                                                                                                                   |
| **Skipped after three refusals**                                                      | Google refused this adjustment three times for another reason, so AdPage stopped trying                                                                                                                                                                                                                                                                                      |

A high share of **No Google Ads conversion** is expected: most orders do not come in through Google Ads. What matters is that orders from Google Ads show **OK**.

## What a conversion action gets as value

A lowered value has to be on the same basis as the value Google already has. A conversion that came in at the order value including VAT must be lowered to an amount including VAT, and one that came in at profit cannot be lowered by an order amount at all.

Google Ads does not report the value of a single conversion, but it does report the value per conversion action per day. AdPage compares the average value per conversion with the average order value from your order webhooks, including and excluding VAT, for each two weeks of the last eight weeks.

| The preview shows                     | What happens on a partial return                                                                                                            |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Order value incl. VAT**             | The new value is what the customer kept, including VAT                                                                                      |
| **Order value excl. VAT**             | The new value is what the customer kept, excluding the VAT of that order                                                                    |
| **Not the order value (e.g. profit)** | Nothing: the action gets profit or a fixed value, so there is no correct new value                                                          |
| **Varies between periods**            | Nothing: the two-week periods do not agree, for example because the tag changed what it sends. The preview shows the average of each period |
| **Cannot be determined**              | Nothing: fewer than 50 conversions or orders in a period, VAT too low to tell the two apart, or Google Ads could not be read                |

Every two-week period with conversions has to point the same way. A tag that sent profit until last month and the order value since then can, on one average over both, look exactly like the order value excluding VAT. Lowering conversions on that basis would put them at a value that is wrong in both periods.

Full returns are always retracted, whatever a conversion action gets as value.

## How it decides

* Only **completed** returns count: the product is back or the return has been processed. A return that is only registered sometimes never arrives.
* A return counts as full when every item came back, or at least 90% of the order value (shipping is usually not refunded).
* Exchanges and repairs do not count here: the revenue stays.
* A return is linked to its order by the order number. The returns platform does not always write it the way your webshop does: Returnless can give 265100 where Shopify shows the order as #2265100. AdPage recognises both. When the returns platform gives the order date, as Returnless does, it must match the order in your webshop within two days. If it does not, or if a number fits more than one order, the return is left alone: a retraction is final, so AdPage would rather skip a return than adjust the wrong order.
* Google accepts adjustments from 24 hours until about 54 days after the conversion. AdPage waits 25 hours and stops at 53 days to stay inside both limits. The age counts from the order, not from the return.
* A conversion is retracted only once. A lowered value is sent again only when the return changes, for example when a second item comes back.
* If Google has no conversion for an order, AdPage tries again the next day while the order is less than three days old, because the daily AdPage upload can arrive after the run. After that it stops. If Google refuses an adjustment three times for another reason, AdPage stops trying for that order as well.

## Check the result

In Google Ads, adjustments show up in the **Conversions** and **Conv. value** columns with the same delay as regular conversions, on the date of the original conversion. Google does not show individual order IDs in its reports, so you see the effect in the totals per conversion action.

In AdPage, **Last sent** at the top of the **Returns as conversion adjustments** page shows the last run: how many conversions were adjusted, how many orders had no Google Ads conversion, and how many adjustments Google refused. Below it are the most recent adjustments Google accepted, by the order name in your webshop, such as #2265100, with **Retracted** or the new value. Hover over a name to see the number the returns platform uses for it.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FzdhevjectBriO8feFrex%2Freturns-to-google-ads-last-sent.webp?alt=media" alt="Last sent at the top of the Returns as conversion adjustments page: the last run and the most recent adjustments, retracted or with a new value"><figcaption><p>Last sent: the last run and the most recent adjustments Google accepted</p></figcaption></figure>

The status under **Send daily** shows whether it runs: **On**, **Off**, **Not set up yet** (no conversion action chosen), **Not connected yet** (a returns platform or Google Ads is missing) or **Last run failed**. A failed run also shows on its tile on the **Boosts** tab, and under **Needs attention** on the **Overview** tab of Data boosts.

## Related

* [Profit on Ad Spend](/optimize-your-setup/profit-on-ad-spend): bid on margin instead of revenue
* [Webhook Matching](/optimize-your-setup/webhook-matching): get every order to AdPage and your ad platforms
* [Returnless](https://docs.adpage.io/data-and-insights/marketing-integrations/returnless): connect Returnless
* [Returnista](https://docs.adpage.io/data-and-insights/marketing-integrations/returnista): connect Returnista


# Connect Google Cloud Service account

Use Firestore, BigQuery and other Google Cloud services from your GTM server container by connecting a Service Account from your own Google Cloud project.

### When do you need this?

Some server-side tags and variables read from or write to Google Cloud. Common examples:

* **Firestore Lookup** variable — enrich events with data stored in Firestore, for example to build an extra conversion action based on customer or order data.
* **Firestore Writer** tags — store event data in Firestore.
* **BigQuery** tags — stream tracking data into your own BigQuery dataset.

These tags authenticate with the Google credentials of the server container. Because your data lives in **your own** Google Cloud project, you create a Service Account in that project and connect it to your AdPage container. AdPage does not hand out a shared Service Account that you grant access to: you stay owner of the account, the permissions and the key.

{% hint style="info" %}
In the AdPage dashboard this setting is called **Google BigQuery**, but the Service Account you upload there is used for all Google Cloud access from your server container, Firestore included.
{% endhint %}

### Step 1: create the Service Account

{% stepper %}
{% step %}

#### Open IAM in your Google Cloud project

In the [Google Cloud Console](https://console.cloud.google.com/), select the project that contains your Firestore database (or BigQuery dataset) and go to **IAM & Admin → Service Accounts**.
{% endstep %}

{% step %}

#### Create the account

Click **Create service account** and give it a recognisable name, for example `adpage-sgtm`.
{% endstep %}

{% step %}

#### Grant the roles

Give the account only the roles your tags need:

| Use case                          | Role                                                                                                    |
| --------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Firestore Lookup (read only)      | `Cloud Datastore Viewer` (`roles/datastore.viewer`)                                                     |
| Firestore Writer (read and write) | `Cloud Datastore User` (`roles/datastore.user`)                                                         |
| BigQuery                          | `BigQuery Data Editor` (`roles/bigquery.dataEditor`) and `BigQuery Job User` (`roles/bigquery.jobUser`) |

Need both Firestore and BigQuery? Give the **same** Service Account all the roles you need. A container holds one Service Account at a time (see [Things to know](#things-to-know)).
{% endstep %}

{% step %}

#### Create a JSON key

Open the Service Account, go to **Keys → Add key → Create new key**, choose **JSON** and download the file.
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
Can't create a key? Your organisation may enforce the policy `iam.disableServiceAccountKeyCreation`. Ask your Google Cloud administrator for an exception for this project.
{% endhint %}

### Step 2: connect the Service Account in AdPage

{% stepper %}
{% step %}

#### Open the container settings

In the [AdPage dashboard](https://data.adpage.io), go to **Containers**, open your container and click **Settings**.
{% endstep %}

{% step %}

#### Upload the JSON file

In the menu on the left, choose **Google BigQuery**. Drag the JSON file into the upload area (or click to select it) and click **Save**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FEqQT6eJORlBQC7tPnEIw%2Fdata-streams-bigquery-export-en.webp?alt=media" alt="BigQuery export screen with the Service Account upload area"><figcaption><p>BigQuery export: upload the JSON key of your Service Account.</p></figcaption></figure>
{% endstep %}

{% step %}

#### Check the status

When the upload succeeds, the section shows that a Service Account is connected.
{% endstep %}
{% endstepper %}

{% hint style="danger" %}
The JSON file contains a private key. Upload it only in the AdPage dashboard and do not send it by email or chat. Delete the downloaded file once it has been uploaded.
{% endhint %}

### Step 3: use it in your GTM server container

For a **Firestore Lookup** variable:

1. In your GTM server container, go to **Variables → New** and choose **Firestore Lookup**.
2. Enter the collection path and the document path or query.
3. Under **Advanced**, enable **Override Project ID** and enter the ID of the Google Cloud project that contains your Firestore database. Without this, the variable looks in the project the server container runs in, not in yours.

The same applies to Firestore and BigQuery tags from the Community Template Gallery: always enter your own project ID.

{% hint style="success" %}
Test it in the GTM Preview Mode. Open a request that uses the variable and check that it returns a value. A permission error usually means a role is missing or the project ID is wrong.
{% endhint %}

### Things to know

* **One Service Account per container.** Uploading a new JSON file replaces the previous one. If you use the container for both BigQuery and Firestore, use one Service Account with all the roles it needs.
* **Rotating the key.** Create a new key in Google Cloud, upload it in AdPage, check your tags in Preview Mode and only then delete the old key in Google Cloud.
* **Revoking access.** Deleting the key or the Service Account in Google Cloud stops access immediately. Tags that depend on it will then fail.


# Shopify

How to set up server-side tagging for a Shopify webhop

***

## Setting up server-side tagging for Shopify

This article walks you through the full setup of server-side tagging on a Shopify store: generating your Google Tag Manager templates, importing them, filling in your IDs, testing them, and finally removing the old tracking connections that Shopify made for you.

### Before you start

This article picks up where **Getting Started** leaves off. Make sure all of the steps in the [Setup AdPage container](/getting-started/setup-adpage-container) article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The **AdPage Shopify app, customer events pixel & webhook** is installed in your store.

{% hint style="warning" %}
If one of these steps is still open, finish it first. Everything below assumes your server container is reachable on your own domain and that the Shopify app is pushing data into the dataLayer.
{% endhint %}

***

### Step 1: Generate your templates in the Template Library

You do not have to build your tags, triggers and variables by hand. AdPage's Template Library generates a complete, tested Google Tag Manager setup for Shopify for you.

1. Go to [data.adpage.io/template-library](https://data.adpage.io/template-library).
2. Select the marketing platforms you want to send data to, for example Google Ads, Meta Ads, TikTok Ads, LinkedIn Ads or Pinterest Ads.
3. Select the Consent Management Platform you use on your Shopify webshop.
4. Generate the templates. You get **two JSON files**: one for your GTM **web** container and one for your GTM **server** container.
5. Download both files and keep them handy.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fo4nPmZrjh5NFMGAYOnPp%2Fimage.png?alt=media&amp;token=a8b98f2d-df97-4c6a-9a20-c91350247029" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Only select the platforms you actually use. Every platform you add creates extra tags and constant variables that you will need to fill in later.
{% endhint %}

***

### Step 2: Import the web container template

1. Open your **GTM web container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **web** JSON file you downloaded.
4. Choose a workspace.&#x20;
   * If you have unpublished changes in your default workspace, we recommend importing into a **new workspace** so your import stays separate from any other work in progress.
5. Choose the import option:
   * **Merge and rename conflicting tags, triggers and variables** for a container that already contains a setup. Nothing existing gets removed.
   * **Overwrite** only for a brand new, empty container.
6. Check the preview of the changes that GTM shows you, then click **Confirm**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F3CKvxX1mSb1O2JBpcE4Q%2Fimage.png?alt=media&amp;token=ee12042d-41d9-4406-95f9-9e2eaf8d3bc1" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM web container yet. The tags in the import are still missing your IDs, which you fill in at step 4.
{% endhint %}

***

### Step 3: Import the server container template

Repeat the same steps in your **GTM server container** with the **server** JSON file.

1. Open your **GTM server container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **server** JSON file.
4. Import into a new workspace and choose **Merge and rename conflicting tags, triggers and variables**.
5. Check the preview and click **Confirm**.
6. Go to **Clients** and check if an extra GA4 client has been set up. If so, delete the imported GA4 client.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyhuHijhZUYGKSi2cG86j%2Fimage.png?alt=media&amp;token=fbe37ee9-0cec-4291-8c7d-b9f5569cb1d6" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM server container yet. The tags in the import are still missing your IDs and tokens, which you fill in at step 4.
{% endhint %}

***

### Step 4: Fill in the constant variables

Both templates are built around **constant variables**. All IDs, tokens and settings live in one place, so you never have to open individual tags to change something.

1. In your GTM web container, go to **Variables**.
2. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
3. Save each variable.
4. In your GTM server container, go to **Variables**.
5. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
6. Save each variable.

Depending on the platforms you selected, you will typically fill in:

<table><thead><tr><th width="118">Container</th><th width="240">Variable</th><th>Value</th></tr></thead><tbody><tr><td>Web</td><td>Server Container URL</td><td>The tagging domain from your CNAME record, for example: <code>https://tagging.domain.com</code></td></tr><tr><td>Web</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Tag ID</a></td><td>Your Pinterest Tag ID, found in the Tag Manager of your Pinterest Ads Account</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Partner ID</a></td><td>Your LinkedIn Partner ID, found in the Signals Manager of your LinkedIn Ads Account</td></tr><tr><td>Web</td><td>Cookiebot Domain Group ID</td><td>The Domain Group ID from your Cookiebot account</td></tr><tr><td>Server</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta API Ttoken</a></td><td>The API Token of your Pixel from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok API Token</a></td><td>The API Token of your Pixel from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion ID</a></td><td>Your Google Ads Conversion ID: <br><code>AW-XXXXXXXXXX</code> minus the <code>AW-</code> part</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion Labels</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in Google Ads. Once set up, you can find their Conversion Labels.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Advertiser ID</a></td><td>The Advertiser ID from your Ad Account. This ID usually starts with 549.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest API Token</a></td><td>The API Token found in your Conversions API settings of your Pinterest Business Account.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn API Token</a></td><td>The API Token which you can generate in your LinkedIn Campaign Manager in the Sources.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Conversion IDs</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in LinkedIn Ads. Once set up, you can find their Conversion IDs in the URL of the conversion.</td></tr></tbody></table>

{% hint style="info" %}
Never leave a constant variable empty. An empty ID means tags fire without a destination, which shows up as missing conversions or failed outgoing requests later on.
{% endhint %}

***

### Step 5: Test in preview mode

You have just imported container templates with complete tracking for GA4 and the marketing platforms you selected. That means everything you need is now present in your GTM containers, and anything that was already there for the same purpose is a duplicate.

#### **Disable your old tags first**

Go through the tags in your web container and pause or delete every tag that measures something your new setup now handles. In practice this is your old GA4 configuration tag, all GA4 event tags for e-commerce steps such as `add_to_cart` and `purchase`, your Meta Pixel tags, your Google Ads remarketing tags, and any custom HTML tags that send data to a platform directly.&#x20;

If you are not sure whether you will need an old tag later, pause it instead of deleting it. You can always remove it in a later version once the new setup has proven itself. Old triggers and variables can stay, they do nothing on their own.

Skip this and preview mode will show two of everything, and after publishing your conversions will be counted twice.

#### Test both containers

1. Open the **Preview mode** in your GTM web container and fill in the URL of your webshop.
2. Open the **Preview mode** in your GTM server container as well, so you can follow the same hits arriving server-side.
3. Walk through the customer journey and check that each step fires once, with the right e-commerce parameters:
   * `page_view`
   * `view_item_list`
   * `view_item`
   * `add_to_cart`
   * `view_cart`
   * `remove_from_cart`
4. For every event, check in the **server** container that the GA4 event request arrives and that your platform tags fire and return a successful response.

{% hint style="warning" %}
If the GA4 event requests don't arrive on the server container's preview mode, it means that the server\_container\_url parameter in the Google Tag gets overwritten somewhere. Check these three options:

* Check if there is another Google Tag active on your GTM web container with the same GA4 Measurement ID. If there is, pause that tag.
* Check if the Google & YouTube App in Shopify has a direct connection set up with the GA4 property you are setting up server-side tagging for. If so, disconnect this connection.
* Check if the Google & YouTube App in Shopify has the 'conversion measurement' option set to 'On'. If so, set the conversion measurement option to 'Off'.
  {% endhint %}

#### Debugging the Shopify checkout

Shopify loads the checkout inside an iframe, which means you cannot debug it directly in Google Tag Manager's preview mode. Your GTM web container preview mode and a dataLayer checker extension will not show you the steps from `begin_checkout` up to and including `purchase`.

To test those steps anyway, install the [DataLayer Checker Plus](https://chromewebstore.google.com/detail/datalayer-checker-plus/blglfmihmnbhfgfbomofeljmididgfhe) extension.

Besides checking the dataLayer of a website, the extension has two extra options behind the gear icon:

* The first option lets you inspect the dataLayer inside the extension.
* The second option injects the standard `<head>` script of your GTM web container. With that script injected, you can debug the entire checkout in both your GTM web container and your GTM server container again.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FOwy7oqioDhtn2AP1nvyt%2Fimage.png?alt=media&amp;token=4dc5dfd9-ea96-449b-b8d4-601d5aa0fc04" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="info" %}
Remember to switch both options off when you are done debugging. If you leave them on, that `<head>` code gets injected on every page you visit.
{% endhint %}

***

### Step 6: Publish both containers

Once everything looks right in preview modes, publish both GTM containers.

Use a clear version name and description, for example "AdPage server-side tagging", so you can roll back if needed.

Your data now runs through your server container. Any connection that Shopify still maintains directly with an advertising platform will send the same events a second time, which leads to duplicated conversions and inflated revenue in your reports.

Go through the platforms below and disconnect what you no longer need.

#### Google Analytics 4

1. Open the **YouTube & Google** app in Shopify and navigate to the settings.
2. Disconnect the Google Analytics property if you see that one is still connected.
3. Make sure the **Conversion measurement** option is switched off.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FkZH2umQpv5dfokhevgMR%2Fimage.png?alt=media&amp;token=027fb520-519b-4c3c-b44f-048e1b13d683" alt=""><figcaption></figcaption></figure>

#### Meta Ads

1. Open the **Facebook & Instagram** app in Shopify and navigate to the settings.
2. Ensure the **Data Sharing** option is switched off.

{% hint style="info" %}
You'll need access to the Facebook Pixel to be able to switch off this option
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FX13srrLuRND5mF6rq5Xk%2Fimage.png?alt=media&amp;token=857391bc-6c5d-4162-ac98-7e6a5702e9d4" alt=""><figcaption></figcaption></figure>

#### TikTok Ads

1. Open the **TikTok** app in Shopify and navigate to the settings.
2. Go to the **Data Sharing** settings.
3. Click **Disconnect** behind the pixel.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FPzV7IYfMTSZRv5yEEBvR%2Fimage.png?alt=media&amp;token=bbfe5cce-18bc-4f1c-b9f7-5de6906680e4" alt="" width="563"><figcaption></figcaption></figure>

#### Pinterest Ads

1. Open the **Pinterest** app in Shopify and navigate to the marketing settings.
2. Disconnect the Pinterest Tag, so you no longer share data directly with Pinterest.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FJsrQFxfsk2BL2DUMwkls%2Fimage.png?alt=media&amp;token=2516526e-3f20-49a7-b431-df6e63078515" alt="" width="563"><figcaption></figcaption></figure>

#### Check your theme and custom pixels

Finally, check the theme code and Shopify's **Customer events** (custom pixels) for hardcoded tracking scripts that were added manually in the past. Remove what is now handled by your server container.

{% hint style="info" %}
After publishing, compare your conversions for a few days against your shop's own order count. Numbers that are consistently too high are usually a sign that an old connection is still active somewhere.&#x20;
{% endhint %}

***

### Need help?

Still seeing missing events, duplicated conversions or unassigned traffic after following these steps? Reach out to our support team and we will take a look with you.


# Cookie recovery on Shopify

Safari deletes tracking cookies after seven days, even when you use your own subdomain for server-side tagging.

Safari deletes tracking cookies after seven days, even when you use your own subdomain for server-side tagging. This article explains why that happens, what the cookie recovery script does about it, and how to install it on your Shopify theme.

### What this script does

The script stores a visitor ID (the `_taggingmk` cookie) in two places:

* **In a first-party cookie on your main domain:** the primary storage location
* **In localStorage:** a backup, used to restore the cookie if it disappears

That ID is the anchor our server uses to rebuild your tracking cookies when a browser wipes them.

### Safari erases your marketing data

Safari's Intelligent Tracking Prevention (ITP) automatically deletes cookies after seven days. Using a custom tracking subdomain such as `tagging.webshop.com` does not solve this: Safari recognises that the subdomain resolves to a different server than your webshop, and treats its cookies as third-party-ish.

The result is that after one week you lose the link to your visitor. Repeat visits from Safari users look like brand new visitors, and your conversion attribution stops adding up.

In practice that means:

* Returning customers are counted as new visitors
* Your customer journey data becomes unreliable
* Attribution analyses go wrong, for example first-click versus returning customer
* Conversion paths are incomplete

#### How cookie recovery works around it

Three steps:

**1. The anchor.** We place a cookie directly on your main domain (`webshop.com`). Because your own website sets it with JavaScript on the primary domain, Safari allows it to live longer than a cookie on your tracking subdomain.

**2. The check.** On every page load, the script sends this anchor ID to our server, the proxy.

**3. The recovery.** Our server checks whether the tracking cookies on `tagging.webshop.com` are still present. If Safari removed them after seven days, the server writes them back based on the anchor ID.

The localStorage backup protects the anchor itself. If the anchor cookie is cleared but localStorage survives, the script restores the cookie from the backup instead of generating a new ID, so the visitor keeps the same identity.

The outcome: your tracking stays accurate over a longer period, which means you can measure and optimise your marketing campaigns properly.

### Installing on Shopify

1. Log in to your Shopify admin.
2. Go to **Online Store → Themes**.
3. On your active theme, click the three dots and choose **Edit code**.
4. In the left sidebar, open **`theme.liquid`** (under Layout).
5. Paste the script below directly after the opening `<head>` tag. Placing it high in the `<head>` matters: it needs to run before your other tracking scripts.
6. Click **Save** in the top right.

```html
<script type="text/javascript">
(function() {
    'use strict';

    // Generate UUID v4
    function mkTagging_generateUUID() {
        if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
            return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, function(c) {
                return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);
            });
        } else {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0;
                var v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    }

    // Get cookie value by name
    function mkTagging_getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    // Set cookie with expiration
    function mkTagging_setCookie(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + value + expires + "; path=/; SameSite=Lax";
    }

    // Safe localStorage wrapper
    function mkTagging_getLocalStorage(key) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                return localStorage.getItem(key);
            }
        } catch (e) {
            console.log('localStorage not available:', e);
        }
        return null;
    }

    function mkTagging_setLocalStorage(key, value) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                localStorage.setItem(key, value);
                return true;
            }
        } catch (e) {
            console.log('localStorage not available:', e);
        }
        return false;
    }

    // Main initialization function
    function mkTagging_initVisitorId() {
        var cookieName = '_taggingmk';
        var storageKey = '_taggingmk_backup';
        var visitorId = null;

        // 1. Check if cookie exists
        visitorId = mkTagging_getCookie(cookieName);

        // 2. If no cookie, check localStorage backup
        if (!visitorId) {
            visitorId = mkTagging_getLocalStorage(storageKey);

            // If found in localStorage but not in cookie, restore the cookie
            if (visitorId) {
                mkTagging_setCookie(cookieName, visitorId, 365);
                console.log('MK Tagging: Visitor ID restored from localStorage');
            }
        }

        // 3. If still no ID, generate a new one
        if (!visitorId) {
            visitorId = mkTagging_generateUUID();
            mkTagging_setCookie(cookieName, visitorId, 365);
            console.log('MK Tagging: New visitor ID generated');
        }

        // 4. Always sync to localStorage as backup
        if (mkTagging_setLocalStorage(storageKey, visitorId)) {
            console.log('MK Tagging: Visitor ID backed up to localStorage');
        }

        return visitorId;
    }

    // Run on DOM ready or immediately if already loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', mkTagging_initVisitorId);
    } else {
        mkTagging_initVisitorId();
    }

    // Create a namespaced object for any exposed functionality
    window.mkTagging = window.mkTagging || {};
    window.mkTagging.getVisitorId = function() {
        return mkTagging_getCookie('_taggingmk') || mkTagging_getLocalStorage('_taggingmk_backup');
    };

})();
</script>
```

### Verifying the installation

Open your website in an incognito window, then open Developer Tools with F12.

#### Test 1: the cookie is created

Go to the **Console** tab. You should see `MK Tagging: New visitor ID generated`, followed by `MK Tagging: Visitor ID backed up to localStorage`.

Then go to **Application → Cookies** and look for the `_taggingmk` cookie. Its value should be a UUID, for example `a3f2e1d4-5b6c-4d7e-8f9a-0b1c2d3e4f5a`. Refresh the page and confirm the value stays the same.

#### Test 2: the localStorage backup works

Go to **Application → Local Storage** and look for `_taggingmk_backup`. Its value must be identical to the cookie value.

#### Test 3: recovery works

Delete the `_taggingmk` cookie manually in Developer Tools, then refresh the page. The Console should now show `MK Tagging: Visitor ID restored from localStorage`, and the cookie should be back with the same value as before.

If the value changed instead of being restored, the localStorage backup is not being read. Check the Console for JavaScript errors and confirm the script is present in the rendered `<head>`.

### How the logic flows

```
Visitor arrives on site
        ↓
Does the cookie exist? → YES → Sync to localStorage → Done
        ↓ NO
Does the localStorage backup exist? → YES → Restore cookie → Done
        ↓ NO
Generate new UUID → Store in cookie + localStorage → Done
```

### Privacy and GDPR

* **No personal data.** The script stores a random UUID only, no personal information.
* **First-party cookie.** The cookie is set on your own domain, not by a third party.
* **Technically functional.** This is a technical cookie used for analytics, which is often permitted without explicit consent.

One caveat: check with your privacy officer whether this cookie qualifies as strictly necessary in your situation, or whether it needs to sit behind consent in your cookie banner. That assessment depends on what you use the data for, not on the script itself.

### Troubleshooting

**The script does not seem to do anything.** Check the Console for JavaScript errors, and make sure the script sits before your other tracking scripts in the `<head>`. If another script throws an error earlier in the page, the recovery script may never run.

**The cookie still gets deleted.** In some Safari modes ITP restricts localStorage as well, which removes the backup along with the cookie. In that case server-side tracking is the more durable primary solution rather than a client-side recovery layer.

**Different IDs across subdomains.** By default the cookie is scoped to the exact hostname. Adjust the `mkTagging_setCookie` function to include `domain=.yourdomain.com` so the same ID is shared across all subdomains.


# Optimising webhooks for Shopify's Express Checkout

How to keep your marketing attribution data when customers pay through Shopify's Express Checkout

This guide explains how to keep your marketing attribution data when customers pay through Shopify's Express Checkout options such as Shop Pay, PayPal Express, Google Pay and Apple Pay. It covers what goes wrong during those checkouts, and how to fix it using Shopify order notes.

### What happens during Express Checkout

When a customer clicks an Express Checkout button, they skip your normal checkout flow. The order is completed outside the session context where your tracking runs, so the client-side purchase event never fires with the visitor's identifiers attached.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FSHvesfDodQTKBncBdu2C%2Fimage.png?alt=media&amp;token=cd27ab1c-c8b2-45fe-9c41-8aefa0bce1f9" alt="" width="563"><figcaption></figcaption></figure>

That means the following data does not reach your order:

* Client ID
* Session ID
* Session count
* UTM parameters
* GCLID, used for Google Ads attribution

How much this costs you depends on how many of your customers use Express Checkout. In practice we see up to 70 percent of orders arriving without any marketing attribution data at all.

### The solution: Shopify order notes

AdPage works around this by writing the marketing data into the order itself, so it travels with the order regardless of which checkout the customer used.

It works in three steps:

1. **Data capture.** The AdPage tracking code collects the marketing data during the visitor's session.
2. **Order notes.** When the order is placed, that data is stored in the `trytagging_data` note attribute on the order.
3. **Webhook delivery.** The complete marketing data reaches AdPage through the order webhook.

**Prerequisite:** order notes only work once webhooks are installed. If you have not set up webhook notifications for your Shopify store yet, do that first, see the Shopify webhook notification setup guide. GTM templates are available for WordPress, WooCommerce, Shopify and Lightspeed.

### Step 1: remove order notes from anywhere customers can see them

Order notes are now carrying technical tracking data. You do not want customers seeing raw marketing JSON on their checkout page, in their emails, or on invoices and packing slips.

This has to be done in two places. Doing only the first is the single most common mistake.

#### 1A. Adjust your theme and checkout

1. Go to **Online Store → Themes**.
2. Click **Customize** on your active theme.
3. Open **Settings** (the gear icon).
4. Go to **Checkout**.
5. Find the section for **Order notes** or **Additional information**.
6. Remove or hide the order notes field from your checkout.

#### 1B. Adjust your notification templates

This step is essential. Even with order notes removed from your theme, they can still appear on packing slips and invoices, because those are rendered from separate templates.

Go to **Settings → Notifications** and work through:

* Order confirmation (customer email)
* Shipping confirmation (customer email)
* Packing slips (PDF)
* Invoice
* Any other order-related notifications you use

Open each template and look for code along these lines:

```liquid
{% if note_attributes %}
  {% for attribute in note_attributes %}
    <p>{{ attribute.first }}: {{ attribute.last }}</p>
  {% endfor %}
{% endif %}
```

Or:

```liquid
{% if attributes %}
  {% for attribute in attributes %}
    {{ attribute.first }}: {{ attribute.last }}
  {% endfor %}
{% endif %}
```

Or simply:

```liquid
{% if note %}
  {{ note }}
{% endif %}
```

You can either delete these blocks or, better, keep them and filter out `trytagging_data` so any genuine note attributes still show:

```liquid
{% if note_attributes %}
  {% for attribute in note_attributes %}
    {% unless attribute.first == "trytagging_data" %}
      <p>{{ attribute.first }}: {{ attribute.last }}</p>
    {% endunless %}
  {% endfor %}
{% endif %}
```

**For developers:** if your theme uses custom code to render order notes on the order confirmation page or in templates, remove or filter snippets like this one as well:

```liquid
{% if order.note %}
  <div class="order-note">
    {{ order.note }}
  </div>
{% endif %}
```

Back up your templates before you edit them.

### Step 2: enable order notes in the AdPage app

1. Go to your **Online Store**.
2. Navigate to **Themes → Edit theme**.
3. Open **App embeds**.
4. Click **Tagging Head**.
5. Find the option **Use order notes for webhook delivery**.
6. Switch it on.
7. Click **Save**.

### Verifying it works

Test both halves: that the data arrives, and that customers cannot see it.

1. Place a test order.
2. Generate a packing slip: go to **Orders**, select the order, then **More actions → Print packing slips**. Check the PDF, no technical JSON should be visible anywhere on it.
3. Send yourself a test order confirmation email and check it the same way.
4. Check your invoice template too, if you use one.

If you still see `trytagging_data` or raw JSON, you have almost certainly missed a notification template in step 1B rather than done something wrong in the app.

### Best practices

**Do:**

* Use order notes only for technical tracking data once this is active
* Run a complete checkout flow after installation, not just a glance at the settings
* Strip order notes from every customer-facing surface: checkout page, order confirmation email, shipping confirmation email, invoice template, packing slip template, and any other notification template
* Test the packing slip PDF with a real order after implementation
* Keep a backup of your templates before editing them
* Re-test the setting after theme updates, since a theme update can restore the original template code

**Don't:**

* Leave order notes visible to customers
* Assume the theme change is enough and skip the notification templates
* Keep using order notes for actual customer comments once this solution is live
* Skip the verification step

### Frequently asked questions

**Can I still collect customer comments?** Not through the order notes field. Add a separate custom field for customer comments, or use Shopify's Customer Notes instead.

**What if I already use order notes for something else?** AdPage writes to a specific `trytagging_data` attribute, which does not collide with your other note attributes. Rather than deleting the whole block from your templates, filter on that one attribute name, see the code examples in step 1B.

**I still see marketing data on my packing slip. Now what?** You have probably only edited your theme, not the notification templates. Go to **Settings → Notifications** and edit the packing slip template as well. Look for code that renders `note_attributes`, `attributes` or `note`, and remove or filter it.

**Does this work for all payment methods?** Yes. It covers Shop Pay, PayPal Express, Google Pay, Apple Pay and the standard checkout.

**How much difference does this actually make?** For one Shopify client, 72 percent of orders were arriving with no UTM data at all. After enabling order notes, marketing attribution came through for orders across every checkout method, including Express Checkout.

**Can I control per template what gets shown?** Yes. Liquid lets you filter note attributes precisely, so you can show internal notes to your fulfilment team while hiding `trytagging_data` from customers.

**What happens to existing orders?** Existing orders keep their current note data. Only orders placed after you enable the setting receive the marketing tracking data.

Still stuck? Get in touch and we will look at your setup with you.

{% hint style="info" %}
Combine this with the AdPage Data Assistant to get real-time insight into your marketing performance, including orders placed through Express Checkout.
{% endhint %}


# dataLayer events in the Shopify customer events pixel

Shopify's Customer Events run inside a sandboxed web pixel, so which dataLayer events are present in AdPage's Customer Events Pixel?

Shopify's Customer Events run inside a sandboxed web pixel, which means the events fired on the checkout and thank-you pages do not show up in the normal dataLayer the way they do on the rest of your store. You cannot inspect them with GTM Preview mode or by typing `window.dataLayer` into the console.

This article lists every event AdPage sends from Customer Events, with a full example payload for each, so you can configure your tags without needing to debug them live.

### Event overview

| Event                          | Page                 | When it fires                                                     |
| ------------------------------ | -------------------- | ----------------------------------------------------------------- |
| `trytagging_user_data`         | Checkout & Thank you | Every page load                                                   |
| `trytagging_begin_checkout`    | Checkout             | When the checkout opens, immediately after `trytagging_user_data` |
| `trytagging_add_address_info`  | Checkout             | Every time the customer completes their full address              |
| `trytagging_add_shipping_info` | Checkout             | Every time the shipping method changes                            |
| `trytagging_add_payment_info`  | Checkout             | Every time the customer enters payment details and clicks pay     |
| `trytagging_purchase`          | Thank you            | On the payment event from Shopify                                 |

In GTM, set up a Custom Event trigger matching the exact event name for each event you want to use. Note that `trytagging_add_address_info`, `trytagging_add_shipping_info` and `trytagging_add_payment_info` can fire more than once per checkout, so add trigger conditions if you need to deduplicate.

### Shared objects

Three blocks repeat across most events. They are shown in full in every payload below, but you only need to understand them once.

**`marketing`** carries the session and click identifiers: the GA cookie values, `client_id`, `session_id`, `session_count`, the advertising click IDs (`fbp`, `fbc`, `ttclid`, `ttp`, `gclid`, `gbraid`, `wbraid`), the original referrer, UTM parameters, user agent and hostname. Identifiers that are not present in the session come through as `null` rather than being omitted, so your variables will always find the key.

**`user_data`** carries customer details. It contains two sets of fields for the same values: the current `customer_*` fields, and an older set (`id`, `email`, `firstName`, and so on). Always use the `customer_*` fields — the others are deprecated and kept only for backwards compatibility.

**Page-level fields** (`event_time`, `page_referrer`, `page_location`, `page_title`) appear on every event.

***

### Checkout page

#### `trytagging_user_data`

Fires on every page load of the checkout.

```json
{
  "event": "trytagging_user_data",
  "device": {
    "__not_supported": true
  },
  "cart": {
    "total": 2629.95
  },
  "page": {
    "title": "Checkout - Example Shop",
    "location": "https://example-shop.myshopify.com/checkouts/cn/CHECKOUT_TOKEN"
  },
  "marketing": {
    "_ga": "GA1.1.1234567890.1700000000",
    "_ga_XXXXXXXXXX": "GS1.1.1700000000.3.1.1700000600.0.0.0",
    "user_id": "00000000-0000-4000-8000-000000000000",
    "client_id": "1234567890.1700000000",
    "session_id": "1700000000",
    "session_count": "3",
    "fbp": null,
    "fbc": null,
    "ttclid": null,
    "ttp": null,
    "gclid": null,
    "gbraid": null,
    "wbraid": null,
    "referrer": "https://example-shop.myshopify.com/",
    "utm_source": null,
    "utm_medium": null,
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "hostname": "example-shop.myshopify.com"
  },
  "event_time": "2025-02-15T13:41:54.481Z",
  "page_referrer": "https://example-shop.myshopify.com/products/example-product",
  "page_location": "https://example-shop.myshopify.com/checkouts/cn/CHECKOUT_TOKEN",
  "page_title": "Checkout - Example Shop"
}
```

#### `trytagging_begin_checkout`

Fires as soon as the checkout opens, directly after the `trytagging_user_data` event.

```json
{
  "event": "trytagging_begin_checkout",
  "ecommerce": {
    "currency": "EUR",
    "value": 2629.95,
    "coupon": "",
    "items": [
      {
        "item_id": "40000000000001",
        "item_sku": "sku-example-1",
        "item_name": "Example Product",
        "item_brand": "Example Shop",
        "item_category": "",
        "item_variant": "Example Product",
        "price": 2629.95,
        "item_product_id": "40000000000001",
        "item_variant_id": "8000000000001",
        "item_image": "https://cdn.shopify.com/s/files/1/0000/0000/0000/products/example-product_64x64.jpg?v=1700000000",
        "google_business_vertical": "retail",
        "quantity": 1
      }
    ]
  },
  "user_data": {
    "customer_id": "",
    "customer_email": "",
    "customer_first_name": "",
    "customer_last_name": "",
    "customer_name": "undefined undefined",
    "customer_phone": "",
    "customer_zip": "",
    "customer_address": "",
    "customer_address2": "",
    "customer_country": "NL",
    "customer_state": "",
    "customer_state_code": "",
    "customer_order_count": "0",
    "customer_total_spent": 2629.95,
    "customer_city": "",
    "customer_new": false,
    "__note": "Please use customer_ fields. Other fields are deperacted",
    "id": "",
    "email": "",
    "firstName": "",
    "lastName": "",
    "phone": "",
    "zip": "",
    "address1": "",
    "address2": "",
    "country": "NL",
    "province": "",
    "provinceCode": "",
    "orderCount": "0",
    "totalSpent": 2629.95,
    "city": "",
    "new_customer": false
  },
  "marketing": {
    "_ga": "GA1.1.1234567890.1700000000",
    "_ga_XXXXXXXXXX": "GS1.1.1700000000.3.1.1700000600.0.0.0",
    "user_id": "00000000-0000-4000-8000-000000000000",
    "client_id": "1234567890.1700000000",
    "session_id": "1700000000",
    "session_count": "3",
    "fbp": null,
    "fbc": null,
    "ttclid": null,
    "ttp": null,
    "gclid": null,
    "gbraid": null,
    "wbraid": null,
    "referrer": "https://example-shop.myshopify.com/",
    "utm_source": null,
    "utm_medium": null,
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "hostname": "example-shop.myshopify.com"
  },
  "event_time": "2025-02-15T13:41:54.562Z",
  "page_referrer": "https://example-shop.myshopify.com/products/example-product",
  "page_location": "https://example-shop.myshopify.com/checkouts/cn/CHECKOUT_TOKEN",
  "page_title": "Checkout - Example Shop"
}
```

Note that at this point the customer fields are still empty — the visitor has not entered anything yet. `customer_name` reads `undefined undefined` because it concatenates two empty name fields.

#### `trytagging_add_address_info`

Fires every time the customer completes their full address details. This event adds a top-level `email` field and an `address` object alongside the usual blocks.

```json
{
  "event": "trytagging_add_address_info",
  "email": "customer@example.com",
  "address": {
    "address1": "Example Street 1",
    "address2": null,
    "city": "Amsterdam",
    "country": "NL",
    "countryCode": "NL",
    "firstName": "Jane",
    "lastName": "Doe",
    "phone": null,
    "province": null,
    "provinceCode": null,
    "zip": "1234 AB"
  },
  "ecommerce": {
    "currency": "EUR",
    "value": 2629.95,
    "coupon": "",
    "items": [
      {
        "item_id": "40000000000001",
        "item_sku": "sku-example-1",
        "item_name": "Example Product",
        "item_brand": "Example Shop",
        "item_category": "",
        "item_variant": "Example Product",
        "price": 2629.95,
        "item_product_id": "40000000000001",
        "item_variant_id": "8000000000001",
        "item_image": "https://cdn.shopify.com/s/files/1/0000/0000/0000/products/example-product_64x64.jpg?v=1700000000",
        "google_business_vertical": "retail",
        "quantity": 1
      }
    ]
  },
  "user_data": {
    "customer_id": "",
    "customer_email": "customer@example.com",
    "customer_first_name": "Jane",
    "customer_last_name": "Doe",
    "customer_name": "Jane Doe",
    "customer_phone": "",
    "customer_zip": "1234 AB",
    "customer_address": "Example Street 1",
    "customer_address2": "",
    "customer_country": "NL",
    "customer_state": "",
    "customer_state_code": "",
    "customer_order_count": "0",
    "customer_total_spent": 2629.95,
    "customer_city": "Amsterdam",
    "customer_new": false,
    "__note": "Please use customer_ fields. Other fields are deperacted",
    "id": "",
    "email": "customer@example.com",
    "firstName": "Jane",
    "lastName": "Doe",
    "phone": "",
    "zip": "1234 AB",
    "address1": "Example Street 1",
    "address2": "",
    "country": "NL",
    "province": "",
    "provinceCode": "",
    "orderCount": "0",
    "totalSpent": 2629.95,
    "city": "Amsterdam",
    "new_customer": false
  },
  "marketing": {
    "_ga": "GA1.1.1234567890.1700000000",
    "_ga_XXXXXXXXXX": "GS1.1.1700000000.3.1.1700000600.0.0.0",
    "user_id": "00000000-0000-4000-8000-000000000000",
    "client_id": "1234567890.1700000000",
    "session_id": "1700000000",
    "session_count": "3",
    "fbp": null,
    "fbc": null,
    "ttclid": null,
    "ttp": null,
    "gclid": null,
    "gbraid": null,
    "wbraid": null,
    "referrer": "https://example-shop.myshopify.com/",
    "utm_source": null,
    "utm_medium": null,
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "hostname": "example-shop.myshopify.com"
  },
  "event_time": "2025-02-15T13:42:19.517Z",
  "page_referrer": "https://example-shop.myshopify.com/products/example-product",
  "page_location": "https://example-shop.myshopify.com/checkouts/cn/CHECKOUT_TOKEN",
  "page_title": "Checkout - Example Shop"
}
```

#### `trytagging_add_shipping_info`

Fires every time the shipping method changes. The `value` now includes shipping costs, and `ecommerce` gains a `shipping_tier` field.

```json
{
  "event": "trytagging_add_shipping_info",
  "email": "customer@example.com",
  "ecommerce": {
    "shipping_tier": "",
    "currency": "EUR",
    "value": 2634.9,
    "coupon": "",
    "items": [
      {
        "item_id": "40000000000001",
        "item_sku": "sku-example-1",
        "item_name": "Example Product",
        "item_brand": "Example Shop",
        "item_category": "",
        "item_variant": "Example Product",
        "price": 2629.95,
        "item_product_id": "40000000000001",
        "item_variant_id": "8000000000001",
        "item_image": "https://cdn.shopify.com/s/files/1/0000/0000/0000/products/example-product_64x64.jpg?v=1700000000",
        "google_business_vertical": "retail",
        "quantity": 1
      }
    ]
  },
  "user_data": {
    "customer_id": "",
    "customer_email": "customer@example.com",
    "customer_first_name": "Jane",
    "customer_last_name": "Doe",
    "customer_name": "Jane Doe",
    "customer_phone": "",
    "customer_zip": "1234 AB",
    "customer_address": "Example Street 1",
    "customer_address2": "",
    "customer_country": "NL",
    "customer_state": "",
    "customer_state_code": "",
    "customer_order_count": "0",
    "customer_total_spent": 2634.9,
    "customer_city": "Amsterdam",
    "customer_new": false,
    "__note": "Please use customer_ fields. Other fields are deperacted",
    "id": "",
    "email": "customer@example.com",
    "firstName": "Jane",
    "lastName": "Doe",
    "phone": "",
    "zip": "1234 AB",
    "address1": "Example Street 1",
    "address2": "",
    "country": "NL",
    "province": "",
    "provinceCode": "",
    "orderCount": "0",
    "totalSpent": 2634.9,
    "city": "Amsterdam",
    "new_customer": false
  },
  "marketing": {
    "_ga": "GA1.1.1234567890.1700000000",
    "_ga_XXXXXXXXXX": "GS1.1.1700000000.3.1.1700000600.0.0.0",
    "user_id": "00000000-0000-4000-8000-000000000000",
    "client_id": "1234567890.1700000000",
    "session_id": "1700000000",
    "session_count": "3",
    "fbp": null,
    "fbc": null,
    "ttclid": null,
    "ttp": null,
    "gclid": null,
    "gbraid": null,
    "wbraid": null,
    "referrer": "https://example-shop.myshopify.com/",
    "utm_source": null,
    "utm_medium": null,
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "hostname": "example-shop.myshopify.com"
  },
  "event_time": "2025-02-15T13:42:20.612Z",
  "page_referrer": "https://example-shop.myshopify.com/products/example-product",
  "page_location": "https://example-shop.myshopify.com/checkouts/cn/CHECKOUT_TOKEN",
  "page_title": "Checkout - Example Shop"
}
```

#### `trytagging_add_payment_info`

Fires every time the customer enters their payment details and clicks pay. Structurally identical to the shipping event, except `ecommerce` carries `payment_type` instead of `shipping_tier`.

```json
{
  "event": "trytagging_add_payment_info",
  "email": "customer@example.com",
  "ecommerce": {
    "payment_type": "",
    "currency": "EUR",
    "value": 2634.9,
    "coupon": "",
    "items": [
      {
        "item_id": "40000000000001",
        "item_sku": "sku-example-1",
        "item_name": "Example Product",
        "item_brand": "Example Shop",
        "item_category": "",
        "item_variant": "Example Product",
        "price": 2629.95,
        "item_product_id": "40000000000001",
        "item_variant_id": "8000000000001",
        "item_image": "https://cdn.shopify.com/s/files/1/0000/0000/0000/products/example-product_64x64.jpg?v=1700000000",
        "google_business_vertical": "retail",
        "quantity": 1
      }
    ]
  },
  "user_data": {
    "customer_id": "",
    "customer_email": "customer@example.com",
    "customer_first_name": "Jane",
    "customer_last_name": "Doe",
    "customer_name": "Jane Doe",
    "customer_phone": "",
    "customer_zip": "1234 AB",
    "customer_address": "Example Street 1",
    "customer_address2": "",
    "customer_country": "NL",
    "customer_state": "",
    "customer_state_code": "",
    "customer_order_count": "0",
    "customer_total_spent": 2634.9,
    "customer_city": "Amsterdam",
    "customer_new": false,
    "__note": "Please use customer_ fields. Other fields are deperacted",
    "id": "",
    "email": "customer@example.com",
    "firstName": "Jane",
    "lastName": "Doe",
    "phone": "",
    "zip": "1234 AB",
    "address1": "Example Street 1",
    "address2": "",
    "country": "NL",
    "province": "",
    "provinceCode": "",
    "orderCount": "0",
    "totalSpent": 2634.9,
    "city": "Amsterdam",
    "new_customer": false
  },
  "marketing": {
    "_ga": "GA1.1.1234567890.1700000000",
    "_ga_XXXXXXXXXX": "GS1.1.1700000000.3.1.1700000600.0.0.0",
    "user_id": "00000000-0000-4000-8000-000000000000",
    "client_id": "1234567890.1700000000",
    "session_id": "1700000000",
    "session_count": "3",
    "fbp": null,
    "fbc": null,
    "ttclid": null,
    "ttp": null,
    "gclid": null,
    "gbraid": null,
    "wbraid": null,
    "referrer": "https://example-shop.myshopify.com/",
    "utm_source": null,
    "utm_medium": null,
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "hostname": "example-shop.myshopify.com"
  },
  "event_time": "2025-02-15T13:48:11.987Z",
  "page_referrer": "https://example-shop.myshopify.com/products/example-product",
  "page_location": "https://example-shop.myshopify.com/checkouts/cn/CHECKOUT_TOKEN",
  "page_title": "Checkout - Example Shop"
}
```

***

### Thank-you page

#### `trytagging_purchase`

Fires on the payment event from Shopify. This is the event to use for your conversion tags. `ecommerce` now contains `transaction_id`, `tax` and `shipping`, and `user_data.customer_id` is populated because the order has created a customer record.

```json
{
  "event": "trytagging_purchase",
  "ecommerce": {
    "transaction_id": "6000000000001",
    "value": 2634.9,
    "tax": 0,
    "shipping": "",
    "currency": "EUR",
    "items": [
      {
        "item_id": "40000000000001",
        "item_sku": "sku-example-1",
        "item_name": "Example Product",
        "item_brand": "Example Shop",
        "item_category": "",
        "item_variant": "Default Title",
        "price": 2629.95,
        "item_product_id": "00000000000000000000000000000000",
        "item_variant_id": "8000000000001",
        "item_image": "https://cdn.shopify.com/s/files/1/0000/0000/0000/products/example-product.jpg?v=1700000000",
        "google_business_vertical": "retail",
        "quantity": 1
      }
    ]
  },
  "user_data": {
    "customer_id": "7000000000001",
    "customer_email": "customer@example.com",
    "customer_first_name": "Jane",
    "customer_last_name": "Doe",
    "customer_name": "Jane Doe",
    "customer_phone": "",
    "customer_zip": "1234 AB",
    "customer_address": "Example Street 1",
    "customer_address2": "",
    "customer_country": "NL",
    "customer_state": "",
    "customer_state_code": "",
    "customer_order_count": "0",
    "customer_total_spent": 2634.9,
    "customer_city": "Amsterdam",
    "customer_new": false,
    "__note": "Please use customer_ fields. Other fields are deperacted",
    "id": "7000000000001",
    "email": "customer@example.com",
    "firstName": "Jane",
    "lastName": "Doe",
    "phone": "",
    "zip": "1234 AB",
    "address1": "Example Street 1",
    "address2": "",
    "country": "NL",
    "province": "",
    "provinceCode": "",
    "orderCount": "0",
    "totalSpent": 2634.9,
    "city": "Amsterdam",
    "new_customer": false
  },
  "marketing": {
    "_ga": "GA1.1.1234567890.1700000000",
    "_ga_XXXXXXXXXX": "GS1.1.1700000000.3.1.1700000900.0.0.0",
    "user_id": "00000000-0000-4000-8000-000000000000",
    "client_id": "1234567890.1700000000",
    "session_id": "1700000000",
    "session_count": "3",
    "fbp": null,
    "fbc": null,
    "ttclid": null,
    "ttp": null,
    "gclid": null,
    "gbraid": null,
    "wbraid": null,
    "referrer": "https://example-shop.myshopify.com/",
    "utm_source": null,
    "utm_medium": null,
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
    "hostname": "example-shop.myshopify.com"
  },
  "event_time": "2025-02-15T13:48:14.579Z",
  "page_referrer": "https://example-shop.myshopify.com/",
  "page_location": "https://example-shop.myshopify.com/checkouts/cn/ORDER_TOKEN/thank_you",
  "page_title": "Thank you for your purchase! - Example Shop - Checkout"
}
```

### A few things worth knowing

**Values are placeholders.** All URLs, identifiers, names, email addresses and addresses in the examples above are anonymised. The field names and structure are exactly what you will receive.

**`item_product_id` changes format on purchase.** On the checkout events it matches `item_id`. On `trytagging_purchase` it is a hash instead. If you map this field to a tag parameter, expect two different formats and pick the one your platform needs.

**`item_variant` changes on purchase.** On checkout events it repeats the product name; on the purchase event it comes from the Shopify variant title, which is `Default Title` for single-variant products.

**Some parameters can come through empty.** `shipping_tier`, `payment_type`, `coupon` and `shipping` are empty strings in these examples. If your GA4 reports show blank values for these, that is why. Set a fallback in your variables if you need a value.

**`device` is not populated.** Shopify's sandbox does not expose device information, hence `"__not_supported": true`.


# Disabling order note population in Shopify

By default, the AdPage Tagging app writes marketing and user information into the order notes of your Shopify orders

By default, the AdPage Tagging app writes marketing and user information into the order notes of your Shopify orders. This data underpins the AdPage backend webhook functionality, which is what reliably forwards conversion data to your server-side tracking setup.

**We strongly recommend leaving this enabled.** Switching it off will affect the stability and completeness of your tracking. Read the alternatives below before you do.

### Why you might want to switch it off

Some shops print their Shopify orders in full as a packing slip or invoice, order notes included. In that case the marketing data AdPage adds becomes visible on documents your customer receives, which is obviously not what you want.

That is a real problem, but disabling order notes is the heaviest possible fix for it. Try these two options first.

#### Option 1: exclude order notes from your print layout

Check whether your packing slip or invoice app offers control over which fields get printed. Many Shopify print apps let you exclude order notes from the layout entirely, which solves the problem without touching your tracking.

#### Option 2: filter out the tracking attribute only

If you are using Shopify's built-in notification and packing slip templates, you can filter the AdPage data out of them in Liquid while leaving everything else intact. This is the preferred solution, because it hides the technical data from customers and keeps your webhook delivery complete. See our guide on optimising webhooks for Express Checkout for the exact template code.

### What you lose by disabling it

If neither option is workable and the order notes genuinely have to stay empty, you can switch the setting off. Be aware of the trade-off first.

Order notes are how marketing data reaches the webhook for orders placed outside your normal checkout flow, Shop Pay, PayPal Express, Google Pay and Apple Pay. With the setting disabled, those orders arrive without client ID, session ID, UTM parameters or GCLID. Depending on how many of your customers use Express Checkout, that can affect a substantial share of your orders, and the attribution data for them is not recoverable afterwards.

If Express Checkout is disabled in your store, the impact is considerably smaller.

### How to disable it

1. Open your Shopify admin.
2. Go to **Online Store**.
3. Click **Customize** on your theme.
4. In the left-hand menu, select **App embeds**.
5. Expand the **Tagging Head** app embed from AdPage Tagging.
6. Uncheck **Use order notes for webhook delivery**.
7. Save using the button in the top right.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F2dQ8Jh7eQcj3oTUq3TlZ%2Fimage.png?alt=media&amp;token=0fc44ed2-4337-43bc-9960-e04f90e24c05" alt=""><figcaption></figcaption></figure>

The change applies to new orders only. Orders already placed keep the data that was written to them.

### Turning it back on

Follow the same steps and re-check the box. Marketing data will start being written to order notes again from that moment, but nothing is backfilled, orders placed while the setting was off stay incomplete.


# Disconnecting old marketing scripts in Shopify

How to disconnect various analytics and advertising tools from your Shopify store to ensure there will be no double tracking.

When you publish your server-side tagging setup, Shopify’s built-in sales channel apps may still be sending data directly to Google, Meta, TikTok and Pinterest. If these connections stay active, events are tracked twice: once through your server-side setup and once through Shopify itself.

This guide explains step by step how to disconnect these native integrations. This turns off third-party tracking from Shopify and makes sure your server container URL is the leading destination for your data, instead of Shopify’s own GA4 connection. Follow the instructions below for Google Analytics 4, Meta Ads, TikTok Ads and Pinterest.

### Google Analytics 4

To disconnect Google Analytics 4:

* Navigate to the Google & YouTube app in Shopify.&#x20;
* Open the settings of this app.
* If a Google Analytics property is still connected, disconnect it.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FVXl4DDLp8TqBWmbwp1X3%2Fimage.png?alt=media&amp;token=6c884de1-a55e-4e4d-af24-15b8ca18ba04" alt=""><figcaption></figcaption></figure>

* Also ensure the Conversion Tracking option is turned off.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FfA1U6TnW7gmkM6m3lxh3%2Fimage.png?alt=media&amp;token=1437481c-1f54-4a09-be1b-d19dfb131692" alt=""><figcaption></figcaption></figure>

### Meta Ads

To disconnect Meta Ads:

* Go to the Facebook & Instagram app in Shopify.
* Click Settings at the top.
* If Data sharing is turned on, ensure that you disable this option.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FvFUXV9FQ77RnygufwXWe%2Fimage%20(56).png?alt=media&amp;token=a56027d1-1b75-4d0f-8196-2636ff28ae09" alt=""><figcaption></figcaption></figure>

* Also check the tracking settings in your Meta Events Manager configuration.

### TikTok Ads

To disconnect TikTok Ads:

* Go to the TikTok app in Shopify.
* Click Settings at the top.
* Go to the Data sharing settings.
* Click Disconnect next to the Pixel.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FLBI6iB924k4SerhcEAmn%2Fimage%20(57).png?alt=media&amp;token=aab9a85b-32a7-40cd-92d8-f7489967f593" alt=""><figcaption></figcaption></figure>

### Pinterest

To disconnect Pinterest:

* Go to the Pinterest app in Shopify.
* Go to the Marketing settings.
* Make sure the Pinterest tag is disconnected, so you no longer share data directly with Pinterest.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FqPuwEduqKXy0RcK2U3MT%2Fimage%20(58).png?alt=media&amp;token=235a589c-34e7-4a90-9cbb-e7e44e2e7625" alt=""><figcaption></figcaption></figure>


# Installing AdPage on a Shopify Markets store

A Shopify Markets store needs a different AdPage setup: each market gets its own GTM container and tagging domain, selected in the theme code instead of in the AdPage app.

Shopify Markets lets you sell in several countries or regions from one Shopify store, each market on its own domain. Two things don't work the standard way. The AdPage Shopify app can't store different settings per domain, and Shopify only lets you create one order webhook for the whole store. This article covers only the steps that differ from the standard implementation.

### Before you start

Duplicate your live theme first (Online Store → Themes → Actions (…) → Duplicate), so you can roll back if needed.

Collect these values for every market:

| Placeholder            | What to fill in                                                               | Example                      |
| ---------------------- | ----------------------------------------------------------------------------- | ---------------------------- |
| \[LANGUAGE CODE]       | The market's language code, as Shopify returns it in request.locale.iso\_code | de                           |
| \[SERVER URL]          | The market's tagging URL, including https\://                                 | <https://tagging.example.de> |
| \[SERVER DOMAIN]       | The same tagging domain, without https\://                                    | tagging.example.de           |
| \[LOADER ID]           | The custom loader ID, if the container uses one                               | Leave empty ('') if not used |
| \[GTM-ID]              | The market's GTM web container ID                                             | GTM-ABC1234                  |
| \[GTM-ID without GTM-] | The same ID without the GTM- prefix                                           | ABC1234                      |
| \[STORE DOMAIN]        | The market's storefront domain                                                | example.de                   |

The theme code selects the container by language code, so every market must use a different language.

### Step 1: Add the Cookie Keeper script

Go to Online Store → Themes → Actions (…) → Edit code and open theme.liquid. Paste the script below in the \<head> section, above the Google Tag Manager code.

The script stores a visitor ID in the \_taggingmk cookie and keeps a backup in localStorage, so the ID is restored if the cookie disappears.

```html
<script type="text/javascript">
(function() {
    'use strict';
    
    // Generate UUID v4 (compatible method)
    function mkTagging_generateUUID() {
        // Fallback for older browsers without crypto API
        if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
            return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, function(c) {
                return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);
            });
        } else {
            // Less secure fallback for very old browsers
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0;
                var v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    }
    
    // Get cookie value by name
    function mkTagging_getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
    
    // Set cookie with expiration
    function mkTagging_setCookie(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        // Set both path and SameSite for better compatibility
        document.cookie = name + "=" + value + expires + "; path=/; SameSite=Lax";
    }
    
    // Safe localStorage wrapper
    function mkTagging_getLocalStorage(key) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                return localStorage.getItem(key);
            }
        } catch (e) {
            // localStorage might be blocked or unavailable
            console.log('localStorage not available:', e);
        }
        return null;
    }
    
    function mkTagging_setLocalStorage(key, value) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                localStorage.setItem(key, value);
                return true;
            }
        } catch (e) {
            // localStorage might be blocked or unavailable
            console.log('localStorage not available:', e);
        }
        return false;
    }
    
    // Main initialization function
    function mkTagging_initVisitorId() {
        var cookieName = '_taggingmk';
        var storageKey = '_taggingmk_backup';
        var visitorId = null;
        
        // 1. Check if cookie exists
        visitorId = mkTagging_getCookie(cookieName);
        
        // 2. If no cookie, check localStorage backup
        if (!visitorId) {
            visitorId = mkTagging_getLocalStorage(storageKey);
            
            // If found in localStorage but not in cookie, restore the cookie
            if (visitorId) {
                mkTagging_setCookie(cookieName, visitorId, 365);
                console.log('MK Tagging: Visitor ID restored from localStorage:', visitorId);
            }
        }
        
        // 3. If still no ID, generate a new one
        if (!visitorId) {
            visitorId = mkTagging_generateUUID();
            mkTagging_setCookie(cookieName, visitorId, 365);
            console.log('MK Tagging: New visitor ID generated:', visitorId);
        }
        
        // 4. Always sync to localStorage as backup (if available)
        if (mkTagging_setLocalStorage(storageKey, visitorId)) {
            console.log('MK Tagging: Visitor ID backed up to localStorage');
        }
        
        // Return the visitor ID for potential use
        return visitorId;
    }
    
    // Run on DOM ready or immediately if already loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', mkTagging_initVisitorId);
    } else {
        // DOM is already loaded
        mkTagging_initVisitorId();
    }
    
    // Create a namespaced object for any exposed functionality
    window.mkTagging = window.mkTagging || {};
    window.mkTagging.getVisitorId = function() {
        return mkTagging_getCookie('_taggingmk') || mkTagging_getLocalStorage('_taggingmk_backup');
    };
    
})();
</script>
```

### Step 2: Add the GTM head code

Paste the code below directly after the Cookie Keeper script, still in the \<head> section. It loads the right GTM container for each market through that market's tagging domain. It also passes consent updates from your cookie banner to Shopify's Customer Privacy API.

Replace \[LANGUAGE CODE], \[GTM-ID], \[SERVER URL] and \[LOADER ID] for each market. The example has three markets: add or remove a when block (four lines) to match your number of markets.

```liquid
{%- case request.locale.iso_code -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
    {%- assign loader_id = '[LOADER ID]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
    {%- assign loader_id = '[LOADER ID]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
    {%- assign loader_id = '[LOADER ID]' -%}
{%- endcase -%}

<script>
  window.trytagging_new_version = {% if loader_id != blank %}true{% else %}false{% endif %};
  window.dataLayerName = "dataLayer";
  window[window.dataLayerName] = window[window.dataLayerName] || [];
  window.trytagging_disable_order_notes = true;
</script>

<script>
  (function () {
    function t(t, e, r) {
      if ("cookie" === t) {
        var n = document.cookie.split(";");
        for (var o = 0; o < n.length; o++) {
          var i = n[o].split("=");
          if (i[0].trim() === e) return i[1];
        }
      } else if ("localStorage" === t) return localStorage.getItem(e);
      else if ("jsVariable" === t) return window[e];
      else console.warn("invalid uid source", t);
    }
    function e(e, r, n) {
      var o = document.createElement("script");
      (o.async = !0), (o.src = r), e.insertBefore(o, n);
    }
    function r(r, n, o, i, a) {
      var c,
        s = !1;
      try {
        var u = navigator.userAgent,
          f = /Version\/([0-9\._]+)(.*Mobile)?.*Safari.*/.exec(u);
        f && parseFloat(f[1]) >= 16.4 && ((c = t(o, i, "")), (s = !0));
      } catch (t) {
        console.error(t);
      }
      var l = (window[a] = window[a] || []);
      l.push({ "gtm.start": new Date().getTime(), event: "gtm.js" });

      var dl = a != "dataLayer" ? "&l=" + a : "";

      var g =
          r +
          "{% if loader_id != blank %}/{{ loader_id }}.js?sp={{ gtm_id | remove: 'GTM-' }}{% else %}/script.js?id={{ gtm_id | remove: 'GTM-' }}{% endif %}" +
          (s ? "&enableCK=true" : "") +
          (c ? "&mcookie=" + encodeURIComponent(c) : "") +
          dl,
        d = document.getElementsByTagName("script")[0];
      e(d.parentNode, g, d);
    }
    r(
      "{{ tagging_url }}",
      "{{ gtm_id | remove: 'GTM-' }}",
      "undefined",
      "undefined",
      window.dataLayerName
    );
  })();

const dataLayerName = window.dataLayerName ?? "dataLayer";
let hasSentConsent = false;

if (window[dataLayerName]) {
  const originalDataLayerPush = window[dataLayerName].push;

  window[dataLayerName].push = (...args) => {
    originalDataLayerPush.apply(window[dataLayerName], args);

    try {
      if (args[0][0] === "consent" && args[0][1] === "update") {
        const consentArgs = {
          analytics: args[0][2].analytics_storage === "granted",
          marketing:
            args[0][2].ad_storage === "granted" &&
            args[0][2].ad_personalization === "granted" &&
            args[0][2].ad_user_data === "granted",
          preferences: args[0][2].personalization_storage === "granted",
          sale_of_data: args[0][2].ad_user_data === "granted",
        };

        // Wait for the consent to be set
        if (!hasSentConsent) {
          window.Shopify.loadFeatures(
            [
              {
                name: "consent-tracking-api",
                version: "0.1",
              },
            ],
            function (error) {
              if (error) console.error("Error loading consent-tracking-api", error);
              window.Shopify.customerPrivacy.setTrackingConsent(
                consentArgs,
                () => {}
              );
            }
          );
          hasSentConsent = true;
        }
      }
    } catch (error) {
      console.error("Error setting tracking consent", error);
    }
  };
}
</script>
```

### Step 3: Update the body section

In the same theme.liquid file, find the GTM code directly after the opening \<body> tag and replace it with the code below. It adds the noscript fallback and loads the AdPage Shopify dataLayer script from the market's tagging domain.

Replace \[LANGUAGE CODE], \[GTM-ID] and \[SERVER URL] with the same values as in step 2. Add or remove a when block (three lines) to match your number of markets.

```liquid
{%- case request.locale.iso_code -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
  {%- when '[LANGUAGE CODE]' -%}
    {%- assign gtm_id = '[GTM-ID]' -%}
    {%- assign tagging_url = '[SERVER URL]' -%}
{%- endcase -%}

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="{{ tagging_url }}/ns.html?id={{ gtm_id }}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager -->

<script>
  (function() {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.defer = true;
    script.src = "{{ tagging_url }}/shopify-datalayer-minified.js";

    script.onerror = () => {
      console.error("Tagging Data Layer: JS script failed to load");
    };

    script.onload = async () => {
      window.taggingHelpers.updateShopSettings(({{- page_title | json -}}), {{- cart.currency.iso_code | json -}});
      await window.taggingHelpers.initFetching();
      window.taggingHelpers.userDataWithCart({{- cart | json -}});

      {%- if collection and template.name == "collection" -%}
      const listId = {{- collection.id | json -}};
      const listName = {{- collection.title | json -}};
      const items = [
        {%- assign itemIndex = 1 -%}
        {%- for product in collection.products -%}
        {%- for variant in product.variants limit:1 -%} {
          item_id : {{- variant.id | json -}},
          item_name: {{- product.title | json -}},
          item_brand: {{- product.vendor | json -}},
          item_category: {{- product.type | json -}},
          item_variant: {{- variant.title | json -}},
          item_sku: {{- variant.sku | json -}},
          price: "{{- product.price | times: 0.01 | json -}}",
          position: {{- itemIndex -}},
          item_variant_id: {{- variant.id | json -}},
          item_product_id: {{- product.id | json -}},
          item_image: {{- product.featured_image | json -}},
          handle: {{- product.handle | json -}}
        },
        {%- endfor -%}
        {%- assign itemIndex = itemIndex | plus: 1 -%}
        {%- endfor -%}];
      window.taggingHelpers.viewItemList(listId, listName, items);
      window.taggingHelpers.bindListItems(listId, listName, items);
      {%- endif -%}

      {%- if product -%}
      const item = {
        {% assign default_variant = product.selected_or_first_available_variant %}
        {%- if default_variant != blank -%}
        defaultVariant : {
          item_id : {{- default_variant.id | json -}},
          item_name: {{- product.title | json -}},
          item_brand: {{- product.vendor | json -}},
          item_category: {{- product.type | json -}},
          item_variant: {{- default_variant.title | json -}},
          item_sku: {{- default_variant.sku | json -}},
          price: "{{- default_variant.price | times: 0.01 | json -}}",
          item_product_id: {{- product.id | json -}},
          item_variant_id: {{- default_variant.id | json -}},
          compareAtPrice: "{{- default_variant.compare_at_price | times: 0.01 | json -}}",
          item_image: {{- product.featured_image | json -}},
          currency: {{- cart.currency.iso_code | json -}},
        },
        {%- else -%}
        defaultVariant : null,
        {%- endif -%}
        items: [
          {%- for variant in product.variants -%} {
            item_id : {{- variant.id | json -}},
            item_name: {{- product.title | json -}},
            item_brand: {{- product.vendor | json -}},
            item_category: {{- product.type | json -}},
            item_variant: {{- variant.title | json -}},
            item_sku: {{- variant.sku | json -}},
            price: "{{- variant.price | times: 0.01 | json -}}",
            item_product_id: {{- product.id | json -}},
            item_variant_id: {{- variant.id | json -}},
            compareAtPrice: "{{- variant.compare_at_price | times: 0.01 | json -}}",
            item_image: {{- product.featured_image | json -}}
          },
          {%- endfor -%}],
      };
      const value = item.defaultVariant?.price ?? item.items[0].price;
      window.taggingHelpers.viewItem(item, value);
      {%- endif -%}

      {%- if request.page_type == "cart" -%}
      window.taggingHelpers.handleViewCart();
      {%- endif -%}

      window.taggingHelpers.init();
    }

    document.body.appendChild(script);
  })();
</script>
```

### Step 4: Add the Customer Events pixel

Go to Settings → Customer events → Add custom pixel and create a new pixel with the code below. This pixel handles tracking in the checkout, where the theme code doesn't run.

Replace \[SERVER DOMAIN], \[STORE DOMAIN], \[GTM-ID] and \[GTM-ID without GTM-]. Note: here \[SERVER DOMAIN] goes in without https\://, because the code adds it. In apShopifyConfig at the top, fill in your main market. Add or remove an if block to match your number of markets.

If one store domain contains another (for example example.com and shop.example.com), put the longer domain first.

```javascript
const apShopifyConfig = {
  version: "1.0.0",
  cookieKeeperType: "cookie",
  cookieKeeperStorageName: "_taggingmk",
  domain: "[SERVER DOMAIN]",
  pixelId: "[GTM-ID]",
};
const page_location = init?.context?.document?.location?.href ?? "";
const load_pixel =
  page_location.includes("checkout") || page_location.length === 0;

function getShopConfig() {
  if (page_location.includes("[STORE DOMAIN]")) {
    return {
      ...apShopifyConfig,
      truncatedPixelId: "[GTM-ID without GTM-]",
      domain: "[SERVER DOMAIN]",
    };
  }

  if (page_location.includes("[STORE DOMAIN]")) {
    return {
      ...apShopifyConfig,
      truncatedPixelId: "[GTM-ID without GTM-]",
      domain: "[SERVER DOMAIN]",
    };
  }

  if (page_location.includes("[STORE DOMAIN]")) {
    return {
      ...apShopifyConfig,
      truncatedPixelId: "[GTM-ID without GTM-]",
      domain: "[SERVER DOMAIN]",
    };
  }

  return apShopifyConfig;
}

if (load_pixel) {
  (function () {
    function t(t, e, r) {
      if ("cookie" === t) {
        var n = document.cookie.split(";");
        for (var o = 0; o < n.length; o++) {
          var i = n[o].split("=");
          if (i[0].trim() === e) return i[1];
        }
      } else if ("localStorage" === t) return localStorage.getItem(e);
      else if ("jsVariable" === t) return window[e];
      else console.warn("invalid uid source", t);
    }
    function e(e, r, n) {
      var o = document.createElement("script");
      (o.async = !0), (o.src = r), e.insertBefore(o, n);
    }
    function r(r, n, o, i, a) {
      var c,
        s = !1;
      try {
        var u = navigator.userAgent,
          f = /Version\/([0-9\._]+)(.*Mobile)?.*Safari.*/.exec(u);
        f && parseFloat(f[1]) >= 16.4 && ((c = t(o, i, "")), (s = !0));
      } catch (t) {
        console.error(t);
      }
      var l = (window[a] = window[a] || []);
      l.push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
      var g =
          r +
          "/Q1dUWlEmZW52.js?tg=" +
          n +
          (s ? "&enableCK=true" : "") +
          (c ? "&mcookie=" + encodeURIComponent(c) : ""),
        d = document.getElementsByTagName("script")[0];
      e(d.parentNode, g, d);
    }
    r(
      `https://${getShopConfig().domain}`,
      getShopConfig().truncatedPixelId,
      "cookie",
      "_taggingmk",
      "dataLayer"
    );
  })();
}

const execute = async (api) => {
  if (load_pixel) {
    console.log(`Loading pixel for ${getShopConfig().domain}`);
    const scriptUrl = `https://${getShopConfig().domain}/pixel-minified.js`;
    try {
      if (scriptUrl) {
        const module = await import(scriptUrl);
        module.default(api, getShopConfig());
      }
    } catch (e) {
      console.error(e);
    }
  }
};

execute({ analytics, browser, init });
```

Save the pixel and click Connect to activate it.

### Step 5: Set up the webhook and the RegEx Table variable

Shopify doesn't let you create a separate manual webhook per market domain. Create one webhook for /order\_created in the Shopify backend.

As a result, the server container and Google Tag Manager receive every webhook from one domain, even though the orders were placed on different market domains.

In Google Tag Manager, don't base your RegEx Table variable on marketing.hostname, as you would for a standard Shopify store. Use parsed\_data.order\_status\_url as its input instead. This URL contains the domain of the market where the order was placed.

The input is now a full URL instead of a hostname. If your RegEx Table patterns match exact hostnames, untick Full matches only under Advanced Settings, or adjust the patterns (for example `.*example\.de.*`).

### Step 6: Check the implementation

Check the following on every market domain:

* Browser console: no JavaScript errors.
* Cookies: the \_taggingmk cookie is created.
* Network tab: requests go to the tagging domain of that market.
* GTM preview: after a test order, the RegEx Table variable returns the value for the market where the order was placed.

### Step 7: Uninstall the AdPage app

Only do this after step 6 confirms that all tracking works with the new implementation.

1. Go to Apps → AdPage.
2. Click Uninstall app or Disable app.
3. Confirm.

The app is no longer needed, because tracking now runs fully through the server-side implementation. No AdPage app installed? Skip this step.


# Magento

How to set up server-side tagging for a Magento webshop

***

## Setting up server-side tagging for Magento

This article walks you through the full setup of server-side tagging on a Magento store: generating your Google Tag Manager templates, importing them, filling in your IDs, testing them, and finally removing the old tracking connections that Magento made for you.

### Before you start

This article picks up where **Getting Started** leaves off. Make sure all of the steps in the [Setup AdPage container](/getting-started/setup-adpage-container) article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The **AdPage Magento Module** is installed in your store.

{% hint style="warning" %}
If one of these steps is still open, finish it first. Everything below assumes your server container is reachable on your own domain and that the Magento Module is pushing data into the dataLayer.
{% endhint %}

{% hint style="info" %}
We recommend setting up the AdPage Magento Module on a staging-enviroment, and following all the steps below based on the frontend of the staging-enviroment.
{% endhint %}

***

### Step 1: Generate your templates in the Template Library

You do not have to build your tags, triggers and variables by hand. AdPage's Template Library generates a complete, tested Google Tag Manager setup for Magento for you.

1. Go to [data.adpage.io/template-library](https://data.adpage.io/template-library).
2. Select the marketing platforms you want to send data to, for example Google Ads, Meta Ads, TikTok Ads, LinkedIn Ads or Pinterest Ads.
3. Select the Consent Management Platform you use on your Magento webshop.
4. Generate the templates. You get **two JSON files**: one for your GTM **web** container and one for your GTM **server** container.
5. Download both files and keep them handy.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fo4nPmZrjh5NFMGAYOnPp%2Fimage.png?alt=media&amp;token=a8b98f2d-df97-4c6a-9a20-c91350247029" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Only select the platforms you actually use. Every platform you add creates extra tags and constant variables that you will need to fill in later.
{% endhint %}

***

### Step 2: Import the web container template

1. Open your **GTM web container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **web** JSON file you downloaded.
4. Choose a workspace.&#x20;
   * If you have unpublished changes in your default workspace, we recommend importing into a **new workspace** so your import stays separate from any other work in progress.
5. Choose the import option:
   * **Merge and rename conflicting tags, triggers and variables** for a container that already contains a setup. Nothing existing gets removed.
   * **Overwrite** only for a brand new, empty container.
6. Check the preview of the changes that GTM shows you, then click **Confirm**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F3CKvxX1mSb1O2JBpcE4Q%2Fimage.png?alt=media&amp;token=ee12042d-41d9-4406-95f9-9e2eaf8d3bc1" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM web container yet. The tags in the import are still missing your IDs, which you fill in at step 4.
{% endhint %}

***

### Step 3: Import the server container template

Repeat the same steps in your **GTM server container** with the **server** JSON file.

1. Open your **GTM server container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **server** JSON file.
4. Import into a new workspace and choose **Merge and rename conflicting tags, triggers and variables**.
5. Check the preview and click **Confirm**.
6. Go to **Clients** and check if an extra GA4 client has been set up. If so, delete the imported GA4 client.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyhuHijhZUYGKSi2cG86j%2Fimage.png?alt=media&amp;token=fbe37ee9-0cec-4291-8c7d-b9f5569cb1d6" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM server container yet. The tags in the import are still missing your IDs and tokens, which you fill in at step 4.
{% endhint %}

***

### Step 4: Fill in the constant variables

Both templates are built around **constant variables**. All IDs, tokens and settings live in one place, so you never have to open individual tags to change something.

1. In your GTM web container, go to **Variables**.
2. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
3. Save each variable.
4. In your GTM server container, go to **Variables**.
5. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
6. Save each variable.

Depending on the platforms you selected, you will typically fill in:

<table><thead><tr><th width="118">Container</th><th width="240">Variable</th><th>Value</th></tr></thead><tbody><tr><td>Web</td><td>Server Container URL</td><td>The tagging domain from your CNAME record, for example: <code>https://tagging.domain.com</code></td></tr><tr><td>Web</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Tag ID</a></td><td>Your Pinterest Tag ID, found in the Tag Manager of your Pinterest Ads Account</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Partner ID</a></td><td>Your LinkedIn Partner ID, found in the Signals Manager of your LinkedIn Ads Account</td></tr><tr><td>Web</td><td>Cookiebot Domain Group ID</td><td>The Domain Group ID from your Cookiebot account</td></tr><tr><td>Server</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta API Ttoken</a></td><td>The API Token of your Pixel from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok API Token</a></td><td>The API Token of your Pixel from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion ID</a></td><td>Your Google Ads Conversion ID: <br><code>AW-XXXXXXXXXX</code> minus the <code>AW-</code> part</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion Labels</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in Google Ads. Once set up, you can find their Conversion Labels.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Advertiser ID</a></td><td>The Advertiser ID from your Ad Account. This ID usually starts with 549.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest API Token</a></td><td>The API Token found in your Conversions API settings of your Pinterest Business Account.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn API Token</a></td><td>The API Token which you can generate in your LinkedIn Campaign Manager in the Sources.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Conversion IDs</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in LinkedIn Ads. Once set up, you can find their Conversion IDs in the URL of the conversion.</td></tr></tbody></table>

{% hint style="info" %}
Never leave a constant variable empty. An empty ID means tags fire without a destination, which shows up as missing conversions or failed outgoing requests later on.
{% endhint %}

***

### Step 5: Test in preview mode

You have just imported container templates with complete tracking for GA4 and the marketing platforms you selected. That means everything you need is now present in your GTM containers, and anything that was already there for the same purpose is a duplicate.

#### **Disable your old tags first**

Go through the tags in your web container and pause or delete every tag that measures something your new setup now handles. In practice this is your old GA4 configuration tag, all GA4 event tags for e-commerce steps such as `add_to_cart` and `purchase`, your Meta Pixel tags, your Google Ads remarketing tags, and any custom HTML tags that send data to a platform directly.&#x20;

If you are not sure whether you will need an old tag later, pause it instead of deleting it. You can always remove it in a later version once the new setup has proven itself. Old triggers and variables can stay, they do nothing on their own.

Skip this and preview mode will show two of everything, and after publishing your conversions will be counted twice.

#### Test both containers

1. Open the **Preview mode** in your GTM web container and fill in the URL of your webshop.
2. Open the **Preview mode** in your GTM server container as well, so you can follow the same hits arriving server-side.
3. Walk through the complete customer journey and check that each step fires once, with the right e-commerce parameters:
   * `page_view`
   * `view_item_list`
   * `view_item`
   * `add_to_cart`
   * `view_cart`
   * `remove_from_cart`
   * `begin_checkout`
   * `add_shipping_info`
   * `add_payment_info`
   * `purchase`
4. For every event, check in the **server** container that the GA4 event request arrives and that your platform tags fire and return a successful response.

***

### Step 6: Clean up, deploy and publish

Everything up to this point has run on your staging environment. Going live means the Magento deploy and the GTM publish need to happen in the right order, and there is one clean-up round to do first.

#### **Remove tracking scripts that are now handled server-side**

Every platform you have moved to your server container should no longer be loaded directly in your Magento frontend. If you set up Meta Ads through server-side tagging, the Meta Pixel base code in your theme has to go. The same applies to a hardcoded gtag.js snippet for GA4 or Google Ads, a TikTok pixel, a Pinterest tag, or any other pixel that is now fired from the server container. If your theme contains a GTM snippet that was placed there manually, remove it as well, because the AdPage module loads the connection to the GTM web container itself.

Go through this list with your developer before anything is pushed, so the removals and the module land in production in the same release.

#### **Deploy to production**

Ask your Magento developer to push the module and the theme changes to production. Wait until the deploy is confirmed and you can see the changes in scripts and dataLayer on your live site.

#### **Publish both GTM containers**

Test again in the preview modes on the live site. If everything still works as intended, you can publish your web and server container. Use a version name and description you will recognise later, for example "AdPage server-side tagging", so you can roll back to the previous version if something turns out to be wrong.

After publishing, run a test purchase on your live site and check in the AdPage interface and your GA4 realtime report whether the events arrive and the conversions are registered once. Any connection that Magento still maintains directly with an advertising platform will send the same event a second time, which leads to duplicated conversions and inflated revenue in your reports.

***

### Need help?

Still seeing missing events, duplicated conversions or unassigned traffic after following these steps? Reach out to our support team and we will take a look with you.


# Configuring Content Security Policy

AdPage's tracking script can get blocked by Content Security Policy. How to identify exactly what's being blocked, and how to allow it properly in Magento.

This article is for Magento developers and IT teams. It explains why AdPage's tracking script and your marketing tags can get blocked by Content Security Policy (CSP), how to identify exactly what's being blocked, and how to allow it properly in Magento.

### What CSP does, and why our script trips it

Content Security Policy is a browser-enforced allowlist. It tells the browser which external sources may be loaded and which inline code may run, which makes Cross-Site Scripting a great deal harder to pull off. Magento ships with the CSP module enabled and, in restrict mode, blocks any external script that hasn't been explicitly allowed.

Our tracking script needs a mention in that allowlist for two reasons:

**It contains additional JavaScript.** Beyond loading the container, the script provides features such as the Cookie Keeper. That's more than a plain vendor snippet does, and some of it runs inline.

**It loads from your own custom domain.** We serve tracking from a subdomain of your site, for example `tagging.yourdomain.com`, configured through a CNAME record in the AdPage dashboard. This makes the request far less likely to be stopped by common adblockers, but it also means the domain is unique to you and cannot be pre-allowlisted by us.

Neither of these is something we can work around from our side. The allowlist lives in your CSP header, so the change has to happen in Magento.

### Find out what's actually being blocked

Don't guess at the domain list. Read it off the browser.

1. Open developer tools (F12) and go to the **Console** tab.
2. Load a page that includes the tracking script (complete a checkout in a test order if you can).
3. Look for CSP violation warnings. Each one names the blocked URL and, importantly, **which directive blocked it**, that tells you where the entry belongs.

A typical violation reads along the lines of *"Refused to load the script … because it violates the following Content Security Policy directive: script-src …"*. The directive name at the end is the one you need to extend.

Two things worth doing while you're in there:

* Check the console again after a checkout, not just on the homepage. Conversion pixels often only fire on the order confirmation page, so a homepage-only check will miss exactly the tags that matter most.
* If your store runs CSP in report-only mode, violations are logged rather than blocked. That's ideal for building your list — but remember that everything will appear to work until you switch to restrict mode.

### The three ways CSP breaks tracking

#### 1. A blocked domain

**Symptom:** the script or a pixel never loads, and the console names the domain.

**Cause:** the domain isn't listed under the relevant directive. This is CSP working as designed, not a misconfiguration.

**Fix:** add the domain to the correct directive. Which directive depends on how the resource is loaded:

| What's loading                                 | Directive                                                      |
| ---------------------------------------------- | -------------------------------------------------------------- |
| Your tagging domain (`tagging.yourdomain.com`) | `script-src`, and `connect-src` if events are sent server-side |
| LinkedIn Insight Tag (`px.ads.linkedin.com`)   | `img-src` (and `script-src` for `snap.licdn.com`)              |
| Pinterest tag (`ct.pinterest.com`)             | `img-src` (and `script-src` for `s.pinimg.com`)                |
| Any tag that posts data via `fetch` or `XHR`   | `connect-src`                                                  |
| Any tag that renders an iframe                 | `frame-src`                                                    |

Treat that table as a pattern, not a complete list. The exact set of domains depends entirely on what's inside your GTM container, and it changes when the container changes. Add only the domains you genuinely use.

#### 2. A blocked inline script (nonce)

**Symptom:** the script loads from an allowed domain, but inline code it injects never executes.

**Cause:** if your `script-src` directive includes a nonce, the browser ignores `unsafe-inline` entirely. From that point on, inline scripts run only when they carry the exact nonce value from the current response header. Google Tag Manager and several tracking scripts inject inline code at runtime, so they're affected.

**Fix:** pass the server-generated nonce through to the container script tag. The server must mint a fresh cryptographic nonce per request, include it in the CSP header, and set the same value as an attribute on the tag:

html

```html
<script
    type="text/javascript"
    src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX"
    nonce="THE_UNIQUE_NONCE_VALUE">
</script>
```

Recent Magento versions expose a nonce provider you can inject into a block or template rather than generating one yourself — check the Adobe documentation for your specific version before rolling your own.

Be aware that under a strict nonce-based policy, **Custom HTML tags and Custom JavaScript variables in GTM may stop working altogether**, since GTM cannot attach your server's nonce to code it writes at runtime. If a tag depends on Custom HTML, plan on either moving that logic server-side or relaxing the policy for it deliberately.

#### 3. Blocked `eval`

**Symptom:** the container loads, but preview mode or certain custom templates fail with an `unsafe-eval` violation.

**Cause:** some tag templates and GTM's own debug tooling evaluate code at runtime.

**Fix:** there isn't a clean one. Allowing `unsafe-eval` weakens the policy meaningfully, so it's worth first checking whether the tag has an alternative implementation. If you only see this in preview mode, you can often live with it and validate the tag another way.

### Making the change in Magento

Magento's CSP configuration is code-managed, not something to patch into a template. Add allowlist entries through a `csp_whitelist.xml` file in your own module or theme — never by editing core files:

xml

```xml
<?xml version="1.0"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">
    <policies>
        <policy id="script-src">
            <values>
                <value id="adpage_tagging" type="host">tagging.yourdomain.com</value>
            </values>
        </policy>
        <policy id="connect-src">
            <values>
                <value id="adpage_tagging_connect" type="host">tagging.yourdomain.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>
```

Place it in `app/code/YourVendor/YourModule/etc/`, then flush the config cache. A few things to keep in mind:

* Storefront and admin have **separate** policies. Tracking belongs to the storefront; scoping it correctly avoids loosening the admin unnecessarily.
* Restrict mode versus report-only mode is configurable per area. Deploy your allowlist while in report-only mode, confirm the console is quiet, and only then enforce.
* Adobe's documentation is the authority on the details and on version differences: [Content Security Policies in Adobe Commerce](https://developer.adobe.com/commerce/php/development/security/content-security-policies/). If you're handing this off to someone else, that link plus your domain list is everything they need.

After deploying, retest properly: load the site, submit a form, complete a test order, and confirm in GTM preview mode that every tag still fires.

### This list will go stale

GTM containers change more often than CSP headers do, which is how tracking quietly breaks months after a working implementation. Build a small habit around it:

* Check the browser console for new CSP warnings periodically, not just after an incident.
* When you add a marketing tag, check whether it introduces a new domain before you publish the container.
* Treat a CSP update as part of the work whenever new tracking functionality ships.

### Still stuck?

If tags remain blocked after configuring the allowlist, email <support@adpage.io> and include:

* Your current CSP configuration, or the response header itself
* The exact console violations, copied rather than paraphrased
* Which tags aren't working, and on which pages

That combination usually lets us pinpoint the missing directive on the first reply.


# WooCommerce

How to set up server-side tagging for a WooCommerce webshop

***

## Setting up server-side tagging for WooCommerce

This article walks you through the full setup of server-side tagging on a WooCommerce store: generating your Google Tag Manager templates, importing them, filling in your IDs, testing them, and finally removing the old tracking connections within the WooCommerce webshop.

### Before you start

This article picks up where **Getting Started** leaves off. Make sure all of the steps in the Setup AdPage container article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The **AdPage Woocommerce Module** is installed in your store.

{% hint style="warning" %}
If one of these steps is still open, finish it first. Everything below assumes your server container is reachable on your own domain and that the AdPage Tagging plugin is pushing data into the dataLayer.
{% endhint %}

***

### Multilingual environments (WPML)

{% hint style="danger" %}
If your WooCommerce webshop runs in multiple languages through WPML, treat every language as its own environment. The AdPage Tagging Pixel is not shared automatically between languages, so it needs to be filled in separately for each language (and for each domain, if your WPML setup uses a separate domain per language).

Skipping a language leaves that language's storefront without a working Tagging Pixel, so purchases and other events made in that language never reach your GTM containers.

![](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FWyuPrdMVYppLHnpvE2XZ%2Fimage.png?alt=media\&token=d3b89cc2-4976-455a-9a39-d8a9eae881de)

To check that every language is configured correctly:

1. In your WordPress backend, open the language switcher in the top menu.
2. Switch to each language one by one.
3. For every language, open the Tagging Pixel settings and confirm the Website URL and GTM Web Container ID are filled in.
4. Save your changes and place a test order in that language to confirm events are still tracked correctly.
   {% endhint %}

### Step 1: Generate your templates in the Template Library

You do not have to build your tags, triggers and variables by hand. AdPage's Template Library generates a complete, tested Google Tag Manager setup for WooCommerce for you.

1. Go to [data.adpage.io/template-library](https://data.adpage.io/template-library).
2. Select the marketing platforms you want to send data to, for example Google Ads, Meta Ads, TikTok Ads, LinkedIn Ads or Pinterest Ads.
3. Select the Consent Management Platform you use on your WooCommerce webshop.
4. Generate the templates. You get **two JSON files**: one for your GTM **web** container and one for your GTM **server** container.
5. Download both files and keep them handy.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fo4nPmZrjh5NFMGAYOnPp%2Fimage.png?alt=media&#x26;token=a8b98f2d-df97-4c6a-9a20-c91350247029" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Only select the platforms you actually use. Every platform you add creates extra tags and constant variables that you will need to fill in later.
{% endhint %}

***

### Step 2: Import the web container template

1. Open your **GTM web container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **web** JSON file you downloaded.
4. Choose a workspace.
   * If you have unpublished changes in your default workspace, we recommend importing into a **new workspace** so your import stays separate from any other work in progress.
5. Choose the import option:
   * **Merge and rename conflicting tags, triggers and variables** for a container that already contains a setup. Nothing existing gets removed.
   * **Overwrite** only for a brand new, empty container.
6. Check the preview of the changes that GTM shows you, then click **Confirm**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F3CKvxX1mSb1O2JBpcE4Q%2Fimage.png?alt=media&#x26;token=ee12042d-41d9-4406-95f9-9e2eaf8d3bc1" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM web container yet. The tags in the import are still missing your IDs, which you fill in at step 4.
{% endhint %}

***

### Step 3: Import the server container template

Repeat the same steps in your **GTM server container** with the **server** JSON file.

1. Open your **GTM server container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **server** JSON file.
4. Import into a new workspace and choose **Merge and rename conflicting tags, triggers and variables**.
5. Check the preview and click **Confirm**.
6. Go to **Clients** and check if an extra GA4 client has been set up. If so, delete the imported GA4 client.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyhuHijhZUYGKSi2cG86j%2Fimage.png?alt=media&#x26;token=fbe37ee9-0cec-4291-8c7d-b9f5569cb1d6" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM server container yet. The tags in the import are still missing your IDs and tokens, which you fill in at step 4.
{% endhint %}

***

### Step 4: Fill in the constant variables

Both templates are built around **constant variables**. All IDs, tokens and settings live in one place, so you never have to open individual tags to change something.

1. In your GTM web container, go to **Variables**.
2. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
3. Save each variable.
4. In your GTM server container, go to **Variables**.
5. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
6. Save each variable.

Depending on the platforms you selected, you will typically fill in:

<table><thead><tr><th width="118">Container</th><th width="240">Variable</th><th>Value</th></tr></thead><tbody><tr><td>Web</td><td>Server Container URL</td><td>The tagging domain from your CNAME record, for example: <code>https://tagging.domain.com</code></td></tr><tr><td>Web</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID:<br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Web</td><td>Meta Pixel ID</td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Web</td><td>TikTok Pixel ID</td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Web</td><td>Pinterest Tag ID</td><td>Your Pinterest Tag ID, found in the Tag Manager of your Pinterest Ads Account</td></tr><tr><td>Web</td><td>LinkedIn Partner ID</td><td>Your LinkedIn Partner ID, found in the Signals Manager of your LinkedIn Ads Account</td></tr><tr><td>Web</td><td>Cookiebot Domain Group ID</td><td>The Domain Group ID from your Cookiebot account</td></tr><tr><td>Server</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID:<br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Server</td><td>Meta Pixel ID</td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Server</td><td>Meta API Ttoken</td><td>The API Token of your Pixel from Meta Events Manager</td></tr><tr><td>Server</td><td>TikTok Pixel ID</td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Server</td><td>TikTok API Token</td><td>The API Token of your Pixel from TikTok Events Manager</td></tr><tr><td>Server</td><td>Google Ads Conversion ID</td><td>Your Google Ads Conversion ID:<br><code>AW-XXXXXXXXXX</code> minus the <code>AW-</code> part</td></tr><tr><td>Server</td><td>Google Ads Conversion Labels</td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in Google Ads. Once set up, you can find their Conversion Labels.</td></tr><tr><td>Server</td><td>Pinterest Advertiser ID</td><td>The Advertiser ID from your Ad Account. This ID usually starts with 549.</td></tr><tr><td>Server</td><td>Pinterest API Token</td><td>The API Token found in your Conversions API settings of your Pinterest Business Account.</td></tr><tr><td>Server</td><td>LinkedIn API Token</td><td>The API Token which you can generate in your LinkedIn Campaign Manager in the Sources.</td></tr><tr><td>Server</td><td>LinkedIn Conversion IDs</td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in LinkedIn Ads. Once set up, you can find their Conversion IDs in the URL of the conversion.</td></tr></tbody></table>

{% hint style="info" %}
Never leave a constant variable empty. An empty ID means tags fire without a destination, which shows up as missing conversions or failed outgoing requests later on.
{% endhint %}

***

### Step 5: Test in preview mode

You have just imported container templates with complete tracking for GA4 and the marketing platforms you selected. That means everything you need is now present in your GTM containers, and anything that was already there for the same purpose is a duplicate.

#### **Disable your old tags first**

Go through the tags in your web container and pause or delete every tag that measures something your new setup now handles. In practice this is your old GA4 configuration tag, all GA4 event tags for e-commerce steps such as `add_to_cart` and `purchase`, your Meta Pixel tags, your Google Ads remarketing tags, and any custom HTML tags that send data to a platform directly.

If you are not sure whether you will need an old tag later, pause it instead of deleting it. You can always remove it in a later version once the new setup has proven itself. Old triggers and variables can stay, they do nothing on their own.

Skip this and preview mode will show two of everything, and after publishing your conversions will be counted twice.

#### Test both containers

1. Open the **Preview mode** in your GTM web container and fill in the URL of your webshop.
2. Open the **Preview mode** in your GTM server container as well, so you can follow the same hits arriving server-side.
3. Walk through the complete customer journey and check that each step fires once, with the right e-commerce parameters:
   * `page_view`
   * `view_item_list`
   * `view_item`
   * `add_to_cart`
   * `view_cart`
   * `remove_from_cart`
   * `begin_checkout`
   * `add_shipping_info`
   * `add_payment_info`
   * `purchase`
4. For every event, check in the **server** container that the GA4 event request arrives and that your platform tags fire and return a successful response.

***

### Step 6: Clean up and publish

Before you publish, make sure your WooCommerce site no longer loads the tracking scripts that now run through your server container. If you set up Meta Ads through server-side tagging, the Meta Pixel base code has to go. The same applies to a gtag.js snippet for GA4 or Google Ads, a TikTok pixel, a Pinterest tag, or any other pixel that is now fired from the server container. Check your theme files, your child theme's functions.php, any header or footer script fields, and the plugins you use, because pixels are often injected by a marketing or conversion plugin rather than by hand.

Also remove the standard GTM snippet if it is still present anywhere. The AdPage plugin loads the connection to the GTM web container itself, so a second snippet means script loading issues.

Once that is done, publish your web and server container. Use a version name and description you will recognise later, for example "AdPage server-side tagging", so you can roll back to the previous version if something turns out to be wrong.

Finish with a test purchase on your live site and check in the AdPage interface and the GA4 realtime report whether the events arrive and the conversions are registered once. Any connection that WooCommerce still maintains directly with an advertising platform will send the same event a second time, which leads to duplicated conversions and inflated revenue in your reports.

***

### Need help?

Still seeing missing events, duplicated conversions or unassigned traffic after following these steps? Reach out to our support team and we will take a look with you.


# generate\_lead dataLayer (Contactform7 & GravityForms)

Track ContactForm7 and GravityForms with a dataLayer event

AdPage's WordPress plugin pushes a dataLayer event the moment someone submits a Gravity Forms or ContactForm7 form. This guide walks you through turning that event into a clean conversion in Google Tag Manager.

Why bother, if you already track form submissions some other way? Because the alternatives are fragile. Triggering on a CSS element such as a thank-you message, on a generic form submission listener, or on a thank-you page URL all leave room for error: the element changes, the submission fails validation, or someone reaches the thank-you page directly. A dataLayer event fires when the form is genuinely submitted and nothing else. If you have that option, use it.

### Setting it up from scratch

#### **1. Create the trigger**

In your GTM **web container**, go to **Triggers** and create a new one. Choose **Custom Event** (the orange option) as the trigger type and enter `trytagging_generate_lead` as the event name. Save it.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FaMneid686Z780GEwYsuw%2Fimage.png?alt=media&amp;token=3ff8af11-1903-4ebc-a770-fffe3ea237ed" alt=""><figcaption></figcaption></figure>

The `trytagging_generate_lead` event is designed to fire only on a Gravity Forms or Contact Form 7 submission, so you don't need any extra conditions.

#### **2. Create the GA4 tag**

Go to **Tags** and create a new tag with **Google Analytics: GA4 Event** as the tag configuration. Then:

* Enter your GA4 Measurement ID, or select the constant variable you already use for it.
* Set the event name to `generate_lead`. You can use a different name here if you'd rather measure something else.
* Attach the trigger you just created, and save.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FopnxWJ2y3ORzVsxUo71d%2Fimage.png?alt=media&amp;token=a22aec0a-e9d8-45b5-b0f2-09dcb1316627" alt=""><figcaption></figcaption></figure>

#### 3. Sending visitor data along (for enhanced conversions)

If you want to pass the email address or other details through to GA4 and Google Ads, you first need to know what the plugin actually put in the dataLayer.

**1. Test the form submission**

Open Google Tag Manager's **Preview Mode** for your web container and submit your form. Find the `trytagging_generate_lead` event and open the **DataLayer** tab, the parameters from your form are listed there.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FhWx5SEKxpnHEL2gf43HG%2Fimage.png?alt=media&amp;token=593f5248-6b45-4fd4-a37b-7370775442df" alt=""><figcaption></figcaption></figure>

**2. Create a dataLayer variable**

In your web container, go to **Variables** and create a new user-defined variable of type **Data Layer Variable**. For the variable name, use one of the keys you just saw in preview mode.

In the example above, the key for the email address is `form_data.your-email`. Yours will depend on the field names in your form, so read them off your own preview output rather than copying blindly.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FN6go3HVWDRosIy8zqA79%2Fimage.png?alt=media&amp;token=af0c4581-1c8e-4b2c-bc02-521a0d74d15f" alt=""><figcaption></figcaption></figure>

**3. Add the parameter to your GA4 tag**

Save the variable, reopen your GA4 event tag, and add a new event parameter:

| Parameter name            | Value                       |
| ------------------------- | --------------------------- |
| `user_data.email_address` | your new dataLayer variable |

Any GA4 parameter starting with `user_data` is formatted automatically so it can be used for GA4 and Google Ads Enhanced Conversions. That prefix is doing real work — don't rename it.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FNnYJL3aahcWvSRzowAc6%2Fimage.png?alt=media&amp;token=03f63755-bd75-4bdb-9c43-c54ea34bba1d" alt=""><figcaption></figcaption></figure>

**4. Check your changes**

Save the tag, open preview mode, and submit the form on your website. You're looking for two things: the **GA4 - generate\_lead** tag firing on submission, and your dataLayer variable actually resolving to a value rather than `undefined`.


# generate\_lead webhooks (Contactform7 & GravityForms)

Alongside your regular tracking, the generate\_lead webhooks arriving at your server container can be passed on to n8n, Zapier or Make and used anywhere downstream.

When someone fills in a form on your WordPress site, that submission is worth more than a name and an email address. AdPage also knows where the visitor came from: the campaign, the click ID, the landing page, the session. This guide shows you how to forward all of it from your Google Tag Manager server container to a platform of your choice, so your CRM or automation flow receives the lead *and* the story behind it.

{% hint style="info" %}
This only works with Gravity Forms or Contact Form 7 on WordPress. Other CMS platforms aren't supported by this feature.
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FJeKZbhjdzEUWSFRpLBjP%2Fimage.png?alt=media&amp;token=3531f4a7-7e92-48c4-967c-12bd06ca5c0b" alt=""><figcaption></figcaption></figure>

### What gets sent along in the webhook

**The lead itself**

* Form fields such as name, email address and phone number
* The page the conversion happened on, plus a timestamp
* Behavioural data from the session

**The marketing attribution**

* UTM parameters: `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`
* Click and browser IDs: `gclid` (Google), `fbc` / `fbp` (Meta), `ttclid` (TikTok)
* Session data: session ID, session count, user agent
* Traffic source: referrer URL and landing page

Once the webhook client has done its work, the payload looks roughly like this:

```json
{
  "event_name": "trytagging_generate_lead",
  "form_data": {
    "name": "John Doe",
    "email": "john-doe@example.com",
    "phone": "+31612345678"
  },
  "marketing": {
    "utm_source": "google",
    "utm_medium": "cpc",
    "utm_campaign": "summer-sale",
    "gclid": "abc123...",
    "fbp": "fb.1.1234567890",
    "user_agent": "Mozilla/5.0...",
    "ip": "192.168.1.1"
  },
  "user_data": {
    "first_name": "John",
    "last_name": "Doe",
    "email": "john-doe@example.com",
    "phone": "+31612345678"
  }
}
```

### Before you start

Make sure you have:

* [ ] A configured Google Tag Manager server-side container
* [ ] The AdPage tracking implementation running on your WordPress site
* [ ] A webhook endpoint from the platform you want to send to (n8n, Zapier or Make)

### Step 1: Add the webhook client

The client is what listens for incoming lead data and turns it into the structured payload shown above.

1. Download the [AdPage Webhook client](https://claude.ai/chat/7a409d3e-4dd5-4870-a74b-b264e50d8632#) from GitHub.
2. In your GTM server container, go to **Templates**, create a new **client template**, and import the `.tpl` file you just downloaded.
3. Go to **Clients**, create a new client, choose **AdPage Webhook Client** as the client configuration, and save.

That's it for the client. It parses the incoming request automatically, so there's nothing to configure inside it.

### Step 2: Create the HTTP request tag

This tag does the actual sending.

1. Go to **Templates** and search the gallery for the **JSON HTTP Request** tag template. Add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FWeFcfld7u6yhz1YLabH3%2Fimage.png?alt=media&amp;token=4cfb5125-b8b4-42d6-a849-28dd302754ac" alt=""><figcaption></figcaption></figure>

2. Create a new tag and select that template as its tag configuration.
3. Fill in the fields:

<table><thead><tr><th width="239">Field</th><th>Value</th></tr></thead><tbody><tr><td>URL</td><td>Your webhook endpoint (n8n, Zapier or Make)</td></tr><tr><td>Request Data</td><td><p><code>form_data</code> → Event Data variable <code>{{form_data}}</code> </p><p></p><p><code>marketing</code> → Event Data variable <code>{{marketing}}</code></p></td></tr><tr><td>Method (under <em>Additional Options</em>)</td><td><code>POST</code></td></tr></tbody></table>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FqIQP4xW9apSL3PXPh4LV%2Fimage.png?alt=media&amp;token=132ce7d6-50f1-4ded-87d3-a57f697597f6" alt=""><figcaption></figcaption></figure>

### Step 3: Add the trigger

The tag needs to fire only when lead data actually comes in.

1. In the tag configuration, click **Triggering** and then the blue plus icon at the top right.
2. Choose **Custom** as the trigger type, then select **Some Events**.
3. Add these two conditions:
   * `{{Client Name}}` **equals** `AdPage Webhook Client`
   * `{{Event Name}}` **equals** `trytagging_generate_lead`
4. Save the trigger, then save the tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F4I6C1MyWvK5RDB02u8Eb%2Fimage.png?alt=media&amp;token=87f6a511-eb63-4f95-abbd-776cf23e43e9" alt=""><figcaption></figcaption></figure>

### Test it with a webhook replay

You don't need to wait for a real form submission. Any webhook that already arrived can be replayed straight into preview mode.

1. Open your server container in the AdPage platform and go to **Webhook Logs**.
2. Find a `generate_lead` webhook and click the circular double-arrow icon to replay it. A popup asks for a preview header.
3. To get that header: open the same server container in GTM, switch to **Preview** mode, click the three dots at the top right and choose **Send requests manually**.
4. Copy the `x-gtm-server-preview` header, paste it into the replay popup, and click **Replay**

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fs4EmltpKJOVQYiXUm3SC%2Fimage.png?alt=media&amp;token=03b44252-7302-4a45-a48d-cebef116ffb1" alt=""><figcaption></figcaption></figure>

A `trytagging_generate_lead` request now appears in your preview window and the JSON HTTP Request tag should show as fired. Open the tag and check that `form_data` and `marketing` are both populated. If they are, you're done.

### When something doesn't work

**The tag doesn't fire**

Check the trigger conditions first, especially whether the event name matches exactly. Then confirm the client is saved and active in the container.

**The tag fires but data is missing**

Look at your variable configuration and your data layer implementation. If `marketing` comes through empty, the attribution data likely isn't being captured on the website side.

**The receiving platform rejects the request**

Check the webhook URL format, any authentication headers the platform requires, and whether it expects a specific payload structure.

**Debugging tips**

* Set the log type to *Always log to console* while you're testing.
* Add a trace ID header so you can follow a single request end to end.
* Start with the basics and add fields once those arrive correctly.
* Watch for a `200 OK` response; anything else is worth investigating.

### Keeping it secure

Send only the fields you actually need, and use an HTTPS endpoint. Where your platform supports it, enable webhook signature verification and set proper authentication headers. If the payload contains sensitive personal data, consider encrypting it and restrict who can reach the endpoint.

### A few good habits

Configure timeout and retry logic so a temporary outage doesn't cost you leads, validate data before sending it, and set up an alert for failed webhooks. Document your field mappings somewhere your future self can find them, and retest after any change to the form or the container.


# Lightspeed

How to set up server-side tagging for a Lightspeed webshop

***

## Setting up server-side tagging for Lightspeed

This article walks you through the full setup of server-side tagging on a Lightspeed store: generating your Google Tag Manager templates, importing them, filling in your IDs, testing them, and finally removing the old tracking connections within the Lightspeed webshop.

### Before you start

This article picks up where **Getting Started** leaves off. Make sure all of the steps in the [Setup AdPage container](/getting-started/setup-adpage-container) article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The **AdPage dataLayer scripts** are installed in your store.

{% hint style="warning" %}
If one of these steps is still open, finish it first. Everything below assumes your server container is reachable on your own domain and that the AdPage dataLayer is present on the webshop's frontend.
{% endhint %}

***

### Step 1: Generate your templates in the Template Library

You do not have to build your tags, triggers and variables by hand. AdPage's Template Library generates a complete, tested Google Tag Manager setup for Lightspeed for you.

1. Go to [data.adpage.io/template-library](https://data.adpage.io/template-library).
2. Select the marketing platforms you want to send data to, for example Google Ads, Meta Ads, TikTok Ads, LinkedIn Ads or Pinterest Ads.
3. Select the Consent Management Platform you use on your Lightspeed webshop.
4. Generate the templates. You get **two JSON files**: one for your GTM **web** container and one for your GTM **server** container.
5. Download both files and keep them handy.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fo4nPmZrjh5NFMGAYOnPp%2Fimage.png?alt=media&amp;token=a8b98f2d-df97-4c6a-9a20-c91350247029" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Only select the platforms you actually use. Every platform you add creates extra tags and constant variables that you will need to fill in later.
{% endhint %}

***

### Step 2: Import the web container template

1. Open your **GTM web container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **web** JSON file you downloaded.
4. Choose a workspace.&#x20;
   * If you have unpublished changes in your default workspace, we recommend importing into a **new workspace** so your import stays separate from any other work in progress.
5. Choose the import option:
   * **Merge and rename conflicting tags, triggers and variables** for a container that already contains a setup. Nothing existing gets removed.
   * **Overwrite** only for a brand new, empty container.
6. Check the preview of the changes that GTM shows you, then click **Confirm**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F3CKvxX1mSb1O2JBpcE4Q%2Fimage.png?alt=media&amp;token=ee12042d-41d9-4406-95f9-9e2eaf8d3bc1" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM web container yet. The tags in the import are still missing your IDs, which you fill in at step 4.
{% endhint %}

***

### Step 3: Import the server container template

Repeat the same steps in your **GTM server container** with the **server** JSON file.

1. Open your **GTM server container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **server** JSON file.
4. Import into a new workspace and choose **Merge and rename conflicting tags, triggers and variables**.
5. Check the preview and click **Confirm**.
6. Go to **Clients** and check if an extra GA4 client has been set up. If so, delete the imported GA4 client.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyhuHijhZUYGKSi2cG86j%2Fimage.png?alt=media&amp;token=fbe37ee9-0cec-4291-8c7d-b9f5569cb1d6" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM server container yet. The tags in the import are still missing your IDs and tokens, which you fill in at step 4.
{% endhint %}

***

### Step 4: Fill in the constant variables

Both templates are built around **constant variables**. All IDs, tokens and settings live in one place, so you never have to open individual tags to change something.

1. In your GTM web container, go to **Variables**.
2. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
3. Save each variable.
4. In your GTM server container, go to **Variables**.
5. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
6. Save each variable.

Depending on the platforms you selected, you will typically fill in:

<table><thead><tr><th width="118">Container</th><th width="240">Variable</th><th>Value</th></tr></thead><tbody><tr><td>Web</td><td>Server Container URL</td><td>The tagging domain from your CNAME record, for example: <code>https://tagging.domain.com</code></td></tr><tr><td>Web</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Tag ID</a></td><td>Your Pinterest Tag ID, found in the Tag Manager of your Pinterest Ads Account</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Partner ID</a></td><td>Your LinkedIn Partner ID, found in the Signals Manager of your LinkedIn Ads Account</td></tr><tr><td>Web</td><td>Cookiebot Domain Group ID</td><td>The Domain Group ID from your Cookiebot account</td></tr><tr><td>Server</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta API Ttoken</a></td><td>The API Token of your Pixel from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok API Token</a></td><td>The API Token of your Pixel from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion ID</a></td><td>Your Google Ads Conversion ID: <br><code>AW-XXXXXXXXXX</code> minus the <code>AW-</code> part</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion Labels</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in Google Ads. Once set up, you can find their Conversion Labels.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Advertiser ID</a></td><td>The Advertiser ID from your Ad Account. This ID usually starts with 549.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest API Token</a></td><td>The API Token found in your Conversions API settings of your Pinterest Business Account.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn API Token</a></td><td>The API Token which you can generate in your LinkedIn Campaign Manager in the Sources.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Conversion IDs</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in LinkedIn Ads. Once set up, you can find their Conversion IDs in the URL of the conversion.</td></tr></tbody></table>

{% hint style="info" %}
Never leave a constant variable empty. An empty ID means tags fire without a destination, which shows up as missing conversions or failed outgoing requests later on.
{% endhint %}

***

### Step 5: Test in preview mode

You have just imported container templates with complete tracking for GA4 and the marketing platforms you selected. That means everything you need is now present in your GTM containers, and anything that was already there for the same purpose is a duplicate.

#### **Disable your old tags first**

Go through the tags in your web container and pause or delete every tag that measures something your new setup now handles. In practice this is your old GA4 configuration tag, all GA4 event tags for e-commerce steps such as `add_to_cart` and `purchase`, your Meta Pixel tags, your Google Ads remarketing tags, and any custom HTML tags that send data to a platform directly.&#x20;

If you are not sure whether you will need an old tag later, pause it instead of deleting it. You can always remove it in a later version once the new setup has proven itself. Old triggers and variables can stay, they do nothing on their own.

Skip this and preview mode will show two of everything, and after publishing your conversions will be counted twice.

#### Test both containers

1. Open the **Preview mode** in your GTM web container and fill in the URL of your webshop.
2. Open the **Preview mode** in your GTM server container as well, so you can follow the same hits arriving server-side.
3. Walk through the complete customer journey and check that each step fires once, with the right e-commerce parameters:
   * `page_view`
   * `view_item_list`
   * `view_item`
   * `add_to_cart`
   * `view_cart`
   * `remove_from_cart`
   * `begin_checkout`
   * `add_shipping_info`
   * `add_payment_info`
   * `purchase`
4. For every event, check in the **server** container that the GA4 event request arrives and that your platform tags fire and return a successful response.

***

### Step 6: Clean up and publish

Before you publish, make sure your Lightspeed shop no longer sends anything directly to the platforms that now run through your server container. Otherwise the same conversions are measured twice, once client-side from Lightspeed and once server-side from your server container, which inflates your conversion counts, breaks your ROAS calculations and feeds advertising platforms the wrong optimisation signals.

#### **Check your Web Extras**

Earlier in this setup you added the AdPage tagging pixel to your Web Extras through three separate scripts. Those scripts should not be present alongside a standard Google Tag Manager snippet, so go through your Web Extras and check whether the regular GTM code is still there. It looks like this:

```
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXXX');</script>
<!-- End Google Tag Manager -->
```

Remove it, including the accompanying noscript block. While you are in the Web Extras, also remove any other tracking script that is now handled server-side, such as a Meta Pixel base code, a gtag.js snippet for GA4, a TikTok pixel or a Pinterest tag.

#### **Disconnect Google Analytics and Meta Ads**

In your Lightspeed backend, go to your settings and open Web Statistics. Here you can see whether an old connection with Google Analytics or Facebook Ads is still active. Click on the platform in question and switch the connection off.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FMNAdwwW0UVlXXbwMfCEa%2Fimage.png?alt=media&amp;token=c828dd42-7bce-4b1c-afef-0b30818a62ea" alt=""><figcaption></figcaption></figure>

#### **Publish both GTM containers**

Once your Lightspeed environment is clean, publish your web and server container. Use a version name and description you will recognise later, for example "AdPage server-side tagging", so you can roll back to the previous version if something turns out to be wrong.

Finish with a test purchase on your live shop and check in the AdPage interface whether the events arrive and the conversions are registered once. Any connection that Lightspeed still maintains directly with an advertising platform will send the same event a second time.

***

### Need help?

Still seeing missing events, duplicated conversions or unassigned traffic after following these steps? Reach out to our support team and we will take a look with you.


# Lightspeed C-series: their new checkout

Lightspeed's new checkout runs entirely inside a cross-origin iframe.

Lightspeed's new checkout runs entirely inside a cross-origin iframe. Because of browser security rules, nothing inside that iframe can be read or tracked from your website, so server-side tagging cannot measure the checkout.

In practice this means `begin_checkout`, `add_shipping_info` and `add_payment_info` cannot be measured at all, and `purchase` only server-side via Lightspeed webhooks (without client ID and session ID, so attribution is less accurate). Custom scripts and dataLayer customisation aren't possible either.

We've raised this issue with Lightspeed. There's currently no planned solution comparable to Shopify's Customer Events API, and no workaround on our side: the restriction comes from the browser, not from our implementation.

### What we recommend

Use Lightspeed's regular checkout. It supports the full AdPage DataLayer, all ecommerce events, and server-side tagging. To switch back: log in to your Lightspeed eCom back office, go to **Settings → Checkout**, disable **Use new checkout**, and save.

We're monitoring this and will update the article if Lightspeed changes anything.


# Generate Lightspeed API Keys for webhooks

How do you generate the API Key and API Secret within Lightspeed to use webhooks.

To use AdPage's backend webhooks with Lightspeed, you'll need an API Key and API Secret from your Lightspeed back office. This guide walks you through creating them and connecting them to your server container.

### Check this first

The Lightspeed Webhooks API connection only works for:

* Single-store setups
* Dutch webshops (`.nl` domains)

It does **not** work for:

* Multistore configurations
* Webshops in countries other than the Netherlands
* International Lightspeed accounts

If your shop falls into the second group, the connection won't establish no matter how the key is configured, so it's worth confirming this before you start rather than after.

### Create the API key in Lightspeed

**1.** Log in to your Lightspeed eCom back office with an administrator account.

**2.** Click **Settings** in the main menu.

**3.** Under your webshop settings, go to **Developers** and open the **API** settings.

**4.** Click **Create new API key**.

**5.** Give the key a recognisable name, for example *AdPage Integration*. Your future self will thank you when there are four keys in the list.

**6.** Set the permissions:

| Access | Scopes                      |
| ------ | --------------------------- |
| Read   | Products, Orders, Customers |
| Write  | Orders                      |

**7.** Once created, Lightspeed shows you two values:

* **API Key** — a long string of letters and numbers
* **API Secret** — a long string of letters and numbers

{% hint style="info" %}
**Copy both immediately and store them somewhere safe.** The API Secret is shown only once. If you lose it, there's no way to retrieve it, you'll have to delete the key and create a new one.
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fts2JAc5z6PpvOwj0lIjI%2Fimage.png?alt=media&amp;token=3d9410b7-b57b-409d-9e66-5bdf85f17953" alt=""><figcaption></figcaption></figure>

### Connect them to AdPage

**8.** Open your server container in the [AdPage platform](https://trytagging.com/auth/login).

**9.** Go to the **Pixel installation instructions**.

**10.** At the bottom of those instructions you'll find the **Lightspeed webhook settings**. Enter your API Key and API Secret there, then enable the functionality.

### Keeping the credentials safe

An API key with read access to your orders and customers is worth protecting properly:

* Store the credentials in a password manager rather than a document or a chat message.
* Never share them with anyone who doesn't need them, and revoke rather than reuse when someone leaves.
* Delete old or unused keys periodically, every key that exists is a key that can leak.
* Use descriptive names so you can tell at a glance what each key is for and whether it's still needed.

### If the connection doesn't work

Work through these in order:

* **Does the shop meet the requirements?** A Dutch single store is a hard condition, not a recommendation.
* **Is the key active** in the Lightspeed back office? Keys can be disabled there independently of AdPage.
* **Are the permissions right?** Missing read access on Orders is the most common cause of a connection that authenticates but returns nothing.
* **Did the secret paste cleanly?** A trailing space or a truncated copy looks identical to a wrong secret.

Then test the API connection from within AdPage to confirm.


# Shopware

Setting up server-side tagging for a Shopware webshop

## Setting up server-side tagging for Shopware

This article walks you through the full setup of server-side tagging on a Shopware store.

### Before you start

This article picks up where **Getting Started** leaves off. Make sure all of the steps in the [Setup AdPage container](/getting-started/setup-adpage-container) article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The **Tagging Pixel script** has been installed to ensure a connection with the GTM web container.

{% hint style="warning" %}
If one of these steps is still open, finish it first. Everything below assumes your server container is reachable on your own domain and that the AdPage dataLayer is present on the webshop's frontend.
{% endhint %}

***

### Step 1: Set up an e-commerce dataLayer

AdPage does not offer a native dataLayer plugin for Shopware, so you will need to set one up yourself. Your shop may already have a dataLayer in place. If it does not, we recommend the following plugin: [Shopware plugin settings for GA4 + remarketing](https://store.shopware.com/en/dtgs888695584742m12/google-tag-manager-ga4-remarketing.html)

Within this plugin, disable everything except enhanced ecommerce and hash enhanced conversion. The plugin can send data to GA4 and Google Ads directly, but that won't be through server-side tagging. Leaving those options enabled would result in duplicate hits. The only thing this plugin needs to do is push e-commerce events to the dataLayer, where your server-side tagging setup will picks them up.

Once installed, open your shop in the browser and confirm that the dataLayer is populated. You should see events such as `view_item`, `add_to_cart` and `purchase` appear as you move through the shop and complete a test order.

*The settings in the plugin:*

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FZdA5IJRT9A23Fi231nU1%2Fimage.png?alt=media&amp;token=608be43b-ea76-48c8-a762-ee6e1e231584" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F93cCnAcG9NCNwBPRkO9h%2Fimage.png?alt=media&amp;token=2fb9e702-ba35-4188-83e0-12f6a6823e05" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FWf7QIjXGziJ3VX1EsVMk%2Fimage.png?alt=media&amp;token=49fb3291-ba0a-48c5-a602-c758898d3409" alt=""><figcaption></figcaption></figure>

***

### Step 2: Set up the AdPage webhook plugin

Set up the webhooks for the purchase event. You do this by installing the AdPage webhook plugin via Composer. The plugin is available [here](https://github.com/AdPageGroup/Shopware).

The webhook sends the order data from Shopware to your AdPage server container directly from the backend, independent of the browser. This makes the purchase event reliable even when a visitor closes the tab immediately after checkout, when the browser blocks tracking, or when consent has not been granted for client side tracking.

If you are not able to install the plugin via Composer yourself, ask your web developer or hosting party to do it for you.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fd9GEKf5eHIgaijGTe9Z6%2Fimage.png?alt=media&amp;token=ffe13dbe-c4b9-4d93-a072-49426b2f8c46" alt=""><figcaption></figcaption></figure>

***

### Step 3: Set up your Sales Channel

Shopware works with a separate configuration for every sales channel. A sales channel can be its own domain, but it can also live within an existing domain. Because plugin settings are applied per sales channel, you configure the AdPage plugin separately for each one.

An example. The "domainx" sales channel covers [domainx.nl](http://domainx.nl/). Alongside it there is a second sales channel, "domainx business", that sits within the same domain and will become available at <https://www.domainx.nl/business> or <https://www.domainx.nl/workwear>. Both need their own configuration.

* Select the sales channels whose transactions you want to forward to your online marketing platforms. The tagging URL can be set per channel.
* If you add or change sales channels later on, you can adjust them in the plugin as well. Make sure the tagging URL you enter for the domain matches the tagging URL configured in your tagging platform.

That last point is the one that most often goes wrong in practice, so if you want I can expand it into a short callout explaining what breaks when the two do not match (webhooks arriving on a container that does not recognise the domain, so purchases never land in the platforms).

***

### Step 4: Set up GA4 tracking in Google Tag Manager

Server-side tagging with an AdPage server container works by receiving GA4 formatted requests from the client. Therefore you have to set up GA4 event tags on the client that send these requests towards your server container URL. And on your server container you'll need a GA4 Client and a GA4 tag in the server container make sure those requests get forwarded to your Google Analytics 4 property as GA4 events.

#### **Google Tag Manager server container steps**

1. **GA4 Client.** A Client receives incoming data on the server. The GA4 Client lets the server read data in GA4 format. It already exists by default under Clients, and needs no changes for a regular setup.
2. **GA4 tag.** Go to Tags and create a new tag with Google Analytics: GA4 as the configuration. Two fields matter most. Measurement ID decides which property the data goes to, and leaving it empty means the tag uses whichever Measurement ID your web container sends along. Event name forces one specific event name, so leave it empty to pass incoming event names through unchanged.
3. **Trigger.** Set the trigger condition to `Client Name` equals `GA4` so all incoming GA4 events are forwarded. If Client Name is not in the dropdown, add it via Choose Built-in variable.
4. **Preview URL.** Go to Admin, open Container settings and add your tracking subdomain under Server container URLs. Without this, server side preview mode will not launch.

#### **Google Tag Manager web container steps**

1. **Override the GA4 endpoint in the Google tag.** The Google tag loads the measurement library and holds the shared configuration for all your GA4 hits. Event tags carry only the event name and parameters, and inherit the rest from the Google tag with the same Measurement ID. Setting the endpoint here once means every event tag follows. Add these three parameters:
   * `server_container_url` = your AdPage server container URL
   * `send_page_view` = `false`
   * `first_party_collection` = `true`
2. **GA4 page\_view event tag.** With `send_page_view` set to `false`, the `page_view` event is no longer created automatically, which is what you want. An automatic `page_view` cannot carry extra parameters, and `event_id` in particular is needed for deduplication on the marketing platforms. Create a new Google Analytics: GA4 Event tag, fill in your Measurement ID and set the event name to `page_view`. For the trigger, use the dataLayer event your Consent Management Platform pushes on every page, or All Pages if there is none.

### **Test before publishing**

Every existing GA4 event tag with the same Measurement ID now routes through your server container as well, including purchases, form submissions and custom events. Open preview mode in both containers side by side, click through your key interactions, and confirm each request reaches your tracking domain, gets claimed by the GA4 Client and leaves for GA4 with the expected parameters. Only publish once you have seen every important event complete that path.

***

### Need help?

Still seeing missing events, duplicated conversions or unassigned traffic after following these steps? Reach out to our support team and we will take a look with you.


# Custom

How to set up server-side tagging for a custom cms webshop

***

## Setting up server-side tagging for Custom

This article walks you through the full setup of server-side tagging on a Custom store: generating your Google Tag Manager templates, importing them, filling in your IDs, testing them, and finally removing the old tracking connections that custom cms made for you.

### Before you start

This article picks up where **Getting Started** leaves off. Make sure all of the steps in the [Setup AdPage container](/getting-started/setup-adpage-container) article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The custom [user Date scripts ](/integrations-websites/custom/add-user-data-script) setup are correctly on your site.
* [ ] The [eCommerce dataLayer](/integrations-websites/custom/add-datalayer-events) and [backend webhooks](/integrations-websites/custom/add-backend-webhooks) setup are correctly on your site.

{% hint style="warning" %}
If one of these steps is still open, finish it first. Everything below assumes your server container is reachable on your own domain and that the User data script, datalayer events and optional webhooks are pushing data.
{% endhint %}

{% hint style="info" %}
We recommend setting up the setup in on a staging-enviroment, and following all the steps below based on the frontend of the staging-enviroment.
{% endhint %}

***

### Step 1: Generate your templates in the Template Library

You do not have to build your tags, triggers and variables by hand. AdPage's Template Library generates a complete, tested Google Tag Manager setup for custom cms for you.

1. Go to [data.adpage.io/template-library](https://data.adpage.io/template-library).
2. Select the marketing platforms you want to send data to, for example Google Ads, Meta Ads, TikTok Ads, LinkedIn Ads or Pinterest Ads.
3. Select the Consent Management Platform you use on your custom webshop.
4. Generate the templates. You get **two JSON files**: one for your GTM **web** container and one for your GTM **server** container.
5. Download both files and keep them handy.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fo4nPmZrjh5NFMGAYOnPp%2Fimage.png?alt=media&amp;token=a8b98f2d-df97-4c6a-9a20-c91350247029" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Only select the platforms you actually use. Every platform you add creates extra tags and constant variables that you will need to fill in later.
{% endhint %}

***

### Step 2: Import the web container template

1. Open your **GTM web container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **web** JSON file you downloaded.
4. Choose a workspace.&#x20;
   * If you have unpublished changes in your default workspace, we recommend importing into a **new workspace** so your import stays separate from any other work in progress.
5. Choose the import option:
   * **Merge and rename conflicting tags, triggers and variables** for a container that already contains a setup. Nothing existing gets removed.
   * **Overwrite** only for a brand new, empty container.
6. Check the preview of the changes that GTM shows you, then click **Confirm**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F3CKvxX1mSb1O2JBpcE4Q%2Fimage.png?alt=media&amp;token=ee12042d-41d9-4406-95f9-9e2eaf8d3bc1" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM web container yet. The tags in the import are still missing your IDs, which you fill in at step 4.
{% endhint %}

***

### Step 3: Import the server container template

Repeat the same steps in your **GTM server container** with the **server** JSON file.

1. Open your **GTM server container**.
2. Go to **Admin** and click **Import Container**.
3. Select the **server** JSON file.
4. Import into a new workspace and choose **Merge and rename conflicting tags, triggers and variables**.
5. Check the preview and click **Confirm**.
6. Go to **Clients** and check if an extra GA4 client has been set up. If so, delete the imported GA4 client.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyhuHijhZUYGKSi2cG86j%2Fimage.png?alt=media&amp;token=fbe37ee9-0cec-4291-8c7d-b9f5569cb1d6" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Do not publish your GTM server container yet. The tags in the import are still missing your IDs and tokens, which you fill in at step 4.
{% endhint %}

***

### Step 4: Fill in the constant variables

Both templates are built around **constant variables**. All IDs, tokens and settings live in one place, so you never have to open individual tags to change something.

1. In your GTM web container, go to **Variables**.
2. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
3. Save each variable.
4. In your GTM server container, go to **Variables**.
5. Open every constant variable, which you can recognize by the "@" in the name. Fill in the correct value per variable. See the table below to know what ID or Token you have to fill in.
6. Save each variable.

Depending on the platforms you selected, you will typically fill in:

<table><thead><tr><th width="118">Container</th><th width="240">Variable</th><th>Value</th></tr></thead><tbody><tr><td>Web</td><td>Server Container URL</td><td>The tagging domain from your CNAME record, for example: <code>https://tagging.domain.com</code></td></tr><tr><td>Web</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Tag ID</a></td><td>Your Pinterest Tag ID, found in the Tag Manager of your Pinterest Ads Account</td></tr><tr><td>Web</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Partner ID</a></td><td>Your LinkedIn Partner ID, found in the Signals Manager of your LinkedIn Ads Account</td></tr><tr><td>Web</td><td>Cookiebot Domain Group ID</td><td>The Domain Group ID from your Cookiebot account</td></tr><tr><td>Server</td><td>GA4 Measurement ID</td><td>Your GA4 property's Measurement ID: <br><code>G-XXXXXXXXXX</code></td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta Pixel ID</a></td><td>Your Pixel ID from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token">Meta API Ttoken</a></td><td>The API Token of your Pixel from Meta Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok Pixel ID</a></td><td>Your Pixel ID from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token">TikTok API Token</a></td><td>The API Token of your Pixel from TikTok Events Manager</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion ID</a></td><td>Your Google Ads Conversion ID: <br><code>AW-XXXXXXXXXX</code> minus the <code>AW-</code> part</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels">Google Ads Conversion Labels</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in Google Ads. Once set up, you can find their Conversion Labels.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest Advertiser ID</a></td><td>The Advertiser ID from your Ad Account. This ID usually starts with 549.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token">Pinterest API Token</a></td><td>The API Token found in your Conversions API settings of your Pinterest Business Account.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn API Token</a></td><td>The API Token which you can generate in your LinkedIn Campaign Manager in the Sources.</td></tr><tr><td>Server</td><td><a href="/integrations-marketingtools/linkedin-ads/where-to-find-the-linkedin-partner-id-conversion-ids-and-api-token">LinkedIn Conversion IDs</a></td><td>Create new <code>purchase</code>, <code>add_to_cart</code>, and <code>begin_checkout</code> conversions in LinkedIn Ads. Once set up, you can find their Conversion IDs in the URL of the conversion.</td></tr></tbody></table>

{% hint style="info" %}
Never leave a constant variable empty. An empty ID means tags fire without a destination, which shows up as missing conversions or failed outgoing requests later on.
{% endhint %}

***

### Step 5: Test in preview mode

You have just imported container templates with complete tracking for GA4 and the marketing platforms you selected. That means everything you need is now present in your GTM containers, and anything that was already there for the same purpose is a duplicate.

#### **Disable your old tags first**

Go through the tags in your web container and pause or delete every tag that measures something your new setup now handles. In practice this is your old GA4 configuration tag, all GA4 event tags for e-commerce steps such as `add_to_cart` and `purchase`, your Meta Pixel tags, your Google Ads remarketing tags, and any custom HTML tags that send data to a platform directly.&#x20;

If you are not sure whether you will need an old tag later, pause it instead of deleting it. You can always remove it in a later version once the new setup has proven itself. Old triggers and variables can stay, they do nothing on their own.

Skip this and preview mode will show two of everything, and after publishing your conversions will be counted twice.

#### Test both containers

1. Open the **Preview mode** in your GTM web container and fill in the URL of your webshop.
2. Open the **Preview mode** in your GTM server container as well, so you can follow the same hits arriving server-side.
3. Walk through the complete customer journey and check that each step fires once, with the right e-commerce parameters:
   * `page_view`
   * `view_item_list`
   * `view_item`
   * `add_to_cart`
   * `view_cart`
   * `remove_from_cart`
   * `begin_checkout`
   * `add_shipping_info`
   * `add_payment_info`
   * `purchase`
4. For every event, check in the **server** container that the GA4 event request arrives and that your platform tags fire and return a successful response.

***

### Step 6: Clean up, deploy and publish

Everything up to this point has run on your staging environment. Going live means the custom cms deploy and the GTM publish need to happen in the right order, and there is one clean-up round to do first.

#### **Remove tracking scripts that are now handled server-side**

Every platform you have moved to your server container should no longer be loaded directly in your Custom frontend. If you set up Meta Ads through server-side tagging, the Meta Pixel base code in your theme has to go. The same applies to a hardcoded gtag.js snippet for GA4 or Google Ads, a TikTok pixel, a Pinterest tag, or any other pixel that is now fired from the server container. If your theme contains a GTM snippet that was placed there manually, remove it as well, because the AdPage module loads the connection to the GTM web container itself.

Go through this list with your developer before anything is pushed, so the removals and the module land in production in the same release.

#### **Deploy to production**

Ask your custom cms developer to push the module and the theme changes to production. Wait until the deploy is confirmed and you can see the changes in scripts and dataLayer on your live site.

#### **Publish both GTM containers**

Test again in the preview modes on the live site. If everything still works as intended, you can publish your web and server container. Use a version name and description you will recognise later, for example "AdPage server-side tagging", so you can roll back to the previous version if something turns out to be wrong.

After publishing, run a test purchase on your live site and check in the AdPage interface and your GA4 realtime report whether the events arrive and the conversions are registered once. Any connection that custom cms still maintains directly with an advertising platform will send the same event a second time, which leads to duplicated conversions and inflated revenue in your reports.

***

### Need help?

Still seeing missing events, duplicated conversions or unassigned traffic after following these steps? Reach out to our support team and we will take a look with you.


# Add User Data Script

This article explains how to add the AdPage User Data Script to a custom website or CMS. This script collects marketing and device data. It also pushes the trytagging\_user\_data event to the dataLayer.

{% hint style="info" %}
**Note:** Only use this script when the AdPage plugin or app is **NOT** installed. The AdPage plugin or app handles this automatically for Shopify, WooCommerce, WordPress, Magento, and Lightspeed.
{% endhint %}

### When should you use this script?

| Situation                              | Script required? |
| -------------------------------------- | ---------------- |
| Custom CMS without the AdPage plugin   | ✅ Yes            |
| Custom-built website                   | ✅ Yes            |
| Platform without an AdPage integration | ✅ Yes            |
| Shopify with the AdPage App            | ❌ No             |
| WooCommerce with the AdPage Plugin     | ❌ No             |
| WordPress with the AdPage Plugin       | ❌ No             |
| Magento with the AdPage Extension      | ❌ No             |
| Lightspeed with the AdPage Pixel       | ❌ No             |

***

### What does this script do?

The User Data Script automatically collects:

* **Device information:** Browser, operating system, and screen resolution.
* **Marketing data:** UTM parameters, referrers, campaign data, and session IDs.
* **User identification:** Client ID, session ID, and session count for accurate attribution.

This data becomes available in the dataLayer through `trytagging_user_data`. This event starts all other tracking. Without it, tracking data is not processed correctly.

#### Why is the load order important?

The `trytagging_user_data` event contains key identifiers. These include `client_id`, `session_id`, and `session_count`. All following events use them. Problems occur if other dataLayer events, such as `view_item` or `add_to_cart`, are pushed **before** this script loads:

* Google Tag misses required configuration parameters.
* Sessions cannot be attributed correctly.
* Webhooks do not work correctly because marketing data is missing.
* GA4 and advertising platforms receive incomplete data, or no data.

***

### Step 1: Find your linked domain

Before installing the script, you need your **linked domain**. You can find it in two ways.

#### Option A: Use the installation link

If you received an installation link from AdPage, the instructions include the domain.

#### Option B: Use the Trytagging dashboard

1. Go to the [adpage platform](https://data.adpage.io/) and sign in.
2. Select the correct container.
3. Go to **Implementation** → **Domain name**.
4. Copy your linked domain, for example `tagging.yourwebsite.com`.

{% hint style="info" %}
**Example:** If your linked domain is `tagging.webshop.nl`, use `https://tagging.webshop.nl/user-data-minified.js` as the script URL.
{% endhint %}

***

### Step 2: Install the script via Google Tag Manager (optional)

{% hint style="warning" %}
**Important: The load order in GTM.**

The `trytagging_user_data` event starts your tracking setup. Without it, Google Tag Manager cannot process events such as `view_item`, `add_to_cart`, and `purchase` correctly.

**Place this script:**

* Place this script in Google Tag Manager
  {% endhint %}

To manage the script through Google Tag Manager instead of your source code:

1. Create a **Custom HTML Tag** in GTM.
2. Paste the complete script, including the `<script>` tags.
3. Set the trigger to **All Pages** or **DOM Ready**.
4. Ensure this tag fires **first**. Use Tag Sequencing if needed.

{% hint style="info" %}
**Important:** Push `trytagging_user_data` before all other ecommerce events. Configure other tags to trigger **after** this event.
{% endhint %}

**Tag setup**

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fw5cGIHvSDDLrTC8KoHf5%2Fimage.png?alt=media&amp;token=70c02990-52db-4a06-8eb7-0fbeaf108226" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FcFKfaZxHjKkt5BI0zkjr%2Fimage.png?alt=media&amp;token=57f2997d-d5c2-4de0-a2ab-dd86507e73e5" alt=""><figcaption></figcaption></figure>

Copy the following script. **Replace** `[YOUR_LINKED_DOMAIN]` with the linked domain from Step 1.

```html
<script>
(function() {
  // Function to load external script with defer
  function loadScript(url) {
    return new Promise(function(resolve, reject) {
      var script = document.createElement('script');
      script.defer = true;
      script.src = url;
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }
  
  // Function to check if taggingHelpers is available
  function checkTaggingHelpers(timeout) {
    timeout = timeout || 10000;
    var startTime = Date.now();
    return new Promise(function(resolve, reject) {
      function check() {
        if (window.taggingHelpers && 
            typeof window.taggingHelpers.getMarketingObject === 'function' && 
            typeof window.taggingHelpers.getDeviceInfo === 'function') {
          resolve();
        } else if (Date.now() - startTime > timeout) {
          reject(new Error('Timeout waiting for taggingHelpers'));
        } else {
          setTimeout(check, 50);
        }
      }
      check();
    });
  }
  
  // Function to collect data from taggingHelpers
  function collectData() {
    try {
      return {
        event: 'trytagging_user_data',
        device: window.taggingHelpers.getDeviceInfo() || {},
        marketing: window.taggingHelpers.getMarketingObject() || {}
      };
    } catch (error) {
      console.error('Error collecting tagging data:', error);
      return null;
    }
  }
  
  // Function to push to dataLayer
  function pushToDataLayer(data) {
    if (!data) return;
    
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push(data);
  }
  
  // Main execution
  function init() {
    loadScript('https://[YOUR_LINKED_DOMAIN]/user-data-minified.js')
      .then(function() {
        return checkTaggingHelpers();
      })
      .then(function() {
        var data = collectData();
        pushToDataLayer(data);
      })
      .catch(function(error) {
        console.error('Error in tagging initialization:', error);
      });
  }
  
  // Start initialization when DOM is ready
  if (document.readyState !== 'loading') {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();
</script>
```

#### Example with a linked domain

If your linked domain is `tagging.webshop.nl`, replace line 42:

```javascript
// From:
loadScript('https://[YOUR_LINKED_DOMAIN]/user-data-minified.js')

// To:
loadScript('https://tagging.webshop.nl/user-data-minified.js')
```

***

### Step 3: Verify the installation

After adding the script, verify that it works correctly.

#### Check 1: Browser console

1. Open your website in Chrome or Firefox.
2. Open Developer Tools with `F12` or `Cmd` + `Option` + `I`.
3. Select the **Console** tab.
4. Confirm there are no red errors related to `tagging` or `user-data`.

#### Check 2: Verify the dataLayer

1. Enter `dataLayer` in the console.
2. Press Enter.
3. Find an object with `event: "trytagging_user_data"`.
4. Confirm the `marketing` and `device` objects contain data.

**Example of correct output:**

```javascript
{
  event: "trytagging_user_data",
  device: {
    browser: "Chrome",
    os: "Windows",
    // ... more device information
  },
  marketing: {
    user_id: "abc123...",
    session_id: "xyz789...",
    // ... more marketing information
  }
}
```

#### Check 3: Network tab

1. Select the **Network** tab in Developer Tools.
2. Refresh the page.
3. Filter for `user-data`.
4. Confirm `user-data-minified.js` loaded successfully with status `200`.

***

### Troubleshooting

#### The script does not load

**Possible causes:**

* The domain name is incorrect.
* The linked domain is not active in Trytagging.
* The URL contains a typo.

**Resolution:**

1. Confirm that you copied the correct domain from Trytagging.
2. Test `https://[your-domain]/user-data-minified.js` directly in your browser.
3. Contact AdPage support if you receive a `404` error.

#### No data in the dataLayer

**Possible causes:**

* The script appears after other tracking scripts.
* A JavaScript error occurs on the page.
* An ad blocker blocks the script.

**Resolution:**

1. Move the script to the start of the `<head>` section.
2. Check the console for JavaScript errors.
3. Test in an incognito window without extensions.

#### `taggingHelpers` is undefined

**Possible causes:**

* The external script has not loaded yet.
* A network problem occurred.

**Resolution:** The script waits up to 10 seconds for loading. If the issue continues, check:

1. Whether the URL is correct.
2. Whether the console shows CORS errors.
3. Whether a firewall blocks the script.

#### Console error: `Timeout waiting for taggingHelpers`

This means the script was still unavailable after 10 seconds.

**Resolution:**

1. Check your internet connection.
2. Confirm that the script URL is reachable.
3. Increase the timeout value if needed: `timeout = timeout || 10000;` on line 11.

***

### Frequently asked questions

#### Can I combine this with the full custom dataLayer?

Yes. This script only provides the `trytagging_user_data` event.

#### Do I need to add the script to every page?

Yes. The script must appear on **every page** of your website. Push `trytagging_user_data` on every page before other tracking events occur.

#### Does this script work with Consent Mode?

Yes. The script supports Google Consent Mode. When you use a CMP, data is collected only after the visitor gives consent.

#### Do I need this script for Data Assistant?

Yes. The Data Assistant Tag requires `trytagging_user_data` as its start event. Without this script, Data Assistant does not work correctly.

#### What if I have multiple domains?

Each domain needs a separate linked domain in Trytagging. Update the script for each domain with the correct URL.


# Add dataLayer events

Learn how to setup custom datalayer events

### 1. build the dataLayer events

AdPage follows the Google Tag Manager dataLayer standard. Learn more about event structure in the [Google documentation](https://support.google.com/analytics/answer/9267735?hl=en).

The following events are important for an eCommerce website:

* user\_data (installed in step 2.1)
* view\_item\_list ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#view_item_list))
* view\_item ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#view_item))
* add\_to\_cart ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#add_to_cart))
* remove\_from\_cart ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#remove_from_cart))
* view\_cart ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#view_cart))
* begin\_checkout ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#begin_checkout))
* add\_payment\_info ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#add_payment_info))
* add\_shipping\_info ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#add_shipping_info))
* purchase ([Google documentation](https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtm#purchase))

> **Note:** These events are a guide for eCommerce websites. Custom events or other website goals, such as lead generation, may require different events.

Prefix events with `trytagging_` to avoid conflicts with existing dataLayer events.

### 2. Add the user\_data datalayer event

The `user_data` event is the first event sent on your website. Add it before other dataLayer events. It acts as the Google Tag Manager start signal. Tracking data may not arrive correctly without it.

{% hint style="info" %}
When using webhooks, each page must override `client_id`, `session_id`, and `session_count` with Google-generated IDs. Trigger the Google tag from the dataLayer `user_data` event. Trigger every other event only after the Google tag.
{% endhint %}

The `user_data` event requires an additional script. Add this script to the `<body>`:

```xml
<script  defer  src="https://[connected_domain_name]/user-data-minified.js">
</script>
```

{% hint style="info" %}
**Note:** Find the connected domain in the installation link. You can also find it under **Implementation** → **Domain name** in the AdPage Tagging dashboard. Update the URL for each domain.
{% endhint %}

This script provides two JavaScript helper functions:

```javascript
window.taggingHelpers.getMarketingObject(); // Marketing object

window.taggingHelpers.getDeviceInfo(); // Device object
```

Then send the first `user_data` event in JavaScript:

```javascript
// Run this code only after window.taggingHelpers is available.
// It loads through a defer tag, so it does not block the website.

window.dataLayer.push({

  event: "trytagging_user_data",

  marketing: window.taggingHelpers.getMarketingObject(),

  device: window.taggingHelpers.getDeviceInfo(),

});
```

Add `marketing` to every subsequent event. This is an example `view_item` event:

```php
window.dataLayer.push({

  event: "trytagging_view_item",

  ecommerce: {

    currency: "EUR",

    value: 100,

    items: [

      {

        item_id: "123456",

        item_name: "Product Name",

        price: 100,

        item_category: "Product Category",

      },

    ],

  },

  marketing: window.taggingHelpers.getMarketingObject(),

});
```

#### 2.1 Optional wait for the user\_data script

We recommend loading the `user_data` script with `defer`. This prioritizes other critical page elements. It also means the script may not be immediately available.

The `user_data` script sends a custom JavaScript event when its functionality becomes available. Use that event as follows:

```javascript
document.addEventListener("trytagging_user_data_ready", (event) => {
  const marketingData = window.taggingHelpers.getMarketingObject();

  console.log("Marketing Data:", marketingData);
});
```


# Add backend webhooks

Learn how to setup custom webhooks

### Before you start

This article picks up where [Custom User Data](/integrations-websites/custom/add-user-data-script) and [custom datalayer](/integrations-websites/custom/add-datalayer-events) leaves off. Make sure all of the steps in the [Setup AdPage container](/getting-started/setup-adpage-container) article have been followed. Which means that:

* [ ] Your **AdPage container** is created.
* [ ] Your AdPage container is **connected to your GTM server container**.
* [ ] The **CNAME record** is added in your DNS settings, so tagging runs on your own (sub)domain.
* [ ] The custom [user Date scripts ](https://docs.adpage.io/integrations-websites/custom/add-the-custom-user-data-script-to-your-website) setup are correctly on your site.
* [ ] The [eCommerce dataLayer](https://docs.adpage.io/integrations-websites/custom/custom-ecommerce-datalayer-and-backend-webhooks-setup) is correctly on your site.

### Install webhooks

Backend [webhooks](https://www.adpage.io/post/webhooks) provide more accurate measurement. In eCommerce, send a webhook when an order is created. This is the primary conversion.

Webhooks require additional website configuration. Test the implementation thoroughly.

Send webhooks to configures server container URL for example:\
`https://tagging.domain-name.com/order_created`&#x20;

### The webhook payload

Use the following payload for an eCommerce website. Send it in JSON format. Do not deviate from this example. Changes can negatively affect tracking.

```perl
{

  "event": "trytagging_purchase",

  "ecommerce": {

    "transaction_id": "43",

    "affiliation": "",

    "value": 45.0,

    "tax": 0.0,

    "shipping": 0.0,

    "currency": "EUR",

    "coupon": "",

    "items": [

      {

        "item_name": "copy hoodiiiee",

        "item_id": "23",

        "price": 45.0,

        "quantity": 1,

        "index": 1

      }

    ]

  },

  "user_data": {

    "customer_id": 1,

    "customer_email": "jeroen@adpage.io",

    "customer_name": "Jeroen Test",

    "customer_phone": "0612345678",

    "customer_address": "Velmolenweg 54a",

    "customer_zip": "5404 LD",

    "customer_country": "NL",

    "customer_city": "Uden",

    "customer_state": "Province",

    "customer_country": "Netherlands",

    "billing_first_name": "Jeroen",

    "billing_last_name": "Test",

    "billing_address": "Velmolenweg 54a",

    "billing_postcode": "5404 LD",

    "billing_state": "",

    "billing_city": "Uden",

    "billing_email": "jeroen@adpage.io",

    "billing_phone": "0612345678",

    "shipping_first_name": "Jeroen",

    "shipping_last_name": "Test",

    "shipping_company": "",

    "shipping_address": "Velmolenweg 54a",

    "shipping_postcode": "5404 LD",

    "shipping_country": "NL",

    "shipping_state": "",

    "shipping_city": "Uden",

    "shipping_phone": "",

    "new_customer": "true"

  },

  "marketing": {

    // Front-end marketing data and the following field:

    "ip": "visitor_ip_address"

  }

}
```

### The marketing object

The marketing object comes from the front-end tracking script. Send this data object in the backend webhook payload. See [add custom user data script to site](/integrations-websites/custom/add-user-data-script).

{% hint style="info" %}
The following function is only an example. Do not copy it directly.
{% endhint %}

```javascript
var marketingData = window.taggingHelpers.getMarketingObject();
var jsonString = JSON.stringify(marketingData);
var base64Data = base64Encode(jsonString);
   
setCookie('trytagging_user_data', base64Data, 30);
```


# Meta Ads

How to set up server-side tagging for Meta Ads

This guide shows you how to configure the Meta (Facebook) Conversions API in your Google Tag Manager server container, step by step.

{% hint style="warning" %}
**This article covers a server-side only setup.** All Meta events are sent from your server container to the Conversions API, there is no Meta Pixel firing in the browser. You can also run Meta Ads **client-side and server-side at the same time**, with event deduplication based on the `event_id` parameter. That setup requires a few different settings, which we describe in [Setting up Meta Ads client-side tagging with event deduplication](/integrations-marketingtools/meta-ads/setting-up-client-side-meta-ads-tracking-with-deduplication). One setting in particular (**Use HttpOnly cookies**) depends on which of the two setups you choose.&#x20;
{% endhint %}

### Before you start

Make sure you have:

* [ ] A working GTM server container that receives events (usually via your Google Tag / GA4 client).
* [ ] Your **Pixel ID** and **API Access Token** from Meta Events Manager. See [Where to find the Meta Pixel ID and the Meta API Token](/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token).

### Step 1: Add the tag template

1. Open your GTM server container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Search for the **Facebook Conversion API** tag template and add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FKxgO3z08RHOjmdbqUVsT%2Fimage.png?alt=media&amp;token=285e035b-a564-4b23-bed9-35abe786b085" alt=""><figcaption></figcaption></figure>

### Step 2: Create the tag

1. Go to **Tags** and create a new tag.
2. Choose the **Facebook Conversion API** template as your tag configuration.
3. Choose **Inherit from client** as the event name setup method. Only change this if you want to send different event names to the Facebook Conversion API than the event names received from the incoming GA4 events.
4. Choose **Website** as the action source.
5. Under **Facebook Pixel ID**, enter your Pixel ID from Meta Events Manager. Under **API Access Token**, enter your API token from Meta Events Manager.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FgSs6rfNbNJkREadhGeKW%2Fimage.png?alt=media&amp;token=b209b048-e761-471c-bf91-9c5ec38508f5" alt=""><figcaption></figcaption></figure>

### Step 3: Set the cookie and event options

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0sTLveszr6vX28nrXYpC%2Fimage.png?alt=media&amp;token=b74dcef1-e9f6-4746-ba24-f5e62c44ccb5" alt=""><figcaption></figcaption></figure>

Set the four checkboxes as follows for a server-side only setup:

| Option                                 | Server-side only | Client-side + server-side (deduplication) |
| -------------------------------------- | ---------------- | ----------------------------------------- |
| Generate `_fbp` cookie if it not exist | Disabled         | Disabled                                  |
| Use HttpOnly cookies                   | **Enabled**      | **Disabled**                              |
| Enable Event Enhancement               | Enabled          | Enabled                                   |
| Use Optimistic Scenario                | Disabled         | Disabled                                  |

**Generate \_fbp cookie if it not exist**

The `_fbp` cookie holds the browser ID: Meta's identifier for the browser. With this option enabled, your server container generates the `_fbp` value itself when it is missing **Recommendation: disable this.** The \_fbp value should not be generated by your server container because then it won't be an identifier Meta issues or recognises. Meta cannot tie it to a person on its own. All it can do is group events that came from the same browser, and that only works if the cookie is reliably written to your tracking domain and returned on every following request.

**Use HttpOnly cookies**

An HttpOnly cookie cannot be read by JavaScript in the browser. It is only sent along with requests to your server. Enabling or disabling this option depends on your setup:

* **Server-side only:** enable it. Nothing in the browser needs to read the cookie, and an HttpOnly cookie cannot be read out by scripts or browser extensions running on your site. It is also less exposed to cookie-clearing behaviour by browsers, because the cookie is set by your server rather than by JavaScript.
* **Client-side and server-side with deduplication:** disable it. The Meta Pixel in the browser will read the \_fbp with JavaScript. If the cookie is HttpOnly, the Pixel cannot see it, generates its own browser ID, and you end up with two different identifiers for the same user. That breaks the match between your browser events and your server events.

**Enable Event Enhancement**

This option lets the tag store user data in a separate HttpOnly cookie (`gtmeec`) on your own domain. **Recommendation: enable this.** It raises your event match quality, which improves attribution and Meta's ability to optimise your campaigns. The data stays in a first-party, HttpOnly cookie that JavaScript cannot access.

{% hint style="info" %}
Do consider your privacy documentation: the tag stores personal data (hashed) in a cookie on your domain, so make sure this is covered in your cookie policy and that the tag only fires with marketing consent.
{% endhint %}

**Use Optimistic Scenario**

Normally the tag waits for Meta's API to confirm that the event was received before reporting back to GTM. With this option enabled, the tag reports success immediately, without waiting for a response. **Recommendation: leave this disabled.** You lose your only view of whether events actually arrive, which makes tracking problems very hard to spot.&#x20;

### Step 4: Add a trigger

1. Give the tag a new trigger. Click **Triggers** under the tag, then click the blue plus icon in the top right.
2. Choose the grey **Custom** option as the trigger configuration.
3. Add your condition. Common options are:

* **Based on specific event names**
  * `{{Event Name}}` matches RegEx `eventname|eventname`
    * Always include `page_view` as the first event name.&#x20;
* **Without a condition**, if you want to send every GA4 event to the Conversions API
  * `{{Client Name}}` equals `GA4`

4. Save the trigger and the tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FTuFNaTS8n5ugIia78FmV%2Fimage.png?alt=media&amp;token=1973d922-d95f-488c-8c44-299169467cd0" alt=""><figcaption></figcaption></figure>

### Step 5: Test

Use the server container preview mode to check that the Facebook Conversion API tag fires on incoming events.

For a more thorough check, add a **Test ID** to the tag and open the Test Events tab in Meta Events Manager. Your events should appear with **Server** listed as the source. Remove the Test ID again once you are done testing.

### Optional: Add or override event parameters

By default, the tag builds its payload from the incoming event on its own. It reads the parameters your web container sends to the server container and maps the ones it recognises to their Meta equivalents. For most setups that is enough.

You can override that mapping, or add parameters the tag does not pick up by itself. Open your Facebook Conversion API tag and expand the sections below the main settings:

* **Server Event Data Override** — for event-level fields, such as the event name or the event ID.
* **User Data** — for identifying parameters, including the browser ID and click ID.
* **Custom Data** — for the commercial details of the event, such as value, currency and product data.

Each section works the same way: you add a property, choose which field you want to fill, and give it a value. That value is normally a variable pointing at a parameter in the incoming event.

There are two reasons to do this:

* **The parameter arrives, but the tag does not map it.** Your web container may send a value under a name the tag does not recognise, or in a structure it cannot read. Pointing the field at the right parameter yourself gets it into the payload.
* **The parameter is wrong or missing.** If the automatic mapping produces a value you do not want to send, an override replaces it.

Which parameters are available to you depends entirely on what your GA4 event tags send from the web container. There is no universal list. Open the server container preview mode, look at an incoming request, and work from the parameters you actually see there.

Two things to keep in mind. The tag hashes user data automatically, so pass values in plain text and do not hash them yourself first. And only map parameters you have a legal basis to send: anything you add here goes to Meta, so it needs to be covered by your consent setup and your privacy statement.


# Setting up client-side Meta Ads tracking with deduplication

Setting up client- and server-side tagging for Meta Ads with event\_id deduplication

Running both server-side and client-side tagging means Meta receives the same conversion twice: once from the browser and once from your server. Deduplication is what stops that from being counted twice. It works when both events carry the **same event name** and the **same event\_id**. Meta then keeps one and discards the duplicate, preferring the server event, which is the more reliable of the two.

So the goal throughout this guide is that your Meta Pixel tag, your GA4 tag and your server-side Conversions API tag all describe the same interaction with the same event ID.

### Before you start

Make sure you have:

* [ ] A working [server-side Conversions API setup](/integrations-marketingtools/meta-ads).
* [ ] Your **Meta Pixel ID**. See [How to find your Meta Pixel ID](/integrations-marketingtools/meta-ads/where-to-find-the-meta-pixel-id-and-the-meta-api-token).
* [ ] A **Unique Event ID** variable in your web container.

### Step 1: Add the tag template

1. Open your GTM web container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Search for the **Meta Pixel** tag template and add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FoqUb2R0Qr1j9tve2uncE%2Fimage.png?alt=media&amp;token=b2addb86-728a-438a-ac30-86e10cae9600" alt=""><figcaption></figcaption></figure>

### Step 2: Create a variable for your Pixel ID

4. Go to **Variables**.
5. Create a new **User-Defined Variable** and choose **Constant** as the variable type.
6. Enter your Meta Pixel ID as the value and save the variable.

{% hint style="info" %}
Using a constant variable rather than typing the ID into each tag means you only have one place to change it later.
{% endhint %}

### Step 3: Create your Meta event tags

1. Go to **Tags** and create a new tag. Select the **Facebook Pixel** template as the tag configuration.
2. In the **Meta Pixel ID** field, select your Pixel ID variable.
3. Under **Event Name**, indicate whether this is a standard or a custom event. Select a standard event from the dropdown menu, or type a custom event name into the input field.
4. Expand **More Settings**. In the **Event ID** field, enter your Unique Event ID variable.
5. As the trigger, select the same trigger you use for the GA4 event tag covering this interaction.
6. Save the tag. And repeat for the other events and conversions you want to set up.

{% hint style="warning" %}
Don't forget to set up the page\_view tag, and use the same trigger as your GA4 page\_view event tag.
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FMaxvl2fB1GhwuKiTOZ5m%2Fimage%20(53).png?alt=media&amp;token=ae9f7556-ffd6-47b7-ab80-b380857a3871" alt=""><figcaption></figcaption></figure>

### Step 4: Add the event\_id to your GA4 events

Your GA4 event tags are what feed the server container, so the event ID has to travel with them. For every interaction you want to deduplicate, add your **Unique Event ID** variable as an event\_id event parameter on the GA4 event tag that fires on that interaction.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0BpvIPXyTvkYHyJ7C8QB%2Fimage.png?alt=media&amp;token=3347dd2c-d02c-42e2-b5cd-a0c12191dc2e" alt=""><figcaption></figcaption></figure>

### Step 5: Test and Verify

Open Google Tag Manager's preview mode to check whether the event\_id in the client-side Meta Event tag matches the server-side Facebook Conversion API tag. If this is not the case, the usual causes are:

* The event names do not match. The Pixel sends one name and the server-side tag sends another.
* The event IDs do not match, or the server-side tag receives no event ID at all.
* The two tags fire on different triggers, so they never describe the same interaction.


# Where to find the Meta Pixel ID and the Meta API Token

How to retrieve the Meta Pixel ID and Meta API Token via the Meta Business Suite

To send server-side events to Meta Ads, you need two values: the Pixel ID of the pixel you want to send events to, and a Conversions API access token that authorises those events. You can find both in the Meta Events Manager.

### Finding your Meta Pixel ID

{% stepper %}
{% step %}

#### Open the Meta Business Suite

Go towards [business.facebook.com](https://business.facebook.com/) to open your Meta Business Suite.
{% endstep %}

{% step %}

#### Open the Meta Events Manager

Select the correct account, and open this account's Events Manager.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FHUdhkIhGbGBgE09aN9Pi%2Fimage.png?alt=media&amp;token=b9f883c2-728b-4354-a104-95cebb37d80e" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Find the Pixel ID

In the Pixel overview, select the correct pixel. In this pixel go towards the Settings and find the Dataset ID.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FYRJl2Mo72OvVinT3uKCX%2Fimage.png?alt=media&amp;token=1791f25a-b3a9-4a1c-bbfb-c07d9eaa725b" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### Finding your Meta API Token

{% stepper %}
{% step %}

#### Open the Meta Business Suite

Go towards [business.facebook.com](https://business.facebook.com/) to open your Meta Business Suite.
{% endstep %}

{% step %}

#### Open the Meta Events Manager

Select the correct account, and open this account's Events Manager.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FrL6QdRaJw7q7KfM4Qy1p%2Fimage.png?alt=media&amp;token=28d80003-5b22-4206-8c6c-2922bf2c2a05" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Generate the API Token

In the Pixel overview, select the correct pixel. In this pixel go towards the Settings and find the Conversion API settings. Here you can generate an API Token by manually generating it.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FfFLz0tlWX5Im7zquMPnK%2Fimage.png?alt=media&amp;token=db6ba4f3-fcea-4c51-b3c5-2e5b4b2bc662" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}


# TikTok Ads

How to set up TikTok Ads tracking through the TikTok Events API

This guide shows you how to configure the TikTok Events API in your Google Tag Manager server container, step by step.&#x20;

{% hint style="warning" %}
**This article covers a server-side only setup.** All TikTok events are sent from your server container to the Events API, there is no TikTok Pixel firing in the browser. You can also run TikTok Ads **client-side and server-side at the same time**, with event deduplication based on a shared event ID. We describe that setup in [Setting up client-side TikTok Ads tracking with deduplication](/integrations-marketingtools/tiktok-ads/setting-up-client-side-tiktok-ads-tracking-with-deduplication).
{% endhint %}

### Before you start

Make sure you have:

* [ ] A working GTM server container that receives events (usually via your Google Tag / GA4 client).
* [ ] Your **TikTok Pixel ID** and **API Access Token**. See [How to find your TikTok Pixel ID and Access Token](/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token).

### Step 1: Add the tag template

1. Open your GTM server container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Search for the **TikTok Events API** tag template and add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FCp6SEiMdzNl6qUWoZM3t%2Fimage.png?alt=media&amp;token=96dcc084-6ba6-4125-80bb-7d7b46f93c09" alt=""><figcaption></figcaption></figure>

### Step 2: Create the Events API tag

1. Go to **Tags** and create a new tag. Choose **TikTok Events API** as the tag configuration.
2. Under **Event Name Setup Method**, choose **Inherit from client**. The tag will then use the event names of the incoming GA4 requests.
3. Fill in your Access Token in the **Access Token** field.
4. Fill in your TikTok Pixel ID in the **TikTok Pixel ID** field.

{% hint style="info" %}
Inheriting the event name means TikTok receives your GA4 event names, such as `purchase` and `add_to_cart`. Those arrive as custom events. TikTok's algorithm works better with its own standard event names, and you need standard events if you later add the TikTok Pixel with deduplication.
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F9lIR2x1wCkMX0JwlTdSn%2Fimage.png?alt=media&amp;token=d0a1c1ed-56d1-4bb2-ae36-1693a396480d" alt=""><figcaption></figcaption></figure>

5. Set the four checkboxes as follows:

| Option                                           | Recommended |
| ------------------------------------------------ | ----------- |
| Generate Browser ID (`_ttp`) cookie if not exist | Disabled    |
| Enable Event Enhancement                         | Enabled     |
| Override Cookies Settings                        | Disabled    |
| Use Optimistic Scenario                          | Disabled    |

**Generate Browser ID (\_ttp) cookie if not exist**

The \_ttp cookie holds the browser ID. In a setup with a TikTok Pixel, the Pixel creates this cookie itself, so the option is redundant there. **Recommendation: leave this disabled.** A \_ttp value your own server invents is not an identifier TikTok issues or recognises. TikTok cannot tie it to a person on its own. All it can do is group events that came from the same browser, and that only works if the cookie is reliably written to your tracking domain and returned on every following request.

**Enable Event Enhancement**

This option lets the tag store user data in a separate HttpOnly cookie (gtmeec-tt) on your own domain. When a later event arrives without user data the tag enriches that event with the stored data.**Recommendation: enable this.** It raises your event match quality, which improves attribution and TikTok's ability to optimise your campaigns.&#x20;

{% hint style="info" %}
Do consider your privacy documentation: the tag stores personal data (hashed) in a cookie on your domain, so make sure this is covered in your cookie policy and that the tag only fires with marketing consent.
{% endhint %}

**Override Cookies Settings**

The tag writes three cookies on your domain: the click ID, the browser ID and the event enhancement cookie. This option lets you override the **domain** and the **SameSite** attribute all three are written with. By default the domain is determined automatically, based on the page URL of the incoming event, with the request headers as a fallback. That is correct for a normal single-domain setup. Only enable it if the automatic behaviour is wrong for your situation, for example when you need the cookies set on your top-level domain because you track across subdomains, or when your SameSite policy has to differ from the default.&#x20;

**Use Optimistic Scenario**

Normally the tag waits for TikTok's API to confirm that the event was received before reporting back to GTM. With this option enabled, the tag reports success immediately, without waiting for a response. **Recommendation: leave this disabled.** You lose your only view of whether events actually arrive, which makes tracking problems very hard to spot.&#x20;

### Step 3: Add a trigger

1. Click **Triggers** under the tag configuration, then click the blue plus icon in the top right to create a new trigger.
2. Choose the grey **Custom** option as the trigger configuration.
3. Select **Some Events** to add conditions. Add your condition. Common options are:

* **Based on specific event names**
  * `{{Event Name}}` matches RegEx `eventname|eventname`
    * Always include `page_view` as the first event name.&#x20;
* **Without a condition**, if you want to send every GA4 event to the Conversions API
  * `{{Client Name}}` equals `GA4`

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F09nuRstySRTL2EgBvnGH%2Fimage.png?alt=media&amp;token=8035df45-7ded-40d4-ac60-102290b992b0" alt=""><figcaption></figcaption></figure>

4. Save the trigger and the tag.

### Step 4: Test

Use the server container preview mode to check that the Facebook Conversion API tag fires on incoming events.

For a more thorough check, add a **Test ID** to the tag and open the Test Events tab in TikTok Ads Manager. Your events should appear with **Server** listed as the source. Remove the Test ID again once you are done testing.

### Optional: Add or override event parameters

By default, the tag builds its payload from the incoming event on its own. It reads the parameters your web container sends to the server container and maps the ones it recognises to their TikTok equivalents. For most setups that is enough.

You can override that mapping, or add parameters the tag does not pick up by itself. Open your TikTok Events API tag and expand the sections below the main settings:

* **Server Event Data Override** — for event-level fields, such as the event ID, referrer, timestamp and URL.
* **User Data** — for identifying parameters, including email, phone number, external ID, click ID and browser ID.
* **Properties** — for the commercial details of the event, such as value, currency, content and query.

Each section works the same way: you add a property, choose which field you want to fill, and give it a value. That value is normally a variable pointing at a parameter in the incoming event. Anything you enter manually takes precedence over what the tag mapped automatically.

There are two reasons to do this:

* **The parameter arrives, but the tag does not map it.** Your web container may send a value under a name the tag does not recognise, or in a structure it cannot read. Pointing the field at the right parameter yourself gets it into the payload.
* **The parameter is wrong or missing.** If the automatic mapping produces a value you do not want to send, an override replaces it.

Which parameters are available to you depends entirely on what your GA4 event tags send from the web container. There is no universal list. Open the server container preview mode, look at an incoming request, and work from the parameters you actually see there.

Two things to keep in mind. The tag hashes user data automatically, so pass values in plain text and do not hash them yourself first. And only map parameters you have a legal basis to send: anything you add here goes to TikTok, so it needs to be covered by your consent setup and your privacy statement.


# Setting up client-side TikTok Ads tracking with deduplication

Setting up client- and server-side tagging for TikTok Ads with event\_id deduplication

Running both server-side and client-side tagging means TikTok receives the same conversion twice: once from the browser and once from your server. Deduplication is what stops that from being counted twice. It works when both events carry the **same event name** and the **same event\_id**. TikTok then keeps one and discards the duplicate, preferring the server event, which is the more reliable of the two.

So the goal throughout this guide is that your TikTok Pixel tag, your GA4 tag and your server-side Events API tag all describe the same interaction with the same event ID.

### Before you start

Make sure you have:

* [ ] A working [server-side Events API setup](/integrations-marketingtools/tiktok-ads).
* [ ] Your **TikTok Pixel ID**. See [How to find your TikTok Pixel ID](/integrations-marketingtools/tiktok-ads/where-to-find-the-tiktok-pixel-id-and-the-tiktok-api-token).
* [ ] A **Unique Event ID** variable in your web container.

### Step 1: Add the tag template

1. Open your GTM web container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Search for the **TikTok Pixel** tag template and add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FeL1XRfXhhb7K37MisywD%2Fimage.png?alt=media&amp;token=c6c57872-e6a9-4978-990e-db40ed580fea" alt=""><figcaption></figcaption></figure>

### Step 2: Create a variable for your Pixel ID

4. Go to **Variables**.
5. Create a new **User-Defined Variable** and choose **Constant** as the variable type.
6. Enter your TikTok Pixel ID as the value and save the variable.

{% hint style="info" %}
Using a constant variable rather than typing the ID into each tag means you only have one place to change it later.
{% endhint %}

### Step 3: Create your TikTok event tags

1. Go to **Tags** and create a new tag. Select the **TikTok Pixel** template as the tag configuration.
2. In the **TikTok Pixel ID** field, select your Pixel ID variable.
3. Under **Event Name**, indicate whether this is a standard or a custom event. Select a standard event from the dropdown menu, or type a custom event name into the input field.
4. Expand **Server Side Tracking Settings**. In the **Event ID** field, enter your Unique Event ID variable.
5. As the trigger, select the same trigger you use for the GA4 event tag covering this interaction.
6. Save the tag. And repeat for the other events and conversions you want to set up.

{% hint style="warning" %}
Don't forget to set up the page\_view tag, and use the same trigger as your GA4 page\_view event tag.
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FOVbc70vJY6Lh0ch0jLGU%2Fimage%20(54).png?alt=media&amp;token=aeb2fe51-e4d6-49b2-b948-0c8b6a429fa7" alt=""><figcaption></figcaption></figure>

### Step 4: Add the event\_id to your GA4 events

Your GA4 event tags are what feed the server container, so the event ID has to travel with them. For every interaction you want to deduplicate, add your **Unique Event ID** variable as an event\_id event parameter on the GA4 event tag that fires on that interaction.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0BpvIPXyTvkYHyJ7C8QB%2Fimage.png?alt=media&amp;token=3347dd2c-d02c-42e2-b5cd-a0c12191dc2e" alt=""><figcaption></figcaption></figure>

### Step 5: Test and Verify

Open Google Tag Manager's preview mode to check whether the event\_id in the client-side TikTok Event tag matches the server-side TikTok Events API tag. If this is not the case, the usual causes are:

* The event names do not match. The Pixel sends one name and the server-side tag sends another.
* The event IDs do not match, or the server-side tag receives no event ID at all.
* The two tags fire on different triggers, so they never describe the same interaction.


# Where to find the TikTok Pixel ID and the TikTok API Token

How to retrieve the TikTok Pixel ID and TikTok API Token in the TikTok Ads Manager

To send server-side events to TikTok, you need two values: the Pixel ID of the pixel you want to send events to, and an Events API access token that authorises those events. You can find both in TikTok Ads Manager.

### **Where to find the Pixel ID**

{% stepper %}
{% step %}

#### Open the TikTok Ads Manager

Log in to TikTok Ads Manager: <https://ads.tiktok.com/>
{% endstep %}

{% step %}

#### Find your Assets

Go to Tools and open Assets.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FdCCxj26X6koFp2fChNxm%2Fimage.png?alt=media&amp;token=3858eacf-9d33-4782-b772-c5ece1cd4bd7" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Open the Events Manager

Select the correct pixel and open the pixel in Events Manager.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FLHptoxotei8km2b9P6Ok%2Fimage.png?alt=media&amp;token=51de2dbc-a19f-4c26-a41a-909dd8f8affd" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Find the Pixel ID

At the top you'll be able to find the Pixel ID.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FdIh8ssht4dZgNVUriXz6%2Fimage.png?alt=media&amp;token=d6a793cf-2435-4a3f-83f5-ca1483d2b1cc" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### **Where to find the API token**

{% stepper %}
{% step %}

### Open the TikTok Ads Manager

Log in to TikTok Ads Manager: <https://ads.tiktok.com/>
{% endstep %}

{% step %}

### Find your Assets

Go to Tools and open Assets.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fl2IP3lDtFvAseaxxFBWM%2Fimage.png?alt=media&amp;token=04c7c660-7abf-45a5-8699-60ec873efa43" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Open the Events Manager

Select the correct pixel and open the pixel in Events Manager.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FuKeaQ1IzuwhGMGgjj7Mc%2Fimage.png?alt=media&amp;token=49b9216e-5aab-47a9-8c9f-cc5080a0be1b" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Generate the API Token

Open the settings of your pixel. Here you can find the button to generate the Access Token for the Events API.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FHhqKuKEnEfpHeRGF586N%2Fimage.png?alt=media&amp;token=80a8247b-0aa3-416d-8902-05f637f845ea" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}


# Google Ads

Setting up Google Ads conversion tracking through the Google Tag Manager server container

This guide shows you how to configure a conversion tag in your Google Tag Manager server container for Google Ads, so your conversions are registered correctly. You need a **Conversion ID** and a **Conversion Label** to complete the setup.&#x20;

{% hint style="warning" %}
**This article covers a server-side only setup.** You can also run Google Ads Ads **client-side**, just make sure that the client-side and server-side tagging don't send data towards the same conversionactions.
{% endhint %}

### Before you start

Make sure you have:

* [ ] A working GTM server container that receives events (usually via your Google Tag / GA4 client).
* [ ] Admin access to the Google Ads account.

### Step 1: Set up the Conversion Linker tag

Your server container needs a **Conversion Linker** tag. The Conversion Linker is what captures the click identifier (the GCLID) and stores it in a first-party cookie. Without it, the conversion tag has nothing to attribute the conversion to, and Google Ads will not connect the conversion to the ad click that caused it.

1. Open the Google Tag Manager server container.
2. Go to **Tags** and create a new tag.
3. Choose **Conversion Linker** as the tag configuration.
4. Add the **All Pages** trigger.
5. Save the tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FiJA1PGCi94IQlfvITelQ%2Fimage.png?alt=media&amp;token=c47d5289-ff83-4f4f-b147-ef99c65cefb2" alt=""><figcaption></figcaption></figure>

### Step 2: Create new conversion actions

When setting up new conversion tracking for Google Ads, you'll need new conversionactions within Google Ads. If you have not set up new conversionactions within Google Ads yet, follow these steps to set them up: [Where to find the Google Ads Conversion ID and Conversion Labels](/integrations-marketingtools/google-ads/where-to-find-the-google-ads-conversion-id-and-conversion-labels).

### Step 3: Set up the Conversion tag

1. Go to **Tags** and create a new tag.
2. Choose **Google Ads Conversion Tracking** as the tag configuration.
3. Fill in the configuration fields:
   * **Conversion ID** — the conversion ID from your Google Ads account.
   * **Conversion Label** — the conversion label of the conversion action in Google Ads.
4. If the value and currency are available in the incoming server container event, fill in the remaining fields with the matching variables:
   * **Conversion Value**
   * **Currency Code**
   * **Provide product-level sales data** (if the items-array is present in the event data)
5. Add a trigger to the tag so the tag fires on the correct incoming event.
6. Save the tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fe3cxnhM6t9rn2NnI1msk%2Fimage.png?alt=media&amp;token=b4f0caa4-c4a6-4ec9-87c5-8a1d9e3fe18e" alt=""><figcaption></figcaption></figure>

### Step 4: Testing

Use the server container preview mode to check that the tag fires when the GA4 event arrives.

Conversions can take a few hours to appear in Google Ads, so preview mode is your fastest confirmation that the tag is working. In Google Ads you can check the status of the conversion action itself after a couple of hours: it stays inactive until it has recorded its first conversion.


# Where to find the Google Ads Conversion ID and Conversion Labels

How to set up new conversion actions to find the Conversion ID and their Conversion Labels

For Google Ads conversion tracking you need two values: the Conversion ID and a Conversion Label. The Conversion ID is the same for your entire Google Ads account. The Conversion Label is different for every conversion action, so you need a separate label for every conversion you want to measure, for example purchase, add to cart and begin checkout.

### **Create new conversion actions**

{% stepper %}
{% step %}

#### Log in to your Google Ads account

Log in to the correct Google Ads account: [https://ads.google.com](https://ads.google.com/)
{% endstep %}

{% step %}

#### Open your Goals

Navigate towards the Goals of your Google Ads account.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FCn4I6oqOAukhQu1cMKam%2Fimage%20(52).png?alt=media&amp;token=a37cd2d0-c242-4d2f-85fb-2d56dcb3c1db" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Create new conversion actions

Create a new conversion action by clickin on the blue button

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FIhPCfnY4uMujQfri7QUn%2Fimage.png?alt=media&amp;token=043e2f1e-0e85-4f68-a310-ba118cf7c801" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Conversions on a website

Select the option Conversions on a website.&#x20;

If you have never set up conversion actions yet, you'll be asked to submit your website URL. After doing this, select the Google Tag option to set up conversions.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FZFy3549cPeTr6Fg47HSE%2Fimage.png?alt=media&amp;token=5a3e0018-3b5e-475c-a2b2-345e8332b1c0" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Select the correct conversion category

In this step you'll be asked to select a category for your new conversion actions. After selecting a category, you can create new conversion action.

If you want to measure purchase events, select the Purchase category.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FbOcH4mZZLjGLdzSAntCo%2Fimage.png?alt=media&amp;token=25808057-d093-42d7-bbc1-61b7d95dbbdd" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Create a new conversion action

When you start creating a new conversion, you'll have to set up these settings:

* Choose **Manually with code**
* In the Conversion Settings, set up:
  * **Secondary action** as Action optimization, to ensure your new conversion action doesn't immediately have effect on your campaigns
  * Fill in a clear **Conversion name**
  * Set up the **Attribution settings** through the Attribution model and the conversion windows
  * Enable the **Enhanced Conversions** setting if you are able to, and want to, send user-provided data with your events like e-mail and phone

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0Bxe1rvUW7M8WcRRYpzt%2Fimage.png?alt=media&amp;token=e6cb3901-454e-416c-9399-dcc29650de10" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Find the Conversion ID and Conversion Labels

If you have set up a new conversion action / multiple conversion actions, you can now find the Conversion ID and Conversion Label(s) in the next step.

In the Set up settings, select **Use Google Tag Manager**. Here you'll be able to find the Conversion ID and Conversion Labels.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FNJBltjojFbPETuOeRFPZ%2Fimage.png?alt=media&amp;token=0b8b840c-e966-49f5-90bd-e38a974430c8" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### **Find the ID and Labels for existing conversion actions**

{% hint style="danger" %}
**Make sure you only set up tracking once for a conversion action. If you already have set up client-side tagging for a specific conversion action, don't set up server-side tagging for the same one. Create a new conversion action by following the steps above if this is the case.**
{% endhint %}

{% stepper %}
{% step %}

#### Log in to your Google Ads account

Log in to the correct Google Ads account: [https://ads.google.com](https://ads.google.com/)
{% endstep %}

{% step %}

#### Open your Goals

Navigate towards the Goals of your Google Ads account.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FCn4I6oqOAukhQu1cMKam%2Fimage%20(52).png?alt=media&amp;token=a37cd2d0-c242-4d2f-85fb-2d56dcb3c1db" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Open the conversion action

Open the correct conversion action by clicking on it. This will open the conversion action details.
{% endstep %}

{% step %}

#### Find the Conversion ID and Label

Scroll to the bottom of the conversion action details. Click on **Manage** behind the Manual Event data source.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fv3hMCEMT7rLuDIkzYXJN%2Fimage.png?alt=media&amp;token=2d7a92f5-b567-4191-83df-4a7d1e61c015" alt=""><figcaption></figcaption></figure>

Select the **Use Google Tag Manager** option to find the Conversion ID and Conversion Label.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F4Ql9FvJiQPfNYQLn11mY%2Fimage.png?alt=media&amp;token=f288c839-0a4a-4d7f-b5a3-bb97fb920707" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}


# Setting up Google Ads remarketing

How to set up Google Ads remarketing in the Google Tag Manager server container

You can set up two types of retargeting tags on your Google Tag Manager server container. One tag handles retargeting based on visited pages, the other handles retargeting based on the eCommerce steps a visitor completes in your webshop.

{% hint style="warning" %}
If you set up retargeting server-side, make sure the same retargeting is no longer running client-side. Running both at once causes duplicate collection. Remarketing can run entirely and exclusively through the server container.
{% endhint %}

### page\_view retargeting

The Google Ads Remarketing tag on page\_view in your server container builds remarketing lists of website visitors, so you can show them targeted ads in Google Ads later. Setting this up server-side gives you better match rates, longer cookie lifetimes, and less dependency on third-party cookies.

1. Open your Google Tag Manager server container.
2. Create a new tag.
3. Select **Google Ads Remarketing** as the tag configuration.
4. Enter your **Conversion ID**.
5. Choose the **All Pages** trigger.
6. Save the tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FhRBPZ2X3f0yZ04xiStGd%2Fimage.png?alt=media&amp;token=b3149733-f365-43e9-bbf0-b40e2e28d153" alt=""><figcaption></figcaption></figure>

### eCommerce retargeting

The Google Ads Remarketing tag for eCommerce sends dynamic product and behavioural data (event name, value, product IDs, page type) to Google Ads, allowing you to show visitors targeted product ads based on the products they viewed. Visitors who viewed a specific product will then automatically see ads for that same product or similar ones.

1. Download this [JSON file](https://adpage.b-cdn.net/GTM-Templates/server-GADS-retargeting.json).
2. Open your Google Tag Manager server container.
3. Import the **JSON file** you just downloaded. This loads 3 variable templates.
4. Create a new tag.
5. Select **Google Ads Remarketing** as the tag configuration.
6. Enter your **Conversion ID**.
7. Tick **Send event data for dynamic remarketing**.
8. Under **Data source**, select **Custom configuration**.
9. For **Event name**, enter the {{Event Name}} variable. For **Event value**, enter your value variable. Don't have one yet? Create it as shown in the screenshot below.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FRX6Y7bWeJCWXKzSLY1Pl%2Fimage.png?alt=media&amp;token=ee65cd74-7ad1-49b5-9aab-247116c6fa03" alt=""><figcaption></figcaption></figure>

10. Select **Provide custom parameters** and select **Custom configuration** as the data source.
11. Enter the following parameters below

| Parameter                  | Value                         |
| -------------------------- | ----------------------------- |
| `google_business_vertical` | retail                        |
| `id`                       | {{Ecom ids}} variable         |
| `ecomm_prodid`             | {{Ecom ids}} variable         |
| `ecomm_totalvalue`         | {{Ecom total value}} variable |
| `ecomm_pagetype`           | {{Ecom page type}} variable   |

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fpr2XAgkhioSx7yEolbhB%2Fimage.png?alt=media&amp;token=f1df43d3-5754-434f-a041-9f09ef50dc04" alt=""><figcaption></figcaption></figure>

12. Create a new trigger. Click **Triggering**, then the blue plus icon in the top right.
13. Select the grey **Custom** option as the trigger configuration. Add these two conditions:

* `{{Client Name}}` variable **equals** `GA4`
* `{{Event Name}}` variable **matches RegEx** `view_item_list|view_item|add_to_cart|purchase`

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FHLQsbCTSuK5SmIaSXVMU%2Fimage.png?alt=media&amp;token=e857eadd-631f-4001-9316-405d042df14a" alt=""><figcaption></figcaption></figure>

14. Save the trigger and the tag.

***

### Validating Google Ads remarketing

There are two ways to validate your setup: directly in Google Ads (historical data) and via Google Tag Assistant (live testing).

#### Method 1: Live testing with Google Preview Mode

1. Open Google Tag Manager's preview mode in both the GTM web & server container.
2. Enter the URL of your webshop. A new tab opens with your website.
3. Perform the following actions on your website to trigger the four events:
   * View a category page (`view_item_list`)
   * Click through to a specific product (`view_item`)
   * Add the product to the cart (`add_to_cart`)
   * Optional: place a test order (`purchase`)
4. Check the server container's preview mode for the incoming requests. Open the Google Ads retargeting tag that fired on the 4 events described above. All of these tags should contain the correct values, item IDs, etc.&#x20;

#### Method 2: Check in Google Ads (Audience manager)

In Google Ads you can see exactly which parameters and events are coming in from your website.

1. Log in to your Google Ads account.
2. In the left menu, click **Tools** (or the wrench icon) → **Shared library** → **Audience manager**.
3. Check whether your remarketing lists are filling up.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FXhAQlB3UcFWYzQA53Zos%2Fimage.png?alt=media&amp;token=1a07b6d1-5125-451f-a8cc-16d6d410a599" alt=""><figcaption></figcaption></figure>

***

### Troubleshooting

**The lists in Audience manager stay at "0"** It can take 24 to 48 hours before newly implemented tags show data in the Google Ads graphs. If Tag Assistant (Method 2) shows the data being sent correctly, there's nothing to worry about, it's a matter of patience.

**Network size shows "Not available"** A list can only actively target advertisers once it contains at least 100 active users (for Display/YouTube) or 1,000 users (for Customer Match) within the past 30 days.

**Error: "IDs do not match feed"** The tag works, but the product ID on the website (e.g. `SKU-123`) differs from the one in the Merchant Center feed (e.g. `123`). Adjust this in your tag settings (for example in Google Tag Manager) so the two stay in sync.


# Setting up Enhanced Conversions for Google Ads

How to set up Enhanced Conversions for Google Ads, client-side via the GTM web container or server-side via the GTM server container

Enhanced Conversions enrich your conversion data with hashed customer data (such as email address, phone number, name and address) to improve the accuracy of your conversion measurement. This article explains how to set it up when you use Google Ads conversion tags in your Google Tag Manager web container (client-side) or in your Google Tag Manager server container (server-side).

***

### Enable Enhanced Conversions in Google Ads

First, turn on Enhanced Conversions in Google Ads so Google Ads can start processing this data.

1. Open your Google Ads account.
2. Go to **Goals** > **Conversions** (in the older interface: **Tools and Settings** > **Conversions**).
3. Select the conversion action.
4. Click **Edit settings**.
5. Turn on **Enhanced conversions** if it isn't enabled yet.
6. Choose **Google Tag Manager** as the implementation method.
7. Click **Save**.

![Enhanced conversions settings in Google Ads](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FcVIGosQBsTC5HUZW1BX6%2Fec-google-ads-settings.png?alt=media)

***

### Option 1: Client-side

With client-side tracking, Enhanced Conversions takes the customer data directly from your visitor's browser session. This means you do all the configuration in your GTM web container. You need to collect the customer data from the dataLayer or local storage while the user is active on your website and has entered this data in a form or in your checkout.

#### Step 1: Create a User-Provided Data variable

1. Open your Google Tag Manager **web** container.
2. Go to **Variables**.
3. Create a new variable with **User-Provided Data** as the variable configuration.
4. If you can retrieve the user data from a variable or from the dataLayer, choose **Manual configuration**. Otherwise, choose **Automatic collection**.
5. If you chose **Manual configuration**, add the matching variable for each data point:

![User-Provided Data variable with manual configuration](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fdz819xycmWokdyn86XFS%2Fec-upd-variable-client.png?alt=media)

6. Save the variable.

#### Step 2: Add the user-provided data to your Google Ads conversion tag

1. Open your Google Tag Manager **web** container.
2. Go to **Tags** and open the relevant **Google Ads Conversion Tracking** tag.
3. Tick **Include user-provided data from your website**.

![Include user-provided data in the Google Ads conversion tag](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FJWQzeU4WBjG7EgGp5HdC%2Fec-gads-conversion-tag.png?alt=media)

4. In the dropdown, select the **User-Provided Data** variable you created in the previous step.
5. Save the tag.

***

### Option 2: Server-side

With server-side tagging, you also collect the customer data from your visitor's browser session, which you do in your GTM web container. You don't need to change anything in your GTM server container: you only make sure the User-Provided Data is forwarded to the server container through your GA4 event tag. Google handles the rest automatically and processes the Enhanced Conversions server-side.

#### Step 1: Create a User-Provided Data variable

1. Open your Google Tag Manager **web** container.
2. Go to **Variables**.
3. Create a new variable with **User-Provided Data** as the variable configuration.
4. If you can retrieve the user data from a variable or from the dataLayer, choose **Manual configuration**. Otherwise, choose **Automatic collection**.
5. If you chose **Manual configuration**, add the matching variable for each data point:

![User-Provided Data variable with manual configuration](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FEODFmge3unXNAQIdKpnU%2Fec-upd-variable-server.png?alt=media)

6. Save the variable.

#### Step 2: Add the User-Provided Data variable to your GA4 event tag

1. Open your Google Tag Manager **web** container.
2. Go to **Tags** and open the relevant **GA4 Event** tag. This must be the event tag for the event name you trigger on in your GTM server container.
3. Add an extra **event parameter**.
4. Name this event parameter `user_data` and set its value to the **User-Provided Data** variable you created in the previous step.
5. Save the tag.

![user\_data event parameter in the GA4 event tag](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FZCUknQGKcN8Dp8aeI4Yj%2Fec-ga4-event-tag.png?alt=media)

***

### Validating Enhanced Conversions

Use the Google Ads audience manager to validate your setup.

![Validating Enhanced Conversions in Google Ads](https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FbUkNFOk8P1HmZS9UpXxY%2Fec-validation.png?alt=media)


# Pinterest Ads

In this guide, we’ll show you, step by step, how to set up tracking in your Google Tag Manager server container to send events to the Pinterest API.&#x20;

{% hint style="warning" %}
**This article covers a server-side only setup.** You can also run Pinterest Ads **client-side and server-side at the same time**, with event deduplication based on a shared event ID. We describe that setup in [Setting up client-side TikTok Ads tracking with deduplication](/integrations-marketingtools/tiktok-ads/setting-up-client-side-tiktok-ads-tracking-with-deduplication).
{% endhint %}

### Before you start

Make sure you have:

* [ ] A working GTM server container that receives events (through your Google Tag & GA4 client).
* [ ] Your **Pinterest Advertiser ID** and **API Access Token**. See [How to find your Pinterest Advertiser ID and Access Token](/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token).

### Step 1: Setting up the Pinterest parameter in the web container

Let's ensure that the needed epik-cookie for Pinterest attribution will be sent towards the server container with every GA4 event request.

{% hint style="warning" %}
If you don't load a Pinterest Tag on your website (no Pinterest Pixel/Tag), Pinterest won't automatically set the `_epik` cookie. If you'd rather not load this tag in the GTM web container, you can also create a Custom JavaScript variable that reads the epik value from the URL query.
{% endhint %}

1. Open your GTM web container and open your **Google Tag**.
2. Add a new parameter.
3. Name this parameter `epik_click_id`.
4. For the value, create a new variable using the lego block icon behind the input field.
5. As the variable configuration, choose **1st Party Cookie** and enter `_epik` as the **Cookie Name**.
6. Save the variable.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FhFNw6mjH7MHS0zIfbSwZ%2Fimage.png?alt=media&amp;token=e8d82a7b-b461-441e-8e21-08587f12f21e" alt=""><figcaption></figcaption></figure>

7. Save the Google Tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F9aFG9aT7WB7vHd52Xywn%2Fimage.png?alt=media&amp;token=43c3e72f-c5fa-493a-8210-57a73bb65480" alt=""><figcaption></figcaption></figure>

### Step 2: Setting up the Pinterest tag in the server container

Now that the Pinterest Click ID is being sent from the client-side container to the server container, we can configure the Pinterest Conversions API tag to forward the right GA4 events including the Click ID.

1. Make sure your Pinterest Advertiser ID and API Token are stored in two constant variables inside your GTM server container. Follow these steps to find your Advertiser ID and Token.
2. Open your GTM server container and go to **Templates**.
3. Under **Tag Templates**, search the gallery for the **Pinterest API for Conversions** tag template and add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fyvs1YbGf2scPd80RDh7V%2Fimage.png?alt=media&amp;token=199c0d10-565d-4257-adff-f92039e665bd" alt=""><figcaption></figcaption></figure>

4. In your GTM server container, go to **Tags** and create a new tag.
5. As the tag configuration, select the Pinterest tag template.
6. In the **Advertiser ID** field, enter your Advertiser ID variable. In the **API Access Token** field, enter your API Token variable.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FyRB6p1dACH2bCUPCpzf1%2Fimage.png?alt=media&amp;token=6cf9f19c-425e-4cda-a2ee-15216684e102" alt=""><figcaption></figcaption></figure>

7. As **Event Name**, choose **Inherit from client**. Use **Override from client** if you want to use different names than the standard GA4 event names.
8. Tick the **Override client data** option and expand **User Data**.
9. Add a new parameter here. Select **Click Id** as the parameter name. For the parameter value, add a new variable using the lego block button.
10. Create a new variable using the blue plus icon in the top right. As the variable configuration, choose **Event Data**. As the **Key Path**, enter `epik_click_id`.
11. Save this variable.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FWBzzZ0qUABRGNdhMzGGx%2Fimage.png?alt=media&amp;token=75910a84-557a-440a-94bf-f99a65a205c2" alt=""><figcaption></figcaption></figure>

7. If you want, you can override more User Data or Event Data here. For example, your visitor's email address via User Data, or the `event_id` of each event via Event Data.
8. Click **Triggering** below the tag configuration. Add a trigger that fires on every incoming GA4 event you want to send towards the Pinterest Conversion API.&#x20;
9. Save the tag.
10. Use the server container preview mode to test whether the Pinterest Conversions API tag fires on incoming events.


# Setting up client-side Pinterest Ads tracking with deduplication

Setting up client- and server-side tagging for Pinterest Ads with event\_id deduplication

Running both server-side and client-side tagging means Pinterest receives the same conversion twice: once from the browser and once from your server. Deduplication is what stops that from being counted twice. It works when both events carry the **same event name** and the **same event\_id**.&#x20;

So the goal throughout this guide is that your Pinterest Tag, your GA4 tag and your server-side Pinterest Conversions API tag all describe the same interaction with the same event ID.

### Before you start

Make sure you have:

* [ ] A working [server-side Pinterest Conversion API setup](/integrations-marketingtools/pinterest-ads).
* [ ] Your **Pinterest Tag ID**. See [How to find your Pinterest Tag ID](/integrations-marketingtools/pinterest-ads/where-to-find-the-pinterest-tag-id-advertiser-id-and-api-token).
* [ ] A **Unique Event ID** variable in your web container.

### Step 1: Create a variable for your Pixel ID

1. Open your GTM **web** container and go to **Variables**.
2. Create a new **User-Defined Variable** and choose **Constant** as the variable type.
3. Enter your Pinterest Tag ID as the value and save the variable.

{% hint style="info" %}
Using a constant variable rather than typing the ID into each tag means you only have one place to change it later.
{% endhint %}

### Step 2: Create your Pinterest Base Code tag

1. Go to **Tags** and create a new tag. Select the **Pinterest Tag** as the tag configuration.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FBscPWVXahmDqtt2sRWCz%2Fimage.png?alt=media&amp;token=a01cad30-f1d7-4f15-a3be-02886cea503a" alt=""><figcaption></figcaption></figure>

2. In the **Tag ID** field, select your Tag ID variable.
3. As the **Event to Fire** select **Base Code Only (no event)**.&#x20;
4. Give this tag the trigger you use for all pages (Page View / cookie\_consent\_update)

### Step 3: Create the conversion tags

1. Create a new tag, select the **Pinterest Tag** as tag configuration.
2. Fill in the **Pinterest Tag ID** variable.
3. As the **Event to Fire** indicate whether this is a standard or a custom event. Select a standard event from the dropdown menu, or type a custom event name into the input field.
4. Select **Custom Parameters** under **Additional Parameters**. Add **event\_id** as parameter name and your Unique Event ID variable as the value.
5. As the trigger, select the same trigger you use for the GA4 event tag covering this interaction.
6. Save the tag. And repeat for the other events and conversions you want to set up.

{% hint style="warning" %}
Don't forget to set up the page\_view tag, and use the same trigger as your GA4 page\_view event tag.
{% endhint %}

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fe7gZuiCmIuEVNFfgHM2v%2Fimage.png?alt=media&amp;token=c83633e0-a9bb-4b6a-882d-93d7d641a05d" alt=""><figcaption></figcaption></figure>

### Step 4: Add the event\_id to your GA4 events

Your GA4 event tags are what feed the server container, so the event ID has to travel with them. For every interaction you want to deduplicate, add your **Unique Event ID** variable as an event\_id event parameter on the GA4 event tag that fires on that interaction.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F0BpvIPXyTvkYHyJ7C8QB%2Fimage.png?alt=media&amp;token=3347dd2c-d02c-42e2-b5cd-a0c12191dc2e" alt=""><figcaption></figcaption></figure>

### Step 5: Test and Verify

Open Google Tag Manager's preview mode to check whether the event\_id in the client-side TikTok Event tag matches the server-side TikTok Events API tag. If this is not the case, the usual causes are:

* The event names do not match. The Pixel sends one name and the server-side tag sends another.
* The event IDs do not match, or the server-side tag receives no event ID at all.
* The two tags fire on different triggers, so they never describe the same interaction.


# Where to find the Pinterest Tag ID, Advertiser ID and API Token

How to retrieve the Pinterest Tag ID, Advertiser ID and API Token

Pinterest works with different identifiers for client-side tagging and for server-side tracking. The Tag ID is used for the Pinterest tag in the browser. The Advertiser ID and the API token are used for the Conversions API.

### Pinterest Tag ID

Go towards your Pinterest Ads Conversions: <https://ads.pinterest.com/conversion_tags/>

Underneath Tag Management you'll be able to find the ID of your Pinterest Tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FYiaLV7g6de04MQZCJfI6%2Fimage.png?alt=media&amp;token=f443cd2c-009f-4203-af58-fd11585b633e" alt=""><figcaption></figcaption></figure>

### Pinterest Advertiser ID

Go towards your Pinterest Business Account: <https://www.pinterest.com/business/login>

In the **Dashboard** you are able to find all the Ad Accounts you have access to in the **Business Overview**. The ID underneath the Ad Account name is the Advertiser ID.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FmaOSaoOz6mHVeWOlisJI%2Fimage.png?alt=media&amp;token=46ace7c5-16f2-4447-a79b-3ff198fc4074" alt=""><figcaption></figcaption></figure>

### Pinterest API Token

Go towards your Pinterest Ads Conversions: <https://ads.pinterest.com/conversion_tags/>

Select the **Set up API** option in the menu. Here you can generate a new token.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FMbIDppjNzEkqesE9kcRt%2Fimage.png?alt=media&amp;token=de03e6e0-96c2-469a-b3e0-c6647e609dc7" alt=""><figcaption></figcaption></figure>


# LinkedIn Ads

How to set up tracking for LinkedIn Ads through the LinkedIn Conversions API

The LinkedIn Conversions API sends event data straight from your server to LinkedIn instead of from the visitor's browser. That means less data lost to browser restrictions, adblockers and privacy settings, and a more accurate picture of what your LinkedIn Ads are actually delivering. It supports the events that matter most: page views, purchases and form submissions.

{% hint style="warning" %}
**This article covers a server-side only setup**, with the exception of a LinkedIn Insight Tag on the GTM web container to ensure the `li_fat_id` cookie gets set.
{% endhint %}

### How the setup fits together

There are four parts to this setup, and the order matters because each one produces something the next needs:

1. **In LinkedIn Campaign Manager**, create a conversion and generate an access token.
2. **In your GTM web container**, capture the `li_fat_id` cookie and pass it along with your GA4 events.
3. **In your GTM server container**, add the LinkedIn template and read `li_fat_id` back out of the incoming event data.
4. **Still in the server container**, build a page view tag and one conversion tag per action you want to measure.

***

{% stepper %}
{% step %}

### 1. Create the conversion in LinkedIn Campaign Manager

You need two values from LinkedIn: a **conversion rule ID** and an **access token**.&#x20;

Let's start by creating a new conversion.

1. Log in to the correct account in the LinkedIn Campaign Manager.
2. In the left menu, go to **Measure → Conversion tracking**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2F2Ku70aPN9Sf8u7m95mK5%2Fimage.png?alt=media&amp;token=f0b0165b-c9cf-4903-8530-8aeb97188ef3" alt=""><figcaption></figcaption></figure>

3. Click **Create conversion → Conversions API**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FgIBLPJGDAg7fAotssEEB%2Fimage.png?alt=media&amp;token=07dfc301-4c05-4a2a-8870-ba0549c2911c" alt=""><figcaption></figcaption></figure>

4. Fill in the settings:

* **Name** — something you'll recognise later, such as *Purchase* or *Lead*
* **Category** — pick the category that matches the action
* **Value** — optional

5. Continue to the next step and select **Direct API** as the data source.
6. Continue again and create the conversion.
7. Reopen the conversion you just created and look at the browser address bar. The conversion rule ID is the number in the URL after `/conversions/`.&#x20;

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FC2uHA0jO4Fi3vRph1m1K%2Fimage.png?alt=media&amp;token=a18d26bb-e7d6-46fe-81c8-da789fa6bc91" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Generate the API Token

1. In Campaign Manager, go to **Signals manager** under **Data**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fg7l2CoCGX6FcN1NBGymY%2Fimage.png?alt=media&amp;token=e0250054-4925-48e1-a4e5-1cba480f8b80" alt=""><figcaption></figcaption></figure>

2. Open the **Direct API** source.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FnSDD9KXBg4JWAvAMzvGm%2Fimage.png?alt=media&amp;token=2782fcd1-e0dc-47bd-aeb6-64420f6eb420" alt=""><figcaption></figcaption></figure>

3. Click **Generate access token**.
4. Copy the token.
5. Store this API token in a **constant variable** in your GTM server container.
   {% endstep %}

{% step %}

### Capture li\_fat\_id in the web container

`li_fat_id` is LinkedIn's first-party ad tracking ID. It's written as a cookie when someone clicks a LinkedIn ad, and it's what allows LinkedIn to connect a server-side conversion back to that click.

{% hint style="warning" %}
This cookie is not created by the Conversions API itself, it has to be set client-side on your own domain first. The easiest way to set it is to install the **LinkedIn Insight Tag** in your GTM web container. When a visitor arrives from a LinkedIn ad, the Insight Tag reads the `li_fat_id` URL parameter and stores it as a first-party cookie, which your tracking setup can then read and send along with each conversion event.
{% endhint %}

1. Open your GTM **web** container and go to **Variables**.
2. Under **User-Defined Variables**, create a new variable.
3. Choose **1st-Party Cookie** as the variable type.
4. Enter `li_fat_id` as the cookie name.
5. Name the variable `Cookie - li_fat_id` and save.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FHaSj7UAijMPk3CYyzElo%2Fimage.png?alt=media&amp;token=82a22be4-192c-459b-a92f-d9483a728e17" alt=""><figcaption></figcaption></figure>

6. Open your **Google Tag** on the GTM web container.
7. Expand **Configuration parameters**, add a parameter with the name `li_fat_id` and the value `{{Cookie - li_fat_id}}`.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fsj5cjHr0mzMPlswkaQEl%2Fimage.png?alt=media&amp;token=704d54e6-6e64-4684-874d-bc8a7abb0098" alt=""><figcaption></figcaption></figure>

8. Save the Google Tag.
9. Open the GTM **server** container.
10. Create a new **Event Data** variable in your server container with `li_fat_id` as the key.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Fk2v7XK94gIk0jqRlAnIn%2Fimage.png?alt=media&amp;token=8214ccdd-36e0-453c-93e2-78a24e3a249a" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Add the LinkedIn template to the server container

1. Open your GTM **server** container and click **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Search for **LinkedIn Conversion API**, select it, and add it to your workspace.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FSGCaZBhZCXI4RpC7jite%2Fimage.png?alt=media&amp;token=823c3cfb-a37d-4545-b2b4-909b2a3319e1" alt=""><figcaption></figcaption></figure>

The LinkedIn integration expects a page view tag alongside your conversions, so set this one up before the conversion tags.

4. Create a new tag in your server container.
5. Choose **LinkedIn Conversion API** as the tag configuration.
6. Set **Event Type** to **Page View**.
7. Attach the **All Pages** trigger and save.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FVYBhANjUUzEpX02Dvsfe%2Fimage.png?alt=media&amp;token=000d0bae-683e-4473-bee2-c3ee6f9a3705" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Set up conversion tags

1. Create a new tag and choose **LinkedIn Conversion API** as the tag configuration.
2. Configure it:
   * **Event Type** — Conversion
   * **Access Token** — your constant variable holding the API token
   * **Conversion Rule ID** — the ID from the URL in step 1
3. For **User IDs**, add an override:
   * Key: `LINKEDIN_FIRST_PARTY_ADS_TRACKING_UUID`
   * Value: your `li_fat_id` Event Data variable
4. Attach a trigger that fires when the relevant GA4 event reaches your server container. For example:
   * Purchase conversion → `event_name` equals `purchase`
   * Lead conversion → `event_name` equals `generate_lead`
5. Save the tag.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FsbRSKA0DZmyLwl0BsQRf%2Fimage.png?alt=media&amp;token=c35649f2-92a6-4a75-8c81-3bad21e6c1b8" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Test the tags

Run the server container in preview mode and trigger the event on your site. Three things to confirm:

* The LinkedIn conversion tag **fires** on the right event, and only on that event.
* `{ED - li_fat_id}}` **resolves to a value** rather than `undefined`. If it's empty, arrive at your site through an actual LinkedIn ad click first, the cookie won't exist otherwise, and a missing cookie looks identical to a broken variable.
* The outgoing request returns a **success response**. An authentication error here almost always means the token or the conversion rule ID went in wrong.
  {% endstep %}
  {% endstepper %}

{% hint style="info" %}
Conversions won't appear in Campaign Manager instantly, so don't treat an empty report in the first few minutes as a failure.
{% endhint %}


# Where to find the LinkedIn Partner ID, Conversion IDs and API Token

How to retreive the LinkedIn Partner ID and set up new conversions to find the Conversion IDs and API Token

LinkedIn works with three values. The Partner ID identifies your ad account and is used by the client-side Insight Tag. A Conversion ID identifies one specific conversion, so you need one for every conversion you want to measure. The API token authorises server-side events through the Conversions API.&#x20;

### **Where to find the Partner ID**

Log in to your [LinkedIn Campaign Manager](https://www.linkedin.com/campaignmanager).

Go to op "Analyseren" in het linker menu en selecteer vervolgens "Insight Tag".

### **Where to find the Conversion IDs**

### **Where to find the API token**


# OpenAI Ads

Configure the OpenAI Pixel and Conversions API with event ID deduplication.

Set up the OpenAI Pixel in the web container first. Then send matching events through the OpenAI Conversions API.

Both tags send the same conversion. Give both tags the same event name and event ID. OpenAI can then deduplicate the events and count one conversion.

This hybrid setup captures browser and server events. It also reduces losses from ad blockers and browser cookie restrictions.

### What you'll configure

You will create:

* An OpenAI Pixel tag in the GTM web container.
* An OpenAI Conversions API tag in the GTM server container.
* One shared `event_id` for each matching browser and server event.

Use this page for the complete implementation. See [OpenAI credentials](/integrations-marketingtools/openai-ads/where-to-find-the-openai-pixel-id-and-api-key), [event ID deduplication](/integrations-marketingtools/openai-ads/chatgpt-ads-event-id-deduplication), and [campaign URL tracking](/integrations-marketingtools/openai-ads/utm-parameters-and-dynamic-tracking-for-chatgpt-ads).

### Before you start

Make sure you have:

* [ ] A GTM web container with GA4 event tags.
* [ ] A GTM server container that receives the GA4 events.
* [ ] The **OpenAI Pixel ID** and **API Key** from OpenAI Ads Manager. See [Where to find the OpenAI Pixel ID and API Key](/integrations-marketingtools/openai-ads/where-to-find-the-openai-pixel-id-and-api-key).
* [ ] A **Unique Event ID** variable in the web container.

{% hint style="info" %}
Confirm that the client's OpenAI Ads Manager account is active. It provides the Pixel ID, conversion configuration, and API key.
{% endhint %}

### Part 1: Set up client-side tracking

#### Step 1: Add the OpenAI Pixel template

1. Open your GTM web container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Search for the **OpenAI Pixel** tag template and add it.

#### Step 2: Create a Pixel ID variable

1. Go to **Variables** and create a **Constant** variable.
2. Set its value to the OpenAI Pixel ID.
3. Save it as your Pixel ID variable.

#### Step 3: Create client-side event tags

1. Create a new **OpenAI Pixel** tag.
2. Select your Pixel ID variable.
3. Choose **Inherit from DataLayer** to reuse the GA4 event name.
4. Choose **Override** only when OpenAI requires a different event name.
5. Keep **Automatic Event Parameters** mapping enabled.
6. Under **Server-Side Tracking Settings**, set **Event ID** to your Unique Event ID variable.
7. Use the same trigger as the matching GA4 event tag.

Repeat this for every event you want to track. Include `page_view` with the same trigger as the GA4 page view tag.

#### Step 4: Pass the event ID to GA4

Add the same Unique Event ID variable to every matching GA4 event tag:

1. Open the GA4 event tag.
2. Add an event parameter named `event_id`.
3. Set its value to the Unique Event ID variable.
4. Save the tag.

The server container can now read the event ID from the GA4 event.

### Part 2: Set up server-side tracking

#### Step 5: Add the Conversions API template

1. Open your GTM server container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Add the **OpenAI Conversions API** tag template.

#### Step 6: Create the server-side tag

1. Create a new **OpenAI Conversions API** tag.
2. Under **Event Name Setup Method**, choose **Inherit from client**.
3. Choose **Override** only when the Pixel tag uses the same override.
4. Choose the correct **Action Source**, such as **Website**.
5. Enter the OpenAI Pixel ID and API key.
6. Keep **Automatic Event Parameters** mapping enabled.

#### Step 7: Pass the event ID to OpenAI

1. Create a server-container variable that reads the incoming `event_id` event parameter.
2. Open the OpenAI Conversions API tag.
3. Under **Server Event Data Parameters**, add **Event ID**.
4. Set its value to the server-side event ID variable.

#### Step 8: Configure consent and the trigger

Enable **Consent Granted / GTM Consent Mode support**. Map it to marketing consent.

Create a trigger for the events you want to send. Use both conditions:

* `{{Event Name}}` matches RegEx `purchase|order_completed`.
* `{{Client Name}}` equals `GA4`.

Leave **Set Click ID cookie** enabled unless the client requires otherwise. It stores OpenAI's click ID in the first-party `__oppref` cookie.

{% hint style="warning" %}
The Pixel and Conversions API tags must use the same event name and event ID. Different values prevent deduplication.
{% endhint %}

### Test and validate the complete setup in preview mode

Before you publish, confirm that the OpenAI cookies reach the server container and that the Conversions API tag forwards the click ID (`oppref`) and the browser reference (`obref`) to OpenAI.

The Pixel stores both values in first-party cookies (`__oppref` and `__obref`). The Conversions API does not capture them for you. The tag must find the click ID in the URL, the cookie, or the event data, and send it as `oppref`. The browser reference goes in `user.obref`, unchanged.

**Prepare the test**

1. Open a clean incognito window. Connect GTM preview mode for both the web container and the server container.
2. Work in a separate workspace. If the tag offers **Validate Only**, enable it for the test, so test events are excluded from measurement. Switch it off again before you publish.
3. Open a landing page with a test click ID, for example `https://yourdomain.com/?oppref=test123`. You can also click a test campaign

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2Ff2X1aEKRdrfC40xHRL4o%2Fimage.png?alt=media&#x26;token=2659006c-e9c3-4ea4-8376-3b0b8ea3156b" alt=""><figcaption></figcaption></figure>

**Where to look in server preview**

| Location                        | What to check                                                                                                                                                                              |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Incoming request (client)       | The `cookie` header contains `__oppref` and `__obref`. If they are missing, the tag cannot read them. The server container is probably not running on a first-party domain of the website. |
| Event Data                      | `page_location` contains the `oppref` parameter. The consent state shows `ad_storage` granted.                                                                                             |
| OpenAI tag → Request            | The URL is `https://bzr.openai.com/v1/events?pid=<PIXEL-ID>`. The body contains `oppref`, `user.obref`, `id` and `source_url`.                                                             |
| Browser → Application → Cookies | `__oppref` exists with the expected domain and expiry. The server container sets it in the `Set-Cookie` header of its response.                                                            |

**Run the test scenarios**

| # | Scenario                                                         | Expected result                                                                                     |
| - | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| 1 | Landing page with `oppref` in the URL, marketing consent granted | The first event contains `oppref`, equal to the URL value. The `__oppref` cookie is set.            |
| 2 | Second page view without `oppref` in the URL                     | `oppref` comes from the cookie and has the same value.                                              |
| 3 | Second ad click with a different `oppref`                        | The new value is sent and the cookie is overwritten.                                                |
| 4 | Direct visit without `oppref`                                    | `oppref` is omitted from the body. It is not an empty string.                                       |
| 5 | Marketing consent denied                                         | No request goes to OpenAI and no cookies are set. Revoking consent removes the cookies.             |
| 6 | Consent given after the landing page loaded                      | The OpenAI tag fires after the consent update and still contains `oppref` from the URL.             |
| 7 | `user.obref`                                                     | Equals the value of the `__obref` cookie and is not hashed.                                         |
| 8 | Pixel and Conversions API together                               | Both send the same event ID, so only one conversion counts.                                         |
| 9 | Purchase sent from a shop webhook                                | No browser cookies are available. Store the click ID with the order and set it manually in the tag. |

**Apply the findings to the template**

1. Update the **OpenAI Conversions API** template to the latest version from the gallery. Check that the user fields in the request body match the OpenAI specification, for example `emails_sha256`, `cities`, `postal_codes` and `countries` as lists.
2. If `oppref` is missing on the first event although `page_location` contains it, set the **Click ID** manually under **Server Event Data Parameters**. Use a variable that reads `oppref` from `page_location` first, then from the `__oppref` cookie, then from the event data. Manual values take precedence over automapped ones, so make sure the variable falls back correctly. Test in preview what happens when the variable is empty.
3. Keep **Set Click ID cookie** enabled. Leave **HTTP Only** on its default (off), so browser scripts can still read the cookie. Choose an expiry that matches OpenAI's cookie lifetime of 30 to 90 days.
4. Fire the OpenAI Pixel `page_view` tag after the consent update. The landing URL contains `oppref` on the first page only. If the tag fires before consent is known, the click ID is lost.
5. Use the same Unique Event ID in both tags. Disable **Autogenerate an Event ID** in the server tag when the Pixel also sends events.

**Check the result after publishing**

In the outgoing request logs, confirm that:

* Landing pages with `oppref` in the URL carry `oppref` in the request body.
* Follow-up page views carry the same value.
* No requests contain `"validate_only": true`.
* The number of non-2xx responses does not increase.

{% hint style="warning" %}
Only send the click ID, hashed emails and cookie values for visitors who granted marketing consent. Test values such as `test123` reach OpenAI as real events unless **Validate Only** is enabled.
{% endhint %}


# Where to find the OpenAI Pixel ID and API Key

How to retrieve the OpenAI Pixel ID and API Key via OpenAI Ads Manager

To set up tracking for OpenAI Ads you'll need two values: the **Pixel ID** for the browser and server tags, and an **API Key** for server-side tags. Both values can be found in the OpenAI Ads Manager account.

{% hint style="info" %}
Access to OpenAI Ads Manager is still limited while the platform is in early rollout. If the client doesn't have these yet, they'll need to request Conversions API access from their OpenAI account team before you can implement this tracking.
{% endhint %}

### Finding the OpenAI Pixel ID

{% stepper %}
{% step %}

#### Open the OpenAI Ads Manager

Open your [OpenAI Ads Manager](https://ads.openai.com/manage/campaigns).
{% endstep %}

{% step %}

#### Go to Conversions

Navigate towards **Conversions** and find (or create) your Pixel in the **Data Source** section

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FimycuCcOQ3z3Ho9C5LhM%2Fimage.png?alt=media&amp;token=d9c8b9b1-38d2-4b6a-96ec-b356795bc0bd" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Copy the Pixel ID

If you already have a Pixel you can copy the ID underneath the Pixel name.

If you don't have a Pixel yet, you can create a new Data Source in the top right with the use of the **+ Create** button.
{% endstep %}
{% endstepper %}

### Finding the API Key

{% stepper %}
{% step %}

#### Open the OpenAI Ads Manager

Open your [OpenAI Ads Manager](https://ads.openai.com/manage/campaigns).
{% endstep %}

{% step %}

#### Go to Conversions

Navigate towards **Conversions** where you can find your pixel Data Source.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FjhuHs5sAgVseFqn2tib5%2Fimage.png?alt=media&amp;token=326f3478-400c-4f2c-a380-b36cb245708b" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Create an API Key

In the top right click on the key-icon to create a new key.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FGjavhabvTV9wNSvKo5yb%2Fimage.png?alt=media&amp;token=46b6ad74-247f-48ac-bebb-9a80eb94fb88" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}


# ChatGPT Ads event ID deduplication

Verify and troubleshoot event ID deduplication for ChatGPT Ads

Use the [main ChatGPT Ads setup guide](/integrations-marketingtools/openai-ads) to configure the Pixel and Conversions API. This page helps you verify and troubleshoot their shared event ID.

Running both server-side and client-side tagging means OpenAI receives the same conversion twice: once from the browser and once from your server. Deduplication stops OpenAI from counting it twice. It works when both events carry the **same event name** and the **same event ID**.

### What must match

For each interaction, pass one ID through this path:

1. The browser OpenAI Pixel sends the event with the Unique Event ID.
2. The matching GA4 event sends that value as `event_id`.
3. The server-side Conversions API tag reads `event_id` and sends it as Event ID.

The browser and server tags must also send the same event name. For example, both tags send `purchase`.

{% hint style="info" %}
The event ID must identify one occurrence of an event. Do not reuse a fixed value for every purchase or lead.
{% endhint %}

### Verify the event ID

Use GTM preview mode in both containers. Trigger one test conversion and compare these values:

1. In the web container, open the OpenAI Pixel tag and record its Event ID.
2. Open the matching GA4 event and confirm its `event_id` parameter has the same value.
3. In the server container, open the OpenAI Conversions API tag and confirm its Event ID matches.

The tags must describe the same interaction. They must fire from the same user action, such as a completed purchase.

### Fix common problems

| Symptom                          | Cause                                         | Fix                                                                                                    |
| -------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| OpenAI counts two conversions    | Event IDs differ, or one tag has no ID        | Pass the Unique Event ID to GA4 as `event_id`, then map it in the server tag.                          |
| The server event has no Event ID | The server variable cannot read `event_id`    | Inspect the incoming GA4 request. Match the variable key exactly.                                      |
| Events are not deduplicated      | Event names differ                            | Use the same inherited name or override in both OpenAI tags.                                           |
| Only one tag fires               | The tag triggers cover different interactions | Use matching triggers for the Pixel and GA4 event. Restrict the server trigger to that incoming event. |

### Confirm in Ads Manager

After preview validation, ask the client to confirm the test conversion in OpenAI Ads Manager. Check that the conversion arrived and is not counted twice.


# UTM parameters & dynamic tracking for ChatGPT Ads

How to structure UTM parameters and OpenAI's dynamic ad tokens for ChatGPT Ads attribution

The [main ChatGPT Ads guide](/integrations-marketingtools/openai-ads) covers browser and server conversion tracking. This page covers campaign-click attribution: sending clean, joinable URL data into GA4, the client's CRM, and their data warehouse.

{% hint style="warning" %}
**This is beta, account-gated behaviour.** OpenAI's public Help Center still states that dynamic macros in landing URLs are unsupported. Some Ads Manager accounts nonetheless expose a "Landing page query parameters" field with dynamic tokens described below. Always confirm in the specific client's account whether this field is visible before building on it, and keep a static-UTM fallback ready in case it isn't (or stops resolving).
{% endhint %}

### The two-layer model

Don't put OpenAI's object IDs into `utm_source` or `utm_medium` — that fragments GA4's channel grouping into one row per campaign. Instead, use two separate layers:

* **Marketing taxonomy** (`utm_source`, `utm_medium`, `utm_campaign`, ...) — stable, human-readable values you set once per campaign. This is what GA4 channel reporting groups on.
* **Technical join keys** (`oai_*` parameters, built from OpenAI's dynamic tokens) — the platform's own object IDs, used to join spend/click data back to sessions, leads and orders in the CRM or warehouse. Names are editable in Ads Manager after launch, IDs are not, so use IDs as the historical join key wherever possible.

### OpenAI's dynamic tokens

When the "Landing page query parameters" field is available for a campaign, these four tokens can be added to it and are resolved into the destination URL at click time:

| Token             | Represents                   | Example value | Recommended target parameter           |
| ----------------- | ---------------------------- | ------------- | -------------------------------------- |
| `{campaign_id}`   | Top-level campaign object    | `cmpn_101`    | `utm_id` (and/or `oai_campaign_id`)    |
| `{ad_group_id}`   | Ad group within the campaign | `adgrp_301`   | `oai_ad_group_id` — **not** `utm_term` |
| `{ad_id}`         | Individual ad                | `ad_501`      | `utm_content` (and/or `oai_ad_id`)     |
| `{ad_account_id}` | OpenAI Ads account           | `adacct_123`  | `oai_account_id`                       |

{% hint style="info" %}
There is no `{product_id}` token for product-feed campaigns. Add the SKU or item ID as a static parameter on each product's landing URL instead, and confirm during QA that it survives when the same URL is reused across products.
{% endhint %}

### Recommended parameter string

For a standard campaign where the query-parameter field is available, append this to the landing page query template in Ads Manager:

```
utm_source=chatgpt&utm_medium=paid_ai&utm_campaign=<static-campaign-slug>&utm_id={campaign_id}&utm_content={ad_id}&utm_source_platform=openai_ads&oai_account_id={ad_account_id}&oai_campaign_id={campaign_id}&oai_ad_group_id={ad_group_id}&oai_ad_id={ad_id}
```

Which, once OpenAI resolves the tokens on an eligible click, arrives on the landing page as something like:

```
https://www.client-site.com/landing?utm_source=chatgpt&utm_medium=paid_ai&utm_campaign=q3-demo-push-emea&utm_id=cmpn_101&utm_content=ad_501&utm_source_platform=openai_ads&oai_account_id=adacct_123&oai_campaign_id=cmpn_101&oai_ad_group_id=adgrp_301&oai_ad_id=ad_501&oppref=gAAAAAb123
```

Keep `utm_source`, `utm_medium`, `utm_campaign` and `utm_source_platform` **static** — type them out per campaign, don't template them. Only the object IDs go through the dynamic tokens; they're tedious to type correctly by hand and that's exactly where a join key needs to be exact.

{% hint style="info" %}
Use one lowercase naming convention throughout (`chatgpt`, not `ChatGPT` or `Chatgpt`). Mixed casing is the most common cause of a campaign showing up as multiple rows in GA4's channel report.
{% endhint %}

### `oppref`: leave it alone

You'll see an `oppref` parameter appended automatically to eligible landing URLs, on top of any configured UTMs. This is OpenAI's click reference for Conversions API attribution. It is unrelated to UTMs and matches the click ID stored in the first-party `__oppref` cookie. Never manually set, overwrite, or strip `oppref` in a redirect. Doing so breaks OpenAI-side attribution.

### Support varies by how the campaign is built

| Campaign type                                | Confidence the dynamic tokens resolve                                                    | What to do                                                                                                                                                   |
| -------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Standard Ads Manager campaign (CPM/CPC/oCPC) | Medium — works when the "Landing page query parameters" field is visible in that account | Use the dynamic tokens; verify with a controlled test click                                                                                                  |
| Product-feed campaigns                       | Low — no product token exists                                                            | Add SKU/item ID statically per product URL                                                                                                                   |
| Bulk CSV creation                            | Low — no documented query-template column                                                | Use fully static UTMs in the landing URL, or set the query-parameter field manually after upload                                                             |
| Public Advertiser API                        | Low — schema has no landing-query-suffix field                                           | Build static query strings from the object IDs already in the API response                                                                                   |
| MMP links (AppsFlyer, Adjust, ...)           | Depends on the MMP                                                                       | Never replace an MMP link with a plain URL — only use that partner's supported custom parameters, and confirm the resolved values survive the redirect chain |

### Capturing the parameters in GTM and GA4

On the client's web container:

1. Make sure the GA4 configuration tag (or your GA4 event tags) picks up `utm_id`, `utm_content` and the other standard UTMs the way it already does for other paid channels — no extra work needed there.
2. For the `oai_*` parameters, they won't populate GA4's built-in traffic-source dimensions automatically. Read them from the URL with a Data Layer or URL variable, send them as an event parameter on your key events, and register matching GA4 custom dimensions if the client wants to report on them (e.g. for creative-level analysis by `oai_ad_id`).
3. If the client has lead forms, parse the landing URL on first page load and write the values into hidden form fields so they land in the CRM: original source/medium, the static campaign slug, `oai_campaign_id`/`utm_id`, `oai_ad_group_id`, `oai_ad_id`/`utm_content`, `oai_account_id`, `oppref`, and the full raw landing URL plus a timestamp (useful for forensic QA later).

{% hint style="warning" %}
Don't put personal data (email, phone, name) into query strings for this or any capture step — it ends up in browser history, server logs and third-party tools.
{% endhint %}

For GA4 channel reporting, set up a custom channel group once per client:

```
Custom channel: Paid AI
Source exactly matches: chatgpt
AND
Medium exactly matches: paid_ai
```

### Troubleshooting

| Symptom                                                      | Likely cause                                                                                                             | Fix                                                                                                                                       |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Landing URL contains the literal text `{campaign_id}`        | This account/campaign type doesn't support token resolution                                                              | Confirm the token picker is available in that exact account; fall back to static values                                                   |
| Only the static UTMs show up, the `oai_*`/dynamic ones don't | Field wasn't saved, or the campaign type doesn't support it                                                              | Re-check the saved field value; test with a fresh eligible click                                                                          |
| Duplicate query keys in the final URL                        | The same key is set both in the ad's destination URL and in the campaign's query-parameter field                         | Give each parameter a single owner — either the ad URL or the campaign suffix, never both                                                 |
| One ChatGPT Ads campaign shows as several rows in GA4        | Inconsistent casing or a campaign-name change (mutable) used as the join key                                             | Normalize source/medium casing; use a stable static slug instead of the live campaign name                                                |
| Ads Manager clicks noticeably exceed GA4 sessions            | Expected gap — page-load failures, consent, redirects, ad blockers and attribution windows all differ from a GA4 session | Compare like-for-like dates/timezones before treating it as a tracking bug                                                                |
| OpenAI-side conversions are missing despite GA4 showing them | `oppref` was stripped somewhere, or the Pixel/Conversions API event IDs don't match                                      | Confirm `oppref` survives every redirect; check that client-side and server-side events share the same event ID (see deduplication guide) |

### QA checklist before launch

* [ ] "Landing page query parameters" field confirmed visible in this exact client account and campaign editor
* [ ] Token values copied from OpenAI's UI, not retyped by hand
* [ ] No leading `?` in the campaign query field
* [ ] One lowercase naming convention used throughout
* [ ] Each parameter is owned by exactly one layer (ad URL **or** campaign suffix, not both)
* [ ] Tested against a destination URL with no existing query string
* [ ] Tested against a destination URL that already has unrelated query parameters
* [ ] Tested against a destination URL with a fragment (e.g. `#pricing`)
* [ ] Followed every redirect and checked the final browser URL — no literal `{...}` braces left anywhere
* [ ] `oppref` present on an eligible test click and confirmed to survive redirects
* [ ] Source, medium, campaign, `utm_id` and `utm_content` verified in GA4 DebugView or Realtime
* [ ] `oai_*` values confirmed to reach the website/CRM/server logs on a test lead or purchase
* [ ] Repeat the test after any campaign edit, URL change, bulk update, feed refresh or MMP-link change — this is a beta feature and can change without notice


# Tracking cookies and consent

Learn which cookies and browser storage identifiers the ChatGPT Ads Measurement Pixel uses, including consent requirements.

When integrating or documenting the ChatGPT Ads Measurement Pixel (`oaiq`) on an e-commerce website, cookies are stored in the user's browser across two distinct domain levels: First-party cookies (set directly on your domain) and Third-party / Cross-site cookies (set on OpenAI's domain).

#### 1. First-Party Cookies (Set on Your Domain)

These cookies are set directly on your domain (e.g., `yourdomain.com`) by the ChatGPT Ads Measurement Pixel JS SDK (`bzrcdn.openai.com`). They are used to retain click-attribution parameters as the visitor navigates through your site.

<table data-header-hidden><thead><tr><th width="98.7777099609375"></th><th width="121.6666259765625"></th><th width="124.22216796875"></th><th width="106.5555419921875"></th><th></th></tr></thead><tbody><tr><td><strong>Cookie Name</strong></td><td><strong>Scope / Domain</strong></td><td><strong>Type</strong></td><td><strong>Expiration</strong></td><td><strong>Purpose &#x26; Description</strong></td></tr><tr><td><code>__oppref</code></td><td><code>.yourdomain.com</code></td><td>Marketing / Attribution</td><td>30 to 90 days</td><td>Stores the OpenAI Partner/Placement Reference <strong>click identifier</strong> (<code>oppref</code>) extracted from the landing page URL. Ensures conversion attribution persists if the user buys later in the same or a subsequent session.</td></tr><tr><td><code>__obref</code></td><td><code>.yourdomain.com</code></td><td>Marketing / Analytics</td><td>90 days</td><td>Stores the OpenAI Link/Listing Reference (<code>obref</code>). It tracks <strong>context-specific ad placement details</strong> (e.g., specific ChatGPT prompt sessions or feed placements).</td></tr></tbody></table>

#### 2. Third-Party / Cross-Site Cookies (Set on OpenAI Domains)

These cookies are set under OpenAI's infrastructure domain (e.g., `.openai.com` / `bzr.openai.com`) when the pixel fires cross-site network requests.

<table data-header-hidden><thead><tr><th width="92.111083984375"></th><th width="133.77783203125"></th><th width="119.22216796875"></th><th width="106"></th><th></th></tr></thead><tbody><tr><td><strong>Cookie Name</strong></td><td><strong>Scope / Domain</strong></td><td><strong>Type</strong></td><td><strong>Expiration</strong></td><td><strong>Purpose &#x26; Description</strong></td></tr><tr><td><code>__obi</code></td><td><code>.openai.com</code></td><td>Marketing / Analytics</td><td>1 Year (365 days)</td><td>OpenAI Browser Identifier. Set with <code>SameSite=None; Secure</code>. Binds off-site conversions on your store to the user's logged-in ChatGPT account or device session.</td></tr></tbody></table>

#### 3. Local Storage Identifiers (Browser Storage)

In addition to traditional cookies, the `oaiq` SDK uses the browser's `localStorage` to preserve state in case cookies are cleared or restricted by privacy features (like Apple's ITP):

* `_oaiq_consent`: Stores the user's current consent decision (`true` or `false`) so the pixel knows whether to collect and transmit measurement events.
* `_oaiq_config`: Temporarily caches the advertiser's Pixel ID configuration to reduce network round-trips during page navigation.

#### Compliance Note for Privacy Documentation (GDPR / ePrivacy)

If you are updating your website's Cookie Banner / CMP (Consent Management Platform) or Privacy Policy:

1. Category: Categorize `__oppref`, `__obref`, and `__obi` under Marketing / Targeting (or Advertising) in your Cookie Banner.
2. Consent Blocking: Ensure the script `oaiq("consent", false)` is explicitly set before initializing the pixel, or gate the script execution entirely until the user grants marketing consent. The pixel defaults to tracking (`consent = true`) unless explicitly blocked.

## Consent and ChatGPT Ads conversions

In the EU, ChatGPT Ads measurement only runs for visitors who accept marketing cookies. Visitors who decline can still buy, but the purchase is usually not linked to the ad click. Ads Manager therefore reports fewer conversions than your shop recorded from ChatGPT traffic.

This page explains what happens, how large the effect can realistically be, and what consent does not explain.

### What happens when a visitor declines

* The OpenAI Pixel sends no measurement events while consent is `false`. Blocked events are not replayed when consent is granted later.
* The `__oppref` (click ID) and `__obref` cookies are only used when measurement consent is granted. Setting consent to `false` removes both.
* The Conversions API does not capture `oppref` itself. It only forwards the value the browser stored. If the server tag is mapped to marketing consent (see step 8 of the setup guide), it does not fire without consent either.
* Result: the order exists in your shop, but OpenAI cannot link it to an ad click.

{% hint style="warning" %}
The OpenAI Pixel starts with consent set to `true`. It only waits for consent if you set `oaiq("consent", false)` before `init`, or block the script until the visitor opts in. If your CMP is not connected to the pixel, the pixel runs for everyone. Check this in GTM preview.
{% endhint %}

### How large is the effect?

Only a share of visitors is affected, not all of them. As a rough rule:

> Measurable conversions ≈ real ChatGPT-sourced orders × consent rate

Example (illustrative, not a measurement): 100 real orders from ChatGPT clicks and a 50% marketing consent rate means at most about 50 orders can be linked to a click. Other gaps (see below) reduce that further.

Consent rates differ widely by site, market and banner design. Published EU benchmarks vary from well below 30% to above 70%, so use the rate from the client's own CMP dashboard rather than an industry average.

OpenAI also mentions **modeled measurement**, which can estimate attribution for conversions without a click ID "where available". Availability per account or region is not documented. Do not rely on it to close the gap. OpenAI states that differences between Ads Manager and other tools can result from browser, consent and storage conditions, and that a difference does not necessarily indicate an error.

### What consent does not explain

Consent removes a share of conversions. It does not explain a total of zero after a meaningful number of clicks. If Ads Manager shows clicks and no conversions at all, check the following first.

| Symptom                                                        | Likely cause                                                                                                                                 |
| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| No conversions at all, server events reach OpenAI              | The server tag is still in test mode (`validate_only`).                                                                                      |
| `oppref` never appears in any event                            | No `page_view` OpenAI Pixel tag, so the click ID is never stored in `__oppref`.                                                              |
| Browser and server events do not count as one purchase         | Different event name or event ID between the Pixel and the Conversions API.                                                                  |
| `oppref` on `page_view` events, but missing on purchase events | The purchase is sent from a shop webhook. Webhooks carry no browser cookies, so the click ID is missing unless it was stored with the order. |
| Browser purchase arrives, but Ads Manager does not count it    | The Pixel tag inherits the dataLayer name and sends a custom event instead of `order_created`.                                               |
| Ads Manager clicks are much higher than sessions in GA4        | Expected gap: consent, ad blockers, page-load failures and attribution windows differ.                                                       |

Rule these out before attributing a gap to consent.

### How to recognize the consent effect

Compare over the same period and time zone:

1. Sessions in GA4 with `utm_source=chatgpt` and `utm_medium=paid_ai`.
2. Orders in the shop from those sessions.
3. Conversions in OpenAI Ads Manager.

If (3) is clearly lower than (2), the tracking checks above are clean, and the client's consent rate is below 100%, the gap is at least partly consent. Analytics tools also depend on consent, so treat (1) and (2) as a lower bound.

### What you can do

* **Connect the CMP to the OpenAI tags.** Fire them only after marketing consent, either through a consent-based trigger group or by setting `oaiq("consent", ...)`.
* **Fire the OpenAI `page_view` tag after the consent update.** The landing URL still contains `oppref` on the first page. If the tag fires before consent is known, that click ID is lost. See Trigger sequence for consent processing. Test what happens when consent is given after the landing page has loaded.
* **Keep the click ID with the order.** If purchases are sent from a shop webhook, store `oppref` with the order or send the purchase from the browser as well, with a shared event ID.
* **Add static UTM parameters** to every campaign so you can see ChatGPT visits and shop orders per campaign. See UTM parameters & dynamic tracking.
* **Judge campaigns on shop orders per source next to Ads Manager**, not on Ads Manager alone.
* **Review the cookie banner** if the consent rate is low. See Ideal cookiebanner setup.

{% hint style="warning" %}
Never send events, hashed emails or `oppref` for visitors who declined, and never override the consent state to report more conversions. OpenAI requires you to follow your site's consent rules and to stop sending data when consent is revoked.
{% endhint %}


# Verify ChatGPT Ads events in the Events stream

Check that conversion events from your site reach OpenAI Ads, using the Events   stream

The Events stream in OpenAI Ads Manager shows the events OpenAI receives from your tracking setup. It works similar to GTM preview mode, but for OpenAI Ads. Use it to confirm that a test conversion arrives before you rely on the reported numbers.

{% hint style="info" %}
This page assumes the OpenAI tag is already set up in your server container. If not, start with [OpenAI Ads](https://docs.adpage.io/integrations-marketingtools/openai-ads).
{% endhint %}

### Before you start

* The OpenAI tag is configured in your server-side GTM (sGTM) container.
* You have access to OpenAI Ads Manager for the correct account.
* You can accept marketing cookies on the website. In the EU, measurement only runs for visitors who accept them. See [Tracking cookies and consent](https://docs.adpage.io/integrations-marketingtools/openai-ads/tracking-cookies-and-consent).

### Steps

{% stepper %}
{% step %}

#### Turn off validate only in the sGTM template

Open your server container, go to **Tags**, and open the OpenAI tag. Turn **\[Validate Only]** off (set it to false), then publish the container.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FZ4qmbYJo0Zajq0wPyT7G%2Fimage.png?alt=media&amp;token=f0aa2974-3ddd-480b-9047-c6b0c0149531" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
While validate only is on, OpenAI checks each event but does not store it. The event will not appear in the Events stream and will not count as a conversion.
{% endhint %}
{% endstep %}

{% step %}

#### Open the Events stream

In OpenAI Ads Manager, go to **Tools** and select **Events stream**.

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FW3fUHj7HI4f8eSGDTVer%2Fimage.png?alt=media&amp;token=662cf8bf-f1c4-4174-9104-928d4769c826" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}
To start measuring, click the **\[Start polling]** button

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FbLEuAOuC6iaNNq1o5r4i%2Fimage.png?alt=media&amp;token=27d93b92-09c8-4960-8479-dd2fd8cace3d" alt=""><figcaption></figcaption></figure>

#### Reproduce the action on your website

Open your website, accept marketing cookies, and perform the action you want to measure, for example adding a product to the cart or completing a test order.
{% endstep %}

{% step %}

#### Check that the event arrives

Return to the Events stream. The event should appear. Check that the:

* **event type** matches the action you performed
* **Pixel ID** is the one configured in your tag
* **event ID** is present

<figure><img src="https://1274044937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FA65KwL1NwewlJbtCXsXd%2Fuploads%2FiVyZmR2snvy7iZgML6hd%2Fimage.png?alt=media&amp;token=49cd371c-92cf-4c10-aa40-e79d385f5dc8" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Check that the event is not counted twice

If you send the same conversion from both the browser pixel and the server, the two events must share the same event ID so OpenAI counts them once. See [ChatGPT Ads event ID deduplication](https://docs.adpage.io/integrations-marketingtools/openai-ads/chatgpt-ads-event-id-deduplication).
{% endstep %}
{% endstepper %}

### Troubleshooting

If the event does not appear, check the following:

| Cause                     | What to check                                                                                                                                                                                                             |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Validate only is still on | The setting is off in the OpenAI tag and the sGTM container is published.                                                                                                                                                 |
| No marketing consent      | Marketing cookies were accepted before the test.                                                                                                                                                                          |
| Wrong credentials         | The Pixel ID and API Key match the ones in Ads Manager. See [Where to find the OpenAI Pixel ID and API Key](https://docs.adpage.io/integrations-marketingtools/openai-ads/where-to-find-the-openai-pixel-id-and-api-key). |
| Invalid timestamp         | Events older than 7 days, or more than 10 minutes in the future, are rejected.                                                                                                                                            |

{% hint style="success" %}
Once the test event shows up in the Events stream, your conversion measurement is live.
{% endhint %}


# Microsoft Ads

Configure the Microsoft UET tag and Conversions API with event ID deduplication.

Set up the Microsoft UET tag in the web container first. Then send matching events through the Microsoft Conversions API (CAPI) from the server container.

Both tags send the same conversion. Give both the same UET Tag ID, the same event name and the same event ID. Microsoft can then deduplicate the events and count one conversion.

This hybrid setup is what Microsoft recommends. UET captures browser context such as the click ID and page details. CAPI adds a server-side path that is not affected by ad blockers and browser cookie restrictions, and that can also report conversions that happen later, outside the browser.

{% hint style="info" %}
This page covers **tracking**: sending conversions to Microsoft Ads. To get Microsoft cost and conversion data into AdPage reports and the Marketing Mix Model, see [Microsoft Advertising](https://claude.ai/data-and-insights/marketing-integrations/microsoft-advertising).
{% endhint %}

#### What you'll configure

You will create:

* A Microsoft UET tag setup in the GTM web container, with consent mode.
* A **Microsoft Ads UET Conversion API** tag in the GTM server container.
* One shared `event_id` for each matching browser and server event.

Use this page for the complete implementation. See also:

* [Where to find the UET Tag ID, Customer ID and API token](/integrations-marketingtools/microsoft-ads/where-to-find-the-uet-tag-id-customer-id-and-api-token)
* [Microsoft Ads event ID deduplication](/integrations-marketingtools/microsoft-ads/microsoft-ads-event-id-deduplication)
* [Click ID, cookies and consent](/integrations-marketingtools/microsoft-ads/click-id-cookies-and-consent)
* [Webhook and offline conversions](/integrations-marketingtools/microsoft-ads/webhook-and-offline-conversions)

#### Before you start

Make sure you have:

* [ ] &#x20;A GTM web container with GA4 event tags.
* [ ] A GTM server container that receives the GA4 events.
* [ ] The **UET Tag ID**, the **Conversions API token** and the **Customer ID** from Microsoft Advertising. See [Where to find the UET Tag ID, Customer ID and API token](/integrations-marketingtools/microsoft-ads/where-to-find-the-uet-tag-id-customer-id-and-api-token).
* [ ] At least one **conversion goal** in Microsoft Advertising that uses this UET tag.
* [ ] A **Unique Event ID** variable in the web container.
* [ ] Auto-tagging enabled in Microsoft Advertising, so ad clicks carry `msclkid` in the landing page URL.

{% hint style="warning" %}
The API token belongs to one specific UET tag. Use the token and the Tag ID of the same tag, in both containers. A token generated for a different UET tag returns `401 Unauthorized`.
{% endhint %}

### Part 1: Set up client-side tracking

#### **Step 1: Create a UET Tag ID variable**

1. Open your GTM web container and go to **Variables**.
2. Create a **Constant** variable.
3. Set its value to the UET Tag ID and save it.

#### **Step 2: Create the UET base tag**

1. Go to **Tags** and create a new tag.
2. Choose **Microsoft Advertising Universal Event Tracking** as the tag configuration. If it is not available yet, add it from the **Community Template Gallery**.
3. Select your UET Tag ID variable.
4. Set the tag type to **Page view**.
5. Use the trigger you use for all pages (Page View or `cookie_consent_update`).

#### **Step 3: Configure UET consent mode**

Microsoft requires UET consent mode for visitors in the EEA, the UK and Switzerland. UET reads one signal, `ad_storage`. It must default to `denied` and update to `granted` only when the visitor accepts marketing cookies.

Open the consent settings in the UET tag and enable the options that take over the GTM consent state and listen for consent updates. This only works when your CMP sets the Google Consent Mode default to `denied` before the UET tag loads. See [Consent Management](/optimize-your-setup/consent-management).

Details and alternatives are on [Click ID, cookies and consent](/integrations-marketingtools/microsoft-ads/click-id-cookies-and-consent).

#### **Step 4: Create the conversion tags**

1. Create a new **Microsoft Advertising Universal Event Tracking** tag.
2. Select your UET Tag ID variable.
3. Set the tag type to a **custom event** and fill in the **Event Action** that your conversion goal in Microsoft Advertising expects, for example `purchase`.
4. For a purchase, add the revenue value and currency.
5. Add a custom parameter named `event_id`:
   * For a purchase, use the order ID.
   * For all other events, use your Unique Event ID variable.
6. Use the same trigger as the matching GA4 event tag.

Repeat this for every event you want to track.

{% hint style="info" %}
Why the order ID for purchases? A purchase can reach the server container from the browser or from a shop webhook. The order ID is the only value both routes know. See [Microsoft Ads event ID deduplication](/integrations-marketingtools/microsoft-ads/microsoft-ads-event-id-deduplication).&#x20;
{% endhint %}

#### **Step 5: Pass the event ID to GA4**

Add the same event ID to every matching GA4 event tag:

1. Open the GA4 event tag.
2. Add an event parameter named `event_id`.
3. Set its value to the same variable you used in the UET tag for that event.
4. Save the tag.

The server container can now read the event ID from the GA4 event.

### Part 2: Set up server-side tracking

#### **Step 6: Add the Conversions API template**

1. Open your GTM server container and go to **Templates**.
2. Under **Tag Templates**, click **Search Gallery**.
3. Add the **Microsoft Ads UET Conversion API** template by Stape.

#### **Step 7: Store the credentials**

Create two **Constant** variables in the server container: one for the UET Tag ID and one for the Conversions API token. You then only have one place to change them.

#### **Step 8: Create the server-side tag**

1. Create a new **Microsoft Ads UET Conversion API** tag.
2. Under **Event Type Setup Method**, choose **Inherit from client**. Choose **Standard** only when you need to set the event type and name by hand.
3. Fill in the **UET Tag ID** and **Authorization Token** variables.
4. Enable **Client-Side ID Sync** and fill in the **Customer ID**. This is not the UET Tag ID.
5. Leave **Use Optimistic Scenario** off. With it on, the tag always reports success, even when Microsoft rejects the request.
6. Add the **User Data Parameters** you have, at least one. Email and phone are hashed by the tag.
7. Keep **Auto-mapping** enabled under **Server Event Data Parameters** and **Event Parameters**.

#### **Step 9: Pass the event ID to Microsoft**

1. Create an **Event Data** variable with key path `event_id`.
2. Open the Microsoft Ads UET Conversion API tag.
3. Under **Server Event Data Parameters**, add **Event ID**.
4. Set its value to the `event_id` variable.

#### **Step 10: Configure consent and the trigger**

The Conversions API treats every event as consented unless it is told otherwise. Gate the tag so it only fires for visitors who accepted marketing cookies:

* Add the consent condition from [Consent Management, step 3](/optimize-your-setup/consent-management#step-3-configure-server-side-triggers-based-on-consent) to the trigger.
* Under **Server Event Data Parameters**, set the **Ad Storage Consent** parameter to granted for these events.

Create a trigger for the events you want to send. Use both conditions:

* `{{Event Name}}` matches RegEx `page_view|purchase` (extend this with your other events).
* `{{Client Name}}` equals `GA4`.

Send `page_view` as well as your conversions. Page load events are what Microsoft uses for destination URL goals and remarketing.

{% hint style="info" %}
The UET tag and the Conversions API tag must use the same UET Tag ID, event name and event ID. A difference in any of the three prevents deduplication.
{% endhint %}

### Test and validate the complete setup in preview mode

Before you publish, confirm that the click ID reaches the server container and that the Conversions API tag forwards it to Microsoft.

{% hint style="danger" %}
The Microsoft Conversions API has no test mode. Every event you send during testing is recorded as a real event. Test with a small number of conversions and keep track of them.&#x20;
{% endhint %}

**Prepare the test**

1. Open a fresh browser session. Connect GTM preview mode for both the web container and the server container.
2. Work in a separate workspace.
3. Open a landing page with a test click ID, for example `https://yourdomain.com/?msclkid=0123456789abcdef0123456789abcdef`. A real `msclkid` is a 32-character hexadecimal string. You can also click a live ad.

**Where to look in server preview**

| Location                        | What to check                                                                                                                                                                                                                                       |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Incoming request (client)       | The `cookie` header contains `_uetmsclkid` and `_uetvid` from the UET tag, or `uet_msclkid` and `uet_vid` set by the server tag. If they are missing, the server container probably does not run on a first-party domain of the website.            |
| Event Data                      | `page_location` contains `msclkid` on the landing page. `event_id` is present. The consent state shows marketing consent granted.                                                                                                                   |
| Microsoft tag → Request         | The URL is `https://capi.uet.microsoft.com/v1/<UET-TAG-ID>/events`. The `Authorization` header uses the Bearer scheme. The body contains `eventType`, `eventId`, `eventName`, `eventTime` and a `userData` object with `msclkid` and `anonymousId`. |
| Microsoft tag → Response        | Status `200`. A `401` means the token and Tag ID do not belong together. A `400` lists the failing field.                                                                                                                                           |
| Browser → Application → Cookies | `uet_msclkid` and `uet_vid` exist with the expected domain and expiry.                                                                                                                                                                              |

**Run the test scenarios**

| # | Scenario                                                          | Expected result                                                                                                                                                       |
| - | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | Landing page with `msclkid` in the URL, marketing consent granted | The first event contains `msclkid`, equal to the URL value without hyphens. The `uet_msclkid` cookie is set.                                                          |
| 2 | Second page view without `msclkid` in the URL                     | `msclkid` comes from the cookie and has the same value.                                                                                                               |
| 3 | Second ad click with a different `msclkid`                        | The new value is sent and the cookie is overwritten.                                                                                                                  |
| 4 | Direct visit without `msclkid`                                    | `msclkid` is omitted from the body. It is not an empty string.                                                                                                        |
| 5 | Marketing consent denied                                          | No request goes to Microsoft and the UET tag stays in denied mode.                                                                                                    |
| 6 | Consent given after the landing page loaded                       | The first Microsoft event after the consent update still contains `msclkid` from the landing page URL.                                                                |
| 7 | UET and Conversions API together                                  | Both send the same event name and event ID, so only one conversion counts.                                                                                            |
| 8 | Purchase sent from a shop webhook                                 | No browser cookies are available. See [Webhook and offline conversions](https://claude.ai/integrations-marketingtools/microsoft-ads/webhook-and-offline-conversions). |

**Check the response for warnings**

A `200` response does not mean every field was accepted. Microsoft removes optional fields it cannot use, such as an invalid hash or currency, and still accepts the event. Open the response body in preview. Every entry with `isWarning: true` is a field that did not reach Microsoft.

**Check the result after publishing**

In the outgoing request logs, confirm that:

* Landing pages with `msclkid` in the URL carry `msclkid` in the request body.
* Follow-up page views carry the same value.
* Purchases carry the same `eventId` as the order ID.
* The number of non-2xx responses does not increase.

In Microsoft Advertising, conversions can take several hours to appear in the conversion goal columns.

{% hint style="warning" %}
Only send the click ID, hashed emails and cookie values for visitors who granted marketing consent.
{% endhint %}


# Where to find the UET Tag ID, Customer ID and API token

Find the three values the Microsoft Ads setup needs in Microsoft Advertising.

The Microsoft Ads setup needs three values from Microsoft Advertising. They look alike but do different jobs, so check which one goes where.

| Value                     | Used in                                        | What it is                                                      |
| ------------------------- | ---------------------------------------------- | --------------------------------------------------------------- |
| **UET Tag ID**            | UET tag (web) and Conversions API tag (server) | The ID of the UET tag that your conversion goals use.           |
| **Conversions API token** | Conversions API tag (server)                   | The key that authorizes server events for that one UET tag.     |
| **Customer ID**           | Conversions API tag, Client-Side ID Sync       | The ID of the Microsoft Advertising customer (manager) account. |

## UET Tag ID

1. Sign in to Microsoft Advertising.
2. In the left-hand menu, go to **Conversions** and open **UET tag**.
3. Copy the **Tag ID** of the tag your conversion goals use.

{% hint style="info" %}
An account can contain several UET tags. Use the tag that your conversion goals are attached to. Events sent to another tag do not count for those goals.
{% endhint %}

## Conversions API token

The token is tied to one UET tag. Generate it for the same tag whose ID you use in GTM.

{% stepper %}
{% step %}

### Open the UET tag

Go to **Conversions** → **UET tag**, find your tag and click the pencil icon to edit it.
{% endstep %}

{% step %}

### Continue to tagging

In **Edit UET tag**, click **Save and next**.
{% endstep %}

{% step %}

### Choose the Conversions API

In **Set up tagging**, select **Use Conversions API**.
{% endstep %}

{% step %}

### Copy the token

In the **Conversions API** section, click **Copy Token**, then **Next** and **Done**. Store the token in a constant variable in your server container.
{% endstep %}
{% endstepper %}

If a token already exists for the tag, Microsoft shows that token instead of creating a new one.

{% hint style="warning" %}
Only the owner of a UET tag can generate a token. With access to a shared tag you can view an existing token, but not create one. If the **Use Conversions API** option is missing, the account may not have access to the Conversions API yet. Contact your Microsoft Advertising account manager.
{% endhint %}

Treat the token like a password. Anyone with the token and the Tag ID can send events to your UET tag.

## Customer ID

The Customer ID is needed for **Client-Side ID Sync**.

1. Sign in to Microsoft Advertising.
2. Look at the URL in your browser.
3. Copy the value of the `cid` parameter.

If you work with several Customer IDs, use the primary one: the Customer ID of the manager account.

{% hint style="warning" %}
The Customer ID is not the UET Tag ID. One customer account can contain several UET tags.
{% endhint %}


# Microsoft Ads event ID deduplication

Make sure a conversion sent by both the UET tag and the Conversions API counts once.

When the UET tag and the Conversions API both send the same conversion, Microsoft receives it twice. Without deduplication, it counts twice and your campaign data is wrong.

Microsoft deduplicates two events when they share all three of these values:

| Value      | UET tag (web)               | Conversions API tag (server)                    |
| ---------- | --------------------------- | ----------------------------------------------- |
| UET Tag ID | Tag ID field                | UET Tag ID field                                |
| Event name | Event Action                | `eventName` in the request body                 |
| Event ID   | `event_id` custom parameter | **Event ID** under Server Event Data Parameters |

## Which event ID to use

| Event            | Event ID                      | Why                                                                                                                                                               |
| ---------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `purchase`       | The order ID                  | A purchase can reach the server from the browser or from a shop webhook. The webhook never carries the browser's random event ID, but it does carry the order ID. |
| All other events | Your Unique Event ID variable | These only come from the browser, so a generated ID per event works.                                                                                              |

Use the same rule on both sides. If the UET purchase tag sends the order ID and the server tag sends a random ID, the purchase counts twice.

{% hint style="info" %}
A stable event ID also protects you against retries. If a request is sent again after a failure, Microsoft recognises the same event ID and does not count it again.
{% endhint %}

## Set it up

{% stepper %}
{% step %}

### Web container

1. Open each **Microsoft Advertising Universal Event Tracking** conversion tag.
2. Add a custom parameter named `event_id` with the value from the table above.
3. Open the matching **GA4 event** tag and add an event parameter `event_id` with the same variable.
   {% endstep %}

{% step %}

### Server container

1. Create an **Event Data** variable with key path `event_id`.
2. Open the **Microsoft Ads UET Conversion API** tag.
3. Under **Server Event Data Parameters**, add **Event ID** and select the variable.
   {% endstep %}
   {% endstepper %}

## Match the event name

With **Inherit from client**, the server tag derives the event name from the incoming GA4 event. Check in preview that the `eventName` in the request body is exactly the **Event Action** of the UET tag for the same interaction. If it is not, switch the server tag to **Standard** for that event and set the name by hand.

## Test

Use GTM preview mode in both containers. Trigger one test conversion and compare:

1. In the web container, the `event_id` and Event Action of the UET tag.
2. The `event_id` parameter of the matching GA4 event.
3. In the server container, the `eventId` and `eventName` in the Microsoft tag's outgoing request body.

All three must show the same event ID, and the UET tag and server tag the same event name.

If they do not match, the usual causes are:

* The event names differ. The UET tag sends one action and the server tag another.
* The server tag receives no `event_id`, because it is missing on the GA4 event tag.
* The tags fire on different triggers, so they do not describe the same interaction.
* The purchase uses the Unique Event ID on one side and the order ID on the other.


# Click ID, cookies and consent

How the Microsoft click ID is stored, how consent works for UET and the Conversions API, and what to check when conversions are missing.

## The click ID (`msclkid`)

With auto-tagging on, Microsoft adds `msclkid` to the landing page URL after an ad click. It is the strongest signal Microsoft has to attribute a conversion to a click. Send it with every event whenever you have it.

The value is a 32-character hexadecimal string. Microsoft expects it without hyphens.

The Microsoft Ads UET Conversion API tag looks for the click ID in this order:

1. The `msclkid` parameter in the page URL.
2. The `uet_msclkid` cookie set by the server container.
3. The `_uetmsclkid` cookie set by the UET tag in the browser.

It does the same for the visitor ID: `uet_vid` from the server, `_uetvid` from the browser, or a newly generated ID when neither exists.

## Cookies

| Cookie        | Set by                       | Holds      |
| ------------- | ---------------------------- | ---------- |
| `_uetmsclkid` | UET tag (browser)            | Click ID   |
| `_uetvid`     | UET tag (browser)            | Visitor ID |
| `uet_msclkid` | Conversions API tag (server) | Click ID   |
| `uet_vid`     | Conversions API tag (server) | Visitor ID |

In the tag's **Anonymous ID and Click ID Settings** you control whether the server tag writes its cookies, and their domain and expiry. Keep the cookies enabled. Microsoft recommends keeping the click ID for 90 days and overwriting it when a newer click comes in.

{% hint style="info" %}
The server container can only read and set these cookies when it runs on a first-party subdomain of the website, such as `tagging.yourdomain.com`.
{% endhint %}

## Client-Side ID Sync

ID Sync links your visitor ID to Microsoft's own identifiers. Microsoft needs it for remarketing and dynamic remarketing, and recommends it for better conversion matching.

ID Sync must run in the browser, not on the server, because Microsoft needs the browser context. With **Client-Side ID Sync** enabled, the server tag has the browser load Microsoft's sync pixel. That is why it needs the **Customer ID**.

The visitor ID used for ID Sync must be the same as the `anonymousId` in the Conversions API events. The tag handles this when both use the same visitor ID cookie.

## Consent in the browser (UET)

Microsoft requires UET consent mode for visitors in the EEA, the UK and Switzerland. UET uses one consent signal, `ad_storage`:

* **Default:** `denied`, set before the visitor makes a choice.
* **Update:** `granted` when the visitor accepts marketing cookies, otherwise it stays `denied`.

With `denied`, UET does not store cookies and Microsoft does not use the visit for attribution or remarketing.

There are two ways to connect it to your CMP:

| Option                                                                                                                            | When to use                                                                                           |
| --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| The consent settings in the **Microsoft Advertising Universal Event Tracking** tag, which take over the Google Consent Mode state | Your CMP already sets Google Consent Mode v2 with a `denied` default. This is the usual AdPage setup. |
| A separate tag that pushes `uetq.push('consent', 'default', ...)` and `uetq.push('consent', 'update', ...)`                       | Your CMP does not use Google Consent Mode.                                                            |

{% hint style="warning" %}
Do not let the UET tag take over the consent state when no Google Consent Mode default exists. Without a default, consent can be treated as granted.
{% endhint %}

Fire the UET page view after the consent state is known. The landing URL contains `msclkid` on the first page only. If the tag fires before consent is known, the click ID can be lost. See [Trigger sequence for consent processing](/optimize-your-setup/consent-management/trigger-sequence-for-consent-processing).

## Consent on the server (Conversions API)

The Conversions API processes every event as consented unless it receives `adStorageConsent: "D"`. It does not read the visitor's cookie banner choice by itself.

So gate the server tag:

{% stepper %}
{% step %}

### Forward the consent status

Forward the consent status from the web container, as described in [Consent Management](/optimize-your-setup/consent-management).
{% endstep %}

{% step %}

### Add a trigger condition

Add a trigger condition so the Microsoft tag only fires when the visitor accepted marketing cookies.
{% endstep %}

{% step %}

### Set ad storage consent

Set the **Ad Storage Consent** parameter in the tag to granted for those events.
{% endstep %}
{% endstepper %}

Events sent with `adStorageConsent: "D"` are not used for attribution or remarketing at all. Blocking the tag for visitors without consent is the cleaner option: no personal data leaves the server container.

## Troubleshooting

| Symptom                                       | Likely cause                                                                                                                                                                                                                 |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| All requests return `401`                     | The token was generated for a different UET tag than the Tag ID in the tag, or the token is not filled in.                                                                                                                   |
| Requests return `400`                         | A required field is missing or invalid, often `eventTime` or `eventType`. The response body names the field and the event index.                                                                                             |
| `200`, but fields are missing in Microsoft    | Microsoft removed optional fields it could not accept. Look for `isWarning: true` in the response body.                                                                                                                      |
| Conversions appear twice                      | Different event ID or event name between UET and the Conversions API, or different UET Tag IDs. See [Microsoft Ads event ID deduplication](/integrations-marketingtools/microsoft-ads/microsoft-ads-event-id-deduplication). |
| Events accepted, no conversions in Microsoft  | The event name does not match the conversion goal, the goal uses a different UET tag, or `msclkid` is missing.                                                                                                               |
| `msclkid` only on the landing page event      | The server tag does not write its cookie, or the server container is not on a first-party domain.                                                                                                                            |
| `msclkid` on page views, missing on purchases | The purchase comes from a shop webhook, which carries no browser cookies. See [Webhook and offline conversions](/integrations-marketingtools/microsoft-ads/webhook-and-offline-conversions).                                 |
| Remarketing audiences do not grow             | Client-Side ID Sync is off or uses the wrong Customer ID.                                                                                                                                                                    |
| The tag always shows as succeeded             | **Use Optimistic Scenario** is on. Turn it off to see real responses.                                                                                                                                                        |

Consent removes a share of conversions. It does not explain zero conversions after a meaningful number of clicks. Rule out the causes above first.


# Webhook and offline conversions

Send purchases from shop webhooks and conversions from outside the website to Microsoft Ads through the Conversions API.

Not every conversion happens in a browser session that the UET tag can see. A purchase can arrive through a shop webhook, and a lead can turn into a sale days later in a CRM or in a store. The Conversions API accepts these events too, as long as they meet two conditions:

* The event is no older than **90 days** (`eventTime`).
* It carries an identifier Microsoft can match, ideally the `msclkid` of the ad click.

{% hint style="info" %}
The 90-day limit is for submitting the event. To count, the conversion must also fall within the attribution window of the conversion goal.
{% endhint %}

### Purchases from shop webhooks

A webhook is sent from the shop's backend. It carries no browser cookies, so the server tag cannot find `msclkid` or the visitor ID in a cookie.

{% stepper %}
{% step %}

#### Store the click ID with the order

Make sure the `msclkid` from the visitor's session is stored with the order and included in the webhook. With [Webhook Matching](/optimize-your-setup/webhook-matching), AdPage links the webhook to the browser session and adds its marketing data. Check in the **Webhook Logs** that `msclkid` is present in the payload.
{% endstep %}

{% step %}

#### Set the click ID manually

Create an **Event Data** variable that reads the click ID from the webhook payload. In the Microsoft Ads UET Conversion API tag, set it as the **Click ID** under **User Data Parameters**. Manual values take precedence over automapped ones.
{% endstep %}

{% step %}

#### Add customer identifiers

Add the customer's email and phone number from the webhook. The tag hashes them. They help Microsoft match the conversion when `msclkid` is missing.
{% endstep %}

{% step %}

#### Use the order ID as event ID

Set **Event ID** to the order ID. The UET purchase tag in the browser must use the order ID too. See [Microsoft Ads event ID deduplication](/integrations-marketingtools/microsoft-ads/microsoft-ads-event-id-deduplication).
{% endstep %}

{% step %}

#### Choose one server route

Send the purchase to Microsoft from either the GA4 event or the webhook, not both. Adjust the trigger of the server tag so only one route fires for purchases.
{% endstep %}
{% endstepper %}

Test this by replaying a webhook in preview mode. See [How do I replay a Webhook in the preview mode?](/faq/debugging-monitoring/how-do-i-replay-a-webhook-in-the-preview-mode)

### Offline and CRM conversions

For conversions that happen later, such as a qualified lead, a signed contract or a store purchase after an ad click, send a custom event to the Conversions API when the conversion happens:

* Use the **actual time** of the conversion as `eventTime`, not the time of sending.
* Include the `msclkid` that was stored when the lead was created.
* Use a stable event ID, such as the deal or order ID, so a retry is not counted twice.
* Create a conversion goal in Microsoft Advertising, on the same UET tag, with an event action that matches the `eventName` you send.

The source of these events is usually your CRM or backend, which sends them to the server container as a webhook. The tag setup is the same as for shop webhooks above.

{% hint style="warning" %}
You can only report an offline conversion with a click ID you stored when the lead came in. Capture `msclkid` in a hidden form field or with the lead record from the start. It cannot be recovered afterwards.
{% endhint %}

### Refunds and changed order values

The Conversions API can correct a conversion afterwards: change its value (restate) or remove it (retract). This requires a `transactionId` on the original event and runs through the Microsoft Advertising Campaign Management API, not through the GTM tag.

### Conversions older than 90 days

Events older than 90 days are rejected. For those, use the offline conversion import in Microsoft Advertising, which works with uploaded files instead of the Conversions API.


# App tracking

Send events from an iOS or Android app through the server container to GA4, Meta Ads, TikTok Ads and Google Ads.

App traffic reaches the server container over a different route than web traffic, and it arrives without cookies, without a page URL, and with device information the ad platforms insist on. That is why an app setup is not a matter of pointing existing tags at a second source: app traffic arrives on its own client, and every platform needs its own tag on that client.

{% hint style="warning" %}
**The rule that prevents most app-tracking issues:** every tag and trigger in a container that handles app traffic filters on `Client Name`. A trigger that only matches an event name fires for web and app alike, which sends app events to a platform as web events, with an empty page URL and no identifiers.
{% endhint %}

## How to read this section

Read the four shared pages first. They apply to every platform, and the platform pages assume you know them.

1. **How app tracking works** — the route from the app to the platforms, and which part belongs to whom.
2. **Preparation and roles** — what must exist before you start, and what you agree with the app developer.
3. **Server container basics** — the GA4 App client, naming, and the trigger rule.
4. **Event data reference** — which fields the Firebase client makes available in the server container.
5. **Identifiers and consent in apps** — the single biggest factor in whether a platform can attribute an app conversion.

Then the platform you need: GA4, Meta Ads, TikTok Ads or Google Ads. Each platform page has the same seven sections, so you can compare them.

Finish with **Testing and verification** and, when something is rejected, **Platform error reference**.

## Scope

This section covers native app events collected with the Firebase SDK and forwarded by a Google Tag Manager server container. It does not cover webviews that show a website inside the app: that traffic runs over the web data stream and is documented with the web setup.


# How app tracking works

The route from the Firebase SDK to the ad platforms, and why app traffic needs its own client and its own tags.

## The route

```
   App (iOS / Android)
   Firebase SDK  ──①──►  GA4 data stream setting  ──②──►  Server container
   (signup, purchase)     (hands the sGTM URL                (tagging.[client].nl)
                           back to the SDK)                   │
                                                    ┌─────────┼──────────┐
                                                    ▼         ▼          ▼
                                               GA4 App    GA4 tag    CAPI tags
                                                client   → property  → Meta / TikTok
```

## The server URL is not in the app

The Firebase SDK reads the server-side GTM URL from the GA4 data stream settings, not from the app code. The app only carries a flag that says server-side upload is allowed. As long as the setting in GA4 is off, the SDK sends straight to GA4 and the server container receives nothing, no matter what the app does.

This is the single most common cause of "no app data arrives", and it is settled in GA4 Admin, per data stream, iOS and Android separately.

## App traffic arrives on its own client

A server container routes an incoming request to the first client that claims it. Firebase requests are claimed by the **GA4 App client** (in GTM: the Google Analytics: GA4 (App) client), which is a different client than the GA4 web client. A container that only has a web client answers Firebase requests with nothing useful, and no tag fires.

Because the client differs, `Client Name` is the one condition that reliably separates app traffic from web traffic inside the container.

## Why every platform needs its own tag

An app event looks different from a web event:

* there are no cookies, so no `fbp`, `fbc`, `ttp` or `gclid`,
* there is no page URL or referrer,
* the platforms require device information instead, and each one wants it in its own shape.

So you cannot point an existing web tag at app traffic and expect it to work. In practice you add, per platform, one tag configured for app events, fired by a trigger that filters on the App client.

{% hint style="warning" %}
A Custom Event trigger that only matches an event name, for example `signup`, matches that event from **every** client, app included. Existing web tags then quietly pick up app traffic and send it as web events. Add `Client Name` to those triggers when a container starts handling app traffic.
{% endhint %}

## What stays the same

The container, the tagging domain, the consent setup and the event naming are shared between web and app. You are adding a second source to an existing container, not building a second container.


# Preparation and roles

What must exist before you start, who owns which part, and the two decisions to take with the app developer up front.

## Prerequisites

* [ ] The app is linked to a **Firebase project**, for iOS and Android.
* [ ] The **GA4 property** has one **app data stream per platform**.
* [ ] A **server container** runs on the client's tagging domain.
* [ ] You have access to Firebase, to GA4 Admin with edit rights, and to the ad accounts you will verify in.
* [ ] The events and their names are agreed, and written down in one shared list.
* [ ] In-app consent is arranged. Website cookie consent does not cover an app.

## Who does what

| Work item                                    | Client | App developer |     AdPage    |
| -------------------------------------------- | :----: | :-----------: | :-----------: |
| Firebase SDK and the sGTM upload flags       |        |       ●       |    Advisory   |
| Ownership of Firebase and GA4                |    ●   |               |               |
| Enabling the sGTM URL per data stream in GA4 |    ●   |               |    Guidance   |
| App client, tags, triggers and publishing    |        |               |       ●       |
| Event names and parameters                   |    ●   |       ●       |    Advisory   |
| Sending an identifier with the event         |        |       ●       | Specification |
| In-app consent                               |    ●   |       ●       |    Advisory   |
| Testing and verification                     |    ●   |               |       ●       |

{% hint style="warning" %}
Confirm ownership before anything else. An external app developer often implements Firebase while the client owns the GA4 configuration, and neither assumes the other is waiting. Most delays in app projects come from this, not from the technical work.
{% endhint %}

## Two decisions to take up front

**1. Which identifier does the app send with a conversion?** App events have no cookies, so the ad platforms need something else to attribute them. Settle this before the app build, because adding it afterwards means a new app release. See **Identifiers and consent in apps**.

**2. Which platforms does the client actually need app conversions in?** GA4, Meta and TikTok can receive app events from the server container. Google Ads works differently and normally does not get a tag at all. Setting that expectation early saves a discussion later.

## What the app needs

* The Firebase Analytics SDK, on both platforms.
* The server-side upload flag:
  * iOS: `GOOGLE_ANALYTICS_SGTM_UPLOAD_ENABLED = true`
  * Android: `<meta-data android:name="google_analytics_sgtm_upload_enabled" android:value="true" />`
* Optionally a preview URL scheme, `tagmanager.sgtm.c.[bundle-id]`, which affects GTM preview only.
* The agreed identifier and any extra event parameters.

The tagging URL itself does **not** belong in `app.json`, `Info.plist` or the Android manifest.


# Server container basics

The GA4 App client, the naming convention, and the trigger rule that keeps app and web traffic apart.

This page covers what you set up once, before touching any platform.

## 1. Add the GA4 App client

In the server container, add a client of type **Google Analytics: GA4 (App)**. Give it a name you will recognise in triggers and in preview, for example `App tracking`. Leave the existing GA4 web client in place, it keeps serving the website.

Without this client, Firebase requests reach the container but no tag ever fires.

## 2. Use one naming convention

Name everything that handles app traffic with the same prefix, so a container stays readable when both sources run side by side:

| Object  | Pattern                      | Example               |
| ------- | ---------------------------- | --------------------- |
| Client  | `App tracking`               | `App tracking`        |
| Trigger | `App - <event>`              | `App - signup`        |
| Tag     | `<Platform> - App - <event>` | `Meta - App - signup` |

## 3. Build every app trigger on the client

An app trigger has two conditions:

* `Client Name` equals the App client, and
* `Event Name` equals the event you want.

Use a Custom trigger with both conditions rather than a Custom Event trigger on the event name alone.

{% hint style="info" %}
While you are here, check the triggers that already exist. Any trigger that fires on an event name without a `Client Name` condition will now also catch app traffic. Either add the condition, or give the app its own tag and let the web tag exclude the App client.
{% endhint %}

## 4. Add one tag per platform

| Platform   | What you add                                     | Notes                                                   |
| ---------- | ------------------------------------------------ | ------------------------------------------------------- |
| GA4        | A second GA4 tag, triggered on the App client    | Events land in the app data stream                      |
| Meta Ads   | A Meta tag with action source `app` and app data | Device information is mandatory                         |
| TikTok Ads | A TikTok tag with the app event source           | The app must exist on the TikTok side                   |
| Google Ads | Usually nothing                                  | App conversions run through the GA4 link, see that page |

## 5. Publish, then verify

Publish the container before asking anyone to test. A tag that sits unpublished in a workspace produces exactly the same symptom as a tag that does not exist, and the client tests against the live container.

After publishing, verify in the container's outgoing requests rather than relying on someone else's preview session. See **Testing and verification**.


# Event data reference

Which fields the GA4 App client makes available in the server container, and how to check what actually arrives.

The platform tags build their payload from the event data that the GA4 App client exposes. These are the fields you map, and the fields a tag's auto-mapping looks for.

## Fields from the GA4 App client

| Field               | Contains                                       | Typically used for                       |
| ------------------- | ---------------------------------------------- | ---------------------------------------- |
| `x-ga-platform`     | `ios` or `android`                             | Meta extinfo position 0, TikTok app info |
| `x-ga-os_version`   | OS version of the device                       | Meta extinfo position 4, mandatory       |
| `x-ga-device_model` | Device model                                   | Meta extinfo, device reporting           |
| `app_id`            | Bundle or package name                         | App identification per platform          |
| `app_version`       | App version                                    | Meta extinfo, debugging per release      |
| `language`          | Device language                                | Meta extinfo, locale                     |
| `app_instance_id`   | Firebase instance id of the install            | `external_id` for the platforms          |
| `user_id`           | The client's own user id, when the app sets it | `external_id`, cross-device              |
| `event_name`        | The event, for example `signup`                | Triggers and event mapping               |
| `ga_session_id`     | GA4 session id                                 | GA4 reporting                            |

Parameters the app itself sends with an event, such as a hashed email address or a value, appear under their own names alongside these fields.

{% hint style="warning" %}
Treat this table as the expected situation, not a guarantee. What the client delivers depends on the SDK version and on what the app sends. Always confirm in preview before you build a mapping on one of these fields.
{% endhint %}

## How to check what arrives

App events do not show up in preview by themselves. A request is only routed to a preview session when it carries the `X-Gtm-Server-Preview` header, and the Firebase SDK only adds that header after the device has been bound to the session. A container sitting in preview therefore stays empty while the app fires events perfectly well.

### Bind the device to the preview session

{% stepper %}
{% step %}

## Start preview

Open the **server** container and click Preview. Not the web container: a preview session on the web container never sees app traffic.
{% endstep %}

{% step %}

## Scan the QR code with the device

Use the option to debug an app. The QR code opens the app through the URL scheme `tagmanager.sgtm.c.[bundle-id]` and stores the preview token, after which the SDK sends the preview header with every upload.
{% endstep %}

{% step %}

## Fire the event

The event now appears in the preview session.
{% endstep %}

{% step %}

## Read the event data

Select the **App tracking** client on the incoming event and open the **Event Data** tab. Look up the fields you intend to map.
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
This only works when the app supports the scheme: on Android a preview activity such as `GoogleAnalyticsServerPreviewActivity`, on iOS the URL scheme plus the SDK's open-URL handler (`Analytics.handleOpen`). App developers often skip the iOS side because it affects preview only. Preview then stays empty while live traffic runs fine, so ask whether it is implemented before concluding that nothing arrives.
{% endhint %}

### Or send a request yourself

The preview screen shows the value of the preview header. Replay a request with that header from curl or Postman and it lands in the same session. Useful for testing a mapping without waiting for an app build.

### Or skip preview entirely

The container's outgoing requests show what actually left and what each platform answered, without a device or a preview session. For the question "does anything arrive at all", that is the faster and more reliable route. See **Testing and verification**.

## Identifiers are not in this list by default

The advertising id of the device (IDFA or GAID) is **not** forwarded by Firebase on its own, and neither is an email address. Those only arrive when the app explicitly sends them. See **Identifiers and consent in apps**.


# Identifiers and consent in apps

App events carry no cookies. This page covers which identifier to send, what each platform accepts, and how consent affects it.

A web event carries cookies that let a platform recognise the visitor. An app event carries none. Without a deliberate choice, the only thing you send is an IP address, and the platform accepts the event but can barely attribute it.

## The options

| Identifier                                 | Where it comes from                                 | Notes                                                              |
| ------------------------------------------ | --------------------------------------------------- | ------------------------------------------------------------------ |
| Hashed email address                       | The app, as an event parameter, hashed with SHA-256 | Strongest option for signups and purchases, works across platforms |
| `madid` (IDFA / GAID)                      | The device, only after tracking permission          | Strong for app campaigns, availability on iOS is limited           |
| `anon_id`                                  | The Meta SDK, when the app has it installed         | Meta only                                                          |
| `external_id`                              | The app's own user id, or `app_instance_id`         | Always available, useful for repeat recognition                    |
| Hashed phone number, first name, last name | The app, as event parameters                        | Extra matching signal alongside the email address                  |

{% hint style="info" %}
Send the email address hashed from the app, and hash it correctly: lower case, trimmed, SHA-256. A platform silently ignores a value it cannot match, so a wrongly hashed field looks exactly like a working one.
{% endhint %}

## What this means per platform

* **Meta** expects identifiers in `user_data`, and device information in `app_data`. It also expects the tracking flags described on the Meta page.
* **TikTok** expects identifiers in the user object of the app event.
* **GA4** does not need any of this. It identifies the app install by itself.
* **Google Ads** does not receive these from the container at all, see the Google Ads page.

## Consent

An app needs its own consent mechanism. The website's cookie banner does not cover it, and the consent signals your container already handles do not arrive from the app unless the app sends them.

Two things to settle with the client:

* who builds the in-app consent screen, usually the app developer,
* what the app sends when the user refuses, so the container can suppress the tags that need consent.

On iOS, the tracking permission prompt (ATT) is a separate question from analytics consent. Only with that permission is the advertising id available, and Meta expects to be told whether it was granted. Never report permission as granted when it was not, also not to make an error message disappear.


# GA4 app events

Forward Firebase app events from the server container to the GA4 property.

{% hint style="info" %}
**Status: outline.** The sections below hold what we confirmed during the first app implementation. Open points are marked as such. Fill them in as soon as a setup confirms them.
{% endhint %}

## 1. What GA4 needs for app events

Less than the ad platforms. The GA4 App client already recognises the install and the app data stream, so the tag only has to forward the event. No device information or identifier has to be added by hand.

## 2. What you set up on the GA4 side

* An app data stream per platform, iOS and Android separately.
* The server-side Tag Manager setting enabled on both streams.
* Nothing else. The measurement id of the web stream plays no part here.

## 3. Tag configuration

| Field      | Value                                            |
| ---------- | ------------------------------------------------ |
| Tag type   | Google Analytics: GA4                            |
| Trigger    | `Client Name` equals the App client              |
| Event name | Inherit from the incoming event                  |
| Parameters | Inherit, unless the client wants something extra |

This is a second tag next to the existing GA4 web tag, not a change to it. A GA4 tag whose trigger filters on the web client will never fire for app traffic, which is a common reason for "the event is in the container but not in GA4".

**Open:** confirm whether one GA4 tag with two triggers is preferable to two separate tags in containers that serve both sources.

## 4. Identifiers this platform accepts

Not applicable. GA4 uses the Firebase instance id. A `user_id` sent by the app is picked up when the property is configured for it.

## 5. How to test

* GA4 Realtime, filtered on the app platform.
* GA4 DebugView, when the app runs in debug mode.
* The container's outgoing requests, see **Testing and verification**.

## 6. Known errors

**Open:** add the errors observed in practice. So far the pattern seen is not an error but silence, caused by a tag that is not triggered on the App client.

## 7. Limits

* App events and web events stay separate streams within one property. Combining them into one user journey is a reporting question, not a tagging question.
* **Open:** describe how app and web sessions relate in reporting once we have a case to point at.


# Meta Ads app events

Send app conversions to Meta through the Conversions API, with the device information Meta requires.

{% hint style="info" %}
**Status: outline.** Sections 1, 3 and 6 are confirmed by a live implementation. The open points are marked.
{% endhint %}

## 1. What Meta needs for app events

An event with action source `app` is only accepted when it carries an `app_data` object containing:

* `extinfo`: an array of 16 values. Position 0 is the extinfo version, `i2` for iOS and `a2` for Android. Position 4 is the OS version. Both are mandatory, the other positions may be empty strings.
* `advertiser_tracking_enabled` and `application_tracking_enabled`.

Without that object Meta answers with HTTP 400, code 100, subcode 2804043, "wrong extinfo version or OS version". The event does not appear in Events Manager, not even under Test Events.

## 2. What you set up on the Meta side

* Access to the ad account and to Events Manager, to verify.
* **Open:** confirm whether app events should go to the existing pixel dataset with action source `app`, or to a separate app dataset registered in Events Manager. Record the consequence for reporting and for campaign optimisation.

## 3. Tag configuration

| Field         | Value                                                           |
| ------------- | --------------------------------------------------------------- |
| Tag type      | Facebook Conversion API (Stape)                                 |
| Trigger       | `Client Name` equals the App client, plus the event name        |
| Action source | `app`                                                           |
| App data      | Automap on, or `extinfo` and both tracking flags mapped by hand |
| User data     | The identifier agreed with the app developer                    |

With a current version of the tag template, **Automap App Data** builds `extinfo` from `x-ga-platform`, `app_id`, `app_version`, `x-ga-os_version`, `x-ga-device_model` and `language`. Two conditions apply: the template must be up to date, and the tag must fire on the App client, because those fields do not exist on the web client.

If the template is older, the App Data section has no automap option and sends an empty object. Update the template, or map `extinfo` yourself. The value field is text, so an array has to come from a variable: either a gallery variable such as Object Builder or JSON Converter, or a variable custom template of your own. A server container has no Custom JavaScript variable type.

{% hint style="warning" %}
Setting the action source to `other` makes Meta accept the event without device information. Use it only as a temporary step while the app is being fixed, never as the final state, because app campaigns need `app` for attribution.
{% endhint %}

## 4. Identifiers this platform accepts

`madid`, `anon_id`, `external_id`, and hashed `em`, `ph`, `fn`, `ln`. See **Identifiers and consent in apps**. Note that the user data variables of a web tag point at web dataLayer paths and are empty for app events, so they have to be remapped.

## 5. How to test

* Events Manager, under Test Events, using a `test_` prefixed event name during the test phase.
* The container's outgoing requests, which show both the payload and Meta's answer. This is the faster route, and it works without access to the client's ad account.

## 6. Known errors

| Response                       | Cause                                                   | Fix                                                                 |
| ------------------------------ | ------------------------------------------------------- | ------------------------------------------------------------------- |
| 400, code 100, subcode 2804043 | `app_data` empty, or the platform or OS version missing | Update the template and switch on automap, or map `extinfo` by hand |

**Open:** extend as we see more of them.

## 7. Limits

* Without an identifier the event is accepted but barely attributable.
* On iOS the advertising id is only available with tracking permission, which caps app attribution on that platform.
* **Open:** describe how these events behave in campaign optimisation once a client has run on it for a while.


# TikTok Ads app events

Send app conversions to TikTok through the Events API.

{% hint style="info" %}
**Status: outline.** This page is largely open. What is certain is what goes wrong when you do nothing, which is described in section 7.
{% endhint %}

## 1. What TikTok needs for app events

TikTok separates web events and app events in its Events API. An app event identifies the app rather than a page, and expects device level information and an identifier.

**Open:** record exactly which fields TikTok requires for a server-side app event, and which of them the GA4 App client can supply.

## 2. What you set up on the TikTok side

**Open:** confirm what has to exist in TikTok Ads Manager before app events are accepted, and where the corresponding id is found. Also confirm whether an app that is not registered on the TikTok side causes a rejection or silent discarding.

## 3. Tag configuration

| Field           | Value                                                    |
| --------------- | -------------------------------------------------------- |
| Tag type        | TikTok Events API (Stape)                                |
| Trigger         | `Client Name` equals the App client, plus the event name |
| Event source    | app, not web                                             |
| App information | **Open**                                                 |
| User data       | The identifier agreed with the app developer             |

## 4. Identifiers this platform accepts

**Open:** confirm which of IDFA, GAID, hashed email address and external id TikTok accepts on the app path.

## 5. How to test

* The event testing tool in TikTok Events Manager.
* The container's outgoing requests.

## 6. Known errors

**Open:** fill in from practice.

## 7. Limits and pitfalls

The pitfall here is not an error but a silent one. A web TikTok tag with a Custom Event trigger on the event name also fires for app traffic and then sends the event with source `web`, an empty page object and nothing but an IP address. TikTok answers with a 200, so nothing looks wrong, while the event is worthless.

Check this whenever a container that already sends TikTok events starts receiving app traffic.


# Google Ads app conversions

Why app conversions for Google Ads do not run through the server container, and which route to use instead.

{% hint style="info" %}
**Status: outline.** The direction is settled, the exact steps are open.
{% endhint %}

## 1. What Google Ads needs for app conversions

Not a server container tag. The Google Ads conversion tag in a server container works with the click identifiers that a browser carries, `gclid`, `gbraid` and `wbraid`, stored in cookies. An app has none of these, so the tag has nothing to attribute the conversion with.

App conversions reach Google Ads over a different route: through the link between the GA4 property and Google Ads, or through an app attribution partner.

{% hint style="warning" %}
Building a Google Ads conversion tag on the App client anyway produces requests that leave with a 200 and land nowhere. Do not do it, and if you find one in an existing container, remove it.
{% endhint %}

## 2. What you set up on the Google side

* The GA4 property linked to the Google Ads account.
* The app conversion event imported as a conversion action in Google Ads.
* **Open:** write out the exact steps, and confirm how the imported app conversion appears next to the existing web conversions.

## 3. Tag configuration

None in the server container. The GA4 app event is the source, so what matters is that the GA4 page is correctly implemented.

## 4. Identifiers this platform accepts

Not applicable over this route. Attribution comes from the GA4 and Google Ads link.

**Open:** determine whether enhanced conversions for leads is usable with an app sourced email address, and under which conditions.

## 5. How to test

**Open:** describe how to verify an imported app conversion in Google Ads, and the delay to expect before it appears.

## 6. Known errors

Not applicable. The failure mode here is not an error but an absence: nothing arrives, because there is nothing to arrive.

## 7. Limits

* App install campaigns and in-app conversions are a separate area, with their own attribution model and, on iOS, SKAdNetwork.
* **Open:** decide whether AdPage supports this, or whether it is handed to an app attribution partner. Write down the answer here, because it is the first question a client asks.


# Testing and verification

Confirm that app events reach the container and that each platform accepts them, without depending on someone else's device.

## The order to test in

{% stepper %}
{% step %}

## Publish first

Publish the container. A client testing against an unpublished workspace sees the same nothing as a client testing against a broken setup.
{% endstep %}

{% step %}

## Fire the event on a real device

A registration, a purchase, whatever the agreed conversion is. A simulator often lacks an advertising id.
{% endstep %}

{% step %}

## Check GA4 Realtime

The event arriving there confirms that the app reaches the container and that the GA4 tag fires.
{% endstep %}

{% step %}

## Check the outgoing requests

This shows per platform whether the event left and what the platform answered. See below.
{% endstep %}

{% step %}

## Check the platform's own test tool

Meta Test Events, the TikTok testing tool. Use a `test_` prefixed event name while testing, and remove the prefix before going live.
{% endstep %}

{% step %}

## Confirm both platforms

iOS and Android separately, before raising the traffic percentage.
{% endstep %}
{% endstepper %}

## Preview, and why it is often empty

An app event only reaches a preview session when the request carries the `X-Gtm-Server-Preview` header. The Firebase SDK adds it only after the device has been bound to the session by scanning the preview QR code, which opens the app through the `tagmanager.sgtm.c.[bundle-id]` URL scheme. Without that step, preview shows nothing while the events are in fact arriving.

The binding also needs support in the app: a preview activity on Android, and the URL scheme plus the SDK's open-URL handler on iOS. That iOS part is regularly left out, because it affects preview only.

So an empty preview is not evidence that nothing arrives. Two other mistakes produce exactly the same picture: previewing the web container instead of the server container, and testing against a workspace that was never published. Confirm in the outgoing requests before you conclude anything.

Once a session is bound, preview is the right place for one question: what does the client actually deliver. Select the **App tracking** client on the incoming event and read the **Event Data** tab. See **Event data reference**.

## Find app events in the outgoing requests

The container's outgoing requests record what was sent to the platforms, including the payload and the answer. Search on app signals rather than on the event name.

* `event_name` is empty on the server-to-server path, so a filter on the event name alone can come back empty while events were in fact sent.
* A Meta app event is recognisable by `"action_source":"app"` in `raw_body`.
* A GA4 app event is recognisable by `firebase_app_id` or `app_instance_id` in `request_url`.
* `status_code` shows whether the platform accepted it, `raw_response` holds the error.

```sql
SELECT created_at, platform, status_code,
       substring(raw_body, 1, 500)     AS body,
       substring(raw_response, 1, 500) AS response
FROM outgoing_requests
WHERE container_id = '[container-id]'
  AND created_at >= now() - INTERVAL 14 DAY
  AND (raw_body ILIKE '%"action_source":"app"%'
       OR request_url ILIKE '%firebase_app_id%'
       OR request_url ILIKE '%app_instance_id%')
ORDER BY created_at DESC
LIMIT 50
```

Per platform, whether any app traffic goes out at all:

```sql
SELECT platform,
       countIf(raw_body ILIKE '%"action_source":"app"%') AS app_events,
       countIf(status_code >= 400)                        AS errors,
       count()                                            AS total
FROM outgoing_requests
WHERE container_id = '[container-id]'
  AND created_at >= now() - INTERVAL 14 DAY
GROUP BY platform
```

## Reading the result

| Result                           | Meaning                                                                            |
| -------------------------------- | ---------------------------------------------------------------------------------- |
| Rows with a 2xx status           | The app reaches the container and the platform accepts the event                   |
| Rows with a 4xx status           | The app reaches the container, the payload is wrong. Read `raw_response`           |
| No rows at all                   | Nothing leaves. Check the GA4 data stream setting, the App client and the triggers |
| App rows present, nothing in GA4 | The GA4 tag is not triggered on the App client                                     |

{% hint style="warning" %}
`raw_body` is empty for GET requests, which carry their payload in the URL, and on containers that do not log bodies. An empty `raw_body` means "not logged", never "parameter missing".
{% endhint %}

## Going live

* Remove the `test_` prefix and switch to the final event names.
* Raise the GA4 traffic percentage to 100, if it was lowered.
* Hand over a short note: what was configured, which events run, and where to monitor them.


# Platform error reference

What the platforms answer when an app event is wrong, and what each response means.

The responses below come from the `raw_response` of the container's outgoing requests. Add a row whenever you resolve a new one, with the literal response text, because that is what a colleague searches on.

## Meta

| Response                                                              | Meaning                                                                                 | Fix                                                                                                     |
| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| 400, code 100, subcode 2804043, "wrong extinfo version or OS version" | Action source is `app` while `app_data.extinfo` is empty, or position 0 or 4 is missing | Update the tag template and switch on automap for app data, or map `extinfo` by hand. See the Meta page |

## TikTok

**Open:** fill in from practice.

## GA4

GA4 answers a valid request with a 204 and no body, so a 204 here says the request was accepted, not that the event is correct. Verify content in Realtime or DebugView.

## Symptoms without an error

Not every problem produces a response. These are the silent ones.

| Symptom                                                   | Cause                                                             | Fix                                                         |
| --------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------- |
| Nothing at all in the outgoing requests                   | The sGTM URL is off in GA4, or on only one of the two app streams | Enable it on both streams                                   |
| App events missing while web traffic runs fine            | No GA4 App client in the container                                | Add the App client                                          |
| The event is in the outgoing requests but not in GA4      | The GA4 tag is triggered on the web client only                   | Add a trigger on the App client                             |
| A platform receives app events as web events              | An event-name trigger without a `Client Name` condition           | Add the condition and give the app its own tag              |
| A platform accepts everything but reports no attribution  | The event carries only an IP address                              | Send an identifier, see the identifiers page                |
| The client sees nothing in preview while events do arrive | Preview is running on the web container                           | Check the container id, and verify in the outgoing requests |


# Account management

Manage accounts, billing, containers, integrations, and data products.

***

### Find your topic

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><i class="fa-users" style="color:$primary;">:users:</i></td><td><strong>Account &#x26; users</strong></td><td>Understand your account hierarchy and manage access for your agency, clients, and company.</td><td><a href="/accountmanagement/account-and-users/account-hierarchy">Account &amp; Users</a></td></tr><tr><td><i class="fa-file-invoice-dollar" style="color:$primary;">:file-invoice-dollar:</i></td><td><strong>Billing</strong></td><td>Set up billing, review invoices, and manage your payment method.</td><td><a href="/accountmanagement/billing/setting-up-billing">Billing</a></td></tr><tr><td><i class="fa-box" style="color:$primary;">:box:</i></td><td><strong>Container management</strong></td><td>Set up containers and review their monthly usage.</td><td><a href="/accountmanagement/container-management/setting-up-a-new-container">Container Management</a></td></tr></tbody></table>


# Account hierarchy

What type of accounts are present in AdPage's software?

AdPage is used by two kinds of organizations:

* **Companies:** a business using server-side tagging on their webshop
* **Agencies:** manage server-side tagging on behalf of their client's companies

The software structure mirrors this exactly. A **company** owns **containers**, and can be part of one or multiple **agencies**. You are a **user**, a person with your own credentials. You as a **user** can be a member of a **company** to manage its **containers**, and of an **agency** to manage the **containers** of your clients.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FkUeriolgpzxjCy8Pt9Zy%2Fcontainers-overview-own-en.webp?alt=media" alt="Containers page listing the containers your company owns"><figcaption><p>A company owns its containers; you see them on the Containers page.</p></figcaption></figure>


# Agency: Add a user to a client

Invite your client to their company's account in AdPage

As an agency you manage multiple companies from one AdPage account. In most cases your own team works in those environments, but there are situations where someone outside your agency needs access as well. Think of the client's own online marketer who wants to check the data, a developer who has to verify a tracking setup, or a new colleague at the client side who takes over the account.

For those situations you can invite people directly into a client's company. They get their own login and their own access to that specific company, so you never have to share credentials or pass around a single account. It also keeps things clean when someone leaves: you remove that one user instead of changing a password everyone knows.

{% stepper %}
{% step %}

### Log in to your agency account

Log in as an agency-user in [AdPage](https://data.adpage.io/auth/login)
{% endstep %}

{% step %}

### Open the settings of your client's company

In your Clients-overview click on the settings icon behind the company you want to invite a new member to.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FbaKtsMQFvvgcXbJKvf9T%2Fimage.png?alt=media&amp;token=90f41c3f-71e4-422a-8902-0bb1f891be9f" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Invite a member

You are able to invite another member to the company in the **Invite mebmer** section.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FxVFDQqPgBAnGcTpvLr9F%2Fimage.png?alt=media&amp;token=1e8cc175-4e11-49ef-be09-a28ff810570d" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### After the invitation

Until the invitation is accepted, the person does not have access yet. If they say they never received anything, ask them to check their spam folder first and confirm that you used the correct email address. If needed you can simply send the invitation again.


# Agency: Add a user to your agency

Most agencies have more than one person involved in their tracking setup. A colleague from marketing who wants to check the data, a developer who has to verify an implementation, or an external specialist who helps you with your setup. Instead of sharing one login, you can give each of them their own access.

{% stepper %}
{% step %}

### Log in to your user account

Log in as a client-user in [AdPage](https://data.adpage.io/auth/login)
{% endstep %}

{% step %}

### Open the Partner program of your account

In your overview click on the add teamlid to invite a new member to.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FYMze8x8jf9PrknbeafD9%2Fimage.png?alt=media&amp;token=77e403e7-3b12-4eaf-b805-f205c5c9caec" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FQZ0eb3L80CoBJoJ55kha%2Fimage.png?alt=media&amp;token=54b7880a-6074-4e21-8c89-1a323e554d08" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Invite a member

You are able to invite another member to the company in the **Invite member** section.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FTzky82EtUuNJxU5CACCz%2Fimage.png?alt=media&amp;token=804de995-3ac3-4439-9e84-7e5bfcb33d55" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### After the invitation

Until the invitation is accepted, the person does not have access yet. If they say they never received anything, ask them to check their spam folder first and confirm that you used the correct email address. If needed you can simply send the invitation again.


# Agency: Notifications for all your clients

Set up email alerts once for every client of your agency: a daily health check, and an email as soon as something new goes wrong.

With **Meldingen voor al je klanten** (Notifications for all your clients) you set up email alerts once for your whole agency, instead of per container. Every container of every client takes part, including clients you add later.

There are two emails:

* **Dagelijkse gezondheidscheck** (Daily health check): every morning, the health score of all your clients, with the ones that need attention at the top.
* **Direct bij een nieuw probleem** (Right away on a new problem): an email as soon as a check finds something new at one of your clients.

{% hint style="info" %}
This feature is in pilot. Don't see **Meldingen** (Notifications) in the menu? Ask <support@adpage.io> to switch it on for your agency.
{% endhint %}

## Who can use it

* Members of the agency can open the page and see the settings.
* Only an owner or admin of the agency can change them. Other members see the page read-only.

## Open the page

Log in to [AdPage](https://data.adpage.io/auth/login). In the menu, under **Tracking**, click **Meldingen** (Notifications).

The page shows the two emails as tiles. Below them, under **Klanten** (Clients), you see all containers of your clients with their health score.

## The two emails

### Dagelijkse gezondheidscheck (Daily health check)

Sent every morning around 7:00 (Amsterdam time), after the nightly check of all containers.

* Containers that need attention come first, with what failed and what is new since yesterday.
* Healthy containers are listed by name below that.

Choose when it goes out:

* **Elke ochtend** (Every morning): also when everything is healthy, so you know the check ran.
* **Alleen als er iets is** (Only when there is something): no email when all your clients are healthy.

### Direct bij een nieuw probleem (Right away on a new problem)

Sent after every check (each night, or when someone starts one), once per finding. Whatever was already wrong when you switched the email on does not count as new.

Choose when we email:

* **Bij elke nieuwe bevinding** (On every new finding): also a warning, as soon as a score drops below 100.
* **Kritiek, of een score onder 80** (Critical, or a score below 80): a new critical finding, or a score that drops below 80. This is the recommended setting.
* **Alleen kritiek** (Only critical): only a new critical finding.

## Set up an email

{% stepper %}
{% step %}

### Open the email

Click the tile of the email. On the left you see an example with your own clients; on the right, the settings.
{% endstep %}

{% step %}

### Switch it on

Turn on **Deze mail aan** (This email on).
{% endstep %}

{% step %}

### Choose when it goes out

Pick one of the options described above.
{% endstep %}

{% step %}

### Add the recipients

Under **Wie krijgt de mails** (Who gets the emails), enter an email address and click **Toevoegen** (Add). You can add up to 10 addresses. Both emails go to the same list. Without a recipient, no email goes out.
{% endstep %}

{% step %}

### Send a test email

Click **Stuur een testmail** (Send a test email). The email goes to your own address, with \[Test] in the subject. Close the window with **Klaar** (Done).
{% endstep %}
{% endstepper %}

Every change is saved right away. The emails are written in the language you use AdPage in when you save.

## Choose which containers take part

Under **Klanten** (Clients), each container has a switch. A new client takes part automatically. Switch a container off for a test container or a client that is on hold.

## How the health score works

The score is the same as on the containers overview: it starts at 100, minus 15 for every critical finding and minus 5 for every warning. A container without a check yet shows **Nog geen score** (No score yet).

## Trial mode

During the pilot, the emails can still be in trial mode. The page then says **De mails staan nog in de proefstand: we meten al, maar sturen nog geen mail.** (The emails are still in trial mode: we're already measuring, but not sending email yet.)

Your settings, the example and the test email already work in trial mode. As soon as AdPage switches your agency to live, the emails go out with the settings you chose. You don't need to change anything.

## Troubleshooting

* **I don't see Meldingen in the menu.** The feature is in pilot and is switched on per agency. Ask <support@adpage.io>.
* **"Meldingen voor al je klanten staat nog niet aan voor je bureau"** (Notifications for all your clients is not switched on for your agency yet). Same as above.
* **"Alleen de eigenaar of een beheerder van het bureau kan dit wijzigen"** (Only the owner or an admin of the agency can change this). Ask an owner or admin of your agency. See [Agency: Add a user to your agency](/accountmanagement/account-and-users/agency-add-a-user-to-your-agency).
* **I don't receive the emails.** Check that the page doesn't say trial mode, that your address is under **Wie krijgt de mails**, and your spam folder. Send a test email to check delivery.
* **A client is missing.** Only clients linked to your agency take part. See [Link your company to an agency](/accountmanagement/account-and-users/link-your-company-to-an-agency).


# Client: Add a user to your company

Invite your client to their company's account in AdPage

Most companies have more than one person involved in their tracking setup. A colleague from marketing who wants to check the data, a developer who has to verify an implementation, or an external specialist who helps you with your setup. Instead of sharing one login, you can give each of them their own access.

{% stepper %}
{% step %}

### Log in to your user account

Log in as a client-user in [AdPage](https://data.adpage.io/auth/login)
{% endstep %}

{% step %}

### Open the settings of your company

In your Containers-overview click on the settings icon behind the company you want to invite a new member to.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2Fmh0VCRTxPlY7d7LsZDiK%2Fimage.png?alt=media&amp;token=e2fd1d73-a4a6-45c6-b6e3-2b0fb348e2c8" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Invite a member

You are able to invite another member to the company in the **Invite mebmer** section.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FSIRhD1VkErsVezxTY5gi%2Fimage.png?alt=media&amp;token=8ea88983-7623-4da7-9cbc-1204589c4df5" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### After the invitation

Until the invitation is accepted, the person does not have access yet. If they say they never received anything, ask them to check their spam folder first and confirm that you used the correct email address. If needed you can simply send the invitation again.


# Link your company to an agency

Give an agency access to your containers with its link code

Working with an agency on your tracking? Link your company to that agency. The agency can then see and manage all containers of your company, in AdPage and through the AI connection (Claude, ChatGPT). You stay the owner of your company, and you decide which agency you link with.

{% hint style="info" %}
A link always needs both sides: you send a request with the agency's link code, and the agency accepts it. Until the agency accepts, it has no access.
{% endhint %}

## How it works

1. The agency sends you its **link code**.
2. As the owner of your company, you paste the code in your company settings and send a request.
3. An owner or admin of the agency accepts the request.

## Agency: find your link code

You see the link code as an owner or admin of the agency.

{% stepper %}
{% step %}

### Open your clients

Log in to [AdPage](https://data.adpage.io/auth/login) and go to **Klanten** (Clients).
{% endstep %}

{% step %}

### Open Klant koppelen

Click **Klant koppelen** (Link client) at the top right.
{% endstep %}

{% step %}

### Copy the code and send it

Under **Koppelcode** (Link code), click the code to copy it. Send it to the owner of your client's company.
{% endstep %}
{% endstepper %}

## Client: send the request

Only the owner of the company can link an agency.

{% stepper %}
{% step %}

### Open the settings of your company

Log in to [AdPage](https://data.adpage.io/auth/login), go to **Containers**, open the tab **Eigen containers** (Own containers) and click the settings icon behind your company.
{% endstep %}

{% step %}

### Paste the link code

In the **Bureau koppelen** (Link agency) section, paste the link code and click **Controleren** (Check).
{% endstep %}

{% step %}

### Check the agency and send the request

AdPage shows the name of the agency the code belongs to. Make sure this is the agency you work with, then click **Verzoek versturen** (Send request).
{% endstep %}
{% endstepper %}

The request stays open for 7 days. Until the agency answers, it shows as **Wacht op akkoord** (Waiting for approval). You can withdraw it with **Intrekken** (Withdraw).

## Agency: accept the request

You receive an email when a client sends a request. Go to **Klanten** › **Klant koppelen**, and under **Verzoeken van klanten** (Requests from clients) click **Accepteren** (Accept). From then on, the client is listed under **Klanten**.

## After linking

* All members of the agency can see and manage the client's containers in AdPage.
* Through the AI connection (Claude, ChatGPT), owners and admins of the agency get access to the client. This can take up to an hour. After that, disconnect and reconnect the AdPage connector in your AI tool.
* In the company settings, the owner sees which agencies the company is linked to.

## Link an agency or add a user?

* **Linking an agency** gives the agency access to your company, and your company appears as a client of the agency.
* **Adding a user** gives one person access to your company, for example a colleague. See [Client: Add a user to your company](/accountmanagement/account-and-users/client-add-a-user-to-your-company).

Not sure how companies, agencies and users relate? See [Account hierarchy](/accountmanagement/account-and-users/account-hierarchy).

## Unlinking an agency

To remove the link between your company and an agency, contact support at <support@adpage.io>.

## Troubleshooting

* **I don't see Klant koppelen or Koppelcode.** Only owners and admins of an agency see the link code.
* **I don't see Bureau koppelen.** Only the owner of a company can link an agency. Ask the owner, or ask AdPage support who the owner is.
* **"Geen bureau gevonden met deze koppelcode"** (No agency found with this link code). Check the code, or ask the agency to send it again.
* **"Er staat al een verzoek open"** (A request is already open). A request between this company and this agency is already waiting. Wait for the agency, or withdraw it and send a new one.
* **The request expired.** Send a new request with the same link code.


# Change your email address

Change the email address you sign in with, confirmed from your new inbox

Your email address is how you sign in to AdPage, so changing it takes one extra step: you confirm the new address before it becomes active. That way a typo can never lock you out, and nobody can move your account to an address that isn't theirs.

Your password stays the same.

{% stepper %}
{% step %}

### Open your settings

Log in to [AdPage](https://data.adpage.io/auth/login) and go to **Settings**.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2F0FuBYaNu7Y9s8OoeoESS%2Faccount-instellingen-gegevens-volledig-en.webp?alt=media" alt="AdPage Settings page with Account details, Language and Two-factor authentication"><figcaption><p>Settings: your account details are at the top.</p></figcaption></figure>
{% endstep %}

{% step %}

### Enter your new address

Under **Account details**, replace your email address. A **Change to …** button appears as soon as the new address is valid.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2F5RVdhxaBgI8XD3nPHBYq%2FArc%202026-09-14%2013.56.59.png?alt=media&amp;token=3301d6f2-e573-43b2-afad-8cfb625babb1" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Confirm it is you

Enter your current password, plus your 2FA code if two-factor authentication is switched on. Then click **Send confirmation link**.

Nothing has changed yet. You stay signed in, and you still sign in with your current address.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FlqzBzjSaJ32nExasvj63%2FArc%202026-09-14%2013.57.11.png?alt=media&amp;token=0bf3b468-97b3-48c7-9deb-b23b88c41b13" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Click the link in your new inbox

Two emails go out at this point: a confirmation link to your **new** address, and a notice to your **current** address with a link to stop the change. Only the confirmation link makes the change happen — if you ignore both emails, your address stays as it is.

Open the confirmation email on your new address and click the link. It is valid for 60 minutes.

If you are asked to sign in, use your **current** address and password — those are still the active ones until the change goes through.
{% endstep %}
{% endstepper %}

Your email address is updated the moment you click the link. From then on you sign in with the new address.

### If you did not request this

A notice also goes to your current address, with a **Stop the change** link. You do not need to be signed in to use it: click it and the request is cancelled.

{% hint style="warning" %}
Change your password as well. Someone was able to reach your account, and cancelling the request does not undo that. If you are not sure what happened, contact AdPage support.
{% endhint %}

### If something does not work

* **The link expired.** It is valid for 60 minutes. Request the change again from your settings.
* **No email arrived.** Check your spam folder, and check the address on the banner in your settings for a typo. If it is wrong, simply request the change again with the right address.
* **"This email address is already in use."** The address belongs to another AdPage account. Use a different one, or contact AdPage support.
* **You hit a limit.** A change can be requested five times per 24 hours, and once per minute.

Working with an agency? Your agency or AdPage support can update your email address for you. In that case there is no confirmation link — the change is applied directly.


# Setting up a new container

Use this guide after completing the initial AdPage setup. It covers creating and configuring one additional container.

{% stepper %}
{% step %}

### Create the container

Open AdPage and add a new container. Agency accounts can first select the client's company, then add the container there.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FPIPEAy6v9qGYqvQINqgh%2Fcontainer-nieuw-stap1-volledig-en.webp?alt=media" alt="Step 1 of 3 of the New container wizard with website domain field"><figcaption><p>Add an extra container.</p></figcaption></figure>

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FzAxTyb5kAQIv5h2H8nk9%2Fnew-container-step2-plan-en.webp?alt=media" alt="Step 2 of 3 of the New container wizard with the plan choice"><figcaption><p>Choose a plan for the new container. Free needs no credit card.</p></figcaption></figure>
{% endstep %}

{% step %}

### Connect the Google Tag Manager server container

Connect the AdPage container using your Google Tag Manager server container's base64 configuration code. This lets you configure tracking rules in that server container.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FqDMvtCV0koJkpt0XAOYG%2Fcontainer-instellingen-servercontainer-detail-en.webp?alt=media" alt="Server container (sGTM) section in the container settings"><figcaption><p>Paste the provisioning code of your Google Tag Manager server container.</p></figcaption></figure>

<details>

<summary>Retrieve the base64 configuration code manually</summary>

In Google Tag Manager, open the server container. Go to **Admin** → **Container settings**.

Click **Set up your tagging server**. Copy the displayed configuration code.

<figure><img src="broken://spaces/vuyv7mcuSvQb9yTkzfeA/files/mVGrEDTl84MBAbQBS5W9" alt="Google Tag Manager server container configuration code."><figcaption></figcaption></figure>

</details>
{% endstep %}

{% step %}

### Configure the tracking domain

Create a custom tagging server URL for this container. Use a subdomain of the website's root domain.

In your DNS provider, create the CNAME record shown during registration. Copy the displayed **Host** value. Set the record target to `projects.trytagging.com`.

{% hint style="info" %}
You can change the CNAME **Host** in the container settings. The target always remains `projects.trytagging.com`.
{% endhint %}

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2FZIdBd7RnEs1JuKYXh8fS%2Fcontainer-instellingen-domeinen-detail-en.webp?alt=media" alt="Domains and SSL section with DNS and SSL status"><figcaption><p>Domains and SSL: your subdomain with its DNS and SSL status.</p></figcaption></figure>
{% endstep %}

{% step %}

### Install the Tagging Pixel

Replace the website's standard Google Tag Manager snippet with the AdPage Tagging Pixel. The pixel connects the website to its Google Tag Manager web container.

{% hint style="warning" %}
Remove the standard Google Tag Manager snippet. Do not run it alongside the Tagging Pixel.
{% endhint %}

Enter the **Website URL** and **Google Tag Manager Web Container ID**. Generate the installation instructions for your platform.

AdPage provides installations for Shopify, WordPress, WooCommerce, Magento, and Lightspeed. Select **Custom CMS** to get the `<head>` and `<body>` snippets.

<figure><img src="https://1908438300-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fvuyv7mcuSvQb9yTkzfeA%2Fuploads%2F0HC556aonftq6IVVjARD%2Fcontainer-instellingen-taggingpixel-detail-en.webp?alt=media" alt="Tagging pixel section with platform choice and installation code"><figcaption><p>Choose your platform and copy the Tagging Pixel installation code.</p></figcaption></figure>

{% hint style="info" %}
Use **Copy the installation link** to share instructions with a website developer.
{% endhint %}
{% endstep %}

{% step %}

### Finish the setup

Open the server container dashboard after completing these steps. The container is ready for tracking-rule configuration.

You can defer the tracking domain and Tagging Pixel steps. Complete them later from the server container dashboard.
{% endstep %}
{% endstepper %}

### Next steps

Configure the tracking rules in the connected Google Tag Manager web and server containers.




---

[Next Page](https://docs.adpage.io/llms-full.txt/1)

