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.
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:
<!-- Paste inside layout/theme.liquid before </head> -->
<script async src="https://api.srctk.com/tracker.min.js" data-site-key="YOUR_SITE_KEY"></script>- In your Shopify Admin, go to Online Store → Themes.
- On your current theme, click the action dropdown (the three dots) and select Edit Code.
- Open the
layout/theme.liquidfile. - Paste the tracking script directly before the closing
</head>tag. - 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.
- In SourceTrack, open Integrations, find the Shopify card and click Connect.
- Click Connect Store (OAuth) and enter your store address, like
my-store.myshopify.com. - 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.
<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.
- In SourceTrack, open Integrations, open the Shopify card and copy the Shopify Webhook Listener URL.
- In your Shopify Admin, go to Settings → Notifications, scroll to Webhooks and click Create Webhook.
- Choose the event
orders/paid, set the format to JSON, and paste the URL. - 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.
- In your Shopify Admin, go to Settings → Customer events.
- Click Add custom pixel, name it
SourceTrack Checkout, and click Add pixel. - Paste the code below into the code editor. Replace
YOUR_SITE_KEYwith your site key. - Click Save, then Connect.
// 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
- Open your store in a new browser window and visit a page.
- In SourceTrack, open Setup & Health. Under Install the script, click Verify installation. You should see First event received.
- 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.
- 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.