Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Connecting Tipser Elements to Google Analytics with Enhanced E-commerce plugin
import _ from 'lodash';
const send = eventData => {
ga('send', eventData);
};
const setECommerceAction = (action, actionData) => {
ga('ec:setAction', action, actionData);
};
const addECommerceProduct = product => {
ga('ec:addProduct', product);
};
const setCurrency = currency => {
ga('set', 'currencyCode', currency);
};
const pushEvent = action => {
const eventData = {
hitType: 'event',
eventCategory: 'E-Commerce',
eventAction: action,
};
send(eventData);
};
const convertToGAProduct = tipserProduct => {
return {
id: tipserProduct.id,
brand: tipserProduct.brand,
price: _.get(tipserProduct, 'salesPrice.value', ''),
name: tipserProduct.name,
quantity: _.get(tipserProduct, 'quantity', 1),
};
};
const emitEcommerceActionWithProduct = (action, product) => {
if (product) {
setCurrency(product.currency);
addECommerceProduct(convertToGAProduct(product));
}
setECommerceAction(action);
pushEvent(action);
};
const checkoutPageOpened = products => {
_.forEach(products, product => {
setCurrency(product.currency);
addECommerceProduct(convertToGAProduct(product));
});
setECommerceAction('checkout');
pushEvent('checkout');
};
const tipserEventCallback = event => {
const { detail } = event;
const { action = '', target = '', object = [] } = detail;
const product = _.get(detail, 'object[0]', {});
const products = product.Products || [];
switch (action) {
case 'View':
if (target === 'Product') {
emitEcommerceActionWithProduct('detail', product);
}
break;
case 'Cart':
if (target === 'Payment') {
checkoutPageOpened(object);
}
if (target === 'Product') {
emitEcommerceActionWithProduct('add', product);
}
break;
case 'CartRemove':
emitEcommerceActionWithProduct('remove', product);
break;
case 'Purchase':
_.forEach(products, tipserProduct => {
setCurrency(tipserProduct.currency);
addECommerceProduct(convertToGAProduct(tipserProduct));
});
setECommerceAction('purchase', {
id: product.OrderId || '',
});
pushEvent('purchase');
break;
default:
}
};
export default tipserEventCallback;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment