(function(shopify) {shopify.extend('WebPixel::Render', function(api) { var analytics=api.analytics,browser=api.browser,init=api.init; // Added with Analyzify v4 - "08-03-2025 08:35" // VARIABLES const px_config = { BING_UET: { id: "97054685", }, flags: { page_viewed: true, product_added_to_cart: "false" == "true" ? true : false, checkout_started: "true" == "true" ? true : false, checkout_contact_info_submitted: true, checkout_address_info_submitted: true, checkout_shipping_info_submitted: true, payment_info_submitted: true, checkout_completed: "true" == "true" ? true : false, }, }; const feed_region = "DE"; const item_id_format = "variant_id"; /* item_id_format Options: - variant_id - product_id (default) - product_sku - null (shopify_XX_product_id_variant_id) */ const consentModeEnabled = "true" == "true" ? true : false; /* consent_mode Options: - true: Consent Mode enabled - false: Consent Mode disabled */ const totalValue_option = null; /* totalValue_option Options: - net: without shipping and taxes - no_shipping: without shipping - no_tax: without taxes - null: total price with shipping and taxes */ const add_to_cart_only_collections = true; const add_to_cart_only_pdp = true; const add_to_cart_only_home = false; const user_data = 'email'; const version = "1.4.0"; const debug = { status: false, detail: false, color: "background:#901e1e;color:#fff;", msg: "Analyzify Bing Pixel ->" } const initData = init?.data || {}; const initCart = initData?.cart || {}; window.uetq = window.uetq || []; async function BingUETInit(BING_UET_ID) { try { (function(w,d,t,r,u){var f,n,i;w[u]=w[u]||[],f=function(){var o={ti:px_config.BING_UET.id, enableAutoSpaTracking: true};o.q=w[u],w[u]=new UET(o),w[u].push("pageLoad")},n=d.createElement(t),n.src=r,n.async=1,n.onload=n.onreadystatechange=function(){var s=this.readyState;s&&s!=="loaded"&&s!=="complete"||(f(),n.onload=n.onreadystatechange=null)},i=d.getElementsByTagName(t)[0],i.parentNode.insertBefore(n,i)})(window,document,"script","//bat.bing.com/bat.js","uetq"); window.uetq = window.uetq || []; if (debug.status) console.log(`%c%s BingUETInit is initiated for ${BING_UET_ID}`, debug.color, debug.msg); // Check if consent mode is enabled if (consentModeEnabled) await uet_consent(); } catch (error) { console.error("%c%s Error in BingUETInit: ", debug.color, debug.msg, error); } } // FUNCTIONS const getTotal = (valueObj, total, shipping, tax, subtotal) => { try { const totalValue = total || valueObj?.totalPrice?.amount || 0; const shippingValue = shipping || valueObj?.shippingLine?.price?.amount || 0; const taxValue = tax || valueObj?.totalTax?.amount || 0; const subTotal = subtotal || valueObj?.subtotalPrice?.amount || 0; let finalValue = 0; switch (totalValue_option) { case 'net': finalValue = subTotal; break; case 'no_shipping': finalValue = subTotal + taxValue; break; case 'no_tax': finalValue = subTotal + shippingValue; break; default: finalValue = totalValue; break; } return Number(parseFloat(finalValue).toFixed(2)); } catch (error) { console.error('getTotal error:', error); return 0; // Ensure a fallback return value } } function doesPagePath(event, paths, scope = 'contain') { const document = event.context.document; const pageLocation = document.location.href; return paths.some((path) => { switch (scope) { case 'start': return pageLocation.startsWith(path); case 'equal': return pageLocation === path; case 'contain': default: return pageLocation.includes(path); } }); } async function uet_consent() { // Consent Mode Initialization try { const consent_version = "1.1"; let initConsent = init?.customerPrivacy || {}; let getCMPCookieValue = null; let getTrackingConsentValue = null; // Check cookies only if initConsent is not available if (!initConsent?.marketingAllowed && !initConsent?.analyticsProcessingAllowed) { try { [getCMPCookieValue, getTrackingConsentValue] = await Promise.all([ browser.cookie.get("_cmp_a"), browser.cookie.get("_tracking_consent"), ]); if (debug?.status) { console.log("%c%s Loading cookie consent values", debug.color, debug.msg, { _cmp_a: getCMPCookieValue, _tracking_consent: getTrackingConsentValue, }); } } catch (error) { console.warn("%c%s Error fetching cookies:", debug?.color, debug?.msg, error); } } if (debug?.status) { console.log("%c%s Initial Consent", debug.color, debug.msg, initConsent || { _cmp_a: getCMPCookieValue, _tracking_consent: getTrackingConsentValue }); } let currentConsent = {}; let currentConsentPurpose = {}; try { const consentCookie = decodeURIComponent(getCMPCookieValue || getTrackingConsentValue); currentConsent = JSON.parse(consentCookie) || {}; currentConsentPurpose = currentConsent?.purposes || {}; } catch (parseError) { console.warn("%c%s Error parsing consent cookie, using defaults:", debug?.color, debug?.msg, parseError); } const cmpConsent = getTrackingConsentValue?.con?.CMP || {}; const consentSettings = { ad_storage: initConsent?.marketingAllowed || currentConsentPurpose?.m === true || (cmpConsent?.m !== undefined && cmpConsent?.m !== '0') ? "granted" : "denied", analytics_storage: initConsent?.analyticsProcessingAllowed || currentConsentPurpose?.a === true || (cmpConsent?.a !== undefined && cmpConsent?.a !== '0') ? "granted" : "denied", ad_user_data: initConsent?.marketingAllowed || currentConsentPurpose?.m === true || (cmpConsent?.m !== undefined && cmpConsent?.m !== '0') ? "granted" : "denied", ad_personalization: initConsent?.marketingAllowed || currentConsentPurpose?.m === true || (cmpConsent?.m !== undefined && cmpConsent?.m !== '0') ? "granted" : "denied", analyzify_consent: ( initConsent?.analyticsProcessingAllowed || (currentConsentPurpose?.a === true || (cmpConsent?.a !== undefined && cmpConsent?.a !== '0')) ) && ( initConsent?.marketingAllowed || currentConsentPurpose?.m === true || (cmpConsent?.m !== undefined && cmpConsent?.m !== '0') ) ? "granted" : "denied", }; if (debug?.status) { console.log("%c%s Final Consent Settings", debug.color, debug.msg, consentSettings); } const consentObj = { ...consentSettings, wait_for_update: 500 }; // Bing - Consent window.uetq.push("consent", "default", consentObj); if (debug.status) console.log(`%c%s Consent settings applied (v${consent_version})`, debug.color, debug.msg, consentObj); } catch (error) { console.error("%c%s Error fetching or parsing consent cookie:", debug.color, debug.msg, JSON.stringify(error)); } if (debug.status) console.log('%c%s uet_consent is initiated!', debug.color, debug.msg); } const getUserData = async (checkoutData, initData) => { // Extract data from init const initCustomer = initData?.customer || {}; const initEmail = initCustomer.email || initData?.email || null; const initPhone = initCustomer.phone || initData?.phone || null; // Extract data from checkoutData const checkoutCustomer = checkoutData?.order?.customer || {}; const checkoutEmail = checkoutData?.email || checkoutCustomer?.email || null; const checkoutPhone = checkoutData?.phone || checkoutCustomer?.phone || null; const billingAddress = checkoutData?.billingAddress || {}; const shippingAddress = checkoutData?.shippingAddress || {}; // Determine the primary data source for user info const email = checkoutEmail || initEmail || null; const phone = checkoutPhone || initPhone || billingAddress?.phone || shippingAddress?.phone || null; const customerId = checkoutCustomer?.id || initCustomer?.id || null; // Create the final user data object const userData = user_data === 'email' ? { em: email, } : { external_id: customerId, em: email, ph: phone, fn: billingAddress?.firstName || shippingAddress?.firstName || initCustomer?.firstName || null, ln: billingAddress?.lastName || shippingAddress?.lastName || initCustomer?.lastName || null, country: billingAddress?.country || shippingAddress?.country || null, zip: billingAddress?.zip || shippingAddress?.zip || null, }; if (debug.status && debug.detail) console.log('%c%s userData', debug.color, debug.msg, userData); return userData; } const bingEvent = (event, data) => { window.uetq.push('event', 'ecommerce', { event_category: event, ...data, }); if (debug.status) console.log(`%c%s ${event}`, debug.color, debug.msg, data); } const checkoutEvents = { checkout_started: 'begin_checkout', accelerated_checkout_started: 'add_contact_info', checkout_contact_info_submitted: 'add_contact_info', checkout_address_info_submitted: 'add_address_info', checkout_shipping_info_submitted: 'add_shipping_info', payment_info_submitted: 'add_payment_info', checkout_completed: "purchase" } const getItemObj = (itemObj) => { try { if (!itemObj) { console.error('Invalid itemObj:', itemObj); return null; } const item = itemObj.variant || itemObj.merchandise || itemObj.productVariant; let selected_id; switch(item_id_format) { case 'variant_id': selected_id = item?.id; break; case 'product_id': selected_id = item?.product?.id; break; case 'product_sku': selected_id = item?.sku || item?.id || item?.product?.id; break; default: selected_id = `shopify_${feed_region}_${item?.product?.id || ''}_${item?.id || ''}`; } const discountAll = itemObj?.discountAllocations?.reduce((total, discount) => { return total + Number(parseFloat(discount?.amount?.amount) || 0); }, 0) || 0; const computedDiscount = itemObj?.finalLinePrice?.amount ? parseFloat(item?.price?.amount - itemObj.finalLinePrice?.amount) : 0; const getDiscount = Number((discountAll || computedDiscount).toFixed(2)); return { id: selected_id || null, name: item?.product?.title?.trim() || item?.title?.trim() || null, category: item?.product?.type || null, sku: item?.sku || null, discount: getDiscount || 0, price: item?.price?.amount || 0, quantity: item?.quantity || itemObj?.quantity || 1, currency: item?.price?.currencyCode || initCart?.cost?.totalAmount?.currencyCode, }; } catch (error) { console.error('getItemObj error:', error); } } const populateEccomm = async (items, pageType) => { try { const eccomm = { ecomm_prodid: [], ecomm_prodname: [], ecomm_totalvalue: 0, ecomm_category: [], ecomm_pagetype: pageType // Set the page type based on the context }; items.forEach(item => { eccomm.ecomm_prodid.push(item?.id || item?.sku); eccomm.ecomm_prodname.push(item?.name); eccomm.ecomm_category.push(item?.category || null); eccomm.ecomm_totalvalue += Number(parseFloat(item?.price * item?.quantity).toFixed(2)); }); return eccomm; } catch(err) { console.log('err', err); } } const getCheckoutEventData = async (checkoutData, pageType) => { const productData = await Promise.all( (checkoutData?.lineItems || []).map(async (item) => { const itemData = await getItemObj(item); return { ...itemData, quantity: item.quantity || 1, }; }) ); const eccomm = await populateEccomm(productData, pageType ? pageType : 'other'); // Calculate the total revenue value const getTotalValue = getTotal(null, checkoutData?.totalPrice?.amount || 0, checkoutData?.shippingLine?.price?.amount || 0, checkoutData?.totalTax?.amount || 0 ); eccomm.ecomm_totalvalue = getTotalValue; return { items: productData, ...eccomm, revenue_value: getTotalValue, currency: checkoutData?.totalPrice?.currencyCode }; } const handleAddToCartEvent = async (cartData) => { const itemData = await getItemObj(cartData); const eccomm = await populateEccomm([itemData], "product"); // Push the add to cart event with the populated eccomm object bingEvent('add_to_cart', { items: [itemData], ...eccomm, revenue_value: eccomm.ecomm_totalvalue, currency: cartData?.cost?.totalAmount?.currencyCode }); } const handleCheckoutEvent = async (eventName, checkoutData, pageType) => { if (debug.status && debug.detail) console.log('%c%s checkoutData in handleCheckoutEvent:', debug.color, debug.msg, checkoutData); // Debugging line if (px_config.flags[eventName]) { await bingEvent(checkoutEvents[eventName], await getCheckoutEventData(checkoutData, pageType)); } const userData = await getUserData(checkoutData, initData); window.uetq.push("set", { pid: userData }); } const logEventDebug = (eventName) => { if (debug.status) { console.log(`%c%s all_events -> ${eventName}`, debug.color, debug.msg); } } analytics.subscribe("all_events", async (event) => { try { const eventHandlers = { page_viewed: async () => { try { if (px_config.flags.page_viewed && doesPagePath(event, ["/checkouts", "/orders"], "contain")) { await BingUETInit(px_config.BING_UET.id); window.uetq.push('event', 'page_view', { event_category: "checkout", }); } } catch(err){ console.error(`${event.name} has an issue`); } }, product_viewed: async () => { //... }, // cartLine product_added_to_cart: async () => { try { if (px_config.flags.product_added_to_cart) { const cartData = event.data.cartLine; await BingUETInit(px_config.BING_UET.id); // for collections if (add_to_cart_only_collections && doesPagePath(event, ["/collections"], 'contain')) { await handleAddToCartEvent(cartData); } // for product detail page if (add_to_cart_only_pdp && doesPagePath(event, ["/products"], 'contain')) { await handleAddToCartEvent(cartData); } // for homepage if (add_to_cart_only_home && doesPagePath(event, ["/"], 'equal')) { await handleAddToCartEvent(cartData); } } } catch(err){ console.error(`${event.name} has an issue`); } }, // merchandise checkout_started: async (event) => { try { handleCheckoutEvent('checkout_started', event.data.checkout, 'other'); } catch(err){ console.error(`${event.name} has an issue`); } }, checkout_contact_info_submitted: async (event) => { try { handleCheckoutEvent('checkout_contact_info_submitted', event.data.checkout, 'other'); } catch(err){ console.error(`${event.name} has an issue`); } }, checkout_address_info_submitted: async (event) => { try { handleCheckoutEvent('checkout_address_info_submitted', event.data.checkout, 'other'); } catch(err){ console.error(`${event.name} has an issue`); } }, checkout_shipping_info_submitted: async (event) => { try { handleCheckoutEvent('checkout_shipping_info_submitted', event.data.checkout, 'other'); } catch(err){ console.error(`${event.name} has an issue`); } }, payment_info_submitted: async (event) => { try { handleCheckoutEvent('payment_info_submitted', event.data.checkout, 'other'); } catch(err){ console.error(`${event.name} has an issue`); } }, checkout_completed: async () => { try { if (px_config.flags.checkout_completed) { await BingUETInit(px_config.BING_UET.id); if (px_config.flags.page_viewed) { window.uetq.push('event', 'page_view', { event_category: "order_confirmation" }); } handleCheckoutEvent('checkout_completed', event.data.checkout, 'purchase'); } } catch(err){ console.error(`${event.name} has an issue`); } } }; if (eventHandlers[event.name]) { await eventHandlers[event.name](event); // Ensure the event is passed to the handler logEventDebug(event.name); } } catch (error) { console.error('all_events error:', error); } }); console.log("%c%s Bing Ads UET Script is loaded!", debug.color, debug.msg); });})(self.webPixelsManager.createShopifyExtend('205685004', 'custom'));