Only use the following code if you are using the legacy tracking code:
Global Project JS Code
console.log('URL:' + location.href);
let enableCurrencyFunctionality = false;
_conv_q = window._conv_q || [];
_conv_q.push({
what: 'addListener',
params: {
event: 'snippet.experiences_evaluated',
handler: function() {
let session_cookie = convert.getCookie('_conv_s');
if (
(JSON.stringify(convert.currentData.experiments) != '{}' ||
JSON.stringify(convert.historicalData.experiments) != '{}') &&
session_cookie
) {
let session_id = session_cookie.substring(
session_cookie.lastIndexOf('sh:') + 3,
session_cookie.lastIndexOf('*')
);
let exp_list = [];
let variation_list = [];
let varID;
if (convert.currentData && convert.data && convert.data.experiments) {
let new_exp = convert.currentData.experiments;
for (let expID in new_exp) {
varID = new_exp[expID].variationId;
// Check for tp attribute from the main data object
if (convert.data.experiments[expID] && convert.data.experiments[expID].tp !== "4") {
if (!exp_list.includes(convert.data.experiments[expID].id)) {
exp_list.push(convert.data.experiments[expID].id);
variation_list.push(varID);
console.log(
'Adding experiment: ' +
convert.data.experiments[expID].id +
':' +
varID);
}
}
}
}
if (convert.historicalData && convert.data && convert.data.experiments) {
let old_exp = convert.historicalData.experiments;
for (let expID in old_exp) {
varID = old_exp[expID].variationId;
// Check for tp attribute from the main data object
if (convert.data.experiments[expID] && convert.data.experiments[expID].tp !== "4") {
if (!exp_list.includes(convert.data.experiments[expID].id)) {
exp_list.push(convert.data.experiments[expID].id);
variation_list.push(varID);
console.log(
'Adding experiment: ' +
convert.data.experiments[expID].id +
':' +
varID
);
}
}
}
}
let convert_attributes = {
cid: convert.data.u_id,
pid: convert.data.prj.id,
vid: session_id,
goals: '',
vars: variation_list,
exps: exp_list,
defaultSegments: convert.getDefaultSegments()
};
// Check and append currency information if enabled
if (enableCurrencyFunctionality) {
if (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));
console.log('convert_attributes initialized with currency info', convert_attributes);
} else {
localStorage.setItem('convert_attributes', JSON.stringify(convert_attributes));
console.log('convert_attributes initialized', convert_attributes);
}
}
}
}
});
Shopify Customer Events Tracking Code
// 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);
});
});