The purchase event done right: revenue, tax, refunds and duplicates
TL;DR
Difficulty: Intermediate
Analytics and the shop disagree on revenue for reasons you can name and mostly fix.
- Decide once what value means. Google asks for net merchandise: item prices without VAT, with tax and shipping in their own fields.
- The transaction ID is the shop's order number, on every payment path. Never empty, never reused.
- Duplicates come from reloaded confirmation pages and double tags; missing sales from payment redirects, ad blockers and refused consent.
- Send the purchase from the shop when the order completes, once, and only with analytics consent on record. In Solidus that is the order_finalized event.
- Send refunds with the returned items, give renewals their own IDs, send each order in its own currency, and test the payload like any other feature.
Put Google Analytics next to your shop's order report and the revenue will differ, sometimes by a third. Most of that gap comes from one event, the purchase, and a handful of decisions and bugs inside it. This chapter takes the event apart field by field and rebuilds it for an invented homeware shop in Limerick, with working code for Rails and Solidus.
Why analytics and the shop never agree on revenue
Open Google Analytics 4 (GA4) next to your shop's order report for the same month and the two revenue figures will differ. Sometimes by a few euro, sometimes by a third. Most shop owners then decide that analytics is "a bit off" and stop trusting it for anything involving money.
That is the wrong conclusion, because most of the gap is not noise. It comes from a handful of specific decisions and bugs in one single event: the purchase event, the message your shop sends to analytics when someone buys. Fix that event and the remaining gap becomes small, explainable and stable. Leave it and every report built on top of it, from return on ad spend to customer value, inherits the error.
This chapter takes the purchase event apart field by field. It covers what "value" should mean, why sales get counted twice, why others never arrive, how refunds and partial refunds work, what happens with subscriptions and foreign currencies, and how to send the event from the shop itself when the order completes, with working code for a Ruby on Rails shop on Solidus. It assumes you have read the tracking plan chapter, which introduces events, parameters and the items array.
A few terms first. An event is one thing that happened, written down and sent to an analytics tool. A parameter is a detail attached to the event, such as the order number. Value is the money amount the event carries. Deduplication means recognising that two messages describe the same sale and counting it once.
Example: the gap at Shannonside Home
Shannonside Home is an invented online homeware shop in Limerick, at shannonsidehome.example. Niamh owns it and Callum is its developer. It sells ceramics, kitchen textiles, lamps and small furniture, about 1,400 products. All numbers in this chapter are invented for the example.
A normal month brings 110,000 sessions. With a conversion rate of 1.8%, that is orders. The average order value is €84, meaning the average amount a customer pays, VAT and delivery included. So the shop's order report shows euro of revenue.
GA4 for the same month shows purchase revenue of €87,216 from 1,104 purchases. Niamh's question is simple: which one is right, and what is wrong with the other? By the end of this chapter Callum will have explained every pound of the difference and fixed the parts that can be fixed.
The purchase event, field by field
Google documents exactly what a GA4 purchase event carries1. There are only a handful of fields, and each one matters:
| Field | Required | What it holds | The usual mistake |
|---|---|---|---|
transaction_id | Yes | The unique order number | Empty, reused, or a placeholder |
value | Practically yes | The money amount of the purchase | A mix of gross, net, with and without delivery |
currency | Yes, if value is set | Three letter ISO 4217 code, such as EUR | Missing, so revenue is not computed properly |
tax | No | Tax on the order | Left out, or already inside value |
shipping | No | Delivery charged on the order | Left out, or already inside value |
coupon | No | The coupon code used | A customer's personal code |
customer_type | No | new or returning | Guessed for guest checkouts |
items | Yes | One entry per product, with price and quantity | Prices that do not add up to value |
Google's documentation adds three instructions that most installations ignore. First, set value to the sum of price times quantity over all items, and do not include shipping or tax. Second, if you set value, currency is required for revenue to be computed accurately. Third, an item's price is the discounted unit price, with the discount itself in the item's discount field1. For customer_type, Google says not to send it when you are unsure, for example on a guest checkout1.
Example: one Shannonside order written as a purchase event
Take order R482913. The customer buys one stoneware vase at €49.10 and two mugs at €14.95 each, and pays €5.00 for delivery. All prices on the site include Irish VAT at the standard rate of 23%2.
The customer pays euro.
Inside that €84.00 sits VAT. To take VAT out of a price that includes it, divide by one plus the rate (see the next section for the formula):
- Vase: after rounding, so the VAT is €9.18.
- Two mugs: after rounding, so the VAT is €5.59.
- Delivery: after rounding, so the VAT is €0.93.
Total VAT: . The net order, without VAT, is . Divide the whole €84.00 by 1.23 and you get €68.29 instead, because VAT is rounded line by line. That is the same kind of penny as the one in the next paragraph.
Following Google's rule, the event carries net item prices, tax and shipping separately:
{
"event": "purchase",
"ecommerce": {
"transaction_id": "R482913",
"currency": "EUR",
"value": 64.24,
"tax": 15.70,
"shipping": 4.07,
"items": [
{ "item_id": "VASE-STONE-L", "item_name": "Stoneware vase, large", "price": 39.92, "quantity": 1 },
{ "item_id": "MUG-SPECKLE", "item_name": "Speckled mug", "price": 12.16, "quantity": 2 }
]
}
}
Notice the value: €64.24, not €64.23. That penny is explained in its own section below, because it is the first of the small gaps Callum has to account for.
Value with or without VAT and delivery: decide once
The single largest reason analytics and the shop disagree is that they measure different things under the same word. The shop's order report usually shows what the customer paid: VAT in, delivery in. Analytics, set up properly, shows net merchandise: VAT out, delivery out. Both are "revenue". Neither is wrong. They are simply different numbers.
There are four common definitions:
| Definition | VAT | Delivery | Typical owner |
|---|---|---|---|
| Gross order total | In | In | The order screen, the payment provider |
| Gross merchandise | In | Out | Older tracking set ups |
| Net merchandise | Out | Out | Google's recommendation for GA4 |
| Net order total | Out | In | The accounts, before delivery costs are netted |
To move between gross and net you need one formula. If a price includes VAT, the net price is the gross price divided by one plus the VAT rate:
where is the price without VAT, is the price the customer sees including VAT, and is the VAT rate written as a decimal, so for the Irish standard rate. A common mistake is to subtract 23% of the gross price instead, which takes out too much. If percentages of percentages feel slippery, Foundations: percentages walks through exactly this case.
My advice is to follow Google's definition for analytics, net merchandise, and to send VAT and delivery in their own tax and shipping fields so nothing is lost. There are three reasons. It is what GA4 expects, so its item revenue and purchase revenue line up. It is closer to what the business actually keeps, which matters the moment you compare revenue with ad spend. And VAT rates differ by product and by country, so a gross figure mixes in money that was never yours. The chapter on unit economics and contribution margin per order shows how net merchandise then flows on into margin.
Whatever you choose, write it into the tracking plan and use the same definition everywhere: GA4, Google Ads conversion values, Meta, and the shop's own revenue report. The disagreement only hurts when nobody knows which definition each system uses.
Example: four honest revenue figures for the same month
Callum computes Shannonside's month under each definition, using order R482913's proportions as the average order (€84.00 gross total, €79.00 gross merchandise, €64.23 net merchandise, €68.30 net total):
- Gross order total:
- Gross merchandise:
- Net merchandise:
- Net order total:
The gap between the first and the last is €39,144.60, almost a quarter of the gross figure, without a single sale going missing. Niamh's €166,320 and a correctly configured GA4 should never match. GA4 should match €127,175.40, minus whatever it cannot see. That turns her question from "why is analytics wrong?" into a much better one: "of the €127,175.40 GA4 should see, where did the other €39,959.40 go?"
Item prices must add up to the value, to the penny where possible
GA4 calculates item revenue from the items array and purchase revenue from value. If the two are built differently, they disagree inside GA4 itself, before the shop even enters the picture. Google's rule is that value equals the sum of price times quantity over all items1:
where is the event's value, is the number of item lines, is the net unit price of line after any discount, and is its quantity. A sum like this is just many ratios added up, covered in Foundations: ratios and rates.
The trap is rounding. A shop stores money per line, with VAT rounded per line. Analytics wants a unit price. Divide a rounded line total by its quantity and you get a price with more than two decimals, which you then round again. Multiply it back and you can land a penny away from the line total.
Example: the penny on the mugs
Two mugs cost €29.90 including VAT. Solidus works out the VAT included in that line as €5.59, so the net line total is . The net unit price is:
Rounded to two decimals, that is €12.16. Multiplied back: . The event's value becomes , while the shop's net merchandise for the order is .
Callum has two choices. He can send the value as the shop's figure, €64.23, and accept that items add up to €64.24. Or he can compute value from the rounded items, €64.24, so GA4 is consistent with itself, and accept a penny of difference against the shop. He picks the second, because Google's rule is explicit, and because a penny per order is a known, bounded tolerance: at most half a penny per item line, which across 1,980 orders is a few euro a month. A penny per order is grand, as long as you know where it comes from. When he later compares the systems, he compares within that tolerance, never to the penny. The chapter on reconciling analytics, ads and orders builds that weekly comparison.
Discounts and coupons: price after the discount
When a coupon reduces a price, two fields carry it. The item's price is the unit price after the discount, and the item's discount is the unit discount. The event level coupon carries the code, and item level coupons are independent of it1.
Order level discounts, such as "€10 off orders over €80", have to be spread across the item lines, because GA4 has no separate field for a discount that belongs to the whole basket. In Solidus, the line item method total_excluding_vat gives the line's amount after its promotion adjustments and without VAT3. The newer Solidus promotions system only ever adjusts line items and shipments, and can spread a fixed amount across all lines4, so with it the discount is already inside every line. With the legacy system, an order level adjustment sits on the order itself, and you spread it across the lines in your own code before sending.
Example: a 10% coupon at Shannonside
A customer buys a linen tablecloth at €70.00 including VAT with the code AUTUMN10, which takes 10% off. The discounted gross price is . Net of VAT:
The undiscounted net price was , so the unit discount, net, is . The item goes out as "price": 51.22, "discount": 5.69, "quantity": 1, the event carries "coupon": "AUTUMN10", and value is €51.22.
A code tied to one person, such as a referral code that contains a name or an email address, never goes into coupon. Google already asks that a transaction ID contains nothing that could identify a customer5, the same care applies to every other field, and the tracking plan chapter explains how to keep personal data out of every parameter.
The transaction ID is the order number, and nothing else
The transaction_id is the field that makes a purchase countable once. GA4 deduplicates purchase events with the same transaction ID, and Google's own guidance adds three warnings: use a unique ID for each order, such as the order confirmation number. Never use the same ID for different users. And never send an empty string, because purchase events with an empty transaction ID are deduplicated against each other, which can make many sales look like one5.
Google Ads works similarly but not identically. It treats a second conversion with the same transaction ID for the same conversion action as a duplicate, and it states that a transaction ID does not fix duplicate view through conversions6. So the same order number must go to every destination: GA4, Google Ads, and Meta (where the matching field is called the event ID, covered in the server side tracking guide).
The safest transaction ID is the shop's own public order number. In Solidus that is Spree::Order#number, a value such as R482913, unique per order and known both to the confirmation page and to the server. Never use the database row ID (it leaks how many orders you take), never a payment provider's reference (one order can have several payments), and never a placeholder like "test" left over from development.
Example: the empty ID that swallowed PayPal orders
Before Callum's rebuild, Shannonside's confirmation page read the order number from a variable that was only filled for card payments. For PayPal orders the page sent "transaction_id": "". About 31% of Shannonside's orders are paid with PayPal, so , about 614 orders a month. Those 614 orders all carried the same empty ID. GA4 treated many of them as repeats of each other, so the PayPal share of purchases in GA4 sat far below 31%, and nobody noticed for months because the total "looked about right". The fix was one line: read the number from the order itself, on every payment path. The broader lesson: test the purchase event once for every payment method you offer, not once in total.
Where duplicates come from, and how to stop them
A duplicate is the same sale arriving twice. Even with GA4's deduplication by transaction ID, duplicates matter: other tools may not deduplicate the same way, and Google Ads only deduplicates within one conversion action and only when it receives the ID6. The usual sources are:
- The confirmation page is loaded again. A reload, the back button, a bookmark, or a link in the order confirmation email that leads back to the same page.
- Two tags send the same event. A purchase tag hard coded in the template and another in Google Tag Manager, both live, often after a migration.
- The browser and the server both send it. Fine when deduplication is set up on purpose, a problem when nobody knows it is happening.
- A payment provider returns the customer twice. Some redirect flows land on the confirmation page, then redirect again.
The robust fix for the first source is simple: the purchase event is part of the order's lifecycle, not of a page view. Send it once, when the order completes, and record that it was sent. The rest of this chapter does exactly that from the server. If you keep a browser purchase tag as well, render its snippet only on the first view of the confirmation page, for example by checking a timestamp column on the order that you set when the snippet is first rendered.
Example: what repeat loads do to return on ad spend
Callum counts confirmation page requests per order in the web server log for one month: 2,118 requests for 1,980 orders, so 138 repeat loads. As a share of orders:
Shannonside's Google Ads conversion tag did not send a transaction ID. Google Ads credited 640 orders to ads that month, and about 7% of those confirmation pages were loaded again, which adds , about 45 duplicate conversions. Google Ads reported 685 conversions instead of 640.
Return on ad spend (ROAS) is the conversion value divided by the ad spend:
where is the total conversion value credited to ads and is the ad spend in the same period. It is a plain ratio, see Foundations: ratios and rates.
With an average net merchandise value of €64.23 and ad spend of €16,500:
That is the figure Google Ads showed, built on conversions. The true figure uses the real ones:
The gap is .
The account looked 7% better than it was. Bidding systems that optimise towards a ROAS target then spend more on the clicks that happen to come back to the confirmation page, which is no reason to spend anything. Adding the order number as the transaction ID removed the 45 duplicates. Which number to steer by, ROAS or profit on ad spend, is the subject of ROAS, POAS and MER.
Payment redirects: PayPal, Klarna and 3D Secure
Many payment methods send the customer away from your shop and back again. PayPal opens its own pages. Pay later providers such as Klarna do the same. Even card payments can take a detour through the card issuer's 3D Secure check. Each detour creates two separate problems.
The return looks like a new visit from the payment provider. When the customer comes back, the browser reports the provider's domain as the referrer. Without configuration, the purchase gets credited to the payment provider instead of the ad or email that brought the customer. GA4 has a setting for exactly this: list the provider's domains as unwanted referrals in the web data stream's tag settings. Google names third party payment processors as the typical case, allows up to 50 domains per data stream, and notes that a user can still appear as a referral if an earlier session started from that domain7.
Some customers never come back. The payment succeeds on the provider's side, the order completes through the provider's notification to your server, and the customer simply closes the tab. The shop has the order. The confirmation page never loads, so a browser purchase tag never fires.
Example: PayPal at Shannonside
Of Shannonside's 614 PayPal orders a month, Callum finds 31 orders where the shop recorded the payment but the web server log shows no request for the confirmation page. That is , about 5.0% of PayPal orders.
Before the fix, all 31 were missing from GA4 every month. Worse, of the PayPal customers who did return, a share was credited to paypal.com as the source. Callum adds PayPal's domains to the unwanted referrals list, which fixes the credit for future sessions, and moves the purchase event to the server, which recovers the 31 orders as long as the customer had agreed to analytics.
Purchases that can never arrive, and the law on consent
Some orders will never reach analytics, however good the code. The largest group is customers who did not agree to analytics in the cookie banner. This is not a bug to engineer around. It is the law working as intended.
In Ireland, regulation 5(3) of the ePrivacy Regulations, S.I. No. 336 of 2011, forbids storing information on a visitor's device or reading it unless the visitor has given consent and has been given clear and comprehensive information. The only exceptions are the transmission of a communication and what is strictly necessary for a service the visitor explicitly asked for8. There is no separate exception for analytics statistics, so analytics runs after consent. The UK, Germany and Austria have their own rules, covered in the consent and tracking guide for the UK, Ireland and the DACH region. This is general information, not legal advice.
The practical rule follows from it. The browser and the server only send a purchase to analytics when the customer agreed to analytics. The orders of everyone else stay in the shop's database, which sees every sale anyway. Server side sending is not a way around a refusal: the guide to event tracking and consent mode explains why, and how Google's consent mode handles the gap.
Other purchases that a browser tag misses, and the server recovers:
- Ad blockers and browser privacy features that block the analytics script.
- Customers who never return from a payment provider, as above.
- Orders placed by phone and entered by staff in the admin.
- Orders on invoice or bank transfer, where the confirmation page is shown but payment arrives later. Count these when the order completes, not when the money arrives, and treat a later non payment like a cancellation (a refund event, below).
Example: the ceiling at Shannonside
Shannonside's banner records analytics consent on 64% of orders. That is the most GA4 may lawfully receive: , so about 1,267 purchases a month. At €64.23 net merchandise each, GA4's lawful ceiling is about euro.
Now the earlier GA4 figure of €87,216 makes sense, and it was wrong twice. Its value per purchase was too high, because the old tag sent gross merchandise with VAT inside, €79 instead of €64.23: . Its count was too low, 1,104 instead of about 1,267, because of the PayPal bug and the customers who never came back from PayPal. Two wrongs had partly cancelled out, which is exactly why nobody had looked. After the rebuild, GA4 should report around 1,267 purchases and €81,400 of purchase revenue, and Callum can explain the rest of the shop's €127,175.40 net merchandise as orders without consent. The full reconciliation, including modelled conversions, is in the reconciliation chapter.
When exactly an order counts as a purchase
Before sending the event from the server, decide which moment in the order's life counts as "purchased". Solidus gives a clear answer. Its default checkout flow moves an order through the states cart, address, delivery, payment (only if payment is required) and confirm, and the complete event then moves it to complete910. Before that transition, Solidus processes the payments. After it, it runs finalize, which locks the promotions, updates payment and shipment states, sets completed_at and publishes the order_finalized event on Solidus's event bus, Spree::Bus910.
That event is the right trigger for the purchase. It fires once per order, after payment processing, regardless of which page the customer ends up on. An order whose payment fails never reaches it: Solidus sends it back to the payment step instead10. An order paid by invoice reaches it with an outstanding balance, which is correct, since the sale happened.
Example: three Shannonside orders on one afternoon
- Order R482913, card, authorised at 2.14pm. Solidus completes it,
order_finalizedfires at 2.14pm, the customer had agreed to analytics, and the purchase goes to GA4 seconds later. - Order R482914, PayPal. The customer pays at 2.20pm and closes the tab. PayPal's notification reaches the shop, the order completes,
order_finalizedfires, consent was recorded at checkout, and the purchase goes to GA4. A browser tag would have missed it. - Order R482915, card declined. Solidus moves the order back to the payment step. No
order_finalized, no purchase. The customer retries with another card at 2.31pm, the order completes, and exactly one purchase is sent.
Sending the purchase from the shop when the order completes
Here is the whole set up for a Rails 8 shop on Solidus, in five small pieces. It sends the purchase to GA4 with the Measurement Protocol, Google's interface for sending events from a server. This chapter keeps it to the purchase and the refund. Sending to several destinations, an outbox table and monitoring are the subject of the next chapter on server events.
Step 1: remember the visitor's analytics IDs and consent on the order
A server event only joins the visitor's journey in GA4 if it carries the same client_id the browser uses. Google's reference says the Measurement Protocol requires client_id for web streams, and recommends session_id for the event to count in session reports11. The browser can read both with the gtag get command, which supports client_id and session_id for GA412.
Callum adds three columns to the orders table, plus a timestamp to record that the event went out:
class AddAnalyticsFieldsToSpreeOrders < ActiveRecord::Migration[8.0]
def change
add_column :spree_orders, :analytics_consent, :boolean, default: false, null: false
add_column :spree_orders, :ga_client_id, :string
add_column :spree_orders, :ga_session_id, :string
add_column :spree_orders, :ga_purchase_sent_at, :datetime
end
end
On the confirm step, a short script fills hidden fields in the form, but only when the shop's own banner says the customer agreed to analytics:
// Confirm step: copy the GA4 IDs into the order form, only with analytics consent
const MEASUREMENT_ID = 'G-XXXXXXXXXX'
const form = document.querySelector('form[data-checkout-step="confirm"]')
const consented = window.consentState?.analytics === true // set by your own banner
if (form && consented && typeof window.gtag === 'function') {
form.elements.analytics_consent.value = '1'
gtag('get', MEASUREMENT_ID, 'client_id', (id) => { form.elements.ga_client_id.value = id })
gtag('get', MEASUREMENT_ID, 'session_id', (id) => { form.elements.ga_session_id.value = id })
}
In the checkout controller, before the order moves from confirm to complete, the values are stored. With the Solidus starter frontend that controller lives in your own app, so this is ordinary Rails:
# Called in the checkout controller's update action on the confirm step
def capture_analytics_ids(order)
consented = params[:analytics_consent] == "1"
order.update_columns(
analytics_consent: consented,
ga_client_id: consented ? params[:ga_client_id].presence : nil,
ga_session_id: consented ? params[:ga_session_id].presence : nil
)
end
Storing consent with the order is what lets the server act lawfully later, and it is also the evidence of what the customer chose. Without consent the IDs are never stored at all.
Step 2: listen for the completed order
Solidus publishes order_finalized with the order attached, and its guides show how to subscribe with a class that includes Omnes::Subscriber, registered in an initializer inside to_prepare13. The guides also advise that subscribers should not hold up or break the main checkout flow13, so the subscriber only queues a background job:
# app/subscribers/analytics_purchase_subscriber.rb
class AnalyticsPurchaseSubscriber
include Omnes::Subscriber
handle :order_finalized,
with: :queue_purchase,
id: :analytics_queue_ga4_purchase
def queue_purchase(event)
order = event[:order]
return unless order.analytics_consent? && order.ga_client_id.present?
Ga4PurchaseJob.perform_later(order.id)
end
end
# config/initializers/analytics_subscribers.rb
Rails.application.config.to_prepare do
AnalyticsPurchaseSubscriber.new.subscribe_to(Spree::Bus)
end
Step 3: build the event from the order
The payload builder turns a Solidus order into exactly the event from the first example. Net unit prices come from total_excluding_vat, which already contains promotions and leaves out VAT3. Value is computed from the rounded items, so GA4's items and value always agree:
# app/models/ga4/purchase_payload.rb
module Ga4
class PurchasePayload
def initialize(order)
@order = order
end
def to_h
items = @order.line_items.map { |line_item| item(line_item) }
{
client_id: @order.ga_client_id,
timestamp_micros: @order.completed_at.to_i * 1_000_000,
events: [{
name: "purchase",
params: {
transaction_id: @order.number,
currency: @order.currency,
value: items.sum { |i| i[:price] * i[:quantity] }.round(2).to_f,
tax: @order.tax_total.to_f,
shipping: @order.shipments.sum(&:total_excluding_vat).round(2).to_f,
session_id: @order.ga_session_id,
items: items.map { |i| i.merge(price: i[:price].to_f) }
}.compact
}]
}
end
private
def item(line_item)
{
item_id: line_item.sku,
item_name: line_item.name,
price: (line_item.total_excluding_vat / line_item.quantity).round(2),
quantity: line_item.quantity
}
end
end
end
Three details matter here. The order number is the transaction ID. Nothing in the payload identifies a person: no name, no email, no address. And timestamp_micros dates the event to the moment the order completed. Google allows events to be backdated by up to 72 hours14, so a job that runs late still lands on the right time.
Step 4: send it, and only mark it sent when Google accepted it
# app/jobs/ga4_purchase_job.rb
require "net/http"
class Ga4PurchaseJob < ApplicationJob
queue_as :analytics
retry_on StandardError, wait: :polynomially_longer, attempts: 5
ENDPOINT = "https://www.google-analytics.com/mp/collect"
def perform(order_id)
order = Spree::Order.find(order_id)
return if order.ga_purchase_sent_at.present?
uri = URI(ENDPOINT)
uri.query = URI.encode_www_form(
measurement_id: Rails.application.credentials.dig(:ga4, :measurement_id),
api_secret: Rails.application.credentials.dig(:ga4, :api_secret)
)
body = Ga4::PurchasePayload.new(order).to_h.to_json
response = Net::HTTP.post(uri, body, "Content-Type" => "application/json")
raise "GA4 answered #{response.code}" unless response.is_a?(Net::HTTPSuccess)
order.update_column(:ga_purchase_sent_at, Time.current)
end
end
The ga_purchase_sent_at check makes the job safe to run twice: a retried job never sends the same purchase again. Google also notes that the Measurement Protocol answers with a success code whenever it receives a request, even when the payload is malformed11. A success code therefore proves delivery, not correctness. Correctness is what the tests in the last section check. For data collected in the EU, Google offers the endpoint region1.google-analytics.com instead11.
Step 5: stop the browser from sending the purchase too
With the server sending every consented purchase, the browser no longer needs to. Remove the purchase tag from the confirmation page and keep every other event in the browser, where the behaviour happens. One sender per event is the simplest way to never think about duplicates again. If you must run both for a while, for example during a migration, send the identical order number from both so GA4 can deduplicate, and remove one as soon as the numbers agree.
Example: order R482913 travels from Limerick to GA4
At 2.14pm the customer's card is authorised. Solidus completes R482913 and publishes order_finalized. The subscriber sees analytics_consent is true and the client ID is 1873249506.1761921220, and queues the job. Two seconds later the job builds the payload: transaction ID R482913, currency EUR, items €39.92 times 1 and €12.16 times 2, value €64.24, tax €15.70, shipping €4.07, timestamp 2.14pm, session ID from the visit. Google answers 204, a success code, and the job writes 2.14pm into ga_purchase_sent_at. If Google had been unreachable, the job would have retried with growing waits, and the timestamp would still have placed the sale at 2.14pm.
Refunds and partial refunds
A purchase is not the end of the money story. Customers return things, and every refund must reach analytics too, or revenue in GA4 stays permanently too high. GA4 has a refund event for this. It needs the original transaction_id and the currency, and Google recommends including the refunded items with their quantities to see refunds per product115. Value follows the same rule as the purchase: net merchandise, without tax and shipping1. GA4's "Purchase revenue" metric is then the revenue from purchases minus refunds, while "Gross purchase revenue" leaves refunds out16.
Refunds also arrive late. In Ireland, when a consumer cancels a distance contract, section 117 of the Consumer Rights Act 2022 obliges the trader to reimburse all payments, including the standard delivery charge, no later than 14 days after being told of the cancellation. For goods, the trader may hold the refund back until the goods are returned or the consumer shows they were sent17. So a refund often lands weeks after the order. Because a refund event is an event like any other, it sits in your reports on the day you send it, in the month of the refund, not in the month of the original order. That is one more reason why a month in GA4 and a month in the shop's order report differ: the shop usually shows each order's current state, refunds included.
In Solidus, a refund for returned goods runs through a reimbursement. When it succeeds, Solidus publishes reimbursement_reimbursed with the reimbursement attached1819. Each return item belongs to one inventory unit, which belongs to a line item, so the refunded quantities per product follow directly:
# app/subscribers/analytics_refund_subscriber.rb
class AnalyticsRefundSubscriber
include Omnes::Subscriber
handle :reimbursement_reimbursed,
with: :queue_refund,
id: :analytics_queue_ga4_refund
def queue_refund(event)
reimbursement = event[:reimbursement]
return unless reimbursement.order.analytics_consent?
Ga4RefundJob.perform_later(reimbursement.id)
end
end
# app/models/ga4/refund_payload.rb (the params part; the job is built like Ga4PurchaseJob)
def refund_params(reimbursement)
order = reimbursement.order
items = reimbursement.return_items.group_by { |ri| ri.inventory_unit.line_item }.map do |line_item, returned|
unit_net = (line_item.total_excluding_vat / line_item.quantity).round(2)
{ item_id: line_item.sku, item_name: line_item.name, price: unit_net.to_f, quantity: returned.size }
end
{
transaction_id: order.number,
currency: order.currency,
value: items.sum { |i| i[:price] * i[:quantity] }.round(2),
items: items
}
end
The unit price is computed exactly as in the purchase, so a refunded mug takes back exactly what the purchase added. For a whole order cancelled before dispatch, Solidus publishes order_canceled19, and the refund event can carry the full net value of the order and all its items. A refund event for an order whose purchase was never sent to GA4, because the customer did not agree to analytics, is skipped by the same consent check.
Example: one mug comes back
The customer from order R482913 returns one of the two mugs. Shannonside refunds €14.95 including VAT for the mug. The refund event carries:
transaction_id: R482913- item
MUG-SPECKLE, price €12.16, quantity 1 - value:
GA4's purchase revenue for this order becomes , which is exactly the net value of the vase and the mug the customer kept ().
Example: how January's refunds trickle in
Shannonside's return rate is 9% of orders, higher for furniture. Callum follows January's orders and records, week by week, what share of January's net merchandise has been refunded so far:
If January's net merchandise is €127,175.40, the refunds that eventually arrive total euro.
By the end of January itself, only the first two to four weeks of refunds for January's orders have arrived. In GA4, the rest lands in February and early March and lowers those months instead. In the shop's order report, which shows each January order with its refunds, January shrinks as the weeks pass. Neither is wrong. They answer different questions: "how much came in this month" against "how much did this month's orders turn out to be worth". For the second question, use the shop's database and wait for the curve to flatten. The cost of returns themselves is the subject of returns in eCommerce, the metric that eats margin.
Subscription renewals and other purchases without a visit
Some purchases happen with nobody on the site: a subscription renews, a standing trade order repeats, an instalment is collected. There is no browser, so only the server can send them. Solidus core does not include subscriptions. They come from an extension or your own code, as the BigQuery set up for Solidus also notes.
Three rules keep renewals honest in analytics. Give each renewal its own transaction ID, such as the subscription's order number for that cycle, because reusing the first order's ID would make GA4 treat every renewal as a duplicate. Send it without a session_id, because no visit happened and inventing one would credit a visit that never took place. And send it only for customers whose analytics consent is on record and not withdrawn, the same rule as for any other purchase.
Many shops send renewals as a separate event, for example subscription_renewal, and keep purchase for orders placed on the site. That keeps conversion rate meaningful, since a renewal has no session to convert. Either choice works if it is written into the tracking plan.
Example: the candle refill club
Shannonside runs a candle refill club: 240 members pay €21.00 a month including VAT. Net of VAT, each renewal is . If Callum sent renewals as purchases, a month would add 240 purchases and euro of net merchandise, but no sessions. The site's conversion rate in GA4 would rise from 1.8% to , about 2.0%, without a single extra customer converting on the site. Callum sends them as subscription_renewal events with value and currency, each with its own ID, and reports subscription revenue as its own line.
Several currencies: send the order's currency, expect small differences
If you sell in more than one currency, every purchase must carry the currency the order was actually placed in, with the matching amounts. Never convert in the browser. GA4 converts each value into the property's reporting currency itself, using the exchange rate from the day before the transaction, while the BigQuery export keeps the raw values in the original currency2021.
Your finance figures use a different rate: the one your payment provider applied on the day it paid out. So the same sale, converted twice on different days with different rates, gives two slightly different euro amounts. That is not an error, and it cannot be fixed. It can only be explained, and kept within a tolerance.
Example: an order to Belfast in sterling
Shannonside also ships to a few neighbouring countries and sells to Northern Ireland and Britain in sterling. An order to Belfast has a net merchandise value of £60.00. The event goes out with "currency": "GBP" and "value": 60.00. Suppose GA4's prior day rate is 1.1750 euro per pound, while the payment provider pays out four days later at 1.1820 (both rates invented for the example). GA4 shows euro, the accounts show euro. The difference is €0.42, about 0.6% of the order. Across a month of sterling orders, the gap moves with the exchange rate, sometimes up, sometimes down. Callum notes the rule in the tracking plan: compare sterling orders in sterling, in the BigQuery export, and expect the euro figures to differ by the currency movement.
Testing the purchase event before anyone trusts it
A purchase event that is wrong quietly corrupts every number built on it, so it deserves the same care as the checkout itself. I build shops test first, and the purchase event gets tests like any other feature. Three levels cover it.
Automated tests on the payload. The payload builder is a plain Ruby class, so it can be tested without a browser. Solidus ships test factories, such as a completed order with totals, that make this quick:
# spec/models/ga4/purchase_payload_spec.rb
require "rails_helper"
RSpec.describe Ga4::PurchasePayload do
let(:order) { create(:completed_order_with_totals, ga_client_id: "123.456") }
let(:params) { described_class.new(order).to_h[:events].first[:params] }
it "uses the order number as the transaction ID" do
expect(params[:transaction_id]).to eq(order.number)
end
it "sets value to the sum of item price times quantity" do
expected = params[:items].sum { |i| (i[:price] * i[:quantity]).round(2) }.round(2)
expect(params[:value]).to eq(expected)
end
it "never contains the customer's email" do
expect(described_class.new(order).to_h.to_json).not_to include(order.email)
end
end
Google's validation server. The Measurement Protocol has a validation endpoint at /debug/mp/collect that returns validation messages instead of recording the event22. Run it in staging against real orders, every time the payload changes.
DebugView in GA4. With debug mode enabled, DebugView shows events as GA4 receives them, in real time23. Place one test order per payment method, card, PayPal, a voucher, a discount code, and check that each purchase arrives once, with the right transaction ID and value.
Then keep watching. A daily query on the shop's own database finds consented orders whose purchase never went out:
SELECT number, completed_at
FROM spree_orders
WHERE analytics_consent = TRUE
AND completed_at < NOW() - INTERVAL '1 hour'
AND ga_purchase_sent_at IS NULL;
An empty result is the goal. Anything else means the job is failing, and the shop knows before the reports do. Alerting and an outbox for several destinations follow in the server events chapter.
Example: the test that caught a voucher
Callum's test orders on staging include one paid entirely with a gift voucher, where Solidus does not need a payment step. DebugView shows the purchase, but with value €0.00. The cause: the voucher order's line items are correct, but his first draft took value from the payment total instead of the items. The automated test above, run against a voucher order factory, now fails if anyone reintroduces that mistake. The fix took ten minutes. Finding it in GA4 three months later, among 1,267 purchases a month, would have taken much longer.
The purchase event checklist
| Check | Right | Wrong |
|---|---|---|
| Transaction ID | The shop's order number, on every payment path | Empty, row ID, payment reference, "test" |
| Value | Net merchandise, equal to the sum of item price times quantity | Gross total with VAT and delivery inside |
| Tax and shipping | In their own fields | Inside value, or missing |
| Currency | The order's own currency code | Missing, or converted in the browser |
| Discounts | Inside the item price, unit discount in discount | Basket discount ignored |
| Trigger | Order completion in the shop, once | Every load of the confirmation page |
| Payment redirects | Provider domains listed as unwanted referrals | Sales credited to the payment provider |
| Consent | Purchase sent only with analytics consent on record | Sent for everyone "because it is the server" |
| Refunds | refund event with transaction ID and items | Never sent |
| Renewals | Own ID per renewal, no invented session | Same ID as the first order |
| Personal data | None in any parameter | Email or name in coupon or items |
| Tests | Automated payload tests, validation server, DebugView per payment method | One test order, once |
Conclusion
Analytics and the shop disagree on revenue for reasons you can name. First, they use different definitions: decide once that analytics carries net merchandise, with VAT and delivery in their own fields, and write it down. Second, the purchase event breaks in specific places: an empty or reused transaction ID, a confirmation page that fires on every reload, payment providers that take customers away and do not always bring them back. Third, some sales can never arrive, because the customer did not agree to analytics, and that gap belongs in your reports as an explained number, not as a bug to engineer around.
The fix that removes most of the trouble at once is to send the purchase from the shop when the order completes, once, with the order number as its ID and the consent stored on the order. Add refunds when reimbursements succeed, give renewals their own IDs, send every order in its own currency, and test the payload like any other feature. What remains is a gap you can explain line by line, which is the whole point of reconciling analytics, ads and orders.