Custom Pixel

Shopify is an ecommerce platform that has everything you need to sell online, on social media, or in person. You can integrate Shopify with mParticle by using Custom Pixels.

Overview

Custom pixels help Shopify to collect customer events on their online store, such as the checkout and post-purchase pages. By using a Custom Pixel, you can log customer events to mParticle without having to modify your theme code.

Custom pixels are loaded in a Lax sandbox, designed for improved security and control over the data that is sent to third parties. As such, there are some limitations to using a Custom Pixel.

However, at this time, a Custom Pixel is the recommended way to integrate mParticle into your Shopify Theme.

Adding the Web SDK to a Shopify Custom Pixel

Before you add a custom pixel, remove or modify any existing pixels to ensure customer events aren’t counted twice. Existing pixel code should be manually removed from any place it exists, including theme.liquid, checkout.liquid (Plus merchants only), and the Additional scripts section of your checkout settings.

Steps:

  1. From your Shopify admin, go to Settings > Customer events.
  2. Give your pixel a unique name. If you enter the name of a custom pixel that already exists, then you’ll be prompted to give your pixel a different name.
  3. Select the Custom Pixels tab if it is there.
  4. Click Add pixel to open the event editor.
  5. Where you see // Step 1. Initialize the JavaScript pixel SDK (make sure to exclude HTML), paste the mParticle Web SDK Snippet (without the <script> tags) into the Shopify Code window.
window.mParticle = {
    config: {
        isDevelopmentMode: true,
        identifyRequest: {
            userIdentities: {
                email: 'email@example.com',
                customerid: '123456',
            },
        },
        identityCallback: function(result) {
            // Do something once an identity call has been made.
            // For more information, see https://docs.mparticle.com/developers/sdk/web/idsync/#sdk-initialization-and-identify
            console.log(result);
        },
        dataPlan: {
           planId: 'my_plan_id',
           planVersion: 2
        }
    },
};

//load the SDK
(
function(t){window.mParticle=window.mParticle||{};window.mParticle.EventType={Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8};window.mParticle.eCommerce={Cart:{}};window.mParticle.Identity={};window.mParticle.config=window.mParticle.config||{};window.mParticle.config.rq=[];window.mParticle.config.snippetVersion=2.3;window.mParticle.ready=function(t){window.mParticle.config.rq.push(t)};var e=["endSession","logError","logBaseEvent","logEvent","logForm","logLink","logPageView","setSessionAttribute","setAppName","setAppVersion","setOptOut","setPosition","startNewSession","startTrackingLocation","stopTrackingLocation"];var o=["setCurrencyCode","logCheckout"];var i=["identify","login","logout","modify"];e.forEach(function(t){window.mParticle[t]=n(t)});o.forEach(function(t){window.mParticle.eCommerce[t]=n(t,"eCommerce")});i.forEach(function(t){window.mParticle.Identity[t]=n(t,"Identity")});function n(e,o){return function(){if(o){e=o+"."+e}var t=Array.prototype.slice.call(arguments);t.unshift(e);window.mParticle.config.rq.push(t)}}var dpId,dpV,config=window.mParticle.config,env=config.isDevelopmentMode?1:0,dbUrl="?env="+env,dataPlan=window.mParticle.config.dataPlan;dataPlan&&(dpId=dataPlan.planId,dpV=dataPlan.planVersion,dpId&&(dpV&&(dpV<1||dpV>1e3)&&(dpV=null),dbUrl+="&plan_id="+dpId+(dpV?"&plan_version="+dpV:"")));var mp=document.createElement("script");mp.type="text/javascript";mp.async=true;mp.src=("https:"==document.location.protocol?"https://jssdkcdns":"http://jssdkcdn")+".mparticle.com/js/v2/"+t+"/mparticle.js" + dbUrl;var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(mp,c)}
)("REPLACE WITH API KEY");
  1. Update "REPLACE WITH API KEY" with your mParticle API Key

  2. Where you see // Step 2. Subscribe to customer events with analytics.subscribe(), and add tracking, add specific customer event mappings (see below) underneath the Web SDK Snippet.
  3. Click Save.

Mapping Shopify Events to mParticle

At present, Shopify provides Standard Events and DOM Events that notify when a user completes a specific action on a Shopify Online Store. By subscribing to these events, you can map to an mParticle Event and log it.

For example, to track a page view:

analytics.subscribe('page_viewed', async (event) => {
    window.mParticle.logPageView('Page View: ' + event.context.document.title, {
        page: event.context.document.location.href,
        title: event.context.document.title,
        referrer: event.context.document.referrer,
    });
});

Standard Events

Below is a list of our recommendations for how to map Shopify Events to mParticle Events. Please be aware that some of the event properties or options may differ based on your Shopify Store configuration.

Please view Shopify’s list of Standard Events for a complete list of event types that Shopify supports.

cart_viewed

analytics.subscribe("cart_viewed", event => {
    window.mParticle.ready(function () {
        var products = [];

        event.data.cart.lines.forEach(function (cartItem) {
            var mpProduct = window.mParticle.eCommerce.createProduct(
                cartItem.merchandise.product.title,      // Name
                cartItem.merchandise.sku,                // SKU
                cartItem.cost.totalAmount.amount,        // Price
                cartItem.quantity,                       // Quantity
                cartItem.merchandise.title,              // Variant
                cartItem.merchandise.product.type,       // Category
                cartItem.merchandise.product.vendor,     // Brand
            );
       
            products.push(mpProduct);
        });

        var transactionAttributes = {
            Step: 1
        };

        window.mParticle.eCommerce.logProductAction(
            window.mParticle.ProductActionType.Checkout, // Product Action Type
            products,                                    // Product(s)
            undefined,                                   // Custom Attributes
            undefined,                                   // Custom Flags
            transactionAttributes                        // TransactionAttributes
        );
    });
});

checkout_completed

analytics.subscribe("checkout_completed", event => {
    window.mParticle.ready(function () {
        var products = [];

        event.data.checkout.lineItems.forEach(function (product) {
            var mpProduct = window.mParticle.eCommerce.createProduct(
                product.title,                  // Name
                product.variant.sku,            // SKU
                product.finalLinePrice.amount,  // Price
                product.quantity,               // Quantity
                product.variant.title,          // Variant
                product.variant.product.type,   // Category
                product.variant.product.vendor, // Brand
            );

            products.push(mpProduct);
        });

        var checkoutTotalPrice = event.data.checkout.totalPrice.amount;
        var transactionAttributes = {
            Step: 3
            Revenue: checkoutTotalPrice,
        };

        window.mParticle.eCommerce.logProductAction(
            window.mParticle.ProductActionType.Checkout, // Product Action Type
            products,                                    // Product(s)
            undefined,                                   // Custom Attributes
            undefined,                                   // Custom Flags
            transactionAttributes                        // TransactionAttributes
        );
    });
});

checkout_started

analytics.subscribe("checkout_started", event => {
    window.mParticle.ready(function () {
        var products = [];

        event.data.checkout.lineItems.forEach(function (product) {
            var mpProduct = window.mParticle.eCommerce.createProduct(
                product.title,                  // Name
                product.variant.sku,            // SKU
                product.finalLinePrice.amount,  // Price
                product.quantity,               // Quantity
                product.variant.title,          // Variant
                product.variant.product.type,   // Category
                product.variant.product.vendor, // Brand
            );

            products.push(mpProduct);
        });

        var transactionAttributes = {
            Step: 2
        };

        window.mParticle.eCommerce.logProductAction(
            window.mParticle.ProductActionType.Checkout, // Product Action Type
            products,                                    // Product(s)
            undefined,                                   // Custom Attributes
            undefined,                                   // Custom Flags
            transactionAttributes                        // TransactionAttributes
        );
    });
});

collection_viewed

 analytics.subscribe("collection_viewed", event => {
    window.mParticle.ready(function () {
        var products = [];

        event.data.collection.productVariants.forEach(function (product) {
            var mpProduct = window.mParticle.eCommerce.createProduct(
                product.title,              // Name
                product.sku,                // SKU
                product.price.amount,       // Price
                1,                          // Quantity
                undefined,                  // Variant
                product.product.type,       // Category
                product.product.vendor,     // Brand
            );
            
            products.push(mpProduct);
        });
  
        var impression = window.mParticle.eCommerce.createImpression(
            event.data.collection.title,
            products
        );

        window.mParticle.eCommerce.logImpression(impression);
    });
 });

page_viewed

analytics.subscribe("page_viewed", event => {
    window.mParticle.ready(function () {
        window.mParticle.logPageView(
            'Page View: ' + event.context.document.title,
            {
                page: event.context.document.location.href,
                title: event.context.document.title,
                referrer: event.context.document.referrer,
            }
        );
    });
});

product_added_to_cart

analytics.subscribe("product_added_to_cart", event => {
    window.mParticle.ready(function () {
        var product = window.mParticle.eCommerce.createProduct(
            event.data.cartLine.merchandise.product.title,  // Name
            event.data.cartLine.merchandise.sku,            // SKU
            event.data.cartLine.merchandise.price.amount,   // Price
            event.data.cartLine.quantity,                   // Quantity
            event.data.cartLine.merchandise.title,          // Variant
            event.data.cartLine.merchandise.type,           // Category
            event.data.cartLine.merchandise.vendor,         // Brand
        );
     
        window.mParticle.eCommerce.logProductAction(
            window.mParticle.ProductActionType.AddToCart,
            product
        );
    });
});

product_removed_from_cart

analytics.subscribe("product_removed_from_cart", event => {
    window.mParticle.ready(function () {
        // We noticed that in some cases, the merchandise or product title comes back as undefined
        var name = event.data.cartLine.merchandise.title || event.data.cartLine.merchandise.untranslatedTitle;
        var product = window.mParticle.eCommerce.createProduct(
            name,                                           // Name
            event.data.cartLine.merchandise.sku,            // SKU
            event.data.cartLine.merchandise.price.amount,   // Price
            event.data.cartLine.quantity,                   // Quantity
            event.data.cartLine.merchandise.title,          // Variant
            event.data.cartLine.merchandise.type,           // Category
            event.data.cartLine.merchandise.vendor,         // Brand
        );
    
        window.mParticle.eCommerce.logProductAction(
            window.mParticle.ProductActionType.RemoveFromCart,
            product
        );
    });
});

product_viewed

analytics.subscribe("product_viewed", event => {
    console.log('subscribing to product viewed', event);

    window.mParticle.ready(function () {
        var product = window.mParticle.eCommerce.createProduct(
            event.data.productVariant.title,              // Name
            event.data.productVariant.sku,                // SKU
            event.data.productVariant.price.amount,       // Price
            1,                                            // Quantity
            undefined,                                    // Variant
            event.data.productVariant.product.type,       // Category
            event.data.productVariant.product.vendor,     // Brand
        );
     
        window.mParticle.eCommerce.logProductAction(
            window.mParticle.ProductActionType.ViewDetail,
            product
        );

    });
});

Was this page helpful?