Sub topic 17
Sending Purchases and Refunds Server-Side with the Measurement Protocol
This chapter assumes you can already send purchase and refund events from the browser. It also assumes you know what transaction_id, items, currency, and value do, and that you can read JSON and basic Node.js. The chapter covers sending the same events from your own server.
Why send events from a server
Browser tracking misses events. Ad blockers, closed tabs before the thank-you page loads, and failed redirects from payment providers all lose purchases. Some events never happen in a browser at all. Refunds are usually issued from an admin panel or a payment provider's webhook, and subscription renewals run on a schedule.
The Measurement Protocol (MP) is an HTTP API that lets your server send events to a GA4 data stream. Use it to add events the browser cannot see. Do not use it as a full replacement for browser tracking. MP does not collect page views, device details, or traffic sources on its own.
The request
You send a POST request with a JSON body to this endpoint:
https://www.google-analytics.com/mp/collect?measurement_id=G-XXXXXXX&api_secret=YOUR_SECRETmeasurement_ididentifies the web data stream.api_secretis created in the GA4 Admin area, under the data stream's Measurement Protocol API secrets. Keep it on the server. Never put it in page source.- The body needs
client_idand aneventsarray. A request can contain up to 25 events.
The client_id is the key detail. GA4 uses it to link your server event to the browser visitor. Read it from the _ga cookie in the browser (the last two dot-separated parts of its value) or from gtag('get', measurementId, 'client_id', callback). Save it with the order when the customer checks out. If you send a made-up client_id, GA4 records a new, unrelated user.
Sending a purchase
The event uses the same names and parameters as in the browser. Put them under params.
{
"client_id": "123456.7654321",
"events": [
{
"name": "purchase",
"params": {
"transaction_id": "T_12345",
"currency": "USD",
"value": 49.98,
"tax": 4.00,
"shipping": 5.99,
"items": [
{
"item_id": "SKU_1001",
"item_name": "Trail Running Shoe",
"price": 24.99,
"quantity": 2
}
]
}
}
]
}Two optional parameters improve reporting:
session_idattaches the event to the visitor's existing session. Without it, the event may appear in a session of its own, and revenue can land in an "(not set)" or direct traffic row. Read it from the_ga_<container-id>cookie, or withgtag('get', measurementId, 'session_id', callback).engagement_time_msecmakes the event count toward engagement. Some reports and the Realtime view ignore events without it.
Sending a refund
A refund references the original order by transaction_id.
- Leave out
itemsto refund the whole order. Sendcurrencyandvaluefor the refunded amount. - Include
itemswithitem_idandquantityto refund part of an order. The body below refunds one of the two shoes.
{
"client_id": "123456.7654321",
"events": [
{
"name": "refund",
"params": {
"transaction_id": "T_12345",
"currency": "USD",
"value": 24.99,
"items": [
{
"item_id": "SKU_1001",
"item_name": "Trail Running Shoe",
"price": 24.99,
"quantity": 1
}
]
}
}
]
}GA4 counts the refund on the day it receives the event, not on the date of the original purchase. A refund sent a month later lowers that later month's net figures.
A complete server script
This Node.js script (version 18 or later, which has fetch built in) validates a refund and then sends it. It reads the secrets from environment variables.
const MEASUREMENT_ID = process.env.GA_MEASUREMENT_ID;
const API_SECRET = process.env.GA_API_SECRET;
async function send(path, body) {
const url = `https://www.google-analytics.com${path}` +
`?measurement_id=${encodeURIComponent(MEASUREMENT_ID)}` +
`&api_secret=${encodeURIComponent(API_SECRET)}`;
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const text = await res.text();
return { status: res.status, text };
}
const refund = {
client_id: '123456.7654321',
events: [{
name: 'refund',
params: {
transaction_id: 'T_12345',
currency: 'USD',
value: 24.99,
items: [{ item_id: 'SKU_1001', item_name: 'Trail Running Shoe', price: 24.99, quantity: 1 }]
}
}]
};
// 1. Check the payload against the validation server.
const check = await send('/debug/mp/collect', refund);
console.log('validation:', check.text);
// 2. Send it for real only if there are no validation messages.
const parsed = JSON.parse(check.text);
if (!parsed.validationMessages || parsed.validationMessages.length === 0) {
const real = await send('/mp/collect', refund);
console.log('sent, status', real.status);
}Save it as refund.mjs and run node refund.mjs.
The silent-failure problem
The real /mp/collect endpoint returns a 2xx status even when the payload is wrong. A bad event is dropped with no error. That is why the script above calls /debug/mp/collect first. The debug endpoint returns a validationMessages array that names the offending field. Use it in development and in tests, not in production traffic, because debug requests are not recorded in reports.
A valid event also does not appear in DebugView by default. To see it there, add "debug_mode": true to the event's params while testing, and remove it afterwards.
Avoiding duplicate revenue
If both the browser and the server send a purchase for the same order, you risk double counting. GA4 does deduplicate purchases that share a transaction_id, but do not rely on that as your only protection. Choose one source for each event type:
- Browser sends
purchase; server sends onlyrefund. This is the simplest pattern. - Server sends both, and the browser sends no revenue events. This is more reliable but needs
client_idandsession_idcaptured at checkout.
In either case, make the server's refund handler idempotent: store which refunds you already sent, so a repeated webhook does not send a second refund.
Limits to remember
| Limit | Value |
|---|---|
| Events per request | 25 |
| Event name length | 40 characters |
| Backdating with `timestamp_micros` | 72 hours |
| Response on bad payload | 2xx, with no error from `/mp/collect` |
Exercise
Your server sends a refund for order T_12345 to /mp/collect, receives a 204 response, and the refund never shows in reports. Name two likely causes and how you would find out which one applies.
Show answer
Likely causes are an invalid payload (for example a missing currency or a malformed items array) and a transactionid that does not match the original purchase. The 204 only means the request was received, not accepted. To find out, post the same body to /debug/mp/collect and read validationMessages for payload errors, then compare the transactionid string character by character with the one on the original purchase event in DebugView or the BigQuery export.
Exercise
Why should you store the browser's clientid with each order, and what happens if you send a random clientid with a purchase?
Show answer
The clientid is how GA4 ties a server event to the visitor who browsed and clicked the ad. With the stored value, the purchase joins the original user and (with sessionid) the original session, so revenue is attributed to the right traffic source. A random client_id creates a new user with no history, so the revenue is not attributed to the original source and user counts are inflated.