Server-to-server postback tracking, explained with working code
If you've ever integrated an affiliate network, an ad platform or a partner program, you've met the postback URL. It's a plain HTTP call, but small mistakes in how you send it lead to missing conversions, double payouts
If you've ever integrated an affiliate network, an ad platform or a partner program, you've met the postback URL. It's a plain HTTP call, but small mistakes in how you send it lead to missing conversions, double payouts and long email threads with partners.
This post walks through the whole flow with code you can copy: where the click ID comes from, how to send the postback from your server, how to make it safe to retry, and how to receive one on the other side.
The flow in 30 seconds
Visitor clicks a tracking link
│
▼
Tracker records the click, creates click_id = 01JD3E28JT97KB6CQ643DZVMXX
│ 302 redirect
▼
https://shop.example/landing?clickid=01JD3E28JT97KB6CQ643DZVMXX
│ your site stores the click_id with the lead/order
▼
Order paid ──► your SERVER calls
https://track.example.com/postback?token=…&click_id=…&txn_id=…&amount=…
No cookies and no browser scripts are involved in the last step, which is why S2S tracking survives ad blockers, Safari's ITP and cookie banners. That's the main reason to prefer it over a tracking pixel.
Step 1: keep the click ID until the conversion
The tracker appends the click ID to your landing page URL. Your only job is not to lose it. The most reliable place is the server: read it on the first request and store it with the session, then with the user or order.
// Express: keep ?clickid=… for 30 days in a first-party cookie, then save it with the order
import express from "express";
import cookieParser from "cookie-parser";
const app = express();
app.use(cookieParser());
app.use((req, res, next) => {
const id = req.query.clickid;
if (typeof id === "string" && /^[0-9A-Za-z_-]{10,64}$/.test(id)) {
res.cookie("click_id", id, { maxAge: 30 * 864e5, httpOnly: true, sameSite: "lax", secure: true });
}
next();
});
app.post("/checkout", async (req, res) => {
const order = await createOrder({ ...req.body, clickId: req.cookies.click_id ?? null });
res.json(order);
});
Validate the format before storing it. The value comes from a URL, so treat it like any other user input.
Step 2: fire the postback from your server
Three rules:
- Server side only. The postback URL carries a secret token. If you fire it from the browser, anyone can read the token and send fake conversions.
- Always send a transaction ID. It makes the call idempotent: the tracker can ignore a duplicate, and you can later change the conversion's status.
- Retry network errors and 5xx, never 4xx. A 4xx means the request itself is wrong (bad token, unknown click ID). Retrying won't fix it.
// Node 18+ (built-in fetch), no dependencies
export async function sendPostback({ clickId, txnId, amount, status = "approved" }) {
const url = new URL(process.env.POSTBACK_URL); // e.g. https://track.example.com/postback
const params = { token: process.env.POSTBACK_TOKEN, click_id: clickId, txn_id: txnId, amount, status };
for (const [k, v] of Object.entries(params)) if (v != null && v !== "") url.searchParams.set(k, String(v));
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch(url, { signal: AbortSignal.timeout(15_000) });
} catch (err) {
if (attempt >= 5) throw err; // network error: retry below
}
if (res?.ok) return await res.text();
if (res && res.status < 500) throw new Error(`Postback refused (${res.status}): ${await res.text()}`);
if (attempt >= 5) throw new Error(`Postback failed after ${attempt} attempts`);
await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt)); // 2s, 4s, 8s, 16s
}
}
URLSearchParams takes care of encoding. Building the query string by concatenation is the most common source of broken postbacks: an & or # inside an order ID silently cuts the URL.
In production, don't call this inside the checkout request. Put it in a job queue (or an outbox table) so a slow tracker never slows down your checkout, and so retries survive a restart.
The same thing in Python, standard library only:
import os, time, urllib.parse, urllib.request, urllib.error
def send_postback(click_id, txn_id, amount=None, status="approved", attempts=5):
params = {"token": os.environ["POSTBACK_TOKEN"], "click_id": click_id,
"txn_id": txn_id, "amount": amount, "status": status}
query = urllib.parse.urlencode({k: v for k, v in params.items() if v not in (None, "")})
url = f'{os.environ["POSTBACK_URL"]}?{query}'
for attempt in range(1, attempts + 1):
try:
with urllib.request.urlopen(url, timeout=15) as res:
return res.read().decode()
except urllib.error.HTTPError as err:
if err.code < 500:
raise RuntimeError(f"Postback refused ({err.code})") from err
except urllib.error.URLError:
pass
if attempt == attempts:
raise RuntimeError("Postback failed")
time.sleep(2 ** attempt)
Step 3: refunds and chargebacks
Conversions change. A sale gets refunded, a lead turns out to be fake. Because you sent a txn_id, you can send the same click ID and transaction ID again with a new status:
await sendPostback({ clickId: order.clickId, txnId: order.id, status: "reversed" });
Most trackers (including the one I work on) treat this as an update, not a new conversion. The partner's commission is removed and they get notified. Without a transaction ID there's no clean way to do this.
Step 4: receiving postbacks
If you're on the other side (an affiliate sending conversions into your own tracker, or a partner notifying you), the receiver needs two properties.
Authenticate the call. Put a long random secret in the URL you hand out, and compare it in constant time:
import { createServer } from "node:http";
import { timingSafeEqual } from "node:crypto";
const SECRET = Buffer.from(process.env.POSTBACK_SECRET);
const same = (a) => a.length === SECRET.length && timingSafeEqual(Buffer.from(a), SECRET);
createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
if (url.pathname !== "/postback") return res.writeHead(404).end();
if (!same(url.searchParams.get("key") ?? "")) return res.writeHead(403).end();
const conversion = {
id: url.searchParams.get("conversion_id"),
clickId: url.searchParams.get("click_id"),
payout: Number(url.searchParams.get("payout") ?? 0),
status: url.searchParams.get("status"),
};
await upsertConversion(conversion); // insert or update by id: never insert twice
res.writeHead(200).end("ok");
}).listen(8080);
Be idempotent. Senders retry on timeouts, and status changes arrive as a second call for the same conversion. Store by conversion ID (or click ID + transaction ID) and update instead of inserting.
Debugging checklist
When conversions don't show up, it's almost always one of these:
-
The macro wasn't replaced. The tracker received the literal text
{clickid}. The sending system uses a different placeholder name. Every platform has its own: Everflow uses{transaction_id}, Affise{clickid}, Offer18{tid}. - The click ID was lost between the landing page and the thank-you page (a redirect that dropped the query string, a different subdomain for checkout).
- No transaction ID, so a second sale from the same click is rejected as a duplicate.
- Wrong token or tracking domain, copied from another advertiser or an old setup.
- Fired from the browser and blocked by an ad blocker. Move it to the server.
A quick way to catch the first and last items before you ship: paste the URL into a postback URL checker, which flags unreplaced macros and missing parameters.
Wrapping up
S2S postbacks are boring in the best way: one HTTP call per conversion, no cookies, no scripts. Most problems come from four things: losing the click ID, building the URL by hand, firing from the browser, and forgetting the transaction ID. Get those right and they just work.
All the snippets above (plus PHP and cURL versions, a click ID capture page and a macro mapping table for Everflow, Affise, Scaleo and Offer18) are in an MIT-licensed repo: rastroaff-examples on GitHub.
I work on RastroAff, an affiliate tracking platform for networks and iGaming. The patterns here apply to any tracker.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.