Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function generateUniqueId(microseconds) {
- // Get the current timestamp in milliseconds
- const timestamp = Date.now();
- // Get the high-resolution time in microseconds
- const highResTime = performance.now() * microseconds;
- // Combine both parts to form a unique ID
- const uniqueId = `${timestamp}-${Math.floor(highResTime)}`;
- return uniqueId;
- }
- function dataLayerError(error) {
- window.dataLayer.push({
- event: "checkout_error",
- gtm: {
- errorMessage: error,
- errorUrl: window.location.href, // Current page URL
- }
- });
- }
- function userDetails() {
- const user_details = {
- log_state: window.user_data.em != null ? "Logged In" : "Logged Out", // User Account Status | Logged In or Logged Out
- user_id: window.user_data.userId, // User Account ID
- // FACEBOOK CAPI (256 Hashed Data)
- // user_hashed_data: {
- email: window.user_hashed_data.em,
- phone_number: window.user_hashed_data.ph,
- first_name: window.user_hashed_data.fn,
- last_name: window.user_hashed_data.ln,
- city: window.user_hashed_data.ct,
- state: window.user_hashed_data.st,
- zip_code: window.user_hashed_data.zp,
- country: window.user_hashed_data.country
- },
- // GOOGLE ADS ENHANCED CONVERSION
- enhanced_conversion: {
- email: window.user_data.em, // Return the users email address
- phone_number: window.user_data.ph, // Return the users phone number
- first_name: window.user_data.fn, // Return the users first name
- last_name: window.user_data.ln, // Return the users last name
- street: window.user_data.street, // Return the users street address
- city: window.user_data.ct, // Return the users City
- state: window.user_data.st, // Return the users state
- zip_code: window.user_data.zp, // Return the users postal zip code
- country: window.user_data.country // Return the users country
- },
- };
- return user_details;
- }
- //page_viewed
- function pageLoaded(content_group) {
- window.dataLayer.push({ page_details: null }); // Clear the previous ecommerce object.
- const pageLoadedEvent = {
- event: "page_loaded",
- page_details: {
- environment: "Production", // Staging or Production
- page_path: window.location.pathname, // Page Path
- page: window.location.pathname + window.location.search, // Full Page Path
- content_group: content_group, // Page Type
- event_id: generateUniqueId(600000000) // Unique Event ID
- },
- // USER DATA OBJECT
- user_details: userDetails() // User details as a separate object within the same event
- };
- window.dataLayer.push(pageLoadedEvent);
- console.log("---Webpixel GTAG: page_viewed datalayer---", window.dataLayer);
- }
- function checkoutUserData(checkout) {
- var fn = checkout.shippingAddress.firstName;
- var ln = checkout.shippingAddress.lastName;
- var ctry = checkout.shippingAddress.country;
- var street = checkout.shippingAddress.address1;
- var ct = checkout.shippingAddress.city;
- var st = checkout.shippingAddress.province;
- var zp = checkout.shippingAddress.zip;
- var em = checkout.email;
- var ph = checkout.shippingAddress.phone;
- var userId = checkout.order.customer.id;
- //Set Key Naming Convention and value
- var userActualData = { "fn": fn, "ln": ln, "street": street, "ct": ct, "st": st, "zp": zp, "country": ctry, "em": em, "ph": ph, "userId": userId };
- //Set Data in Local Storag
- localStorage.setItem("gtm_user_data", JSON.stringify(userActualData));
- //get user hashed data
- window.user_hashed_data = [];
- //get user data
- window.user_data = JSON.parse(localStorage.getItem("gtm_user_data"));
- }
- //checkout_started
- analytics.subscribe('checkout_started', async (event) => {
- const checkout = event.data.checkout;
- checkoutUserData(checkout);
- //GTM INSTALL SCRIPT - should be updated with actual gtm
- (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
- new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
- j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
- 'https://sst.citymattress.com/gtm.js?id='+i+dl+
- '>m_auth=a8Phiutm86iB3SPpPn6IgA>m_preview=env-2>m_cookies_win=x';f.parentNode.insertBefore(j,f);
- })(window,document,'script','dataLayer','GTM-MVJZFKN');
- window.dataLayer = window.dataLayer || [];
- pageLoaded('Checkout');
- let items = [];
- let cart_qty = 0;
- checkout.lineItems.map((item, index) => {
- cart_qty += item.quantity;
- let discount = 0;
- let variantTitle = item.variant.product.title;
- let item_category3 = '';
- let item_category4 = '';
- let item_category5 = '';
- if (item.variant.title != null) {
- variantTitle = item.variant.title;
- let variantTitleSplit = item.variant.title.split(' / ');
- item_category3 = variantTitleSplit[0];
- item_category4 = variantTitleSplit[1];
- item_category5 = variantTitleSplit[2];
- }
- items.push(
- {
- item_id: item.id, // Parent Sku
- item_name: item.title, // Product Name (w/o variant info)
- affiliation: "Shopify Store", // Segment
- currency: checkout.currencyCode, // Product Currency Code
- coupon: null, // Product Level Coupon/Promo
- discount: discount,
- index: index, // Product Click Position in List
- item_brand: item.variant.product.vendor, // Product Brand
- item_category: item.variant.product.type, // Product Type
- item_category2: null, // (Review Available Data)
- item_category3: item_category3, // Product Size | Option 1 (productGlobalObject)
- item_category4: item_category4, // Product Color | Option 2 (productGlobalObject)
- item_category5: item_category5, // Product Color | Option 3 (productGlobalObject)
- item_variant: variantTitle, // Product Variant ID
- item_carousel_title: null, // Original View / Click Product List Carousel Title
- item_list_id: "Product Listing", // Original View / Click Page Type
- item_list_name: "Site Browse", // Site Browse, Product Carousel, or Search Results
- location_id: "Checkout Page", // Current Page Type | Event Location
- price: item.variant.price.amount, // Product Price | Actual Selling Price
- quantity: item.quantity, // Quantity added to cart
- item_sku: item.variant.sku, // Product Sku
- item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
- item_stock_message: item.variant.available ? "In Stock" : "Out of Stock", // In Stock or Out of Stock
- item_stock_quantity: null // Stock Quantity Amount
- }
- );
- });
- let product_revenue = checkout.subtotalPrice.amount;
- let order_discount = checkout.discountsAmount.amount;
- let tax_amount = checkout.totalTax.amount;
- let value = parseFloat(product_revenue) - parseFloat(order_discount) + parseFloat(tax_amount);
- try{
- window.dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
- const checkoutStartedEvent = {
- event: "begin_checkout",
- ecommerce: {
- event_id: generateUniqueId(100000000), // Unique Event ID (Changes per event)
- timestamp: event.timestamp,
- token: event.data.checkout.token,
- url: event.context.document.location.href,
- client_id: event.clientId, //this need to be removed
- content_group: "Checkout", // Page Type
- currency: checkout.currencyCode, // Currency Code
- value: value, // Event Value
- discount: order_discount, // Order Level Discount Amount
- coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null, // Coupon Code
- checkout_section: "Step 1: Checkout Started", // Identify the Checkout Step
- sku_count: checkout.lineItems.length, // Count of unique SKUs
- cart_qty: cart_qty, // Sum of quantity in cart
- product_revenue: product_revenue, // Revenue from products
- // USER DATA OBJECT
- user_details: userDetails(), // User details object
- // GA4 ITEMS ARRAY
- items: items // Items array object
- }
- };
- window.dataLayer.push(checkoutStartedEvent);
- console.log("---Webpixel GTAG: checkout_started datalayer---", window.dataLayer);
- } catch (error) {
- console.error('Failed to push begin checkout event to dataLayer:', error);
- dataLayerError(error);
- }
- });
- //checkout_contact_info_submitted
- analytics.subscribe('checkout_contact_info_submitted', (event) => {
- const checkout = event.data.checkout;
- checkoutUserData(checkout);
- let items = [];
- let cart_qty = 0;
- checkout.lineItems.map((item, index) => {
- cart_qty += item.quantity;
- let discount = 0;
- let variantTitle = item.variant.product.title;
- let item_category3 = '';
- let item_category4 = '';
- let item_category5 = '';
- if (item.variant.title != null) {
- variantTitle = item.variant.title;
- let variantTitleSplit = item.variant.title.split(' / ');
- item_category3 = variantTitleSplit[0];
- item_category4 = variantTitleSplit[1];
- item_category5 = variantTitleSplit[2];
- }
- items.push(
- {
- item_id: item.id, // Parent Sku
- item_name: item.title, // Product Name (w/o variant info)
- affiliation: "Shopify Store", // Segment
- currency: checkout.currencyCode, // Product Currency Code
- coupon: null, // Product Level Coupon/Promo
- discount: discount,
- index: index, // Product Click Position in List
- item_brand: item.variant.product.vendor, // Product Brand
- item_category: item.variant.product.type, // Product Type
- item_category2: null, // (Review Available Data)
- item_category3: item_category3, // Product Size | Option 1 (productGlobalObject)
- item_category4: item_category4, // Product Color | Option 2 (productGlobalObject)
- item_category5: item_category5, // Product Color | Option 3 (productGlobalObject)
- item_variant: variantTitle, // Product Variant ID
- item_carousel_title: null, // Original View / Click Product List Carousel Title
- item_list_id: "Product Listing", // Original View / Click Page Type
- item_list_name: "Site Browse", // Site Browse, Product Carousel, or Search Results
- location_id: "Checkout Page", // Current Page Type | Event Location
- price: item.variant.price.amount, // Product Price | Actual Selling Price
- quantity: item.quantity, // Quantity added to cart
- item_sku: item.variant.sku, // Product Sku
- item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
- item_stock_message: item.variant.available ? "In Stock" : "Out of Stock", // In Stock or Out of Stock
- item_stock_quantity: null // Stock Quantity Amount
- }
- );
- });
- let product_revenue = checkout.subtotalPrice.amount;
- let order_discount = checkout.discountsAmount.amount;
- let tax_amount = checkout.totalTax.amount;
- let value = parseFloat(product_revenue) - parseFloat(order_discount) + parseFloat(tax_amount);
- try{
- window.dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
- const addContactInfoEvent = {
- event: "add_contact_info",
- ecommerce: {
- event_id: generateUniqueId(200000000), // Unique Event ID (Needs to Change on each event)
- timestamp: event.timestamp,
- token: event.data.checkout.token,
- url: event.context.document.location.href,
- client_id: event.clientId, // this should be removed
- content_group: "Checkout", // Page Type
- currency: checkout.currencyCode, // Currency Code
- value: value, // Event Value
- discount: order_discount, // Order Level Discount Amount | Amount Off
- coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null, // e.g. Return Coupon Code / Name
- checkout_section: "Step 2: Contact Info Submitted", // Identify the Checkout Step
- sku_count: checkout.lineItems.length, // Count of unique skus adding to cart
- cart_qty: cart_qty, // Sum of quantity in cart
- product_revenue: product_revenue, // Revenue from products
- // USER DATA OBJECT
- user_details: userDetails(), // User details object
- // GA4 ITEMS ARRAY
- items: items // Items array object
- }
- };
- window.dataLayer.push(addContactInfoEvent);
- console.log('---Webpixel GTAG: checkout_contact_info_submitted datalayer---', window.dataLayer);
- } catch (error) {
- console.error('Failed to push add_contact_info event to dataLayer:', error);
- dataLayerError(error);
- }
- });
- //checkout_shipping_info_submitted
- analytics.subscribe('checkout_shipping_info_submitted', (event) => {
- const checkout = event.data.checkout;
- checkoutUserData(checkout);
- let items = [];
- let cart_qty = 0;
- checkout.lineItems.map((item, index) => {
- cart_qty += item.quantity;
- let discount = 0;
- let variantTitle = item.variant.product.title;
- let item_category3 = '';
- let item_category4 = '';
- let item_category5 = '';
- if (item.variant.title != null) {
- variantTitle = item.variant.title;
- let variantTitleSplit = item.variant.title.split(' / ');
- item_category3 = variantTitleSplit[0];
- item_category4 = variantTitleSplit[1];
- item_category5 = variantTitleSplit[2];
- }
- items.push(
- {
- item_id: item.id, // Parent Sku
- item_name: item.title, // Product Name (w/o variant info)
- affiliation: "Shopify Store", // Segment
- currency: checkout.currencyCode, // Product Currency Code
- coupon: null, // Product Level Coupon/Promo
- discount: discount,
- index: index, // Product Click Position in List
- item_brand: item.variant.product.vendor, // Product Brand
- item_category: item.variant.product.type, // Product Type
- item_category2: null, // (Review Available Data)
- item_category3: item_category3, // Product Size | Option 1 (productGlobalObject)
- item_category4: item_category4, // Product Color | Option 2 (productGlobalObject)
- item_category5: item_category5, // Product Color | Option 3 (productGlobalObject)
- item_variant: variantTitle, // Product Variant ID
- item_carousel_title: null, // Original View / Click Product List Carousel Title
- item_list_id: "Product Listing", // Original View / Click Page Type
- item_list_name: "Site Browse", // Site Browse, Product Carousel, or Search Results
- location_id: "Checkout Page", // Current Page Type | Event Location
- price: item.variant.price.amount, // Product Price | Actual Selling Price
- quantity: item.quantity, // Quantity added to cart
- item_sku: item.variant.sku, // Product Sku
- item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
- item_stock_message: item.variant.available ? "In Stock" : "Out of Stock", // In Stock or Out of Stock
- item_stock_quantity: null // Stock Quantity Amount
- }
- );
- });
- let product_revenue = checkout.subtotalPrice.amount;
- let shipping_amount = checkout.shippingLine.price.amount;
- let shipping_method = null;
- if (checkout.delivery.selectedDeliveryOptions.length > 0) {
- shipping_method = checkout.delivery.selectedDeliveryOptions[0].title;
- }
- try{
- window.dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
- const addShippingInfoEvent = {
- event: "add_shipping_info",
- ecommerce: {
- event_id: generateUniqueId(300000000), // Unique Event ID (Needs to Change on each event)
- timestamp: event.timestamp,
- token: event.data.checkout.token,
- url: event.context.document.location.href,
- client_id: event.clientId, // this should be removed
- content_group: "Checkout", // Page Type
- currency: checkout.currencyCode, // Currency Code
- value: checkout.totalPrice.amount, // Event Value
- discount: checkout.discountsAmount.amount, // Order Level Discount Amount | Amount Off
- coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null, // e.g. Return Coupon Code / Name
- checkout_section: "Step 3: Shipping Method Completed", // Identify the Checkout Step
- shipping_tier: shipping_method, // (Example) or $6 Flat Rate USPS Shipping
- shipping: shipping_amount,
- sku_count: checkout.lineItems.length, // Count of unique skus adding to cart
- cart_qty: cart_qty, // Sum of quantity in cart
- product_revenue: product_revenue, // Revenue from products
- // USER DATA OBJECT
- user_details: userDetails(), // User details object
- // GA4 ITEMS ARRAY
- items: items // Items array object
- }
- };
- };
- window.dataLayer.push(addShippingInfoEvent);
- console.log("---Webpixel GTAG: checkout_shipping_info_submitted datalayer---", window.dataLayer);
- }catch (error) {
- console.error('Failed to push add_shipping_info event to dataLayer:', error);
- dataLayerError(error);
- }
- });
- //payment_info_submitted
- analytics.subscribe('payment_info_submitted', (event) => {
- const checkout = event.data.checkout;
- checkoutUserData(checkout);
- let items = [];
- let cart_qty = 0;
- checkout.lineItems.map((item, index) => {
- cart_qty += item.quantity;
- let discount = 0;
- let variantTitle = item.variant.product.title;
- let item_category3 = '';
- let item_category4 = '';
- let item_category5 = '';
- if (item.variant.title != null) {
- variantTitle = item.variant.title;
- let variantTitleSplit = item.variant.title.split(' / ');
- item_category3 = variantTitleSplit[0];
- item_category4 = variantTitleSplit[1];
- item_category5 = variantTitleSplit[2];
- }
- items.push(
- {
- item_id: item.id, // Parent Sku
- item_name: item.title, // Product Name (w/o variant info)
- affiliation: "Shopify Store", // Segment
- currency: checkout.currencyCode, // Product Currency Code
- coupon: null, // Product Level Coupon/Promo
- discount: discount,
- index: index, // Product Click Position in List
- item_brand: item.variant.product.vendor, // Product Brand
- item_category: item.variant.product.type, // Product Type
- item_category2: null, // (Review Available Data)
- item_category3: item_category3, // Product Size | Option 1 (productGlobalObject)
- item_category4: item_category4, // Product Color | Option 2 (productGlobalObject)
- item_category5: item_category5, // Product Color | Option 3 (productGlobalObject)
- item_variant: variantTitle, // Product Variant ID
- item_carousel_title: null, // Original View / Click Product List Carousel Title
- item_list_id: "Product Listing", // Original View / Click Page Type
- item_list_name: "Site Browse", // Site Browse, Product Carousel, or Search Results
- location_id: "Checkout Page", // Current Page Type | Event Location
- price: item.variant.price.amount, // Product Price | Actual Selling Price
- quantity: item.quantity, // Quantity added to cart
- item_sku: item.variant.sku, // Product Sku
- item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
- item_stock_message: item.variant.available ? "In Stock" : "Out of Stock", // In Stock or Out of Stock
- item_stock_quantity: null // Stock Quantity Amount
- }
- );
- });
- let product_revenue = checkout.subtotalPrice.amount;
- let order_discount = checkout.discountsAmount.amount;
- try{
- window.dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
- const addPaymentInfoEvent = {
- event: "add_payment_info",
- ecommerce: {
- event_id: generateUniqueId(400000000), // Unique Event ID (Needs to Change on each event)
- timestamp: event.timestamp,
- token: event.data.checkout.token,
- url: event.context.document.location.href,
- client_id: event.clientId,
- content_group: "Checkout", // Page Type
- currency: checkout.currencyCode, // Currency Code
- value: checkout.totalPrice.amount, // Event Value
- discount: order_discount, // Order Level Discount Amount | Amount Off
- coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null, // e.g. Return Coupon Code / Name
- checkout_section: "Step 4: Payment Info Completed", // Identify the Checkout Step
- sku_count: checkout.lineItems.length, // Count of unique skus adding to cart
- cart_qty: cart_qty, // Sum of quantity in cart
- product_revenue: product_revenue,
- payment_type: checkout.transactions.gateway, // Credit Card or PayPal
- payment_method: null, // Visa, MasterCard, Amex, Discover
- // USER DATA OBJECT
- user_details: userDetails(), // User details object
- // GA4 ITEMS ARRAY
- items: items // Items array object
- };
- window.dataLayer.push(addPaymentInfoEvent);
- console.log("---Webpixel GTAG: payment_info_submitted datalayer---", window.dataLayer);
- } catch (error) {
- console.error('Failed to push payment_info_submitted event to dataLayer:', error);
- dataLayerError(error);
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement