Skip to content

Instantly share code, notes, and snippets.

@anthonygore
Created April 22, 2021 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonygore/ffe3e6a321020e867bde65d2c0eb4116 to your computer and use it in GitHub Desktop.
Save anthonygore/ffe3e6a321020e867bde65d2c0eb4116 to your computer and use it in GitHub Desktop.
Snipcart - Google Tag Manager - Google Analytics 4
function formatItems (items) {
return items.map(function (item, index) {
return {
item_name: item.name,
item_id: item.id,
price: `${item.totalPriceWithoutDiscountsAndTaxes}`,
quantity: `${item.quantity}`,
index: index+1
};
});
}
function itemAdded(item){
const obj = {
event: 'add_to_cart',
ecommerce: {
items: formatItems([item])
}
};
dataLayer.push({ ecommerce: null });
dataLayer.push(obj);
}
function itemRemoved(item){
const obj = {
event: 'remove_from_cart',
ecommerce: {
items: formatItems([item])
}
};
dataLayer.push({ ecommerce: null });
dataLayer.push(obj);
}
function createCouponString(discounts) {
const names = discounts.map(discount => discount.name);
return names.join(",");
}
function orderCompleted(order) {
const obj = {
event: 'purchase',
ecommerce: {
transaction_id: order.token,
affiliation: 'Website',
value: order.total,
tax: order.taxesTotal,
shipping: order.shippingInformation.fees,
currency: order.currency,
coupon: createCouponString(order.discounts),
items: formatItems(order.items)
}
};
dataLayer.push({ ecommerce: null });
dataLayer.push(obj);
}
function cartOpened() {
const obj = {
event: 'begin_checkout',
ecommerce: {
items: formatItems(Snipcart.api.items.all())
}
};
dataLayer.push({ ecommerce: null });
dataLayer.push(obj);
}
module.exports = function () {
document.addEventListener('snipcart.ready', function() {
Snipcart.subscribe('item.added', function(item) {
itemAdded(item);
});
Snipcart.subscribe('item.removed', function(item) {
itemRemoved(item);
});
Snipcart.subscribe('order.completed', function(order) {
orderCompleted(order);
});
Snipcart.subscribe('cart.opened', function() {
cartOpened();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment