An Easy Guide to Enhanced Ecommerce Analytics with Google Tag Manager

Ah, analytics.

Beacons of light in the dark. Signals among the noise!

From online stores to startups, we all need them.

And we all say we've got them covered:

"Of course we're tracking metrics & KPIs!"

But are we, really?

See, the bittersweet beauty of analytics is that you can always dive deeper.

But the further you go, the more complex it gets. To not lose your way, you'll need the right tools.

In this post, we're going to explore two such tools. More specifically, we'll see how to leverage Google Analytics' Enhanced Ecommerce via Google Tag Manager (GTM).

This wouldn't have been possible without the help from our friend Nicolas at Deux Huit Huit—the agency responsible for one of the cleanest Snipcart customizations ever. He was kind enough to send over code snippets and details on how his team uses Snipcart + GTM + Google Analytics (GA) Enhanced Ecommerce to provide better analytics for their clients.

This short Google Tag Manager guide aims at extending Snipcart's analytics capabilities. But the integration logic you'll see here can easily be applied to any other application.

And hopefully, the resources we'll share will also help.

What's Google Tag Manager again?

intro-google-tag-manager-guide

Launched in 2012, Google Tag Manager is a free product catering to digital marketers' analytics needs. It allows webmasters to centralize tag management—often JavaScript tracking snippets—within a single interface. Of course, GTM plays well with other Google products, such as Google Analytics Enhanced Ecommerce, which we'll discuss in this post. It also supports 3rd-party vendor tags and custom tags.

The first important thing GTM does is to consolidate all of your tracking tags. PPC/display/social campaigns, re-targeting efforts, on-site behavior & events... they all end up in one Google Tag Manager container. Selective triggers and performance optimization are built-in to make sure firing all these tags won't mess with your site's UX.

The second, crucial thing GTM does is to allow non-technical, marketing-oriented folks to add, remove or modify tracking tags in an easy-to-use interface. And that's key. It extracts tracking analytics from the website's code, making it possible for marketing people to handle their business without messing with developers'. It's a smart separation we can appreciate, being fans of decoupling stuff at Snipcart.

Want to learn more about how Google Tag Manager works? Start here or here. And for all things GTM & digital analytics, we recommend Simo Ahava's blog. Kickass content.

And how does Google Analytics Enhanced Ecommerce fit in with GTM?

google-analytics-enhanced-ecommerce-example

The benefits we just listed are why an agency like Deux Huit Huit uses GTM as a messaging layer for all analytics-related systems. And since they chose Snipcart for many e-commerce projects, they decided to integrate it into GTM using our JavaScript API. In Nicolas' own words:

It's pretty easy to create a reusable mapping with Snipcart, using the JavaScript framework of your choice, or even with plain JS.

See, Snipcart, like many e-commerce solutions, offers an out-of-the-box integration with GA Ecommerce Tracking. But for developers & digital agencies, the metrics available through this simple module can be too high-level. That's where GA's Enhanced Ecommerce plugin comes into play.

Simply put, Google Analytics' Enhanced Ecommerce enables more granular tracking of the shopping experience. It allows merchants to fine-tune their e-commerce operation with more relevant, event-driven data.

So, in this case, it's what's used to pass data from GTM to Google Analytics.

Integrated with Snipcart, this could allow us to answer questions like:

  • When and where are items most added to cart during a visit?
  • Which pages generate the most completed cart checkouts?
  • What's the checkout step with the highest rate of cart drop off?
  • Which products are bought more often? Which are dropped more often?
  • Which of my domains is performing better?

You can then use these insights to experiment with discount scenarios, shipping fees, email promotions, site architecture, on-site messaging, etc.

Now, let's see how to set up this whole thing!

Google Tag Manager tutorial for Snipcart & Enhanced Ecommerce

google-tag-manager-tutorial-enhanced-ecommerce

1. Setting up appropriate events on your site

The first thing we'll need to do here is to hook into Snipcart's events. To help you do so, here's basic boilerplate code using jQuery:

// file: snipcart-events.js
(function ($, Snipcart) {
    
    var ready = function () {
        // Snipcart is ready
        Snipcart.execute('bind', 'item.added', itemAddedEvent);
        Snipcart.execute('bind', 'item.removed', itemRemovedEvent);
        Snipcart.execute('bind', 'order.completed', orderCompleted);
        Snipcart.execute('bind', 'cart.opened', cartOpenedEvent);
        Snipcart.execute('bind', 'cart.closed', cartClosedEvent);
        Snipcart.execute('bind', 'page.change', pageChanged);
    };
    
    var init = function () {
        // Register the ready event
        Snipcart.execute('bind', 'app.ready', ready);
    };
    
    // Hook on jQuery's DOM Loaded event
    $(init);
    
})(window.jQuery, window.Snipcart); // Assuming jQuery and Snipcart files are loaded before this file

The only things missing in this boilerplate are the events handlers. We'd advise always creating abstractions between systems. This way, if the third party code changes, you'd only need to adapt the "glue" code in one place. Following this principle, we'd end up with something like this:

// file: snipcart-events.js
(function ($, Snipcart) {
    
    var itemAddedEvent = function (item) {
        App.notify('snipcart.itemAdded', {
            item: item
        });
    };
    
    var itemRemovedEvent = function (item) {
        App.notify('snipcart.itemRemoved', {
            item: item
        });
    };
    
    var orderCompleted = function (order) {
        App.notify('snipcart.completed', {
            order: order,
            items: Snipcart.api.items.all()
        });
    };
    
    var cartOpenedEvent = function () {
        App.notify('snipcart.open', {
            items: Snipcart.api.items.all()
        });
    };
    
    var cartClosedEvent = function () {
        App.notify('snipcart.close', {
            items: Snipcart.api.items.all()
        });
    };
    
    var pageChanged = function (page) {
        App.notify('snipcart.pageChanged', {
            page: page,
            items: Snipcart.api.items.all()
        });
    };
    
    // ... plus the earlier code
    
})(window.jQuery, window.Snipcart); // Assuming jQuery and Snipcart files are loaded before this file

A keen eye will see that the handles only pass Snipcart's messages into the ones used in your system. For this Google Tag Manager example, a simple—and totally invented—App.notify() function is used to pass Snipcart information in your standardized message bus.

2. Implementing Enhanced Ecommerce with the Google Tag Manager Data Layer (dataLayer.push())

After abstracting Snipcart implementation details and proxying these messages into our own, the only thing left to do is to implement the handlers that will communicate with GTM. What's nice about the separation demonstrated earlier is that the implementation is hot-pluggable, i.e. each of the two files won't make the app crash in the presence of the other file.

2.1 Adding a function transforming Snipcart's object into GA product data

Product data is the Enhanced Ecommerce schema provided by Google Analytics in our case. So if we want to send events to GA, we'll have to use this format. Luckily, it's just a matter of selecting a few Snipcart item properties:

// file: snipcart-gtm.js
(function ($) {

    var createProductsFromItems = function (items) {
        return items.map(function (item) {
            return {
                name: item.name,
                description: item.description,
                id: item.id,
                price: item.price,
                brand: item.brand,
                category: item.category,
                quantity: item.quantity
            };
        });
    };

})(window.jQuery);

2.2 Creating events handlers

Once we have our conversion function in place, it's easy to just call GTM. Here we'd assume these methods would be registered into your app's messaging system.

// file: snipcart-gtm.js
(function ($) {

    var createProductsFromItems = ...;

    var onItemAdded = function (item) {
        dataLayer.push({
            event: 'ecom',
            eventCategory: 'addToCart',
            eventLabel: item.name,
            eventValue: item.price,
            options: {},
            ecommerce: {
                currencyCode: 'CAD',
                add: {
                    products: createProductsFromItems([data.item])
                }
            }
        });
    };

    var onItemRemoved = function (item) {
        dataLayer.push({
            event: 'ecom',
            eventCategory: 'removeFromCart',
            eventLabel: item.name,
            eventValue: item.price,
            options: {},
            ecommerce: {
                currencyCode: 'CAD',
                remove: {
                    products: createProductsFromItems([item])
                }
            }
        });
    };

    var onOrderCompleted = function (order, items) {
        dataLayer.push({
            event: 'ecom',
            eventCategory: 'VPV',
            eventAction: 'order-completed',
            options: {},
            ecommerce: {
                currencyCode: order.currency,
                purchase: {
                    actionField: {
                        id: order.token,
                        affiliation: 'Website',
                        revenue: order.total,
                        tax: _.reduce(order.taxes, function (memo, tax) {
                            return memo + tax.amount;
                        }, 0),
                        shipping: 0,
                        invoiceNumber: order.invoiceNumber
                    },
                    products: createProductsFromItems(items),
                    userId: order.userId
                }
            }
        });
    };

    var onPageChanged = function (page, items) {
        dataLayer.push({
            event: 'ecom',
            eventCategory: 'VPV',
            eventAction: page,
            options: {},
            ecommerce: {
                checkout: {
                    products: createProductsFromItems(items)
                }
            }
        });
    };

    var onCartOpen = function (items) {
        dataLayer.push({
            event: 'ecom',
            eventCategory: 'VPV',
            eventAction: 'cart-open',
            options: {},
            ecommerce: {
                cartclose: {
                    products: createProductsFromItems(items)
                }
            }
        });
    };

    var onCartClose = function (items) {
        dataLayer.push({
            event: 'ecom',
            eventCategory: 'VPV',
            eventAction: 'cart-close',
            options: {},
            ecommerce: {
                cartopen: {
                    products: createProductsFromItems(items)
                }
            }
        });
    };
})(window.jQuery);

2.3 Creating the trigger and the tag in GTM

For our integration to work, we'll need to create a Custom Event trigger for all events named 'ecom'.

google-tag-manager-custom-event-trigger

And create variables for each values in the objects we push:

google-tag-manager-enhanced-ecommerce-event-tracking

Now we can sit back and watch the metrics roll in directly in Google Analytics!

Conclusion & Enhanced Ecommerce notes

With GTM & Enhanced Ecommerce, extracting deeper shopping experience analytics from Snipcart and pushing them into Google Analytics is relatively easy. Same thing goes for any other e-commerce solution that offers a decent API.

Three things to note about Enhanced Ecommerce that weren't discussed in the guide:

  1. Make sure "page changes" are counted only once
  2. The "product impressions" would need to be tracked on your side, since Snipcart doesn't generate on-site product pages, only product HTML markup.
  3. You shouldn't be using the traditional GA Ecommerce Tracking (ecommerce.js) with Enhanced Ecommerce (details).

For Snipcart users, coupling the method in this post with the e-commerce insights in your merchant dashboard will give you a detailed portrait of your online store's performance. And as our product keeps evolving, we'll add more relevant, out of the box behavioral analytics too.

Again, we'd like to thank Nicolas from Deux Huit Huit for his big input on this post. This short Enhanced Ecommerce + Google Tag Manager guide wouldn't have been valuable without it.

We hope this helps you step your shopping analytics game up, be it with Snipcart or any other e-commerce application!


If you found this post interesting, please take a second to share it on Twitter. Got any questions regarding Snipcart, GTM, or Enhanced Ecommerce? Hit the comments!

Suggested posts: