Hey everyone, I’m having trouble with Google Tag Manager and Enhanced E-Commerce. My online store sends data to Google Analytics using a specific code snippet instead of the dataLayer. The code looks like this:
ga('ec:setAction', 'purchase', {
'id': '2023',
'revenue': '99.99',
'shipping': '5.00',
'tax': 7.50
});
ga('send', 'pageview');
I want to grab the ‘revenue’ value and put it in a Tag Manager variable. I tried using a Custom JavaScript Variable with this code:
function() {
var ecommerceData = ga.getAll()[0].get('ecommerce');
return ecommerceData ? ecommerceData.purchase.revenue : undefined;
}
But it’s not working. Any ideas on how to correctly capture the revenue in GTM? Thanks in advance for your help!
Sophie, I’ve encountered this issue before. The problem is that your custom JavaScript variable is trying to access the ecommerce object directly from Google Analytics, which isn’t available in GTM’s context. Instead, you’ll need to intercept the GA call before it happens.
Try wrapping the original ga function and capture the data when it’s called:
(function() {
var originalGa = window.ga;
window.ga = function() {
if (arguments[1] === 'ec:setAction' && arguments[2] === 'purchase') {
dataLayer.push({
'event': 'purchase',
'transactionRevenue': arguments[3].revenue
});
}
return originalGa.apply(this, arguments);
};
})();
Place this code before your existing GA code. Then, in GTM, create a Data Layer Variable for ‘transactionRevenue’ and use it in your tags. This method preserves your current setup while allowing GTM to access the data.
hey sophie, try pusin your purchase data into datalayer directly. after the ga() call, add:
dataLayer.push({
“event”: “purchase”,
“revenue”: “99.99”
});
then set a variable in gtm for revenue. hope this helps!
Hey Sophie26! Your e-commerce tracking challenge sounds familiar. Have you considered using the Google Tag Manager debug console to see what data is actually available when the purchase happens? It might give you some clues about what’s going on behind the scenes.
Also, I’m curious - why are you using the older ga() method instead of gtag()? Is it because of legacy code? If you’re open to updating, the newer gtag() approach might make things easier in the long run.
One thing you could try is to create a custom HTML tag in GTM that listens for the ga() call and then pushes the data to the dataLayer. Something like:
<script>
(function() {
var originalGa = window.ga;
window.ga = function() {
if (arguments[1] === 'ec:setAction' && arguments[2] === 'purchase') {
window.dataLayer.push({
'event': 'purchase_detected',
'purchase_revenue': arguments[3].revenue
});
}
return originalGa.apply(this, arguments);
};
})();
</script>
Then you could create a trigger for the ‘purchase_detected’ event and use a dataLayer variable to grab the revenue. What do you think about this approach? Have you tried something similar before?