E-commerce Platform Integration
Implement GA4 e-commerce tracking on Shopify, WooCommerce, Magento, and other platforms.
Platform Comparison
| Platform | Native GA4 | Data Layer | Customization | |----------|------------|------------|---------------| | Shopify | Basic app | Web Pixels | Limited | | WooCommerce | Plugin | Full access | High | | Magento | Extension | Full access | High | | BigCommerce | Built-in | Limited | Medium | | Squarespace | Basic | Limited | Low |
Shopify Integration
Option 1: Native GA4 App (Basic)
Limited but quick setup:
- Sales Channels → Online Store → Preferences
- Add GA4 Measurement ID
- Enable Enhanced E-commerce
Limitations:
- Limited event customization
- No server-side
- Basic attribution
Option 2: Shopify Web Pixels (Recommended)
More control with Customer Events:
// Settings → Customer events → Add custom pixel
// Subscribe to all checkout events
analytics.subscribe('checkout_started', (event) => {
const checkout = event.data.checkout;
gtag('event', 'begin_checkout', {
currency: checkout.currencyCode,
value: checkout.totalPrice.amount,
items: checkout.lineItems.map(item => ({
item_id: item.variant.sku,
item_name: item.title,
price: item.variant.price.amount,
quantity: item.quantity
}))
});
});
analytics.subscribe('checkout_completed', (event) => {
const checkout = event.data.checkout;
gtag('event', 'purchase', {
transaction_id: checkout.order.id,
currency: checkout.currencyCode,
value: checkout.totalPrice.amount,
tax: checkout.totalTax.amount,
shipping: checkout.shippingLine?.price.amount || 0,
items: checkout.lineItems.map(item => ({
item_id: item.variant.sku,
item_name: item.title,
price: item.variant.price.amount,
quantity: item.quantity
}))
});
});
Option 3: Theme Customization + GTM
Add to theme.liquid:
<!-- In <head> -->
<script>
window.dataLayer = window.dataLayer || [];
</script>
{% if template contains 'product' %}
<script>
dataLayer.push({
event: 'view_item',
ecommerce: {
currency: '{{ shop.currency }}',
value: {{ product.price | divided_by: 100.0 }},
items: [{
item_id: '{{ product.variants.first.sku | default: product.id }}',
item_name: '{{ product.title | escape }}',
item_brand: '{{ product.vendor | escape }}',
item_category: '{{ product.type | escape }}',
price: {{ product.price | divided_by: 100.0 }},
quantity: 1
}]
}
});
</script>
{% endif %}
{% if template contains 'cart' %}
<script>
dataLayer.push({
event: 'view_cart',
ecommerce: {
currency: '{{ shop.currency }}',
value: {{ cart.total_price | divided_by: 100.0 }},
items: [
{% for item in cart.items %}
{
item_id: '{{ item.sku | default: item.variant_id }}',
item_name: '{{ item.product.title | escape }}',
price: {{ item.price | divided_by: 100.0 }},
quantity: {{ item.quantity }}
}{% unless forloop.last %},{% endunless %}
{% endfor %}
]
}
});
</script>
{% endif %}
Shopify Plus: Checkout Extensibility
// checkout.liquid (Shopify Plus only)
{% if first_time_accessed %}
<script>
dataLayer.push({
event: 'begin_checkout',
ecommerce: {
currency: '{{ checkout.currency }}',
value: {{ checkout.total_price | divided_by: 100.0 }},
items: [
{% for item in checkout.line_items %}
{
item_id: '{{ item.sku }}',
item_name: '{{ item.title | escape }}',
price: {{ item.price | divided_by: 100.0 }},
quantity: {{ item.quantity }}
}{% unless forloop.last %},{% endunless %}
{% endfor %}
]
}
});
</script>
{% endif %}
WooCommerce Integration
Option 1: WooCommerce Google Analytics Plugin
- Install WooCommerce Google Analytics Integration
- Configure with GA4 Measurement ID
- Enable e-commerce tracking
Option 2: GTM4WP Plugin (Recommended)
Best for full GTM control:
- Install GTM4WP plugin
- Configure GTM container ID
- Enable e-commerce data layer
Option 3: Custom Implementation
Add to functions.php or custom plugin:
// Add data layer to header
add_action('wp_head', 'custom_ga4_datalayer', 1);
function custom_ga4_datalayer() {
echo '<script>window.dataLayer = window.dataLayer || [];</script>';
}
// Product page view
add_action('woocommerce_after_single_product', 'ga4_view_item');
function ga4_view_item() {
global $product;
?>
<script>
dataLayer.push({ ecommerce: null });
dataLayer.push({
event: 'view_item',
ecommerce: {
currency: '<?php echo get_woocommerce_currency(); ?>',
value: <?php echo $product->get_price(); ?>,
items: [{
item_id: '<?php echo $product->get_sku(); ?>',
item_name: '<?php echo esc_js($product->get_name()); ?>',
item_category: '<?php echo esc_js(implode('/', wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']))); ?>',
price: <?php echo $product->get_price(); ?>,
quantity: 1
}]
}
});
</script>
<?php
}
// Add to cart
add_action('woocommerce_add_to_cart', 'ga4_add_to_cart', 10, 6);
function ga4_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
$product = wc_get_product($product_id);
?>
<script>
dataLayer.push({ ecommerce: null });
dataLayer.push({
event: 'add_to_cart',
ecommerce: {
currency: '<?php echo get_woocommerce_currency(); ?>',
value: <?php echo $product->get_price() * $quantity; ?>,
items: [{
item_id: '<?php echo $product->get_sku(); ?>',
item_name: '<?php echo esc_js($product->get_name()); ?>',
price: <?php echo $product->get_price(); ?>,
quantity: <?php echo $quantity; ?>
}]
}
});
</script>
<?php
}
// Purchase event (on thank you page)
add_action('woocommerce_thankyou', 'ga4_purchase_event');
function ga4_purchase_event($order_id) {
if (!$order_id) return;
// Check if already tracked
if (get_post_meta($order_id, '_ga4_tracked', true)) return;
$order = wc_get_order($order_id);
$items = array();
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = array(
'item_id' => $product->get_sku(),
'item_name' => $item->get_name(),
'price' => $order->get_item_total($item),
'quantity' => $item->get_quantity()
);
}
?>
<script>
dataLayer.push({ ecommerce: null });
dataLayer.push({
event: 'purchase',
ecommerce: {
transaction_id: '<?php echo $order->get_order_number(); ?>',
value: <?php echo $order->get_total(); ?>,
tax: <?php echo $order->get_total_tax(); ?>,
shipping: <?php echo $order->get_shipping_total(); ?>,
currency: '<?php echo $order->get_currency(); ?>',
items: <?php echo json_encode($items); ?>
}
});
</script>
<?php
// Mark as tracked
update_post_meta($order_id, '_ga4_tracked', true);
}
Magento 2 Integration
GTM Extension Setup
- Install Magento GTM extension (Mageworx, Amasty, or similar)
- Configure GTM container ID
- Enable e-commerce data layer
Custom Implementation
Create module: VendorName_Analytics
// etc/frontend/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\Block\Onepage\Success">
<plugin name="ga4_purchase_tracking" type="VendorName\Analytics\Plugin\PurchaseTracking"/>
</type>
</config>
// Plugin/PurchaseTracking.php
<?php
namespace VendorName\Analytics\Plugin;
class PurchaseTracking
{
protected $checkoutSession;
public function __construct(
\Magento\Checkout\Model\Session $checkoutSession
) {
$this->checkoutSession = $checkoutSession;
}
public function afterToHtml($subject, $result)
{
$order = $this->checkoutSession->getLastRealOrder();
if (!$order->getId()) {
return $result;
}
$items = [];
foreach ($order->getAllVisibleItems() as $item) {
$items[] = [
'item_id' => $item->getSku(),
'item_name' => $item->getName(),
'price' => (float) $item->getPrice(),
'quantity' => (int) $item->getQtyOrdered()
];
}
$purchaseData = [
'event' => 'purchase',
'ecommerce' => [
'transaction_id' => $order->getIncrementId(),
'value' => (float) $order->getGrandTotal(),
'tax' => (float) $order->getTaxAmount(),
'shipping' => (float) $order->getShippingAmount(),
'currency' => $order->getOrderCurrencyCode(),
'items' => $items
]
];
$script = sprintf(
'<script>dataLayer.push(%s);</script>',
json_encode($purchaseData)
);
return $result . $script;
}
}
BigCommerce Integration
Built-in GA4 Support
- Channel Manager → Scripts
- Add GA4 gtag.js script
Enhanced E-commerce
<!-- Script Manager: Footer Scripts -->
<script>
// BigCommerce exposes product data
{{#if page_type '==' 'product'}}
dataLayer.push({
event: 'view_item',
ecommerce: {
currency: '{{currency_selector.active_currency_code}}',
value: {{product.price.value}},
items: [{
item_id: '{{product.sku}}',
item_name: '{{product.title}}',
item_brand: '{{product.brand.name}}',
price: {{product.price.value}}
}]
}
});
{{/if}}
</script>
Server-Side Tracking
Benefits for E-commerce
| Benefit | Impact | |---------|--------| | Ad blocker bypass | +20-35% conversion data | | First-party cookies | Better user tracking | | Data enrichment | Add inventory, margin data | | Reduced client load | Faster page speed |
Architecture
┌─────────────────────────────────────────────────────────┐
│ E-commerce Site │
│ │ │
│ ┌─────────────┴─────────────┐ │
│ │ │ │
│ ▼ ▼ │
│ Client-Side GTM Backend Webhook │
│ (Basic events) (Order data) │
│ │ │ │
│ └─────────────┬─────────────┘ │
│ │ │
│ ▼ │
│ Server-Side Container │
│ (Enrichment, routing) │
│ │ │
│ ┌─────────────┼─────────────┐ │
│ ▼ ▼ ▼ │
│ GA4 Meta CAPI Google Ads │
│ │
└─────────────────────────────────────────────────────────┘
Shopify Webhook Example
// Server receiving Shopify webhook
app.post('/shopify-webhook/orders-paid', async (req, res) => {
const order = req.body;
// Get GA client_id from order note or metafield
const clientId = order.note_attributes?.find(
a => a.name === 'ga_client_id'
)?.value;
if (clientId) {
// Send to GA4 server container
await fetch('https://gtm.yoursite.com/collect', {
method: 'POST',
body: JSON.stringify({
client_id: clientId,
events: [{
name: 'purchase',
params: {
transaction_id: order.id.toString(),
value: parseFloat(order.total_price),
currency: order.currency,
items: order.line_items.map(item => ({
item_id: item.sku,
item_name: item.title,
price: parseFloat(item.price),
quantity: item.quantity
}))
}
}]
})
});
}
res.status(200).send('OK');
});
Testing & Validation
E-commerce Verification Checklist
- [ ] Product list views on category pages
- [ ] Product detail views track correctly
- [ ] Add to cart captures variant/quantity
- [ ] Cart view shows correct total
- [ ] Checkout steps fire in order
- [ ] Purchase fires once per order
- [ ] Transaction ID is unique
- [ ] Revenue matches order total
- [ ] Tax and shipping captured
- [ ] All items in purchase event
GTM Preview Mode
- Navigate through complete purchase flow
- Verify each e-commerce event
- Check item arrays populated
- Confirm values match product prices
GA4 DebugView
- Enable debug mode
- Complete test purchase
- Verify events and parameters
- Check for errors/warnings
Previous: Advertising Integration Related: E-commerce Analytics