To track revenue and other e-commerce metrics in Google Analytics 4 (GA4), you'll need to set up a data layer and configure Google Tag Manager (GTM) accordingly. Here's a step-by-step guide tailored for a Magento-based website:
🛒 Step 1: Implement the Data Layer on the Purchase Confirmation Page
On your Magento store's order success page, insert the following script to push transaction data to the dataLayer
:
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: "purchase",
ecommerce: {
transaction_id: "{{ order.increment_id }}",
value: {{ order.grand_total }},
currency: "{{ order.order_currency_code }}",
items: [
{% for item in order.items %}
{
item_name: "{{ item.name }}",
item_id: "{{ item.sku }}",
price: {{ item.price }},
quantity: {{ item.qty_ordered }}
}{% if not loop.last %},{% endif %}
{% endfor %}
]
}
});
</script>
Notes:
- Replace the templating syntax (
{{ }}
and{% %}
) with the appropriate variables and loops based on your Magento version and templating engine (e.g., PHTML, Twig). - Ensure this script is placed before the GTM container script to guarantee that GTM can access the data when it loads.
🧰 Step 2: Configure Google Tag Manager (GTM)
Create Data Layer Variables in GTM:
- Navigate to Variables in GTM.
- Click New and select Data Layer Variable.
- Set the Data Layer Variable Name to match the keys in your data layer (e.g.,
ecommerce.transaction_id
,ecommerce.value
,ecommerce.currency
).
- Repeat this process for each variable you need to capture
- Go to Triggers and click New.
- Choose Custom Event as the trigger type.
- Set the Event Name to
purchase
.
- This trigger will fire when the
purchase
event is pushed to the data layer
Create a GA4 Event Tag:
- Navigate to Tags and click New.
- Select GA4 Event as the tag type.
- Choose your existing GA4 Configuration Tag or create a new one with your Measurement ID.
- Set the Event Name to
purchase
.
- Under Event Parameters, add the variables you created earlier (e.g.,
transaction_id
,value
,currency
,items
).
- Assign the trigger you set up in the previous step to this tag.
🔍 Step 3: Test Your Implementation
Use GTM's Preview Mode:
- Click Preview in GTM and enter your website's URL.
- Complete a test purchase to reach the order confirmation page.
- Ensure that the
purchase
event appears in the Summary panel and that the data layer variables are populated correctly.
Verify in GA4 DebugView:
- In your GA4 property, navigate to Configure > DebugView.
- Confirm that the
purchase
event is received with the correct parameters.
📈 Step 4: Publish Your Changes
Once you've verified that everything is working correctly in preview mode:
- Click Submit in GTM to publish your container changes.
- Monitor your GA4 reports to ensure that revenue and other e-commerce metrics are being tracked accurately.