Integrating Convert Experiences with Shopify

Important Notes about this setup.

Important

Step 1: Find your Convert Experiences Account-Project ids.

In Convert Experiences, retrieve the project ID number from the place highlighted in the image below. 

Configuration - + Demo - Convert (1).png

Step 2: Add the Convert Experiences Script to your Shopify Theme

To integrate the two platforms, please go to Sales Channels > Online Store > Themes > More Actions > Edit Code

mceclip3.png

Select the theme.liquid file and paste the tracking code just before the first "{% if %}" section, as shown in the screenshot below:

mceclip4.png

In the area indicated above, paste the code shown below. Make sure you replace the project ID  and account ID number with your own IDs that you got mentioned earlier in this article.

<!-- begin Convert Experiences code-->
<script type="text/javascript">
 var _conv_page_type = "{{ request.page_type }}";
 var _conv_category_id = "{{ collection.id }}";
 var _conv_category_name = "{{ collection.title }}";
 var _conv_product_sku = "{{ product.selected_variant.sku }}";
 var _conv_product_name = "{{ product.title }}";
 var _conv_product_price = "{{ product.price_min | money_without_currency }}";
 var _conv_customer_id = "{{ customer.id }}";
 var _conv_custom_v1 = "{{ product.tags.first }}";
 var _conv_custom_v2 = "{{ collection.current_type }}";
 var _conv_custom_v3 = "{{ cart.item_count }}";
 var _conv_custom_v4 = "{{ cart.total_price | money_without_currency }}";
</script>
<script type="text/javascript" src="//cdn-3.convertexperiments.com/js/<REPLACE THIS WITH PROJECT ID NUMBER>.js"></script>
<!-- end Convert Experiences code -->

Don't forget to save your changes in Shopify.

Step 3: Add Convert Tracking Code on Checkout Pages on Shopify Plus 

If you use Shopify Plus, then you also have the possibility to add the Convert Experiences script in checkout pages (pages after /cart but before thank_you/purchase_confirmation). This is not possible for non Shopify Plus subscriptions as Shopify does not allow third party scripts to be running on checkout pages.

Edit the checkout.liquid file and place your Convert Tracking Code to appear on /checkout/ pages. 

Just go to your Project Configuration to get your Convert Tracking Code ("basic snippet") and paste it into the template as shown below.

mceclip1.png

mceclip0.png

Step 4: Add the checkout page domain to your Project's Active Websites

This only applies to non-Shopify Plus users.

On Shopify, the checkout pages are either presented under a central Shopify subdomain (checkout.shopify.com) or your own domain, depending on the type of Shopify account you have. In either situation, you need to add that domain to your Project's Configuration:

mceclip2.png

Step 5: Forward tracking cookies to the checkout domain

This only applies to non-Shopify Plus users.

If you are not using your own domain or if you are using a totally different domain than your main domain for the checkout pages, you will need to manually forward the tracking cookies so that experiments fired on the shop pages can be connected later on to a conversion. To do that, on the cart page where the visitor redirects from your main domain, you need to read the convert tracking cookies and forward them to the checkout domain as explained below.  

Go to Online Store > Themes > Current Theme > Actions > Edit Code  as explained in step 2). Go to "Sections" and select the "cart-template.liquid". Then, add the following JavaScript, just before the <form> tag:

mceclip5.png

<script type="text/javascript">
function _conv_copy_cookies(form) {
try {
var _conv_v = encodeURIComponent(convert.getCookie("_conv_v"));
var _conv_s = encodeURIComponent(convert.getCookie("_conv_s"));
form.action = '/cart?_conv_v=' + _conv_v + '&_conv_s=' + _conv_s;
} catch (e) {}
return true;
}
</script>

Next, add the following inside the <form> tag:

onsubmit="return _conv_copy_cookies(this)"

After this, you should be done. Now, the Convert Experiences cookies should be forwarded to the checkout URL as two GET variables: _conv_v and _conv_s;

Note: If you use a subdomain of your main domain for checkout, then you probably do not have to complete this step. Cookies will be saved under the root domain, making them available on the shop and checkout pages.

Step 6: Setup your Shopify Customer Events tracking

  1. Create two Code (JavaScript) triggered goals. Name one Purchase Shopify Customer Event, and another one Added to the Cart Shopify Customer Event. Have their Ids handy to insert them on the script you will add to the Shopify Customer Events section.

  2.  On your Shopify Admin interface go to Settings > Customer Events. Create a Custom one. Name it Convert Tracking.

    Chimpuppystore · Customers · Shopify.png

    Chimpuppystore · Customer events · Shopify.png

    Insert the code below and edit it, save it, and connect it.

    Chimpuppystore · Convert Revenue Tracking · Shopify.png

    // Edit the following goal ids to match your own created goals
    purchase_goalid = '100411697';
    addToCart_goalid = '100134910';

    function postTransaction (convert_attributes_str){
    var convert_attributes = JSON.parse(convert_attributes_str);

    if (convert_attributes) {

    //build POST data to be sent
    const post = {
    'cid': convert_attributes.cid,
    'pid': convert_attributes.pid,
    'seg': convert_attributes.defaultSegments,
    's': 'shopify',
    'vid': convert_attributes.vid,
    'ev': [
    {
    'evt': 'tr',
    'goals': [purchase_goalid],
    'exps': convert_attributes.exps,
    'vars': convert_attributes.vars,
    'r': parseFloat(purchase_event.data.checkout.totalPrice.amount),
    'prc': purchase_event.data.checkout.lineItems.length
    },
    {
    'evt': 'hitGoal',
    'goals': [purchase_goalid],
    'exps': convert_attributes.exps,
    'vars': convert_attributes.vars
    }
    ]
    }
    const data = JSON.stringify(post);
    console.log('Data:'+data);
    browser.sendBeacon(`https://${convert_attributes.pid}.metrics.convertexperiments.com/track`, data);
    }
    }

    function postConversion (convert_attributes_str,goalid){
    console.log('Convert: Triggering Add to Cart Shopify Customer Event with goal id:'+goalid)
    var convert_attributes = JSON.parse(convert_attributes_str);

    if (convert_attributes) {

    //build POST data to be sent
    const post = {
    'cid': convert_attributes.cid,
    'pid': convert_attributes.pid,
    'seg': convert_attributes.defaultSegments,
    's': 'shopify',
    'vid': convert_attributes.vid,
    'ev': [
    {
    'evt': 'hitGoal',
    'goals': [goalid],
    'exps': convert_attributes.exps,
    'vars': convert_attributes.vars
    }
    ]
    }
    const data = JSON.stringify(post);
    console.log('Data:'+data);
    browser.sendBeacon(`https://${convert_attributes.pid}.metrics.convertexperiments.com/track`, data);
    }
    }

    analytics.subscribe("checkout_completed", async (event) => {
    purchase_event = event;
    browser.localStorage.getItem('convert_attributes').then(postTransaction,console.log('Convert localStorage retrieval failed.'));
    });

    analytics.subscribe("product_added_to_cart", async (event) => {
    browser.localStorage.getItem('convert_attributes')
    .then((result) => postConversion(result, addToCart_goalid))
    .catch((error) => {
    console.log('Convert localStorage retrieval failed.')
    });
    });
  3. Insert the following code in the Convert > Project > Configuration > Global Project Javascript.

    console.log('URL:'+location.href);

    // Flag to control currency functionality
    var enableCurrencyFunctionality = true; // Set this to false to disable the currency functionality

    // Function to dynamically load the Shopify currency.js library
    function loadCurrencyJsLibrary(callback) {
    var script = document.createElement('script');
    script.src = 'https://cdn.shopify.com/s/javascripts/currencies.js';
    script.onload = function() {
    console.log('Shopify currency.js library loaded');
    callback();
    };
    script.onerror = function() {
    console.error('Error loading Shopify currency.js library');
    };
    document.head.appendChild(script);
    }

    // Function to update convert_attributes with currency information
    function updateConvertAttributes() {
    try {
    let session_cookie = convert.getCookie('_conv_s');
    if (!session_cookie || !convert.currentData || !convert.historicalData || !convert.data || !convert.data.experiments) {
    console.error('Required data is missing');
    return;
    }

    let session_id = session_cookie.substring(session_cookie.lastIndexOf('sh:') + 3, session_cookie.lastIndexOf('*'));
    let exp_list = [];
    let variation_list = [];

    // Function to process experiments
    function processExperiments(experiments) {
    for (let expID in experiments) {
    if (Object.hasOwnProperty.call(experiments, expID)) {
    let experiment = convert.data.experiments[expID];
    if (experiment && experiment.tp !== "4") {
    let varID = experiments[expID].variation_id;
    if (!exp_list.includes(expID)) {
    exp_list.push(expID);
    }
    if (!variation_list.includes(varID)) {
    variation_list.push(varID);
    }
    }
    }
    }
    }

    // Collect experiments and variations, excluding those with tp equal to 4
    processExperiments(convert.currentData.experiments);
    processExperiments(convert.historicalData.experiments);

    let convert_attributes = {
    cid: convert.data.u_id,
    pid: convert.data.prj.id,
    vid: session_id,
    goals: '', // Set your revenue goal id
    vars: variation_list,
    exps: exp_list,
    defaultSegments: convert.getDefaultSegments()
    };

    // Check the flag and validate currency information before adding it
    if (enableCurrencyFunctionality && Shopify && Shopify.currency && Currency) {
    let baseCurrency = Shopify.currency.active;
    let presentmentCurrency = Shopify.currency.current;
    let conversionRate = Currency.convert(1, baseCurrency, presentmentCurrency);

    if (!isNaN(conversionRate) && conversionRate !== 0) {
    let currencySymbol = Currency.symbol;
    convert_attributes.conversionRate = conversionRate;
    convert_attributes.presentmentCurrency = presentmentCurrency;
    convert_attributes.currencySymbol = currencySymbol;
    } else {
    console.error('Invalid conversion rate. Not adding currency information.');
    }
    }

    localStorage.setItem('convert_attributes', JSON.stringify(convert_attributes));
    } catch (error) {
    console.error('An error occurred:', error);
    }
    }

    // Load the currency.js library and then update convert_attributes
    if (enableCurrencyFunctionality) {
    loadCurrencyJsLibrary(function() {
    if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', updateConvertAttributes);
    } else {
    updateConvertAttributes();
    }
    });
    } else {
    if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', updateConvertAttributes);
    } else {
    updateConvertAttributes();
    }
    }

    Step 7: Verify your Shopify installation

You should verify your installation using the following guide: Shopify Setup Verification Guide

Need assistance? Start a conversation with our Support Team.
CONVERT MORE

Reliably Convert More Site Visitors, Even If Everything Else is Changing in Your Business.

START 15-DAY FREE TRIAL
✓ No Credit Card  ✓ Easy Set-Up  ✓ Access All Features

Comments