Created
February 9, 2021 09:14
-
-
Save piotr-sobczyk/c652fd03488e4bd4003d66c763b5127d to your computer and use it in GitHub Desktop.
Connecting Tipser Elements to Google Analytics with Enhanced E-commerce plugin
This file contains 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
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