How to

Implement Retrack in Shopify

This page will guide you through the process of implementing script tracking for Retrack in Shopify. The implementation differs in some way compared to other platforms due to the limited access to Shopify's core functionality. Instead we rely on existing features available in the web interface.

Please be careful when implementing the tracking code. We don't take responsibility for any damage caused. Test the implementation thoroughly.

Saving the Retrack UUID

It's usually best to create a new redirect page to save the click UUID, but it Shopify we'll instead listen for the click parameter on all pages. Let's add the code to handle this.

  1. Click on Sales channels in the menu and select Online Store.
  2. Click on Themes if it's not already selected.
  3. Find your active theme and click on Customize.
  4. Switch to the code editor by clicking on the three dots in the header and then Edit code.
    Events
  5. Find the theme.liquid file and click on it.
  6. Scoll down and find the closing </body> and paste the following code above it:
    <script type="text/javascript">
        const url = new URL(window.location.href);
        const urlParams = new URLSearchParams(url.search);
    
        if (urlParams.has('utm_source') && urlParams.get('utm_medium') == 'retrack' && urlParams.has('click')) {
            const currentDate = new Date(Date.now());
            const retrackCookieExpires = currentDate.setDate(currentDate.getDate() + 10);
            const retrackCookie = `retrack_click=${urlParams.get('click')};expires=${retrackCookieExpires};path=/;secure;samesite=lax`;
    
            document.cookie = retrackCookie;
        }
    </script>
    
  7. The result should look something like this:
    Events
  8. Save the file and exit the code editor.

Tracking Purchases

The actual tracking of the purchases takes place in the checkout, and only for visitors that has the cookie we saved above. Let's add the code to the built in script editor that Shopify provides.

  1. Navigate to the store settings and click on Checkout in the menu.
  2. Scroll down to Order status page where you will find an input field for Additional scripts.
    Events
  3. Append the following code and don't forget to replace the {eventUUID} with real values from your own program:
    <script type="text/javascript">
        // Fetch all cookies
        const cookies = document.cookie.split(';')
            .map(cookie => cookie.split('='))
            .reduce((a, b) => {
                return {
                    ...a,
                    [b[0].trim()]: b[1],
                };
            }, {})
    
        // Load tracking script for Retrack if the click cookie exists
        if (cookies.retrack_click) {
            !function(){"re" in window||(window.re=function(){window.re.q.push(arguments)},window.re.q=[]);var e=document.createElement("script");e.src="https://retrack-app.com/track/v2/script",e.async=!0;var n=document.scripts[0];n.parentElement.insertBefore(e,n.nextSibling)}();
        
            // Object. Required
            re('addTransaction', {
                // UUID. Base event for the transaction. Can be overridden on product level using addProduct
                event: '{eventUUID}',
        
                // UUID. Replace with actual click UUID from cookie: Example: ce5fc4b5-0ddc-4176-ba64-44c3423bbae1
                click: cookies.retrack_click,
        
                // String. Replace with actual order number. Example: test123
                orderNumber: '{{ order.id }}',
        
                // Numeric. Replace with actual order sum in minor units (ie cents), excluding VAT. Example: 8000 (80 SEK)
                orderSum: {{ order.line_items_subtotal_price }},
        
                // Numeric. Replace with actual VAT sum in minor units (ie cents). Example: 2000 (20 SEK)
                vatSum: {{ order.tax_price }},
        
                // String. Replace with actual currency. Example: SEK
                currency: 'SEK',
        
                // String. Optional (remove or leave empty if not applicable). Replace with actual voucher / coupon code. Comma separated if there are multiple codes.
                voucher: '',
        
                // String. Optional (remove or leave empty if not applicable). Applicable if the order has a general discount. Use minor units (ie cents)
                discountSum: {discountSum}
            });
                    
            {% for item in order.line_items %}
                // Object. Optional, but preferred. Required with multiple events in the same transaction
                re('addProduct', {
                    // UUID. Optional. This will override the base event for the transaction. Useful for orders with products belonging to multiple events
                    event: '{eventUUID}',
        
                    // String.Product reference. Could be SKU, ISBN or any other ID. Example: test123
                    reference: '{{ item.variant.sku }}',
        
                    // String. Product name. Example: Adidas Superstar
                    name: '{{ item.title }}',
        
                    // Numeric. Num products. Example: 1
                    quantity: {{ item.quantity }},
        
                    // Numeric. Price per product in minor units (ie cents), excluding VAT. Example: 8000 (80 SEK)
                    price: {{ item.price }},
        
                    // Numeric. VAT amount per product in minor units (ie cents). Example: 2000 (20 SEK)
                    vat: {{ item.tax_line.rate|default: 0 }}
                });
            {% endfor %}
                
            re('send');
        }
    </script>
    
  4. It should look something like this after:
    Events

Optional - track products to different events

The above implementation will track all purchases to one single event, which means that all products will generate the same commission. That's usually the wanted behavior, but sometimes different products should generate different commissions. Retrack has support for this via multiple events.

Your account manager will create the events which will then be visible in the portal. The script generator will generate a different script for each event, from which you will also find the UUID to be added to the tracking script.
Events One shopping cart can contain multiple products that might be tracked to different events. The tracking code needs to determine which products should be tracked to which event. There are at least two easy ways to do this in Shopify - by using 1) tagging system, or 1) collection system. Here's an example using tags where we have tagged some products with slow-movers. Just replace the {eventUUID} and {eventUUID2} with the real UUID from your script generator.

re('addProduct', {
    {% assign product_tags_string = product.tags | join: \' \' %}
    event: '{% if product_tags_string contains 'slow-movers' %}{eventUUID2}{% else %}{eventUUID}{% endif %}'
    ...
}

Done

That's it! You have now implemented tracking for Retrack. We would now like to test the implementation before it goes live. Reach out to us with testing instructions.