Last active
April 6, 2020 19:46
-
-
Save scottious/f4f5c717d07a8e03c59fe4698eebe567 to your computer and use it in GitHub Desktop.
Sending Snipcart enhanced ecommerce events with Google Tag Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Making sure Snipcart is ready | |
document.addEventListener('snipcart.ready', function() { | |
//Subscribing to different events | |
Snipcart.events.on('item.added', (parsedCartItem) => { | |
itemAdded(parsedCartItem.result.item); | |
}); | |
Snipcart.events.on('cart.confirmed', (cartConfirmResponse) => { | |
orderCompleted(cartConfirmResponse.cart); | |
}); | |
}); | |
function itemAdded(item){ | |
dataLayer.push({ | |
event: 'shoppingCartEvent', | |
eventCategory: 'Cart Update', | |
eventAction: 'New Item Added To Cart', | |
eventLabel: item.name, | |
eventValue: item.price, | |
ecommerce: { | |
currencyCode: 'NZD', // edit this for your local currency | |
add: { | |
products: { | |
name: item.name, | |
description: item.description, | |
id: item.id, | |
price: item.price, | |
quantity: item.quantity | |
} | |
} | |
} | |
}); | |
} | |
function orderCompleted(order){ | |
dataLayer.push({ | |
event: 'shoppingCartEvent', | |
eventCategory: 'Order Update', | |
eventAction: 'New Order Completed', | |
ecommerce: { | |
currencyCode: order.currency, | |
purchase: { | |
actionField: { | |
id: order.token, | |
affiliation: 'Website', | |
revenue: order.total, | |
tax: order.taxesTotal, | |
shipping: order.shippingInformation.fees, | |
invoiceNumber: order.invoiceNumber | |
}, | |
products: createProductsFromItems(order.items), | |
userId: order.user.id | |
} | |
} | |
}); | |
} | |
function createProductsFromItems (items) { | |
return items.map(function (item) { | |
return { | |
name: item.name, | |
description: item.description, | |
id: item.id, | |
price: item.price, | |
quantity: item.quantity | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment