Google analytics 4 events sometimes not arriving - google-analytics

I am tracking purchases on a site in google analytics by sending a custom event from JavaScript to Google Tag Manager on the "successful purchase" page. Most of the time this works perfectly, but in some cases it seems the event just doesn't arrive to Google Analytics.
Initially I thought that maybe visiting the success page couldn't be relied on, but then I added an additional call after triggering the event that logs the sending of the event to my database. To my surprise, the events so far always get logged to my database, but they still sometimes don't show up in analytics. This is the code that does this:
const event = {
'event': 'purchase',
'ecommerce': {
'transaction_id': orderData.id,
'value': orderData.price,
'currency': 'EUR',
'coupon': orderData.CouponCode,
"items": orderData.services.map(elem => ({
'item_id': elem.id,
'item_name': elem.name,
'price': elem.price,
'item_type': elem.type,
'quantity': 1,
})),
}
};
// Send GA4 purchase event
dataLayer.push(event);
// Log to my db
fetch("/ajax/trackAnalytics", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
event,
cleaning_id: orderData.id
})
})
Let's take the 2nd of December as an example. According to google analytics these were the incoming purchases:
But in my database I received the following logs (I redacted the "items" field because it contained customer information but it shouldn't matter):
{
"event":"purchase",
"ecommerce":{
"transaction_id":6520,
"value":73.89,
"currency":"EUR",
"coupon":null
},
"timestamp":"2022-12-02T15:10:47+00:00"
}
{
"event":"purchase",
"ecommerce":{
"transaction_id":6519,
"value":67.99,
"currency":"EUR",
"coupon":null
},
"timestamp":"2022-12-02T15:57:44+00:00"
}
{
"event":"purchase",
"ecommerce":{
"transaction_id":6487,
"value":197.05,
"currency":"EUR",
"coupon":null
},
"timestamp":"2022-12-02T19:17:54+00:00"
}
As you can see, everything matches up except the transaction with ID 6520.
I tried creating orders that contained the exact elements 6520 did but I wasn't able to reproduce the issue that way. I also tried doing the same with a tracker blocker enabled on my browser but still the data came through.
The tag manager setup is the following:
Purchase trigger:
Purchase tag:

Sometimes if the user installed the ad block extension on their browser.
These kind of the analytic tags will not fire at all.
You said you tried installed some kind of this and it will work. This mean you might installed the different blocker as the user's.
Not every kind of blocker will block GA request. But still some of them did.
There are still many reasons cause the GA4 hit not sent. But if we are using the client side GTM container. It will always have some different with backend data. Just more or less.

As Darrellwan suggested, adding the line window.dataLayer = window.dataLayer || []; before dataLayer.push seems to have solved the problem, but it's not 100% clear.

Related

How to get GA transaction info out of Salesforce B2B LWC and keep the same session

I am looking for a way to pass transaction data up from a LWC (lightning web component) to GA and not start a new session.
The primary issue is that the helper on the custom lighting web component is firing correctly, however when the ga(ecommerce, send) fires from within the LWC, it is setting a different clientID in the browswer.
If i try using ga(function(tracker) {var clientId = tracker.get('clientId');}); in the LWC it errors out as clientId is undefined.
I would like to be able to use the clientId instead of autolinker when calling
ga('create', trackingId, 'auto', { allowLinker: true });
ga('require', 'linker');
ga('require', 'ecommerce');
ga('linker:autoLink', [$A.get("$Label.c.Community_Site_URL")]);
there's two pushes going out. One is grand total via datalayer, the other is via ga add transaction
datalayer push
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'transactionId ': order.Id,
'transactionAffiliation': order.SalesStore.Name,
'transactionTotal ': order.GrandTotalAmount,
'transactionShipping': order.TotalAdjustedDeliveryAmount,
'transactionTax': order.TotalTaxAmount
});
GA Add transaction
ga('ecommerce:addTransaction', {
'id': order.Id,
'affiliation': order.SalesStore.Name,
'revenue': order.GrandTotalAmount,
'shipping': order.TotalAdjustedDeliveryAmount,
'tax': order.TotalTaxAmount
});
orderItems.forEach(item => {
ga('ecommerce:addItem', {
'id': order.Id,
'name': item.orderItemInstance.zzzz.Name,
'sku': item.orderItemInstance.zzzz.StockKeepingUnit,
'price': item.orderItemInstance.TotalPrice,
'quantity': item.orderItemInstance.Quantity
});
});
ga('ecommerce:send');
This successfully fires to GA, and we can see the transactions. However, using the chrome extension, I can see that a new session has started for just the transaction event. So, for the main user session it will show the user visiting checkout and then order complete page, but no transaction info, while we see single page sessions for the transactions (and no campaign or adwords association).
is it possible to pass a value from the main window clientId to the LWC? that should allow us to link to the same session
Another solution mentioned passing data from the LWC to Aura. However, we already have the data going to GA. ("Whatever data you want to send to Google Analytics, send it from LWC to Aura through an event. And From Aura Component, fire a Google analytics event along with data received from LWC.") https://salesforce.stackexchange.com/questions/299303/google-analytics-event-tracking-in-community-using-lwc
this is a different use case as I just want the clientId and session to match
is there a GTM solution that will allow us to post to the main datalayer as opposed to how the datalayer push is working now?

Google analytics tag manager e-commerce dataLayer not sent

I am trying to send e-commerce events to google analytics using gtm (Google Analytics : Universal Analytics), this is my code
const loadGa = (next, retry) => {
if (!retry) retry = 0;
if (typeof ga === 'function') {
return next(null);
}
if (retry > 10) return next(new Error('Can not load google analytics'));
retry++;
setTimeout(() => loadGa(next, retry), 500);
}
const addProductGa = product => {
loadGa((err) => {
if (err) return console.error(err);
dataLayer.push({
event: 'addToCart',
ecommerce: {
currencyCode: 'EUR',
add: {
products: [{
name: product.name,
id: product.id,
price: product.acquisitionAmount / 100,
quantity: 1
}]
}
}
});
})
}
const purchaseGa = (charge, product) => {
loadGa((err) => {
if (err) return console.error(err);
dataLayer.push({
ecommerce: {
currencyCode: 'EUR',
purchase: {
actionField: {
id: charge.id,
revenue: charge.amount
},
products: [{
name: product.name,
id: product.id,
price: product.acquisitionAmount / 100,
quantity: 1
}]
}
}
});
})
}
For the example if I call the addProductGa
call to GTM
call to analytics
send basic tracking data
It seems that my e-commerce data are not sent, I can not see them in the network call to analytics server and I have no data on Google Analytics
What I can say:
By default dataLayer.push doesn't send data anywhere, it just feeds the dataLayer. You need GTM triggers and tags to send the data, which brings me to the next point
Missing event key in some of your dataLayer.push calls (eg purchase): I know you're following examples given in the GTM ecom spec but IMO it's confusing: some of them show an event-based collections (with the event key set), others pageview-based collection (without the event key set). To simplify your setup you should:
Always set the event key
Configure a trigger to handle those events
Full setup: once you have an event property on all your dataLayer calls, you can generically track them all using a setup similar to the one shown below (you should change the trigger to be a regex matching all your ecommerce events, also don't forget to enable Enhanced Ecommerce in the GA settings).
If the issue persists you should enable the GTM preview/debug which will tell you why certain tags aren't firing and will show you the debug of the dataLayer values it contains
If GTM confirms tags are firing but you don't see GA tracking on the network, you want to use the Chrome GA debugger which will show you in details what's happening and potentially why hits are not sent.
Don't forget to publish GTM once you have it all troubleshooted and working

redux-beacon: enhanced ecommerce actions not being fired

I'm using redux-beacon to manage google analytics enhanced ecommerce actions. What I'm noticing is that pageview events are being fired off fine but the enhanced ecommerce actions are not being sent. It's like they are being stored in the datalayer but no network request is being triggered. I'm new to enhanced ecommerce tracking so perhaps I'm missing something?
For example, here I have the events which are triggered when viewing a product:
export const analyticsEcommerceProduct = trackEcommProduct((action) => {
const { product } = action;
return {
id: product.id,
name: product.title,
category: product.type
};
}, CLIENT_TAG);
export const analyticsEcommerceAction = trackEcommAction((action) => {
const { actionType, id, revenue } = action;
return {
actionName: actionType,
id,
revenue
};
}, CLIENT_TAG);
Which are added to my eventMap:
const eventsMap = {
CLIENT_ANALYTICS_PAGEVIEW: clientPageView,
CLIENT_ANALYTICS_ECOMM_PRODUCT: analyticsEcommerceProduct,
CLIENT_ANALYTICS_ECOMM_ACTION: analyticsEcommerceAction
};
const middleware = createMiddleware(eventsMap, GoogleAnalytics(), GoogleTagManager());
Now when I land on the product page the analyticsEcommerceProduct and analyticsEcommerceAction events are firing as expected but no network request is made to send this information:
Is there some sort of event to 'send' the data that I need to add?
Is there some sort of event to 'send' the data that I need to add?
Yes, I believe so. In reading the examples that Google provides here: https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce, it looks like the eCommerce actions set meta data that will be sent along with the next event or pageview. Each example either ends with a ga('send', 'pageview'); or an event call like:
ga('send', 'event', 'Checkout', 'Option', {
hitCallback: function() {
// Advance to next page.
}
});
I'd try going to a new page and inspecting the call made there to see if it includes the data you need. If it does, I'll think of a way to make this easier for redux-beacon users. At the very least I think some documentation/tips are in order. As always, I'm open to suggestions/pr's.

Social shares tracking in GA

This is pretty much covered topic for original FB/Twitter buttons. But what if I have my own "share on fb" button? Like this:
<div id="fb_share"><a target="_blank" href="http://www.facebook.com/share.php?u=blah-blah">Share on FB</a></div>
so I've come up with the folloing solution:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location
});
//console.log('tracked');
});
That is placed AFTER the Google Analytics code.
Despite the fact it wont catch FB callback - it is supposed to do the trick but for some reason I still cannot see any results in Analytics so the question is this: will the solution actually work? In fact it could be even like this I believe:
FB
Your 'share on Facebook' links causes the page to navigate (and not open a new window/tab). When this navigation happens, most mainstream browsers cancel all pending HTTP requests for the current page and then navigates to the new page (fb.com)
In this scenario, one of the pending HTTP requests will be the GA event tracking call which will therefore never complete and never be received by the GA servers.
What you need to use is the GA hit callback functionality, this essentially cancels the native navigation (to FB), sends the tracking call and waits enough time for it to complete and then does a JavaScript redirection to the next page.
You should read the google docs here
In your case your event tracking function should be similar to this:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location,
'hitCallback': function(){
window.location = this.href;
}
});
//console.log('tracked');
return false;
});
So I've made the following changes:
Added the hitCallback property to the event tracking call. this is an anonymous function that is called once the GA servers have sent their response to the event tracking.
added a 'return false' statement which cancels the native functionality and then relies on the hitCallback function to do the navigating.

Google Tag manager not registering Transactions for enhanced Ecommerce

I am running a single page checkout and the pagevies are showing fine. however the purchase transactions doesn't seem to be being processed in Google analytics.
I have the data layer up
and it seems to be registering the purchase event,
I have tag enabled with a page view on gtm.dom which has the enhanced ecommerce tag ticked,
but still nothing .
Here is the output from the Datalayer if any one can help would be really appreciative :
[
{
"ecommerce":{
"purchase":{
"actionField":{
"id":"145000010",
"revenue":295,
"tax":"0.0000",
"shipping":"5.0000",
"coupon":""
},
"products":[{
"id":"ace002",
"name":"perfume10Lt",
"price":"295.0000",
"quantity":"1.0000"
}]
},
"currencyCode":"USD"
},
"event":"purchase"
},
{
"gtm.start":1438797700099,
"event":"gtm.js"
},
{
"ecommerce":{
"impressions":0,
"promoView":0
}
},
{
"event":"gtm.dom"
},
{
"event":"gtm.load"
}
]
Added as requested by comments: The tag seems be being called at GTM.dom so i know its definitely running.
Here is the tracking tag:
Here is the image from the trigger
Change your trigger to fire the tag on the 'purchase' event instead. It may be failing because the ecommerce data layer hasn't been pushed yet before the gtm.Dom event happens.

Resources