Add tracker to Post-purchase page
2min
To install Google Tag Manager and track purchases correctly if you use upsells you need to add the below tracking code to the Post-purchase page.
Post-purchase page tracking code
Make sure to replace GTM-XXXXX with your Google Tag Manager contianer id.
HTML
|
<script name="sliderule-tracking" data-ot-ignore> var upsellCount = 0; // UTILS ----------------------------------------------------------------- // Function called after original order is placed, pre upsell. function onCheckout(initialOrder, shopifyObject) { var postPurchaseEvent = shopifyObject.wasPostPurchasePageSeen ? "refresh_post_purchase" : "purchase"; pushSlideruleData( initialOrder, initialOrder.lineItems, false, null, shopifyObject, postPurchaseEvent ); } // Function called when upsell is taken. Seperate the new/upsell // items from the items in the initial order and then send a purchase event // for just the new items. function onCheckoutAmended(upsellOrder, initialOrder, shopifyObject) { // identify which items were added to the initial order, if any. upsellCount++; // The line item id is unique for order items, even if the items contained are the same. // We can use this to seperate out items from the initial order from the upsell. var initialItemIds = initialOrder.lineItems.map(function (line) { return line.id; }); var addedItems = upsellOrder.lineItems.filter(function (line) { return initialItemIds.indexOf(line.id) < 0; }); // if no new items were added skip tracking var postPurchaseEvent = addedItems.length === 0 ? "refresh_post_purchase" : "purchase"; pushSlideruleData( upsellOrder, addedItems, true, initialOrder, shopifyObject, postPurchaseEvent ); } function pushSlideruleData( order, addedItems, isUpsell, initialOrder, shopifyObject, postPurchaseEvent ) { window.slideruleData.postPurchaseEvent = postPurchaseEvent; var userProperties = getUserProperties(order); var orderData = getOrderData( order, isUpsell, initialOrder, addedItems, shopifyObject ); if (isUpsell) { window.dataLayer.push({ event: "purchase", ecommerce: { is_upsell: isUpsell, ecommerce_event: true, fired_from: "SlideRule Analytics", upsell_count: upsellCount, transaction_id: orderData.id, order_number: orderData.number, customer_id: userProperties.customer_id, currency: order.currency, shipping: orderData.shipping, value: orderData.revenue, tax: orderData.tax, items: getLineItems(addedItems), }, }); console.log("SlideRule Analytics: track:", { event: "purchase", ecommerce: { is_upsell: isUpsell, ecommerce_event: true, fired_from: "SlideRule Analytics", upsell_count: upsellCount, transaction_id: orderData.id, order_number: orderData.number, customer_id: userProperties.customer_id, currency: order.currency, shipping: orderData.shipping, value: orderData.revenue, tax: orderData.tax, items: getLineItems(addedItems), }, }); } else { window.slideruleData.orderInformation = { is_upsell: isUpsell, upsell_count: upsellCount, transaction_id: orderData.id, order_number: orderData.number, customer_id: userProperties.customer_id, currency: order.currency, shipping: orderData.shipping, value: orderData.revenue, tax: orderData.tax, items: getLineItems(addedItems), }; window.slideruleData.customer = { id: userProperties.customer_id, email: userProperties.customer_email, firstName: userProperties.customer_first_name, lastName: userProperties.customer_last_name, }; } } // Returns a user properties object function getUserProperties(data) { return { customer_id: data.customer.id.toString(), customer_email: data.customer.email, customer_first_name: data.customer.firstName, customer_last_name: data.customer.lastName, }; } // Gets line items in purchase function getLineItems(lineItems) { return lineItems.map(function (item) { return { item_id: item.variant.id.toString(), item_name: item.title.replace(/&/g, "&"), price: item.price, quantity: item.quantity, }; }); } function getOrderData( order, isUpsell, initialOrder, addedItems, shopifyObject ) { var revenue = isUpsell ? getAdditionalRevenue(order, initialOrder) : order.totalPrice; var subtotal = isUpsell ? getAdditionalSubtotal(order, initialOrder) : order.subtotalPrice; try { affiliation = new URL(shopifyObject.pageUrl).hostname; } catch (e) { affiliation = ""; } return { affiliation: affiliation, // This is the longer order id that shows in the url on an order page id: getOrderId(order.id, isUpsell).toString(), // This should be the #1240 that shows in order page. number: order.number.toString(), // This is total discount. Dollar value, not percentage // On the first order we can look at the discounts object. On upsells, we can't. // This needs to be a string. discount_amount: getDiscountAmount(order, isUpsell, addedItems), // We can't determine shipping & tax. For the time being put the difference between subtotal and rev in tax shipping: 0, tax: (parseFloat(revenue) - parseFloat(subtotal)).toString(), revenue: revenue, sub_total: subtotal, }; } function getDiscountAmount(shopifyOrder, isUpsell, addedItems) { if ( shopifyOrder.discounts === null || typeof shopifyOrder.discounts === "undefined" ) return "0"; if (shopifyOrder.discounts.length === 0) return "0"; // If this isn't an upsell we can look at the discounts object. if (!isUpsell) { // Collect all the discounts on the first order. return shopifyOrder.discounts .reduce(function (acc, discount) { return (acc += parseFloat(discount.amount)); }, 0) .toFixed(2) .toString(); // If this an upsell we have to look at the line item discounts // The discount block provided doesn't only applies to the first order. } else { return addedItems .reduce(function (acc, addedItem) { return (acc += parseFloat(addedItem.lineLevelTotalDiscount)); }, 0) .toFixed(2) .toString(); } } function getOrderId(orderId, isUpsell) { return isUpsell ? orderId.toString() + "-US" + upsellCount.toString() : orderId; } function getAdditionalRevenue(newOrder, initialOrder) { return ( parseFloat(newOrder.totalPrice) - parseFloat(initialOrder.totalPrice) ).toFixed(2); } function getAdditionalSubtotal(newOrder, initialOrder) { return ( parseFloat(newOrder.subtotalPrice) - parseFloat(initialOrder.subtotalPrice) ).toFixed(2); } function test() { onCheckoutAmended(newOrder, initialOrder); } // END UTILS ----------------------------------------------------------------- // Start main (function () { window.slideruleData = { version: "v0.0.1", referralExclusion: "/(paypal|visa|MasterCard|clicksafe|arcot\\.com|geschuetzteinkaufen|checkout\\.shopify\\.com|checkout\\.rechargeapps\\.com|portal\\.afterpay\\.com|payfort)/", googleSignals: true, anonymizeIp: true, productClicks: true, persistentUserId: true, hideBranding: false, ecommerce: { currencyCode: window.Shopify.shop.currency, impressions: [], }, pageType: "post-purchase", destinations: { google_tag_manager: { containerIds: ["GTM-XXXXX"], }, }, cookieUpdate: true, }; // EVENT HOOKS ----------------------------------------------------------- onCheckout(window.Shopify.order, window.Shopify); Shopify.on("CheckoutAmended", function (newOrder, initialOrder) { onCheckoutAmended(newOrder, initialOrder, window.Shopify); }); // END EVENT HOOKS ------------------------------------------------------- try { module.exports = exports = { onCheckoutAmended: onCheckoutAmended, onCheckout: onCheckout, resetUpsellCount: function () { upsellCount = 0; }, }; } catch (e) {} })(); </script> <script async type="text/javascript" src="https://grow.slideruleanalytics.com/eluredils-g.js" ></script>

Updated 24 Apr 2023
Did this page help you?
Yes
No