SlideRule

Add tracker to Post-purchase page

How to add SlideRule's GTM tracker code to your Shopify store's Post-purchase page.

Kevin McLaughlinKevin McLaughlin
July 28, 2025

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.

<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) {
      // TODO: remove this hack for upsell tracking
      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),
        },
        user_properties: {
          accepts_marketing: userProperties.accepts_marketing,
          email: userProperties.customer_email,
          first_name: userProperties.customer_first_name,
          has_account: userProperties.has_account,
          customer_id: userProperties.customer_id,
          last_name: userProperties.customer_last_name,
          name: `${userProperties.customer_first_name} ${userProperties.customer_last_name}`,
          has_account: userProperties.has_account,
          orders_count: userProperties.orders_count,
          total_spent: userProperties.total_spent,
        },
      });
      console.log('SlideRule Analytics: hack 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),
        },
        user_properties: {
          accepts_marketing: userProperties.accepts_marketing,
          email: userProperties.customer_email,
          first_name: userProperties.customer_first_name,
          has_account: userProperties.has_account,
          customer_id: userProperties.customer_id,
          last_name: userProperties.customer_last_name,
          name: `${userProperties.customer_first_name} ${userProperties.customer_last_name}`,
          has_account: userProperties.has_account,
          orders_count: userProperties.orders_count,
          total_spent: userProperties.total_spent,
        },
      });
    } 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),
        user_properties: {
          accepts_marketing: userProperties.accepts_marketing,
          email: userProperties.customer_email,
          first_name: userProperties.customer_first_name,
          has_account: userProperties.has_account,
          customer_id: userProperties.customer_id,
          last_name: userProperties.customer_last_name,
          name: `${userProperties.customer_first_name} ${userProperties.customer_last_name}`,
          has_account: userProperties.has_account,
          orders_count: userProperties.orders_count,
          total_spent: userProperties.total_spent,
        },
      };

      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,
      accepts_marketing: data.customer.acceptsMarketing,
      has_account: data.customer.hasAccount,
      orders_count: data.customer.ordersCount,
      total_spent: data.customer.totalSpent,
    };
  }

  // 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(/&amp;/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);
  }

  // END UTILS -----------------------------------------------------------------

  // Start main
  (function () {
    window.slideruleData = {
      version: 'v0.0.2',
      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>