Enhancing Shopify's Buy Button with UTM Parameters (Updated Version)

At some point the lifecycle hooks event method I wrote earlier to capture UTMs and pass into your checkout page stopped working. So here is an updated version. This method does not use the lifecycle events. Apparantly Shopify updated SDK stopped exposing event model and checkout URL in these events. If you find a smarter solution elsewhere, I'd be happy to link to it.

A while ago, I wrote a solution to pass UTM parameters in Shopify buy Button checkout from your landing page URL to capture traffic sources. This method utilized the Shopify lifecycle events to pass the parameters. This is an updated solution that utilizes Product Component Customization instead.

There are lots of discussions around manipulating Shopify button checkout URL. Some want to use it pass parameters for their local site, others to pass a parameter for a discount code, but perhaps the most sought after problem is how to pass UTM parameters to the the checkout page. It is from one of these discussions on Github about passing a discount code that I took this solution from.

It’s important to note that there is an open feature request on Git for adding line items with custom attributes to the Shopify Buy Button. The implementation of this feature could significantly simplify the customization of the button’s destination, akin to the capabilities available in the JS Buy SDK. I recommend subscribing to updates on this issue to stay informed.

Alright, lets dig into the solution.

But wait! before we start talking about the solution, I just want to put out a disclaimer:
This solution has been tested only when you want users to go straight to the checkout page (without modals and add to cart functionality in the button). For other scenarious, feel free to test the implementation and write in comments what you find 🙂

Lets really get started now by defining our objective 😉

Objective:

Our goal is to modify the Shopify Buy Button so that it not only facilitates the buying process but also retains valuable campaign tracking information through UTM parameters. This ensures that when a user proceeds to the checkout, the UTM parameters are appended to the URL, allowing for accurate tracking of user engagement and campaign effectiveness right through the purchase process.

Process Breakdown:

Lets first review what we’ll do step by step.

UTM Parameter Capture and Serialization

We first define a function that will be responsible to capture the UTM parameters from your landing page (much like in our previous solution) where your Buy Button is hosted. We’ll call this getUTMParameters.

What it does?
URL Parsing: This function uses the browser’s URL parsing capabilities to locate and store each UTM parameter present. It filters parameters to ensure only those that are UTM-related (i.e., those starting with “utm_”) are captured.

Serialization: Once captured, these parameters are serialized into a string that can be appended to URLs, preparing them to be included in the checkout URL.

Shopify Buy Button Initialization

You do not have to worry about this part. This is automatically done via the code you get for the buy button but I just add it here for context.

Script Injection: The script dynamically loads Shopify’s Buy Button SDK from their CDN, ensuring the latest version of the library is used.

Client Initialization: It initializes the Shopify Buy Button client with the store’s domain and an access token, setting up the necessary credentials for interactions with Shopify’s backend.

Store domain: Make sure that your domain URL is correctly added here. In most cases, your buy button contains a line of code with the domain set as your-domain.myshopify.com. This has 2 implications:

  1. The checkout URL where users are redirected on buy button click would be your-domain.myshopify.com/checkouts/
  2. In Google Analytics, you’ll have to set up a cross-domain tracking and add this subdomain in your property settings.

Product Component Customization

Component Creation: The script creates a product component using the createComponent method, which represents a purchasable item on the website.

Custom Button Destination: Traditionally, the buttonDestination property defines where the button leads (e.g., a cart or direct checkout). Here, it is overridden with a custom function that not only initiates checkout but also modifies the checkout URL.

Checkout Process Manipulation:
The custom function intercepts the default checkout process. Upon button click, it:

  1. Triggers a user event for analytics.
  2. Creates a checkout session using the Shopify API with the selected product variant and quantity.
  3. Modifies the resulting checkout URL by appending the serialized UTM parameters, ensuring that marketing data is retained.
  4. Redirects the user to this new URL in a new popup.

Now that we have the process laid out. Lets look at the code.

Lets Start with the UTM Function

   
    // Function to capture UTM parameters from the URL
    function getUTMParameters() {
        var params = {};
        var parser = document.createElement('a');
        parser.href = window.location.href;
        var query = parser.search.substring(1);
        var vars = query.split('&');
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split('=');
            if (pair[0].startsWith('utm_')) { // Ensure only UTM parameters are captured
                params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
            }
        }
        return params;
    }

    var utmParams = getUTMParameters();
    var serializedUTMParams = Object.keys(utmParams).map(function(key) {
        return key + '=' + utmParams[key];
    }).join('&');

Place this snippet between

(function () {

and

var scriptURL =

in your Shopify code. These are most likely lines 4 and 5 of your Shopify button code.

Shopify Buy Button Initialization

The scriptURL is where the Shopify Buy Button Initialization happens (#2 in the process descriibed above). You do not have to do much here – no customization required.

Product Component Customization

Find this line in your code
ShopifyBuy.UI.onReady(client).then(function (ui) {

This will be followed by the customization you’ve set for your product and might look like this

ui.createComponent('product', {
id: '4727244226645',
node: document.getElementById('product-component-1712464649781'),
moneyFormat: '%24%7B%7Bamount%7D%7D',
options: {
  "product": {
    "styles": {
        // removed style code for brevity
    },
    "buttonDestination": "checkout",
    "text": {
      "button": "Buy now"
    }
  },


The highlighted lines in the above code is what you have to identify. This is your product component. Note that there are 3 properties styles, buttonDestination and text. These can be in any order for your code but we’ll be making a key change to the buttonDestination property. A lot of code will now be added for magical things 🙂

Copy the following code and replace the current buttonDestination line completely

 

 "buttonDestination": function(that) {
                            that._userEvent('openCheckout');
                            that.props.tracker.track('Direct Checkout', {});
                            let checkoutWindow;
                            if (that.config.cart.popup) {
                                checkoutWindow = window.open('', 'checkout');
                            } else {
                                checkoutWindow = window;
                            }
                            const input = {
                                lineItems: [{
                                    variantId: that.selectedVariant.id,
                                    quantity: that.selectedQuantity,
                                }],
                            };

                            that.props.client.checkout.create(input).then((checkout) => {
                                let suffix = '&';
                                if (checkout.webUrl.indexOf('?') === -1) suffix = '?';
                                const checkoutUrl = `${checkout.webUrl}${suffix}${serializedUTMParams}`;
                                checkoutWindow.location = checkoutUrl;
                            });
                        },

If you read this code carefully, this is doing all that was described in the process above.

The product part of your final code will now look like this

                    "product": {
                        "styles": {
                           // style codes removed for brevity
                        },
                        "buttonDestination": function(that) {
                            that._userEvent('openCheckout');
                            that.props.tracker.track('Direct Checkout', {});
                            let checkoutWindow;
                            if (that.config.cart.popup) {
                                checkoutWindow = window.open('', 'checkout');
                            } else {
                                checkoutWindow = window;
                            }
                            const input = {
                                lineItems: [{
                                    variantId: that.selectedVariant.id,
                                    quantity: that.selectedQuantity,
                                }],
                            };

                            that.props.client.checkout.create(input).then((checkout) => {
                                let suffix = '&';
                                if (checkout.webUrl.indexOf('?') === -1) suffix = '?';
                                const checkoutUrl = `${checkout.webUrl}${suffix}${serializedUTMParams}`;
                                checkoutWindow.location = checkoutUrl;
                            });
                        },
                        
                        "text": {
                            "button": "Buy now"
                        }
                    }

And that should do the job for you.

Hard-coding UTM Parameters to Shopify Buy Button 

To hard code the parameters you could simply change the UTM params function on top. You do not need a function instead you just need to change the value of this variable to your UTM parameters

var serializedUTMParams

your code would look like this

<div id='product-component-1712464649781'></div>
<script type="text/javascript">
/*<![CDATA[*/
(function () {
// Hardcode your UTM parameters
var serializedUTMParams = "utm_source=unbounce&utm_medium=shopify-button&utm_campaign=button-testing&utm_content=harcoverbook&utm_term=test";

// Load the Shopify Buy Button script
var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';

Change the red highlighted portion to the UTMs you want.

Finally, note that your checkout page is set to open in a new tab currently.

Let us know if you hit any issues.

What happens if your landing page URL is different than your store URL?

We are now talking about cross-domain (if your landing page is on a different URL than your shopify store). If yes and you do not have cross domain tracking implemented, the page URL will show up as a referral in Google Analytics. Otherwise, it will tie back to the original traffic source from which the visit originated or direct/none.

So lets review what are the benefits of Tracking with UTM parameters

Enhanced User Interaction Data: Provides detailed insights into how users are interacting with the Buy Button specifically related to direct checkout actions.

Campaign Effectiveness:
Allows marketers to directly correlate marketing efforts with sales conversions, particularly in campaigns designed to encourage immediate purchases.

Behavioral Insights:
Helps understand user behavior patterns that bypass the traditional cart process, which could inform broader e-commerce strategy and website layout optimization.

0 Comments

    Leave a Reply