Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- analytics.subscribe("checkout_completed", event => {
- (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://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
- })(window,document,'script','dataLayer','GTM-XXXXXXX');
- var totalDiscount = 0;
- var shippingDiscount = event.data.checkout.discountApplications.find(discount => discount.targetType === "SHIPPING_LINE");
- if (shippingDiscount) {
- shippingDiscount = "true";
- totalDiscount += event.data.checkout.shippingLine.price.amount;
- }
- else {
- shippingDiscount = "false";
- }
- event.data.checkout.lineItems.forEach(lineItem => {
- lineItem.discountAllocations.forEach(discountAllocation => {
- totalDiscount += discountAllocation.amount.amount;
- });
- });
- var items = event.data.checkout.lineItems.map(item => ({
- item_name: item.variant.product.title,
- item_id: item.variant.product.id,
- currency: item.variant.price.currencyCode,
- price: item.variant.price.amount - item.discountAllocations[0].amount.amount,
- price_before_discount : item.variant.price.amount,
- item_category: item.variant.product.type,
- item_category5: item.variant.title,
- item_variant: item.variant.title,
- quantity: item.quantity
- }));
- async function hashString(input) {
- const encoder = new TextEncoder();
- const data = encoder.encode(input);
- const hash = await crypto.subtle.digest('SHA-256', data);
- return Array.from(new Uint8Array(hash)).map(byte => byte.toString(16).padStart(2, '0')).join('');
- }
- (async () => {
- const inputString = event.data.checkout.email;
- const hashedEmail = await hashString(inputString);
- dataLayer.push({
- event: 'purchase',
- email: event.data.checkout.email,
- hashed_email: hashedEmail,
- first_name: event.data.checkout.billingAddress.firstName,
- last_name: event.data.checkout.billingAddress.lastName,
- address: event.data.checkout.billingAddress.address1,
- city: event.data.checkout.billingAddress.city,
- state: event.data.checkout.billingAddress.provinceCode,
- country: event.data.checkout.billingAddress.countryCode,
- zipcode: event.data.checkout.billingAddress.zip,
- phone: event.data.checkout.billingAddress.phone,
- ecommerce: {
- currency: event.data.checkout.currencyCode,
- value: event.data.checkout.totalPrice.amount,
- tax: event.data.checkout.totalTax.amount,
- shipping: event.data.checkout.shippingLine.price.amount,
- affiliation: 'example',
- transaction_id: event.data.checkout.order.id,
- coupon: event.data.checkout.discountApplications[0].title,
- shipping_discount: shippingDiscount,
- total_discount: totalDiscount,
- items: items
- }
- });
- console.log(dataLayer);
- })();
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement