Skip to docs navigation
On this page

Add SourceTrack to Shopify

Add one script to your store and connect your orders. Then you can see which ads, searches and AI referrals turn into paid orders.

You need: a SourceTrack account, and access to your Shopify Admin to edit your theme code.

WarningIntegration notice: Integrations offers a one-click Connect Store (OAuth) for Shopify. It sets up order tracking in your store for you. The manual steps below are the fallback if you do not use Connect Store, or if it reports that setup was incomplete. Connecting alone does not tie an order back to its marketing source. The cart snippet in Step 3 does that.

Step 1: Add the tracking script to your theme

Copy your snippet from Setup & Health in SourceTrack, under Install the script. It already includes your site key. It looks like this:

Liquidlayout/theme.liquid
<!-- Paste inside layout/theme.liquid before </head> -->
<script async src="https://api.srctk.com/tracker.min.js" data-site-key="YOUR_SITE_KEY"></script>
  1. In your Shopify Admin, go to Online Store → Themes.
  2. On your current theme, click the action dropdown (the three dots) and select Edit Code.
  3. Open the layout/theme.liquid file.
  4. Paste the tracking script directly before the closing </head> tag.
  5. Save theme.liquid. Shopify publishes the change to your live theme straight away.

Step 2: Connect your store

This sends your paid orders and refunds to SourceTrack.

  1. In SourceTrack, open Integrations, find the Shopify card and click Connect.
  2. Click Connect Store (OAuth) and enter your store address, like my-store.myshopify.com.
  3. Approve the connection in Shopify.

SourceTrack then shows whether setup finished. If it says setup is incomplete, disconnect and reconnect the store from the same card, or use Step 4.

Step 3: Add the cart snippet

This saves each visitor's ID on their cart, so SourceTrack can match an order to the visit that earned it. Without it, orders are recorded but show as unattributed. Paste this snippet into layout/theme.liquid, just before the closing </body> tag. It also saves the shopper's choice from Shopify's cookie banner. When a shopper says no to marketing, SourceTrack sends that order to none of your ad platforms.

HTMLlayout/theme.liquid, end of body
<script>
// SourceTrack: save the visitor ID, the shopper's Shopify consent choice and ad click IDs on the cart.
(function () {
  var CLICK_IDS = ["gclid","gbraid","wbraid","fbclid","msclkid","ttclid","li_fat_id","rdt_cid"];
  var root = (window.Shopify && window.Shopify.routes && window.Shopify.routes.root) || '/';
  var lastSent = null, timer = null;
  function lsGet(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } }
  function cookie(name) {
    var parts = document.cookie ? document.cookie.split('; ') : [];
    for (var i = 0; i < parts.length; i++) {
      var eq = parts[i].indexOf('=');
      if (parts[i].slice(0, eq) === name) { try { return decodeURIComponent(parts[i].slice(eq + 1)); } catch (e) { return null; } }
    }
    return null;
  }
  function decision(v) { return v === 'yes' || v === 'no' ? v : ''; }
  function collect() {
    var attrs = {};
    var visitorId = lsGet('st_aid') || window._st_aid || null;
    if (visitorId) attrs['st_aid'] = String(visitorId);
    var privacy = window.Shopify && window.Shopify.customerPrivacy;
    var consent = null, marketingAllowed = false;
    if (privacy) {
      try { consent = privacy.currentVisitorConsent(); } catch (e) {}
      try { marketingAllowed = privacy.marketingAllowed() === true; } catch (e) {}
    }
    attrs.__st_consent_marketing = decision(consent && consent.marketing);
    attrs.__st_consent_analytics = decision(consent && consent.analytics);
    attrs.__st_consent_sale_of_data = decision(consent && consent.sale_of_data);
    // Ad IDs only while Shopify allows marketing for this shopper; otherwise any saved earlier are cleared.
    var params = new URLSearchParams(window.location.search);
    var clickTs = Date.parse(lsGet('st_click_ts') || '');
    var storedFresh = clickTs > 0 && Date.now() - clickTs < 90 * 86400000;
    var fbclidFromUrl = false;
    for (var i = 0; i < CLICK_IDS.length; i++) {
      var v = '';
      if (marketingAllowed) {
        v = params.get(CLICK_IDS[i]) || '';
        if (v && CLICK_IDS[i] === 'fbclid') fbclidFromUrl = true;
        if (!v && storedFresh) v = lsGet('st_cid_' + CLICK_IDS[i]) || '';
      }
      attrs['__st_' + CLICK_IDS[i]] = v;
    }
    var fbc = marketingAllowed ? cookie('_fbc') : null;
    if (!fbc && attrs.__st_fbclid) fbc = 'fb.1.' + (fbclidFromUrl ? Date.now() : clickTs) + '.' + attrs.__st_fbclid;
    attrs.__st_fbc = fbc || '';
    attrs.__st_fbp = (marketingAllowed && cookie('_fbp')) || '';
    var ga = marketingAllowed ? (cookie('_ga') || '').split('.') : [];
    attrs.__st_ga_client_id = ga.length === 4 ? ga[2] + '.' + ga[3] : '';
    return attrs;
  }
  function send() {
    timer = null;
    var body = JSON.stringify({ attributes: collect() });
    if (body === lastSent) return;
    // Only a cart that already holds items: never create a cart just to carry these.
    fetch(root + 'cart.js', { credentials: 'same-origin' })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (cart) {
        if (!cart || !cart.item_count) return;
        return fetch(root + 'cart/update.js', {
          method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: body
        }).then(function (r) { if (r.ok) lastSent = body; });
      })
      .catch(function () {});
  }
  function schedule() { if (!timer) timer = setTimeout(send, 400); }
  try {
    new PerformanceObserver(function (list) {
      var entries = list.getEntries();
      for (var i = 0; i < entries.length; i++) {
        if (/cart[/](add|change|update|clear)/.test(String(entries[i].name))) { schedule(); return; }
      }
    }).observe({ type: 'resource' });
  } catch (e) {}
  document.addEventListener('visitorConsentCollected', schedule);
  function start() {
    schedule();
    setTimeout(schedule, 2000);
    setTimeout(schedule, 6000);
  }
  if (window.Shopify && typeof window.Shopify.loadFeatures === 'function') {
    window.Shopify.loadFeatures([{ name: 'consent-tracking-api', version: '0.1' }], function () { start(); });
  } else {
    start();
  }
})();
</script>

Step 4: Set up the order webhook by hand

Skip this step if Connect Store finished without a warning.

  1. In SourceTrack, open Integrations, open the Shopify card and copy the Shopify Webhook Listener URL.
  2. In your Shopify Admin, go to Settings → Notifications, scroll to Webhooks and click Create Webhook.
  3. Choose the event orders/paid, set the format to JSON, and paste the URL.
  4. Save the webhook. Copy the signing secret Shopify shows for your webhooks and paste it into the Shopify card in SourceTrack. Then click Save signing secret.

The signing secret lets SourceTrack reject any message that did not come from your store. You can also choose orders/create. SourceTrack then records only orders that are already paid.

Step 5 (optional): Record checkout starts

Shopify runs checkout in its own protected area, so your theme script does not run there. A custom pixel adds a checkout-started event.

  1. In your Shopify Admin, go to Settings → Customer events.
  2. Click Add custom pixel, name it SourceTrack Checkout, and click Add pixel.
  3. Paste the code below into the code editor. Replace YOUR_SITE_KEY with your site key.
  4. Click Save, then Connect.
JavaScriptShopify custom pixel
// In Shopify Admin > Settings > Customer events > Add custom pixel
analytics.subscribe('checkout_started', (event) => {
  const checkout = event.data?.checkout;
  fetch('https://api.srctk.com/api/track', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    keepalive: true,
    body: JSON.stringify({
      site_key: 'YOUR_SITE_KEY',
      event: 'checkout_started',
      properties: {
        shopify_source: 'web_pixels',
        currency: checkout?.currencyCode,
        checkout_total: checkout?.totalPrice?.amount ? Number(checkout.totalPrice.amount) : undefined,
        item_count: Array.isArray(checkout?.lineItems) ? checkout.lineItems.length : undefined
      }
    })
  });
});

Check that it worked

  1. Open your store in a new browser window and visit a page.
  2. In SourceTrack, open Setup & Health. Under Install the script, click Verify installation. You should see First event received.
  3. Place a real, low-value order. Orders made with Shopify's test gateway or test mode are ignored, so they do not show as revenue.
  4. In SourceTrack, open Integrations and the Shopify card. Under Recent webhook activity, your order should appear with the status success.

If it did not work

  • Orders show as unattributed: Check that the cart snippet in Step 3 and the tracking script in Step 1 are both in theme.liquid. Without the script, there is no visitor ID to save.
  • No orders appear: Check that you finished Step 2 or Step 4. Unpaid orders and test orders are not recorded.
  • Still nothing: See Troubleshooting.

Next step

Your Shopify setup is done. You can find more options in our Developer Portal.

Still stuck?

Email support@sourcetrack.ai with your site and what you have tried.

Start 28-day free trial
  • Google Ads
  • Meta
  • LinkedIn
  • Microsoft Ads
  • TikTok
  • Stripe
  • Shopify
  • HubSpot
  • GA4
  • Search Console
  • WooCommerce
  • Webflow
  • WordPress
  • Typeform
  • Calendly
  • Intercom
  • Zapier
Works with