Integrating Convert Experiences with Shopify

Important:
Before you start installing the Convert Shopify integration, make sure you read the Shopify Get Started guide so you choose the right integration.


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. 

s1

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

s2

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

s3

In the area indicated above, paste the code shown below. Make sure you replace the XXXXXXX  with your own account ID and the YYYYYY  number with your own project ID, which was 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-4.convertexperiments.com/v1/js/XXXXXXXX-YYYYYYYYY.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.

 

s4

 

s5

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:

s6

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 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:

s7

<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.

    s8
    s9

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

    s10

Shopify Customer Event Code

Add the following code to your Shopify Admin > Settings > Customer Events > New Pixel section. Make sure you replace the goal ids with the ones you just created. If you have the legacy tracking code (then none Beta one), please find the code here.

// Fill in the following lines with your own goals

purchase_goalid = '100136097';
addToCart_goalid = '100134910';
checkoutStarted_goalid = '100132287';

function postTransaction(convert_attributes_str, purchase_event, purchase_goalid) {
console.log("Starting postTransaction function.");

try {
var convert_attributes = JSON.parse(convert_attributes_str);

if (convert_attributes && purchase_event) {
console.log("Building POST data for transaction.");

// Start with the original transaction amount
let transactionAmount = parseFloat(purchase_event.data.checkout.totalPrice.amount);

// Apply conversion rate if it exists and is not one
if (convert_attributes.conversionRate && convert_attributes.conversionRate !== 1) {
transactionAmount *= convert_attributes.conversion_rate;
console.log(`Transaction amount adjusted by conversion rate (${convert_attributes.conversionRate}): ${transactionAmount}`);
}

const post = {
'cid': convert_attributes.cid,
'pid': convert_attributes.pid,
'seg': convert_attributes.defaultSegments,
's': 'shopify',
'vid': convert_attributes.vid,
'tid': purchase_event.data.checkout.order_id,
'ev': [{
'evt': 'tr',
'goals': [purchase_goalid],
'exps': convert_attributes.exps,
'vars': convert_attributes.vars,
'r': transactionAmount, // Use the possibly adjusted amount
'prc': purchase_event.data.checkout.lineItems.length
}]
};
const data = JSON.stringify(post);
const beaconUrl = `https://${convert_attributes.pid}.metrics.convertexperiments.com/track`;
const beaconResult = browser.sendBeacon(beaconUrl, data);
console.log("sendBeacon result:", beaconResult);
} else {
console.error("Invalid or missing convert_attributes or purchase_event.");
}
} catch (error) {
console.error('Error in postTransaction:', error);
}
}


function postConversion(convert_attributes_str, goalid) {
console.log('Convert: Starting postConversion function with goal id:', goalid);

try {
var convert_attributes = JSON.parse(convert_attributes_str);

if (convert_attributes) {
console.log("Building POST data for goal hit.");
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);
const beaconUrl = `https://${convert_attributes.pid}.metrics.convertexperiments.com/track`;
const beaconResult = browser.sendBeacon(beaconUrl, data);
console.log("sendBeacon result:", beaconResult);
} else {
console.error("Invalid or missing convert_attributes or purchase_event.");
}
} catch (error) {
console.error('Error in postTransaction:', error);
}
}

analytics.subscribe("checkout_completed", async (event) => {
console.log("Event received for checkout_completed.");

browser.localStorage.getItem('convert_attributes')
.then((result) => {
postConversion(result, purchase_goalid);
return result;
})
.then((originalResult) => {
return postTransaction(originalResult, event, purchase_goalid);
})
.catch((error) => {
console.error('Error in checkout_completed promise chain:', error);
});
});

analytics.subscribe("product_added_to_cart", async (event) => {
console.log("Event received for product_added_to_cart.");

browser.localStorage.getItem('convert_attributes')
.then((result) => {
return postConversion(result, addToCart_goalid);
})
.catch((error) => {
console.error('Error retrieving convert_attributes for product_added_to_cart:', error);
});
});

analytics.subscribe("checkout_started", async (event) => {
console.log("Event received for checkout_started.");

browser.localStorage.getItem('convert_attributes')
.then((result) => {
return postConversion(result, checkoutStarted_goalid);
})
.catch((error) => {
console.error('Error retrieving convert_attributes for checkout_started:', error);
});
});

Global Project JS code

Add the following code to your Convert App > Your Project > Configuration > Project Global JS section. If you have the legacy tracking code (then none Beta one), please find the code here.

console.log('URL:' + location.href);
let enableCurrencyFunctionality = false;

// Ensuring _conv_q is initialized
window._conv_q = window._conv_q || [];
window._conv_q.push({
what: 'addListener',
params: {
event: 'snippet.experiences_evaluated',
handler: function() {
let session_cookie = convert.getCookie('_conv_s');
if (!session_cookie) {
console.error('Session cookie not found.');
return;
}

let session_id = session_cookie.substring(
session_cookie.indexOf('sh:') + 3,
session_cookie.indexOf('*')
);

let exp_list = [];
let variation_list = [];

// Function to process experiences from currentData and historicalData
function processExperiences(sourceData, allData, isHistorical = false) {
for (let expID in sourceData) {
// Retrieve the type from main data structure to decide exclusion
let type = allData.experiences[expID]?.type;
if (type === "deploy") {
console.log('Skipping deploy type experiment:', expID);
continue; // Skip processing if type is "deploy"
}

let experience = sourceData[expID];
let variation = experience.variation || {};
let varID = variation.id || experience.variation_id;

if (varID && !exp_list.includes(expID)) {
exp_list.push(expID);
variation_list.push(varID);
console.log(
'Adding experiment:',
expID,
'with variation:',
varID,
'from',
isHistorical ? 'historical data' : 'current data'
);
}
}
}

// Process current and historical data
if (convert.currentData && convert.currentData.experiences) {
processExperiences(convert.currentData.experiences, convert.data);
}

if (convert.historicalData && convert.historicalData.experiences) {
processExperiences(convert.historicalData.experiences, convert.data, true);
}

// Convert segments to the first format
function alignSegmentsToFirstFormat(segFromSecondFormat) {
const alignedSeg = {
browser: segFromSecondFormat.browser,
devices: segFromSecondFormat.devices,
source: segFromSecondFormat.source,
campaign: segFromSecondFormat.campaign,
ctry: segFromSecondFormat.country || "",
cust: Array.isArray(segFromSecondFormat.customSegments) ? segFromSecondFormat.customSegments : [],
};
return alignedSeg;
}

let convert_attributes = {
cid: convert.data.account_id,
pid: convert.data.project.id,
vid: session_id,
goals: JSON.stringify(convert.currentData.goals || {}),
vars: variation_list,
exps: exp_list,
defaultSegments: alignSegmentsToFirstFormat(convert.getDefaultSegments()),
conversionRate: 1, // Default value, modify as necessary
presentmentCurrency: "USD", // Default currency, modify as necessary
currencySymbol: "$" // Default symbol, modify as necessary
};

if (enableCurrencyFunctionality && typeof Shopify !== 'undefined' && Shopify.currency && typeof Currency !== 'undefined') {
let baseCurrency = Shopify.currency.active;
let presentmentCurrency = Shopify.currency.current;
let conversionRate = Currency.convert(1, baseCurrency, presentmentCurrency);

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

localStorage.setItem('convert_attributes', JSON.stringify(convert_attributes));
console.log('convert_attributes initialized:', convert_attributes);
}
}
});

Step 7: Verify your Shopify Setup

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

GA4 Event import for Shopify Sites

Although it might seem logical to import your GA4 events to track purchases on your Shopify store, this is not possible. This is because the Convert tracking code needs to be installed on the Order Status page. However, this is not possible due to the new Shopify Checkout Extensibility. You will have to set up Customer events, such as in step 6 to be able to track revenue on Shopify using this installation setup.