> For the complete documentation index, see [llms.txt](https://docs.adpage.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.adpage.io/documentation/documentation-nl/integraties-websites/shopify/adpage-installeren-in-een-shopify-markets-winkel.md).

# AdPage installeren in een Shopify Markets-winkel

Voor een Shopify Markets-winkel is een andere AdPage-configuratie nodig: elke markt krijgt een eigen GTM-container en taggingdomein, die je in de themacode selecteert in plaats van in de AdPage-app.

Met Shopify Markets kun je vanuit één Shopify-winkel in meerdere landen of regio’s verkopen, met voor elke markt een eigen domein. Twee dingen werken niet op de gebruikelijke manier. De Shopify-app van AdPage kan geen verschillende instellingen per domein opslaan, en Shopify laat je maar één orderwebhook voor de hele winkel maken. Dit artikel behandelt alleen de stappen die afwijken van de standaardimplementatie.

### Voordat je begint

Dupliceer eerst je live thema (Online winkel → Thema’s → Acties (…) → Dupliceren), zodat je zo nodig kunt terugzetten.

Verzamel voor elke markt de volgende waarden:

| Tijdelijke aanduiding  | Wat je moet invullen                                                               | Voorbeeld                                   |
| ---------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------- |
| \[LANGUAGE CODE]       | De taalcode van de markt, zoals Shopify die teruggeeft in request.locale.iso\_code | de                                          |
| \[SERVER URL]          | De tagging-URL van de markt, inclusief https\://                                   | <https://tagging.example.de>                |
| \[SERVER DOMAIN]       | Hetzelfde taggingdomein, zonder https\://                                          | tagging.example.de                          |
| \[LOADER ID]           | De aangepaste loader-ID, als de container er een gebruikt                          | Laat leeg ('') als deze niet wordt gebruikt |
| \[GTM-ID]              | De GTM-webcontainer-ID van de markt                                                | GTM-ABC1234                                 |
| \[GTM-ID without GTM-] | Dezelfde ID zonder het voorvoegsel GTM-                                            | ABC1234                                     |
| \[STORE DOMAIN]        | Het winkeldomein van de markt                                                      | example.de                                  |

De themacode selecteert de container op basis van de taalcode. Daarom moet elke markt een andere taal gebruiken.

### Stap 1: Het Cookie Keeper-script toevoegen

Ga naar Online winkel → Thema’s → Acties (…) → Code bewerken en open theme.liquid. Plak het onderstaande script in de sectie \<head>, boven de Google Tag Manager-code.

Het script slaat een bezoekers-ID op in de cookie \_taggingmk en bewaart een back-up in localStorage, zodat de ID wordt hersteld als de cookie verdwijnt.

```html
<script type="text/javascript">
(function() {
    'use strict';
    
    // UUID v4 genereren (compatibele methode)
    function mkTagging_generateUUID() {
        // Terugvaloptie voor oudere browsers zonder 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 {
            // Minder veilige terugvaloptie voor zeer oude 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);
            });
        }
    }
    
    // Cookiewaarde ophalen op naam
    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;
    }
    
    // Cookie instellen met vervaldatum
    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();
        }
        // Zowel path als SameSite instellen voor betere compatibiliteit
        document.cookie = name + "=" + value + expires + "; path=/; SameSite=Lax";
    }
    
    // Veilige wrapper voor localStorage
    function mkTagging_getLocalStorage(key) {
        try {
            if (typeof Storage !== 'undefined' && window.localStorage) {
                return localStorage.getItem(key);
            }
        } catch (e) {
            // localStorage is mogelijk geblokkeerd of niet beschikbaar
            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 is mogelijk geblokkeerd of niet beschikbaar
            console.log('localStorage not available:', e);
        }
        return false;
    }
    
    // Hoofdfunctie voor initialisatie
    function mkTagging_initVisitorId() {
        var cookieName = '_taggingmk';
        var storageKey = '_taggingmk_backup';
        var visitorId = null;
        
        // 1. Controleren of de cookie bestaat
        visitorId = mkTagging_getCookie(cookieName);
        
        // 2. Als er geen cookie is, de reservekopie in localStorage controleren
        if (!visitorId) {
            visitorId = mkTagging_getLocalStorage(storageKey);
            
            // Als de ID in localStorage is gevonden, maar niet in de cookie, de cookie herstellen
            if (visitorId) {
                mkTagging_setCookie(cookieName, visitorId, 365);
                console.log('MK Tagging: Visitor ID restored from localStorage:', visitorId);
            }
        }
        
        // 3. Als er nog steeds geen ID is, een nieuwe genereren
        if (!visitorId) {
            visitorId = mkTagging_generateUUID();
            mkTagging_setCookie(cookieName, visitorId, 365);
            console.log('MK Tagging: New visitor ID generated:', visitorId);
        }
        
        // 4. Altijd synchroniseren met localStorage als reservekopie (indien beschikbaar)
        if (mkTagging_setLocalStorage(storageKey, visitorId)) {
            console.log('MK Tagging: Visitor ID backed up to localStorage');
        }
        
        // De bezoekers-ID retourneren voor eventueel gebruik
        return visitorId;
    }
    
    // Uitvoeren zodra de DOM gereed is, of direct als deze al is geladen
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', mkTagging_initVisitorId);
    } else {
        // DOM is al geladen
        mkTagging_initVisitorId();
    }
    
    // Maak een object met een eigen naamruimte voor alle functionaliteit die beschikbaar wordt gesteld
    window.mkTagging = window.mkTagging || {};
    window.mkTagging.getVisitorId = function() {
        return mkTagging_getCookie('_taggingmk') || mkTagging_getLocalStorage('_taggingmk_backup');
    };
    
})();
</script>
```

### Stap 2: Voeg de GTM-code voor de head toe

Plak de onderstaande code direct na het Cookie Keeper-script, nog steeds in de sectie \<head>. De code laadt voor elke markt de juiste GTM-container via het tagdomein van die markt. De code geeft ook toestemmingsupdates van je cookiebanner door aan de Customer Privacy API van Shopify.

Vervang \[LANGUAGE CODE], \[GTM-ID], \[SERVER URL] en \[LOADER ID] voor elke markt. Het voorbeeld bevat drie markten: voeg een when-blok (vier regels) toe of verwijder er een om het aantal markten te laten overeenkomen.

```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",
        };

        // Wacht tot de toestemming is ingesteld
        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>
```

### Stap 3: De body-sectie bijwerken

Zoek in hetzelfde bestand theme.liquid de GTM-code direct na de openingstag \<body> en vervang deze door de onderstaande code. Hiermee wordt de noscript-fallback toegevoegd en wordt het AdPage Shopify-dataLayerscript geladen vanaf het tagdomein van de markt.

Vervang \[LANGUAGE CODE], \[GTM-ID] en \[SERVER URL] door dezelfde waarden als in stap 2. Voeg een when-blok (drie regels) toe of verwijder er een, zodat dit overeenkomt met het aantal markten.

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

### Stap 4: De pixel voor klantgebeurtenissen toevoegen

Ga naar Instellingen → Klantgebeurtenissen → Aangepaste pixel toevoegen en maak een nieuwe pixel met de onderstaande code. Deze pixel houdt gebeurtenissen bij tijdens het afrekenen, waar de themacode niet wordt uitgevoerd.

Vervang \[SERVER DOMAIN], \[STORE DOMAIN], \[GTM-ID] en \[GTM-ID without GTM-]. Opmerking: gebruik voor \[SERVER DOMAIN] geen https\://, want de code voegt dit zelf toe. Vul bovenaan bij apShopifyConfig je hoofdmarkt in. Voeg een if-blok toe of verwijder er een, afhankelijk van het aantal markten.

Als het ene winkeldomein het andere bevat (bijvoorbeeld example.com en shop.example.com), plaats je het langste domein eerst.

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

Sla de pixel op en klik op Verbinden om deze te activeren.

### Stap 5: De webhook en de RegEx Table-variabele instellen

Shopify staat niet toe dat je per marktdomein een aparte handmatige webhook maakt. Maak in de Shopify-backend één webhook voor /order\_created.

Daardoor ontvangen de servercontainer en Google Tag Manager elke webhook van één domein, ook als de bestellingen op verschillende marktdomeinen zijn geplaatst.

Baseer je RegEx Table-variabele in Google Tag Manager niet op marketing.hostname, zoals je bij een standaard Shopify-winkel zou doen. Gebruik in plaats daarvan parsed\_data.order\_status\_url als invoer. Deze URL bevat het domein van de markt waarop de bestelling is geplaatst.

De invoer is nu een volledige URL in plaats van een hostnaam. Als je RegEx Table-patronen exact overeenkomen met hostnamen, schakel je onder Geavanceerde instellingen de optie Alleen volledige overeenkomsten uit of pas je de patronen aan (bijvoorbeeld `.*example\.de.*`).

### Stap 6: De implementatie controleren

Controleer het volgende op elk marktdomein:

* Browserconsole: geen JavaScript-fouten.
* Cookies: de cookie \_taggingmk wordt aangemaakt.
* Tabblad Netwerk: verzoeken gaan naar het taggingdomein van die markt.
* GTM-preview: na een testbestelling retourneert de RegEx Table-variabele de waarde voor de markt waarin de bestelling is geplaatst.

### Stap 7: verwijder de AdPage-app

Doe dit alleen nadat stap 6 bevestigt dat alle tracking met de nieuwe implementatie werkt.

1. Ga naar Apps → AdPage.
2. Klik op App verwijderen of App uitschakelen.
3. Bevestig.

De app is niet langer nodig, omdat tracking nu volledig via de server-side-implementatie verloopt. Is de AdPage-app niet geïnstalleerd? Sla deze stap dan over.


---

# 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
If you need additional information that is not directly available in this page, you can query the documentation 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/documentation/documentation-nl/integraties-websites/shopify/adpage-installeren-in-een-shopify-markets-winkel.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.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
