Skip to content

Instantly share code, notes, and snippets.

@baorv
Last active July 14, 2020 02:15
Show Gist options
  • Save baorv/c4bcf5e21e7a5b31ad4e76df3c67d870 to your computer and use it in GitHub Desktop.
Save baorv/c4bcf5e21e7a5b31ad4e76df3c67d870 to your computer and use it in GitHub Desktop.
<script type="text/javascript">
var buildProductFieldObject = function(object, quantity) {
var product = {};
if (object.title) {
product.name = object.title;
}
if (object.id) {
product.id = object.id;
}
if (object.price) {
product.price = parseFloat(object.price) / 100;
}
if (object.vendor) {
product.brand = object.vendor;
}
if (quantity) {
product.quantity = quantity;
}
return product;
};
if (typeof Shopify.Checkout !== 'undefined' && typeof Shopify.checkout !== 'undefined' && Shopify.Checkout.page === 'thank_you') {
var orderId = Shopify.checkout.order_id;
var totalPrice = Shopify.checkout.total_price;
var totalTax = Shopify.checkout.total_tax;
var totalShipping = Shopify.checkout.shipping_rate.price || 0;
var coupon = Shopify.checkout.discount;
var orderId = Shopify.checkout.order_id;
var totalPrice = Shopify.checkout.total_price;
var totalTax = Shopify.checkout.total_tax;
var totalShipping = Shopify.checkout.shipping_rate.price || 0;
var coupon = Shopify.checkout.discount;
var orderProducts = [];
for (var k = 0; k < Shopify.checkout.line_items.length; k++) {
var orderProduct = Shopify.checkout.line_items[k];
orderProducts.push(
buildProductFieldObject(orderProduct)
);
}
// Call GTM to tell event checkout
var thankyouEvent = {
event: 'purchase',
ecommerce: {
purchase: {
actionField: {
id: orderId,
revenue: totalPrice,
tax: totalTax,
shipping: totalShipping,
coupon: coupon
},
products: orderProducts
}
}
};
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(thankyouEvent);
}
</script>
<!-- Google Tag Manager -->
<script>(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-*******');</script>
<!-- End Google Tag Manager -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment