### Get Checkout Data and Track Checkout Start Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Fetches checkout details from the BigCommerce API and processes physical items to track the checkout started event. ```javascript function getCheckoutData(callback) { if(__BC.checkoutId){ getData(`/api/storefront/checkouts/${__BC.checkoutId}`).then((data) => { if (data.cart && data.cart.lineItems.physicalItems.length) { for (const product of data.cart.lineItems.physicalItems) { products.push({ product_id: product.productId, product_sku: product.sku, product_name: product.name, product_brand: product.brand, product_price: product.salePrice, product_quantity: product.quantity }); } __BC.analyticsData = { checkout_id: data.id, order_id: data.orderId, value: data.grandTotal, revenue: data.subtotal, shipping: data.shippingCostTotal, tax: data.taxTotal, discount: data.cart.discountAmount, currency: data.cart.currency.code, products: products, }; if(callback){ callback(); } } }); if (mailSelector && mailSelector[0]) { userEmail = mailSelector[0].innerHTML; } } } ``` -------------------------------- ### Track Checkout Started Event Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html This snippet tracks the 'checkout_started' event, mapping product data and composing custom properties. It's used when a customer initiates the checkout process. ```javascript if (typeof window.bodlEvents.checkout.checkoutStarted === 'function') { window.bodlEvents.checkout.checkoutStarted(async (payload) => { try { var cust_prop = composeCustomProperties('checkout_started', payload); var mappedProducts = bigcommerce_products_mapping(payload, 'line_items'); _cl.trackClick('Checkout made', { customProperties: cust_prop, productProperties: mappedProducts }); } catch (e) { console.log('CL checkoutBegin error', e); } }); } ``` -------------------------------- ### Get Product Details and Send Add-to-Cart Event Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Fetches cart details to identify products that were added to the cart and then triggers an 'onAddToCart' event with product details. ```javascript function getProductAndSend(productIds) { getData(`/api/storefront/carts`).then((data) => { var cart = data[0]; if (cart && cart.lineItems.physicalItems.length) { for (const product of cart.lineItems.physicalItems) { if(productIds.includes(""+product.productId)){ onAddToCart(product.productId, { "product_name": product.name, "product_id": product.productId, "product_quantity": product.quantity, "product_price": product.salePrice, "product_category": escapeHtml(product.category || ""), "product_sku": product.sku }); delete_cookie("cl_bc_ajax_atc_" + product.productId); } } } }); } ``` -------------------------------- ### Get Purchase Data and Track Purchase Event Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Fetches order details for a completed purchase from the BigCommerce API and processes physical items to track a purchase event. ```javascript async function getPurchaseData(callback) { if(__BC.orderId){ getData(`/api/storefront/order/${__BC.orderId}`).then((data) => { if(data.lineItems.physicalItems.length) { for (const product of data.lineItems.physicalItems) { products.push({ product_id: product.productId, product_sku: product.sku, product_name: product.name, product_brand: product.brand, product_price: product.salePrice, product_quantity: product.quantity }); } __BC.analyticsData = { order_id: data.orderId, value: data.orderAmount, revenue: data.orderAmount, shipping: data.shippingCostTotal, tax: data.taxTotal, discount: data.discountAmount, currency: data.currency.code, status: data.status, products: products, billingInfo: data.billingAddress }; if(callback){ callback(); } } }) } } ``` -------------------------------- ### Fetch Data from URL Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Asynchronously fetches JSON data from a given URL using the GET method with no-cache headers. Handles potential network errors implicitly via fetch API. ```javascript async function getData(url) { const response = await fetch(url, { method: 'GET', cache: 'no-cache', headers: { 'Content-Type': 'application/json', }, }); return response.json(); } ``` -------------------------------- ### Get Cookie Value Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Retrieves the value of a specified cookie from the document. Returns null if the cookie is not found. ```javascript function getCookie(name) { const value = ` ${document.cookie}`; const parts = value.split(` ${name}=`); if (parts.length === 2) { return parts.pop().split(";").shift(); } return null; } ``` -------------------------------- ### Track Checkout Begin Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Initiates tracking for the checkout process. It fetches checkout data, identifies user information, and prepares properties for tracking. Ensure window.bodlEvents.checkout.checkoutBegin is available and the API endpoint is accessible. ```javascript if (typeof window.bodlEvents.checkout.checkoutBegin === 'function') { window.bodlEvents.checkout.checkoutBegin(async (payload) => { const checkoutId = '{{checkout.id}}'; let products = []; let userInfo = {}; try { const data = await getData(`/api/storefront/checkouts/${checkoutId}`); var email = data.billingAddress?.email; var customer_id = window.bodl.shopper.customer_id; let proPerties = { "customProperties":{ "user_traits":{ "bc_customer_id": { "t": "string", "v": customer_id, }, "email":{ "t": "string", "v": email, }, }, "identify_by_email":{ "t":"string", "v": email, "ib": true } } }; if (typeof _cl !== 'undefined') { var cust_prop = composeCusto ``` -------------------------------- ### Initialize CustomerLabs Pixel Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/shopify_custom_pixel/additional_script_post_purchase_page.html This script initializes the CustomerLabs analytics object and loads the tracking script. Replace CUSTOMELABS_ACCOUNT_ID with your actual account ID. ```javascript !function(t,e,r,c,a,n,s){t.ClAnalyticsObject=a,t[a]=t[a]||[],t[a].methods=["trackSubmit","trackClick","pageview","identify","track"],t[a].factory=function(e){return function(){var r=Array.prototype.slice.call(arguments);return r.unshift(e),t[a].push(r),t[a]}};for(var i=0;i { let userConsentTrack = false; const consentCookie = getCookie(`${window.CLabsgbVar.appId}_userConsent`); if(consentCookie && consentCookie !== null && consentCookie !== ""){ const userConsent = JSON.parse(consentCookie); if(userConsent.consentUpdated){ userConsentTrack = true; } } if(!userConsentTrack){ const userConsent = { ad_storage: payload.advertising, analytics_storage: payload.analytics, functional_storage: payload.functional, ad_personalization: payload.advertising, ad_user_data: payload.advertising, } _cl.trackConsent(userConsent); } }); } // If window.bodlEvents.consent.updated is available, then... if (typeof window.bodl ``` -------------------------------- ### BigCommerce Events Manager Initialization Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Initializes various e-commerce event tracking functionalities based on the current page type in BigCommerce. ```javascript addProductEventListeners(); var searchPage = new RegExp(__BC.searchPage, "g"); findATCAndSend(); switch (__BC.pageType) { case 'category': onCategoryView(__BC.categoryName); break; case 'product': onProductDetailsView(); break; case 'checkout': getCheckoutData(onCheckoutStarted); break; case 'orderconfirmation': getPurchaseData(onPurchase); break; case 'cart': onViewCart(); initRemoveFromCartObserver(); break; default: if (__BC.pageType === 'search' || document.location.pathname.match(searchPage)){ onSearchPage(); } break; } ``` -------------------------------- ### Track Product Detail View Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Tracks a product detail view event. This function captures product information and sends it to CustomerLabs. ```javascript function onProductDetailsView() { var cust_prop = { "content_type": "product_group", "content_category": escapeHtml("{{product.category}}"), "currency": __BC__.currency } if(__BC__.fb_skip_contents){ cust_prop["skip_contents"] = true; } _cl.pageview("Product viewed", { "customProperties": cust_prop, "productProperties": [{ "product_name": '{{product.title}}', // Name or ID is required. "product_id": '{{product.id}}', "product_price": '{{product.price.without_tax.value}}', "product_category": escapeHtml('{{product.category}}'), "product_variant": '{{product.sku}}', "product_sku": '{{product.sku}}' }] }) } ``` -------------------------------- ### Shopify Liquid Theme Integration Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/README.md Paste the CustomerLabs tag and the include tag under the header section of your theme's liquid file to enable tracking. ```liquid {% include "cl_default_ecommerce_events" %} ``` -------------------------------- ### Subscribe to BODL Events on Window Load Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html This snippet ensures that the `subscribeOnBodlEvents` function is called once the entire page has finished loading. This is crucial for initializing event listeners correctly. ```javascript window.addEventListener('load', subscribeOnBodlEvents, false); ``` -------------------------------- ### Track Product Viewed Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks when a product is viewed. It maps product data and sends a click event with custom properties if _cl is defined. Ensure window.bodlEvents.product.pageViewed is available. ```javascript if (typeof window.bodlEvents.product.pageViewed === 'function') { window.bodlEvents.product.pageViewed((payload) => { try { var products = bigcommerce_products_mapping(payload, 'line_items'); var customProperties = composeCustomProperties('product_viewed', payload); _cl.trackClick('Product viewed', { customProperties: customProperties, productProperties: products }); } catch (e) { console.warn('CL pageViewed error', e); } }); } ``` -------------------------------- ### Observe DOM for Cart Changes and Set Remove Listener Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Initializes a MutationObserver to detect when the cart is added to the DOM and then sets up a listener for remove-from-cart actions. ```javascript function initRemoveFromCartObserver() { var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; function checkChanges(mutations) { for (let mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach(element => { if(element.className == "cart"){ setRemoveCartListener(); } }); } } } var observer = new MutationObserver(checkChanges); var target = document.querySelector(".body") observer.observe(target, {childList: true, subtree: true}) } ``` -------------------------------- ### Track Payment Info Provided Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks when payment details are provided during checkout. It maps product data and sends a click event. Ensure window.bodlEvents.checkout.paymentDetailsProvided is available. ```javascript if (typeof window.bodlEvents.checkout.paymentDetailsProvided === 'function') { window.bodlEvents.checkout.paymentDetailsProvided((payload) => { var cust_prop = composeCustomProperties('payment_info_submitted', payload); var products = bigcommerce_products_mapping(payload, 'line_items'); _cl.trackClick('AddPaymentInfo', { customProperties: cust_prop, productProperties: products }); }); } ``` -------------------------------- ### Track Product Search Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks product searches performed by the user. It composes custom properties and sends a pageview event if _cl is defined. Ensure window.bodlEvents.product.searchPerformed is available. ```javascript if (typeof window.bodlEvents.product.searchPerformed === 'function') { window.bodlEvents.product.searchPerformed((payload) => { try { if (typeof _cl !== 'undefined') { var customProperties = composeCustomProperties('search_submitted', payload); _cl.pageview('Search made', { customProperties: customProperties }); } } catch (e) { console.warn('CL searchPerformed error', e); } }); } ``` -------------------------------- ### Track Shipping Info Provided Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks when shipping details are provided during checkout. It maps product data and sends a click event. Ensure window.bodlEvents.checkout.shippingDetailsProvided is available. ```javascript if (typeof window.bodlEvents.checkout.shippingDetailsProvided === 'function') { window.bodlEvents.checkout.shippingDetailsProvided((payload) => { var cust_prop = composeCustomProperties('checkout_shipping_info_submitted', payload); var products = bigcommerce_products_mapping(payload, 'line_items'); _cl.trackClick('AddShippingInfo', { customProperties: cust_prop, productProperties: products }); }); } ``` -------------------------------- ### Track Checkout Initiation Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Tracks a 'Checkout made' event when a user initiates the checkout process. It sends custom properties and product details available in analyticsData. ```javascript function onCheckoutStarted() { var props = {}; var analyticsData = __BC__.analyticsData; for(var k in analyticsData){ if(k != "products" && analyticsData[k]){ props[k] = analyticsData[k]; } } if(__BC__.fb_skip_contents){ props["skip_contents"] = true; } var propertiesToSend = { "customProperties": props, "productProperties": analyticsData.products } _cl.pageview("Checkout made", propertiesToSend) } ``` -------------------------------- ### Identify Customer with Additional Script Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/additional_script_order_status_page.html Use this snippet to identify a customer with additional properties on the order status page. Ensure the Customer.js library is loaded. ```html {% unless customer %} {% endunless %} ``` -------------------------------- ### Track Consent Updates Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Listens for consent updates and tracks the user's consent preferences using _cl.trackConsent. Ensure window.bodlEvents.consent.updated is available. ```javascript if (typeof window.bodlEvents.consent.updated === 'function') { window.bodlEvents.consent.updated((payload) => { const userConsent = { ad_storage: payload.advertising, analytics_storage: payload.analytics, functional_storage: payload.functional, ad_personalization: payload.advertising, ad_user_data: payload.advertising, }; _cl.trackConsent(userConsent); }); } ``` -------------------------------- ### Identify User Traits by Email Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/additional_script_order_status_page.html This snippet collects billing and shipping address information from both checkout and order objects, combines them, and then identifies the user by their email address. It prepares user traits for an analytics platform. ```javascript var checkout_billing_address = clearObject({{checkout.billing_address | json}} || {}); var checkout_shipping_address = clearObject({{checkout.shipping_address | json}} || {}); var order_billing_address = clearObject({{order.billing_address | json}} || {}); var order_shipping_address = clearObject({{order.shipping_address | json}} || {}); var checkout_address = Object.assign({}, checkout_billing_address, checkout_shipping_address); var order_address = Object.assign({}, order_billing_address, order_shipping_address); var cltraits = Object.assign({}, checkout_address, order_address); cltraits["email"] = {{order.email | json}} || {{checkout.email | json}}; if(cltraits["email"]){ var user_traits = {} for(var trait in cltraits){ if(cltraits[trait]){ user_traits[trait] = { "t": "string", "v": cltraits[trait] } } } var props = { "customProperties": { "user_traits": { "t": "Object", "v": user_traits }, "identify_by_email": { "t":"string", "v": cltraits["email"], } ``` -------------------------------- ### Shopify Webhook Creation for Add Payment Info Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/README.md Create a new webhook in Shopify for 'Checkouts (checkouts/update)' events, selecting JSON format and the latest version, to track add_payment_info events. ```json { "webhook": { "topic": "checkouts/update", "address": "YOUR_WORKFLOW_URL", "format": "json", "version": "2023-10" } } ``` -------------------------------- ### BigCommerce E-commerce Event Tracking Helper Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html This is the main JavaScript helper function for tracking e-commerce events on BigCommerce. It includes utility functions for HTML decoding, escaping, URL parameter retrieval, and cookie management, along with configuration for event bindings. ```javascript window.clShopifyTrack = function() { function htmlDecode(input) { if (!input) return ''; var parsedInput = input.replace(/(\r\n|\n|\r)/gm, ''); var doc = new DOMParser().parseFromString(parsedInput, 'text/html'); return JSON.parse(doc.documentElement.textContent); } function escapeHtml(str) { return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'"); } function getURLParams(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$& উত্ত"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); }; function set_cookie(name, value) { document.cookie = name + '=' + value + '; Path=/;'; }; function get_cookie(name) { return document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''; }; function get_cookie_startwith(key) { var regex = new RegExp('(^|;)\\s*' + key + '\\w*\\s*=\\s*([^;]+)', 'g'); var matches = document.cookie.matchAll(regex); var match = matches.next(); var values = [] while (!match.done) { values.push(match.value[2]); match = matches.next(); } return values; } function delete_cookie(name) { document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; }; __BC__ = { pageType: '{{page_type}}', categoryName: escapeHtml('{{category.name}}'), currency: '{{currency_selector.active_currency_code}}', analyticsData: window.analyticsData || {}, cartItems: htmlDecode("{{json cart.items}}"), checkoutId: '{{checkout.id}}' || 0, orderId: '{{checkout.order.id}}' || 0, mainPageAjaxAddButton: false, // set true if the products list has ajax "add to cart" button fb_skip_contents: false, } /* Product Event listener */ function addProductEventListeners() { var mainPageAddButton = Czzle(__BC__.mainPageAddButton) || []; var productPageAddButton = Czzle(__BC__.productPageAddButton) || []; var quickViewModal = Czzle(__BC__.quickViewModal) || []; // Main Page - Add to Cart click if (mainPageAddButton.length > 0) { for (var i = 0; i < mainPageAddButton.length; i++) { const el = mainPageAddButton[i]; el.addEventListener('click', (event) => { var index = event.target.href.indexOf('product_id'); var productId = event.target.href.slice(index).split('=')[1]; onAddToCart(productId, undefined); }) } } // Product Page - Add to Cart click if (productPageAddButton.length > 0) { for (var j = 0; j < productPageAddButton.length; j++) { const el = productPageAddButton[j]; el.addEventListener('click', () => { onAddToCart('{{product.id}}', { "product_name": '{{product.title}}', "product_id": '{{product.id}}', "product_price": '{{product.price.without_tax.value}}', "product_category": escapeHtml('{{product.category}}'), "product_variant": '{{product.sku}}', "product_sku": '{{product.sku}}' }); }); } } // Remove from Cart click setRemoveCartListener(); if (quickViewModal.length > 0) { for (var l = 0; l < quickViewModal.length; l++) { const el = quickViewModal[l]; el.addEventListener('click', (e) => { if (e.target && e.target.id == __BC__.quickViewCartButtonId) { const productId = document.querySelector(__BC__.modalHiddenProductId).value; onAddToCart(productId, undefined); } }); } } } function setRemoveCartListener() { var cartPageRemoveButton = Czzle(__BC__.cartPageRemoveButton) || []; if (cartPageRemoveButton.length > 0) { for (var k = 0; k < cartPageRemoveButton.length; k++) { const el = cartPageRemoveButton[k]; el.addEventListener('click', () => { onRemoveFromCart(el.attr ``` -------------------------------- ### Find and Send Add-to-Cart Events Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Checks for pending add-to-cart events stored in cookies and processes them by fetching product details and sending an add-to-cart event. ```javascript function findATCAndSend(){ var pendingList = get_cookie_startwith("cl_bc_ajax_atc_"); if(pendingList.length > 0){ getProductAndSend(pendingList); } } ``` -------------------------------- ### Include Shopify Snippet in theme.liquid Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/README.md Add this Liquid code to your theme.liquid file after the customerlabs tracking code to include the custom snippet. ```liquid {% include "cl_default_ecommerce_events" %} ``` -------------------------------- ### Fetch Data from URL Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html A utility function to fetch JSON data from a given URL using the Fetch API with specified headers and cache settings. ```javascript async function getData(url) { const response = await fetch(url, { method: 'GET', cache: 'no-cache', headers: { 'Content-Type': 'application/json', }, }); return response.json(); } ``` -------------------------------- ### Track Cart Viewed Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks when the cart is viewed. It maps product data and sends a click event with custom properties if _cl is defined. Ensure window.bodlEvents.cart.viewed is available. ```javascript if (typeof window.bodlEvents.cart.viewed === 'function') { window.bodlEvents.cart.viewed((payload) => { try { if (typeof _cl !== 'undefined') { var cust_prop = composeCustomProperties('cart_viewed', payload); var products = bigcommerce_products_mapping(payload, 'line_items'); _cl.trackClick('Cart viewed', { customProperties: cust_prop, productProperties: products }); } } catch (e) { console.warn('CL cart.viewed error', e); } }); } ``` -------------------------------- ### Track Purchase on Shopify Post-Purchase Page Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/shopify_custom_pixel/additional_script_post_purchase_page.html This function tracks a purchase event on the Shopify post-purchase page. It sends product details, transaction information, and customer traits to CustomerLabs. It also prevents duplicate tracking for the same transaction using localStorage. ```javascript window.clShopifyTrack = function(){ if (!window.Shopify.wasPostPurchasePageSeen) { var order = window.Shopify.order; var products = order.lineItems.map(function(item){ return { "product_id": Number(item.id).toString(), "product_name": item.title, "product_category": item.product.type, "product_price": item.price, "product_quantity": item.quantity, "product_variant": Number(item.variant.sku).toString() } }); var propertiesToSend = { "customProperties": { "transaction_number": { "t": "string", "v": Number(order.id).toString(), }, "value": { "t": "number", "v": order.totalPrice }, "currency": { "t": "string", "v": order.currency } }, "productProperties": products } var transaction_number = Number(order.id).toString() if(transaction_number && window.localStorage){ var purchases_str = localStorage.getItem('cl_past_purchases') || "{}"; var purchases = JSON.parse(purchases_str); if(!purchases[transaction_number]){ _cl.trackClick('Purchased', propertiesToSend); purchases[transaction_number] = "true"; window.localStorage.setItem("cl_past_purchases", JSON.stringify(purchases)); } }else{ _cl.trackClick('Purchased', propertiesToSend); } var cltraits = order.customer; if(cltraits["email"]){ var user_traits = {} for(var trait in cltraits){ if(cltraits[trait]){ user_traits[trait] = { "t": "string", "v": cltraits[trait] } } } var props = { "customProperties": { "user_traits": { "t": "Object", "v": user_traits }, "identify_by_email": {"t":"string", "v": cltraits["email"], "ib": true } } } _cl.identify(props) } } } ``` -------------------------------- ### Track Purchase Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Tracks a 'Purchased' event upon successful order completion. It includes custom properties, product details, and uses localStorage to prevent duplicate tracking of the same order. ```javascript function onPurchase() { var customProps = {}; var analyticsData = __BC__.analyticsData; for(var k in analyticsData){ if(k != "products" && k != "billingInfo" && analyticsData[k]){ customProps[k] = analyticsData[k]; } } if(__BC__.fb_skip_contents){ customProps["skip_contents"] = true; } var propertiesToSend = { "customProperties": customProps, "productProperties": analyticsData.products } if(analyticsData.order_id && window.localStorage){ var purchases_str = localStorage.getItem('cl_past_purchases') || "{}"; var purchases = JSON.parse(purchases_str); if(!purchases[""+analyticsData.order_id]){ _cl.trackClick('Purchased', propertiesToSend); purchases[""+analyticsData.order_id] = "true"; window.localStorage.setItem("cl_past_purchases", JSON.stringify(purchases)); } }else{ _cl.trackClick('Purchased', propertiesToSend); } if(analyticsData.billingInfo){ var userAttributes = {}; var billingInfo = an ``` -------------------------------- ### Track Category View Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Tracks a category view event. Use this when a user navigates to a category page. ```javascript function onCategoryView(categoryName) { _cl.pageview("Category viewed", {"customProperties": {"category_name": categoryName}}) } ``` -------------------------------- ### Shopify Additional Scripts for Purchase Events Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/README.md Add the CustomerLabs tag and the cl_default_ecommerce_events script to the additional scripts section in Shopify's order processing settings to track purchase events from the browser. ```html ``` -------------------------------- ### Track Category Viewed Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks when a product category is viewed. It composes custom properties and sends a click event if _cl is defined. Ensure window.bodlEvents.product.categoryViewed is available. ```javascript if (typeof window.bodlEvents.product.categoryViewed === 'function') { window.bodlEvents.product.categoryViewed((payload) => { try { if (typeof _cl !== 'undefined') { var customProperties = composeCustomProperties('category_viewed', payload); _cl.trackClick('Category viewed', { customProperties: customProperties }); } } catch (e) { console.warn('CL categoryViewed error', e); } }); } ``` -------------------------------- ### Track Search Page View Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Sends a pageview event to CustomerLabs when a search results page is loaded, including the search term as a custom property. ```javascript function onSearchPage() { var customProperties = { 'search_string': { 't': 'string', 'v': __BC.searchTermQuery } }; _cl.pageview("Search made", {"customProperties": customProperties}); } ``` -------------------------------- ### Identify User with Billing Info Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/cl_default_ecommerce_events.html Captures user attributes from billing information and sends an identify event to CustomerLabs, specifically marking the email as an identifier. ```javascript alyticsData.billingInfo; if(billingInfo.email){ for(var k in billingInfo){ if(k != "customFields" && billingInfo[k]){ userAttributes[k] = { "t": "string", "v": billingInfo[k] }; } } var props = { "customProperties": { "user_traits": { "t": "Object", "v": userAttributes }, "identify_by_email": { "t":"string", "v": userAttributes["email"].v, "ib": true } } } _cl.identify(props) } } ``` -------------------------------- ### Map BigCommerce Product Data Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Transforms raw BigCommerce product data from event payloads into a structured format for analytics. It calculates discounts if applicable. ```javascript var bigcommerce_products_mapping = function(eventData, itemGroup) { var products = []; var items = eventData[itemGroup]; if(items && itemGroup && items.length > 0) { //items for(var i=0;i< items.length;i++) { var productData = items[i]; var product = { "product_id": productData.product_id, "product_sku": productData.sku, "product_name": productData.product_name, "product_price": productData.purchase_price, "product_brand": productData.brand_name, "product_type": productData.product_type, "product_quantity": productData.quantity, "product_variant": productData.variant_id, }; // Compute discount based on base_price (original) and purchase_price (discounted) var basePrice = Number(productData.base_price); var purchasePrice = Number(productData.purchase_price); if(!isNaN(basePrice) && !isNaN(purchasePrice) && basePrice > 0) { var discountAmount = Math.max(0, basePrice - purchasePrice); if(discountAmount > 0) { product["product_discount_price"] = discountAmount; product["product_discount_percentage"] = Math.round((discountAmount / basePrice) * 100); product["product_discount_applied"] = true; } } products.push(product); } } return products; } ``` -------------------------------- ### Shopify Order Status Page Tracking Function Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/shopify_custom_pixel/additional_script_order_status_page.html Defines the `clShopifyTrack` function to capture and send purchase data from Shopify's order status page. It formats product and transaction details before sending them. ```javascript window.clShopifyTrack = function(){ {% unless post_purchase_page_accessed %} {% if first_time_accessed %} var products = [] {% for line_item in checkout.line_items %} products.push({ 'product_id': {"t": "string", "v": {{line_item.product_id | json}}}, 'product_sku': {"t": "string", "v": {{line_item.sku | json}}}, 'product_variant': {"t": "string", "v": {{line_item.variant_id | json}}}, 'product_name': {"t": "string", "v": {{line_item.title | json}}}, 'product_type': {"t": "string", "v": {{line_item.product.type | json}}}, 'product_price': {"t": "string", "v": '{{shop.money_format}}'.includes('with_comma_separator') ? {{line_item.price | money_without_currency | remove: "." | json}}.replace(',', '.') : {{line_item.price | money_without_currency | remove: "," | json}} }, 'product_quantity':{"t": "string", "v": {{line_item.quantity | json}}} }); {% endfor %} var transactionData = { 'transaction_number' : {'t': 'string', 'v': {{checkout.order_id | json}} }, 'transaction_id' : {'t': 'string', 'v': {{checkout.order_number | json}} }, 'transaction_affiliation' : {'t': 'string', 'v': {{shop.name | json}} }, 'transaction_total' : {'t': 'number', 'v': '{{shop.money_format}}'.includes('with_comma_separator') ? {{checkout.total_price | money_without_currency | remove: "." | json}}.replace(',', '.') : {{checkout.total_price | money_without_currency | remove: "," | json}} }, 'tax' : {'t': 'number', 'v': '{{shop.money_format}}'.includes('with_comma_separator') ? {{checkout.tax_price | money_without_currency | remove: "." | json}}.replace(',', '.') : {{checkout.tax_price | money_without_currency | remove: "," | json}} }, 'shipping' : {'t': 'number', 'v': '{{shop.money_format}}'.includes('with_comma_separator') ? {{checkout.shipping_price | money_without_currency | remove: "." | json}}.replace(',', '.') : {{checkout.shipping_price | money_without_currency | remove: "," | json}} }, 'subtotal' : {'t': 'number', 'v': '{{shop.money_format}}'.includes('with_comma_separator') ? {{checkout.subtotal_price | money_without_currency | remove: "." | json}}.replace(',', '.') : {{checkout.subtotal_price | money_without_currency | remove: "," | json}} }, {% for discount in checkout.discounts %} 'promo_code' : {'t': 'string', 'v': {{discount.code | json}} }, 'discount' : {'t': 'number', 'v': {{discount.amount | money_without_currency | json}} }, {% endfor %} }; transactionData["content_type"] = {"t": "string", "v": "product_group"}; transactionData["currency"] = {"t": "string", "v": {{ checkout.currency | json}}}; /* * If you want the purchase value to be without shipping cost, * Just replace `checkout.total_price` with `checkout.subtotal_price` in below line */ transactionData["value"] = {"t": "number", "v": Number('{{shop.money_format}}'.includes('with_comma_separator') ? {{checkout.total_price | money_without_currency | remove: "." | json}}.replace(',', '.') : {{checkout.total_price | money_without_currency | remove: "," | json}})}; var propertiesToSend = { 'customProperties': transactionData, 'productProperties': products }; setTimeout(function(){ if(transactionData.transaction_number && transactionData.transaction_number.v && window.localStorage){ var purchases_str = localStorage.getItem('cl_past_purchases') || "{}"; var purchases = JSON.parse(purchases_str); if(!purchases[transactionData.transaction_number.v]){ _cl.trackClick('Purchased', propertiesToSend); purchases[transactionData.transaction_number.v] = "true"; window.localStorage.setItem("cl_past_purchases", JSON.stringify(purchases)); } }else{ _cl.trackClick('Purchased', propertiesToSend); } }, 3000) {% endif %} {% endunless %} var checkout_billing_address = clearObject({{checkout.billing_address | json}} || {}); var checkout_shipping_address = clearObject({{checkout.shipping_address | json}} || {}); var order_billing_address = clearObject({{order.billing_address | json}} || {}); var order_shipping_address = clearObject({{order.shipping_address | json}} || {}); var checkout_address = Object.assign ``` -------------------------------- ### Track Shopify Purchases Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/shopify/additional_script_post_purchase_page.html Use this snippet to track purchase events on the Shopify post-purchase page. It captures order details and product information, sending them to the tracking service. It also includes logic to prevent duplicate tracking for the same transaction ID. ```javascript window.clShopifyTrack = function(){ if (!window.Shopify.wasPostPurchasePageSeen) { var order = window.Shopify.order; var products = order.lineItems.map(function(item){ return { "product_id": Number(item.id).toString(), "product_name": item.title, "product_category": item.product.type, "product_price": item.price, "product_quantity": item.quantity, "product_variant": Number(item.variant.sku).toString() } }); var propertiesToSend = { "customProperties": { "transaction_id": { "t": "string", "v": Number(order.id).toString(), }, "value": { "t": "number", "v": order.totalPrice }, "currency": { "t": "string", "v": order.currency } }, "productProperties": products } var transaction_id = Number(order.id).toString() if(transaction_id && window.localStorage){ var purchases_str = localStorage.getItem('cl_past_purchases') || "{}"; var purchases = JSON.parse(purchases_str); if(!purchases[transaction_id]){ _cl.trackClick('Purchased', propertiesToSend); purchases[transaction_id] = "true"; window.localStorage.setItem("cl_past_purchases", JSON.stringify(purchases)); } } else { _cl.trackClick('Purchased', propertiesToSend); } var cltraits = order.customer; if(cltraits["email"]){ var user_traits = {} for(var trait in cltraits){ if(cltraits[trait]){ user_traits[trait] = { "t": "string", "v": cltraits[trait] } } } var props = { "customProperties": { "user_traits": { "t": "Object", "v": user_traits }, "identify_by_email": {"t":"string", "v": cltraits["email"], "ib": true} } } _cl.identify(props) } } } ``` -------------------------------- ### Track Add to Cart Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Tracks when an item is added to the cart. It maps product data and sends a click event with custom properties if _cl is defined. Ensure window.bodlEvents.cart.addItem is available. ```javascript if (typeof window.bodlEvents.cart.addItem === 'function') { window.bodlEvents.cart.addItem((payload) => { try { if (typeof _cl !== 'undefined') { var cust_prop = composeCustomProperties('added_to_cart', payload); var products = bigcommerce_products_mapping(payload, 'line_items'); _cl.trackClick('Added to cart', { customProperties: cust_prop, productProperties: products }); } } catch (e) { console.warn('CL addItem error', e); } }); } ``` -------------------------------- ### Track Order Purchased Event Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html This snippet tracks the 'orderPurchased' event after a successful purchase. It retrieves order details, formats customer and product information, and sends the data to the analytics tracker. Ensure that `getData` and `bigcommerce_products_mapping` are correctly implemented. ```javascript if (typeof window.bodlEvents.checkout.orderPurchased === 'function') { window.bodlEvents.checkout.orderPurchased(async (payload) => { let products = []; try { const data = await getData(`/api/storefront/order/${payload.order_id}`); let customer_id = window.bodl.shopper.customer_id; let billingInfo = data.billingAddress; let customProperties = { "user_traits":{ "bc_customer_id": {"t": "string", "v": customer_id}, "email":{"t": "string", "v": billingInfo.email}, "first_name":{"t": "string", "v": billingInfo.firstName}, "last_name":{"t": "string", "v": billingInfo.lastName}, "company":{"t": "string", "v": billingInfo.company}, "address1":{"t": "string", "v": billingInfo.address1}, "address2":{"t": "string", "v": billingInfo.address2}, "city":{"t": "string", "v": billingInfo.city}, "phone":{"t": "string", "v": billingInfo.phone} } } if (billingInfo.email && billingInfo.email !== null && billingInfo.email !== "") { customProperties["identify_by_email"] = {"t": "string", "v": billingInfo.email, "ib": true}; if (billingInfo.phone && billingInfo.phone !== null && billingInfo.phone !== "") { customProperties["external_ids"] = {"t": "Object", "v": {"identify_by_phone": {"t": "string", "v": billingInfo.phone}}} } } else if (billingInfo.phone && billingInfo.phone !== null && billingInfo.phone !== "") { customProperties["identify_by_phone"] = {"t": "string", "v": billingInfo.phone, "ib": true}; } if (typeof _cl !== 'undefined') { var cust_prop = composeCustomProperties('checkout_completed', payload); var mappedProducts = bigcommerce_products_mapping(payload, 'line_items'); _cl.trackClick('Purchased', { customProperties: cust_prop, productProperties: mappedProducts }); } if(billingInfo.email || billingInfo.phone || customer_id){ triggerIdentify({"customProperties": customProperties}); } } catch (e) { console.warn('CL orderPurchased error', e); } }); } ``` -------------------------------- ### Compose Custom Event Properties Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Generates custom data properties for various BigCommerce events, including product views, searches, and checkout steps. Sets default currency to 'INR'. ```javascript var composeCustomProperties = function(eventName, eventData) { var customData = { "content_type": "product_group" }; if(eventName && eventData) { switch (eventName) { case "product_viewed": customData.currency = eventData.currency || "INR"; customData.value = eventData.product_value || 1; break; case "collection_viewed": customData.category_name = eventData.category_name || ""; customData.category_id = eventData.category_id || ""; break; case "product_added_to_cart": case "product_removed_from_cart": customData.currency = eventData.currency || "INR"; customData.value = eventData.product_value || 1; break; case "search_submitted": customData.search_string = eventData.search_keyword || ""; break; case "cart_viewed": customData.currency = eventData.currency || "INR"; customData.value = eventData.cart_value || 1; break; case "checkout_started": case "checkout_address_info_submitted": case "checkout_contact_info_submitted": case "checkout_shipping_info_submitted": case "payment_info_submitted": customData.currency = eventData.currency || "INR"; customData.value = eventData.cart_value || 1; break; case "checkout_completed": var transaction_number = eventData.order_id; customData.transaction_number = transaction_number; customData.currency = eventData.currency || "INR"; customData.subtotal = eventData.subtotal || 0; customData.tax = eventData.tax || 0; customData.value = eventData.cart_value || 1; customData.shipping = eventData.shipping_price || 0; customData.customer_id = eventData.customer_id || ""; break; default: console.log("Unrecognized Event captured by Bigcommerce Pixel"); break; } return customData; } return {}; }; ``` -------------------------------- ### Trigger Identify Event Source: https://github.com/customerlabs/customerlabs_js_helpers/blob/master/bigcommerce/bigcommerce_analytics_script.html Triggers the CustomerLabs identify event with provided properties. Ensure properties are correctly formatted before calling. ```javascript var triggerIdentify = function(proPerties) { if(proPerties){ _cl.identify(proPerties); } } ```