Advertisement
Vojkovic

woom datalayer

Sep 23rd, 2024
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function generateUniqueId(microseconds) {
  2.   // Get the current timestamp in milliseconds
  3.   const timestamp = Date.now();
  4.  
  5.   // Get the high-resolution time in microseconds
  6.   const highResTime = performance.now() * microseconds;
  7.  
  8.   // Combine both parts to form a unique ID
  9.   const uniqueId = `${timestamp}-${Math.floor(highResTime)}`;
  10.  
  11.   return uniqueId;
  12. }
  13.  
  14. function dataLayerError(error) {
  15.   window.dataLayer.push({
  16.       event: "checkout_error",
  17.       gtm: {
  18.           errorMessage: error,
  19.           errorUrl: window.location.href, // Current page URL
  20.       }
  21.   });
  22. }
  23.  
  24. function userDetails() {
  25.   const user_details = {
  26.       log_state: window.user_data.em != null ? "Logged In" : "Logged Out",                             // User Account Status | Logged In or Logged Out
  27.       user_id: window.user_data.userId,                             // User Account ID
  28.       // FACEBOOK CAPI (256 Hashed Data)
  29.       // user_hashed_data: {
  30.            email: window.user_hashed_data.em,
  31.            phone_number: window.user_hashed_data.ph,
  32.            first_name: window.user_hashed_data.fn,
  33.            last_name: window.user_hashed_data.ln,
  34.            city: window.user_hashed_data.ct,
  35.            state: window.user_hashed_data.st,
  36.            zip_code: window.user_hashed_data.zp,
  37.            country: window.user_hashed_data.country
  38.        },
  39.       // GOOGLE ADS ENHANCED CONVERSION
  40.       enhanced_conversion: {
  41.           email: window.user_data.em,       // Return the users email address
  42.           phone_number: window.user_data.ph,              // Return the users phone number
  43.           first_name: window.user_data.fn,                    // Return the users first name
  44.           last_name: window.user_data.ln,                     // Return the users last name
  45.           street: window.user_data.street,        // Return the users street address
  46.           city: window.user_data.ct,                   // Return the users City
  47.           state: window.user_data.st,                             // Return the users state
  48.           zip_code: window.user_data.zp,                       // Return the users postal zip code
  49.           country: window.user_data.country                            // Return the users country
  50.       },
  51.   };
  52.   return user_details;
  53. }
  54.  
  55. //page_viewed
  56. function pageLoaded(content_group) {
  57.   window.dataLayer.push({ page_details: null });  // Clear the previous ecommerce object.
  58.   const pageLoadedEvent = {
  59.     event: "page_loaded",
  60.     page_details: {
  61.       environment: "Production", // Staging or Production
  62.       page_path: window.location.pathname, // Page Path
  63.       page: window.location.pathname + window.location.search, // Full Page Path
  64.       content_group: content_group, // Page Type
  65.       event_id: generateUniqueId(600000000) // Unique Event ID
  66.     },
  67.     // USER DATA OBJECT
  68.     user_details: userDetails() // User details as a separate object within the same event
  69.   };
  70.   window.dataLayer.push(pageLoadedEvent);
  71.   console.log("---Webpixel GTAG: page_viewed datalayer---", window.dataLayer);
  72. }
  73.  
  74. function checkoutUserData(checkout) {
  75.   var fn = checkout.shippingAddress.firstName;
  76.   var ln = checkout.shippingAddress.lastName;
  77.   var ctry = checkout.shippingAddress.country;
  78.   var street = checkout.shippingAddress.address1;
  79.   var ct = checkout.shippingAddress.city;
  80.   var st = checkout.shippingAddress.province;
  81.   var zp = checkout.shippingAddress.zip;
  82.   var em = checkout.email;
  83.   var ph = checkout.shippingAddress.phone;
  84.   var userId = checkout.order.customer.id;
  85.  
  86.  
  87.   //Set Key Naming Convention and value
  88.   var userActualData = { "fn": fn, "ln": ln, "street": street, "ct": ct, "st": st, "zp": zp, "country": ctry, "em": em, "ph": ph, "userId": userId };
  89.  
  90.   //Set Data in Local Storag
  91.   localStorage.setItem("gtm_user_data", JSON.stringify(userActualData));
  92.  
  93.   //get user hashed data
  94.   window.user_hashed_data = [];
  95.  
  96.   //get user data
  97.   window.user_data = JSON.parse(localStorage.getItem("gtm_user_data"));
  98. }
  99.  
  100. //checkout_started
  101. analytics.subscribe('checkout_started', async (event) => {
  102.   const checkout = event.data.checkout;
  103.   checkoutUserData(checkout);
  104.  
  105.   //GTM INSTALL SCRIPT - should be updated with actual gtm
  106.   (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  107.   new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  108.   j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  109.   'https://sst.citymattress.com/gtm.js?id='+i+dl+
  110.   '&gtm_auth=a8Phiutm86iB3SPpPn6IgA&gtm_preview=env-2&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
  111.   })(window,document,'script','dataLayer','GTM-MVJZFKN');
  112.   window.dataLayer = window.dataLayer || [];
  113.  
  114.   pageLoaded('Checkout');
  115.   let items = [];
  116.   let cart_qty = 0;
  117.   checkout.lineItems.map((item, index) => {
  118.       cart_qty += item.quantity;
  119.       let discount = 0;
  120.  
  121.       let variantTitle = item.variant.product.title;
  122.       let item_category3 = '';
  123.       let item_category4 = '';
  124.       let item_category5 = '';
  125.       if (item.variant.title != null) {
  126.           variantTitle = item.variant.title;
  127.           let variantTitleSplit = item.variant.title.split(' / ');
  128.           item_category3 = variantTitleSplit[0];
  129.           item_category4 = variantTitleSplit[1];
  130.           item_category5 = variantTitleSplit[2];
  131.       }
  132.       items.push(
  133.           {
  134.               item_id: item.id,                           // Parent Sku
  135.               item_name: item.title, // Product Name (w/o variant info)
  136.               affiliation: "Shopify Store",                       // Segment
  137.               currency: checkout.currencyCode,                                    // Product Currency Code
  138.               coupon: null,                                // Product Level Coupon/Promo
  139.               discount: discount,
  140.               index: index,                                           // Product Click Position in List
  141.               item_brand: item.variant.product.vendor,                             // Product Brand
  142.               item_category: item.variant.product.type,                           // Product Type
  143.               item_category2: null,                          // (Review Available Data)
  144.               item_category3: item_category3,                         // Product Size | Option 1 (productGlobalObject)
  145.               item_category4: item_category4,                            // Product Color | Option 2 (productGlobalObject)
  146.               item_category5: item_category5,                          // Product Color | Option 3 (productGlobalObject)
  147.               item_variant: variantTitle,                     // Product Variant ID
  148.               item_carousel_title: null,                     // Original View / Click Product List Carousel Title
  149.               item_list_id: "Product Listing",                    // Original View / Click Page Type
  150.               item_list_name: "Site Browse",                      // Site Browse, Product Carousel, or Search Results
  151.               location_id: "Checkout Page",                      // Current Page Type | Event Location
  152.               price: item.variant.price.amount,                                      // Product Price | Actual Selling Price
  153.               quantity: item.quantity,                                        // Quantity added to cart
  154.               item_sku: item.variant.sku,                       // Product Sku
  155.               item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
  156.               item_stock_message: item.variant.available ? "In Stock" : "Out of Stock",                     // In Stock or Out of Stock
  157.               item_stock_quantity: null                            // Stock Quantity Amount
  158.           }
  159.       );
  160.   });
  161.  
  162.   let product_revenue = checkout.subtotalPrice.amount;
  163.   let order_discount = checkout.discountsAmount.amount;
  164.   let tax_amount = checkout.totalTax.amount;
  165.   let value = parseFloat(product_revenue) - parseFloat(order_discount) + parseFloat(tax_amount);
  166.  
  167.   try{
  168.       window.dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
  169.       const checkoutStartedEvent = {
  170.           event: "begin_checkout",
  171.           ecommerce: {
  172.               event_id: generateUniqueId(100000000), // Unique Event ID (Changes per event)
  173.               timestamp: event.timestamp,
  174.               token: event.data.checkout.token,
  175.               url: event.context.document.location.href,
  176.               client_id: event.clientId, //this need to be removed
  177.               content_group: "Checkout", // Page Type
  178.               currency: checkout.currencyCode, // Currency Code
  179.               value: value, // Event Value
  180.               discount: order_discount, // Order Level Discount Amount
  181.               coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null, // Coupon Code
  182.               checkout_section: "Step 1: Checkout Started", // Identify the Checkout Step
  183.               sku_count: checkout.lineItems.length, // Count of unique SKUs
  184.               cart_qty: cart_qty, // Sum of quantity in cart
  185.               product_revenue: product_revenue, // Revenue from products
  186.     // USER DATA OBJECT
  187.              user_details: userDetails(), // User details object
  188.     // GA4 ITEMS ARRAY
  189.              items: items // Items array object
  190.   }
  191. };
  192.       window.dataLayer.push(checkoutStartedEvent);
  193.       console.log("---Webpixel GTAG: checkout_started datalayer---", window.dataLayer);
  194.   } catch (error) {
  195.       console.error('Failed to push begin checkout event to dataLayer:', error);
  196.       dataLayerError(error);
  197.   }
  198. });
  199.  
  200. //checkout_contact_info_submitted
  201. analytics.subscribe('checkout_contact_info_submitted', (event) => {
  202.   const checkout = event.data.checkout;
  203.   checkoutUserData(checkout);
  204.   let items = [];
  205.   let cart_qty = 0;
  206.   checkout.lineItems.map((item, index) => {
  207.       cart_qty += item.quantity;
  208.       let discount = 0;
  209.      
  210.       let variantTitle = item.variant.product.title;
  211.       let item_category3 = '';
  212.       let item_category4 = '';
  213.       let item_category5 = '';
  214.       if (item.variant.title != null) {
  215.           variantTitle = item.variant.title;
  216.           let variantTitleSplit = item.variant.title.split(' / ');
  217.           item_category3 = variantTitleSplit[0];
  218.           item_category4 = variantTitleSplit[1];
  219.           item_category5 = variantTitleSplit[2];
  220.       }
  221.       items.push(
  222.           {
  223.           item_id: item.id,                           // Parent Sku
  224.           item_name: item.title, // Product Name (w/o variant info)
  225.           affiliation: "Shopify Store",                       // Segment
  226.           currency: checkout.currencyCode,                                    // Product Currency Code
  227.           coupon: null,                                // Product Level Coupon/Promo
  228.           discount: discount,
  229.           index: index,                                           // Product Click Position in List
  230.           item_brand: item.variant.product.vendor,                             // Product Brand
  231.           item_category: item.variant.product.type,                           // Product Type
  232.           item_category2: null,                          // (Review Available Data)
  233.           item_category3: item_category3,                         // Product Size | Option 1 (productGlobalObject)
  234.           item_category4: item_category4,                            // Product Color | Option 2 (productGlobalObject)
  235.           item_category5: item_category5,                          // Product Color | Option 3 (productGlobalObject)
  236.           item_variant: variantTitle,                     // Product Variant ID
  237.           item_carousel_title: null,                     // Original View / Click Product List Carousel Title
  238.           item_list_id: "Product Listing",                    // Original View / Click Page Type
  239.           item_list_name: "Site Browse",                      // Site Browse, Product Carousel, or Search Results
  240.           location_id: "Checkout Page",                      // Current Page Type | Event Location
  241.           price: item.variant.price.amount,                                      // Product Price | Actual Selling Price
  242.           quantity: item.quantity,                                        // Quantity added to cart
  243.           item_sku: item.variant.sku,                       // Product Sku
  244.           item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
  245.           item_stock_message: item.variant.available ? "In Stock" : "Out of Stock",                     // In Stock or Out of Stock
  246.           item_stock_quantity: null                            // Stock Quantity Amount
  247.           }
  248.       );
  249.   });
  250.  
  251.   let product_revenue = checkout.subtotalPrice.amount;
  252.   let order_discount = checkout.discountsAmount.amount;
  253.   let tax_amount = checkout.totalTax.amount;
  254.   let value = parseFloat(product_revenue) - parseFloat(order_discount) + parseFloat(tax_amount);
  255.  
  256.   try{
  257.       window.dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
  258.       const addContactInfoEvent = {
  259.           event: "add_contact_info",
  260.           ecommerce: {
  261.               event_id: generateUniqueId(200000000), // Unique Event ID (Needs to Change on each event)
  262.               timestamp: event.timestamp,
  263.               token: event.data.checkout.token,
  264.               url: event.context.document.location.href,
  265.               client_id: event.clientId, // this should be removed
  266.               content_group: "Checkout",                            // Page Type
  267.               currency: checkout.currencyCode,                                  // Currency Code
  268.               value: value,                                    // Event Value
  269.               discount: order_discount,                                  // Order Level Discount Amount | Amount Off  
  270.               coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null,                                // e.g. Return Coupon Code / Name
  271.               checkout_section: "Step 2: Contact Info Submitted",      // Identify the Checkout Step
  272.               sku_count: checkout.lineItems.length,                                     // Count of unique skus adding to cart
  273.               cart_qty: cart_qty,                                     // Sum of quantity in cart
  274.               product_revenue: product_revenue, // Revenue from products
  275.     // USER DATA OBJECT
  276.               user_details: userDetails(), // User details object
  277.     // GA4 ITEMS ARRAY
  278.               items: items // Items array object
  279.   }
  280. };
  281.       window.dataLayer.push(addContactInfoEvent);
  282.       console.log('---Webpixel GTAG: checkout_contact_info_submitted datalayer---', window.dataLayer);
  283.   } catch (error) {
  284.       console.error('Failed to push add_contact_info event to dataLayer:', error);
  285.       dataLayerError(error);
  286.   }
  287. });
  288.  
  289. //checkout_shipping_info_submitted
  290. analytics.subscribe('checkout_shipping_info_submitted', (event) => {
  291.   const checkout = event.data.checkout;
  292.   checkoutUserData(checkout);
  293.   let items = [];
  294.   let cart_qty = 0;
  295.   checkout.lineItems.map((item, index) => {
  296.       cart_qty += item.quantity;
  297.       let discount = 0;
  298.      
  299.       let variantTitle = item.variant.product.title;
  300.       let item_category3 = '';
  301.       let item_category4 = '';
  302.       let item_category5 = '';
  303.       if (item.variant.title != null) {
  304.           variantTitle = item.variant.title;
  305.           let variantTitleSplit = item.variant.title.split(' / ');
  306.           item_category3 = variantTitleSplit[0];
  307.           item_category4 = variantTitleSplit[1];
  308.           item_category5 = variantTitleSplit[2];
  309.       }
  310.       items.push(
  311.           {
  312.           item_id: item.id,                           // Parent Sku
  313.           item_name: item.title, // Product Name (w/o variant info)
  314.           affiliation: "Shopify Store",                       // Segment
  315.           currency: checkout.currencyCode,                                    // Product Currency Code
  316.           coupon: null,                                // Product Level Coupon/Promo
  317.           discount: discount,
  318.           index: index,                                           // Product Click Position in List
  319.           item_brand: item.variant.product.vendor,                             // Product Brand
  320.           item_category: item.variant.product.type,                           // Product Type
  321.           item_category2: null,                          // (Review Available Data)
  322.           item_category3: item_category3,                         // Product Size | Option 1 (productGlobalObject)
  323.           item_category4: item_category4,                            // Product Color | Option 2 (productGlobalObject)
  324.           item_category5: item_category5,                          // Product Color | Option 3 (productGlobalObject)
  325.           item_variant: variantTitle,                     // Product Variant ID
  326.           item_carousel_title: null,                     // Original View / Click Product List Carousel Title
  327.           item_list_id: "Product Listing",                    // Original View / Click Page Type
  328.           item_list_name: "Site Browse",                      // Site Browse, Product Carousel, or Search Results
  329.           location_id: "Checkout Page",                      // Current Page Type | Event Location
  330.           price: item.variant.price.amount,                                      // Product Price | Actual Selling Price
  331.           quantity: item.quantity,                                        // Quantity added to cart
  332.           item_sku: item.variant.sku,                       // Product Sku
  333.           item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
  334.           item_stock_message: item.variant.available ? "In Stock" : "Out of Stock",                     // In Stock or Out of Stock
  335.           item_stock_quantity: null                            // Stock Quantity Amount
  336.           }
  337.       );
  338.   });
  339.  
  340.   let product_revenue = checkout.subtotalPrice.amount;
  341.   let shipping_amount = checkout.shippingLine.price.amount;
  342.   let shipping_method =  null;
  343.   if (checkout.delivery.selectedDeliveryOptions.length > 0) {
  344.       shipping_method = checkout.delivery.selectedDeliveryOptions[0].title;
  345.   }
  346.  
  347.   try{
  348.       window.dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
  349.       const addShippingInfoEvent = {
  350.           event: "add_shipping_info",
  351.           ecommerce: {
  352.               event_id: generateUniqueId(300000000), // Unique Event ID (Needs to Change on each event)
  353.               timestamp: event.timestamp,
  354.               token: event.data.checkout.token,
  355.               url: event.context.document.location.href,
  356.               client_id: event.clientId, // this should be removed
  357.               content_group: "Checkout",                            // Page Type
  358.               currency: checkout.currencyCode,                                  // Currency Code
  359.               value: checkout.totalPrice.amount,                                    // Event Value
  360.               discount: checkout.discountsAmount.amount,                                  // Order Level Discount Amount | Amount Off  
  361.               coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null,                                // e.g. Return Coupon Code / Name
  362.               checkout_section: "Step 3: Shipping Method Completed", // Identify the Checkout Step
  363.               shipping_tier: shipping_method,       // (Example) or $6 Flat Rate USPS Shipping
  364.               shipping: shipping_amount,
  365.               sku_count: checkout.lineItems.length,                                     // Count of unique skus adding to cart
  366.               cart_qty: cart_qty,                                     // Sum of quantity in cart
  367.               product_revenue: product_revenue, // Revenue from products
  368.     // USER DATA OBJECT
  369.               user_details: userDetails(), // User details object
  370.     // GA4 ITEMS ARRAY
  371.               items: items // Items array object
  372.   }
  373. };
  374.   };
  375.  
  376.       window.dataLayer.push(addShippingInfoEvent);
  377.       console.log("---Webpixel GTAG: checkout_shipping_info_submitted datalayer---", window.dataLayer);
  378.   }catch (error) {
  379.       console.error('Failed to push add_shipping_info event to dataLayer:', error);
  380.       dataLayerError(error);
  381.   }
  382. });
  383.  
  384. //payment_info_submitted
  385. analytics.subscribe('payment_info_submitted', (event) => {
  386.   const checkout = event.data.checkout;
  387.   checkoutUserData(checkout);
  388.   let items = [];
  389.   let cart_qty = 0;
  390.   checkout.lineItems.map((item, index) => {
  391.       cart_qty += item.quantity;
  392.       let discount = 0;
  393.      
  394.       let variantTitle = item.variant.product.title;
  395.       let item_category3 = '';
  396.       let item_category4 = '';
  397.       let item_category5 = '';
  398.       if (item.variant.title != null) {
  399.           variantTitle = item.variant.title;
  400.           let variantTitleSplit = item.variant.title.split(' / ');
  401.           item_category3 = variantTitleSplit[0];
  402.           item_category4 = variantTitleSplit[1];
  403.           item_category5 = variantTitleSplit[2];
  404.       }
  405.       items.push(
  406.           {
  407.           item_id: item.id,                           // Parent Sku
  408.           item_name: item.title, // Product Name (w/o variant info)
  409.           affiliation: "Shopify Store",                       // Segment
  410.           currency: checkout.currencyCode,                                    // Product Currency Code
  411.           coupon: null,                                // Product Level Coupon/Promo
  412.           discount: discount,
  413.           index: index,                                           // Product Click Position in List
  414.           item_brand: item.variant.product.vendor,                             // Product Brand
  415.           item_category: item.variant.product.type,                           // Product Type
  416.           item_category2: null,                          // (Review Available Data)
  417.           item_category3: item_category3,                         // Product Size | Option 1 (productGlobalObject)
  418.           item_category4: item_category4,                            // Product Color | Option 2 (productGlobalObject)
  419.           item_category5: item_category5,                          // Product Color | Option 3 (productGlobalObject)
  420.           item_variant: variantTitle,                     // Product Variant ID
  421.           item_carousel_title: null,                     // Original View / Click Product List Carousel Title
  422.           item_list_id: "Product Listing",                    // Original View / Click Page Type
  423.           item_list_name: "Site Browse",                      // Site Browse, Product Carousel, or Search Results
  424.           location_id: "Checkout Page",                      // Current Page Type | Event Location
  425.           price: item.variant.price.amount,                                      // Product Price | Actual Selling Price
  426.           quantity: item.quantity,                                        // Quantity added to cart
  427.           item_sku: item.variant.sku,                       // Product Sku
  428.           item_shopify_id: "shopify_US_" + item.variant.product.id + "_" + item.variant.id, // Full Sku (Parent + Variant)
  429.           item_stock_message: item.variant.available ? "In Stock" : "Out of Stock",                     // In Stock or Out of Stock
  430.           item_stock_quantity: null                            // Stock Quantity Amount
  431.           }
  432.       );
  433.   });
  434.   let product_revenue = checkout.subtotalPrice.amount;
  435.   let order_discount = checkout.discountsAmount.amount;
  436.  
  437.   try{
  438.       window.dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
  439.       const addPaymentInfoEvent = {
  440.           event: "add_payment_info",
  441.           ecommerce: {
  442.               event_id: generateUniqueId(400000000), // Unique Event ID (Needs to Change on each event)
  443.               timestamp: event.timestamp,
  444.               token: event.data.checkout.token,
  445.               url: event.context.document.location.href,
  446.               client_id: event.clientId,
  447.               content_group: "Checkout",                            // Page Type
  448.               currency: checkout.currencyCode,                                  // Currency Code
  449.               value: checkout.totalPrice.amount,                                    // Event Value
  450.               discount: order_discount,                                  // Order Level Discount Amount | Amount Off  
  451.               coupon: checkout.discountApplications.length ? checkout.discountApplications[0].title : null,                                // e.g. Return Coupon Code / Name
  452.               checkout_section: "Step 4: Payment Info Completed", // Identify the Checkout Step        
  453.               sku_count: checkout.lineItems.length,                                     // Count of unique skus adding to cart
  454.               cart_qty: cart_qty,                                     // Sum of quantity in cart
  455.               product_revenue: product_revenue,
  456.               payment_type: checkout.transactions.gateway,                        // Credit Card or PayPal
  457.               payment_method: null,                             // Visa, MasterCard, Amex, Discover
  458.         // USER DATA OBJECT
  459.         user_details: userDetails(), // User details object
  460.        // GA4 ITEMS ARRAY
  461.         items: items // Items array object
  462.   };
  463.       window.dataLayer.push(addPaymentInfoEvent);
  464.       console.log("---Webpixel GTAG: payment_info_submitted datalayer---", window.dataLayer);
  465.   } catch (error) {
  466.       console.error('Failed to push payment_info_submitted event to dataLayer:', error);
  467.       dataLayerError(error);
  468.   }
  469. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement