Idempotent Annual Passes: Fulfilling a Payment Webhook Once, and Only Once
Selling a one-year pass on a small site is deceptively simple: one price, one product, no seats, no renewal.
The payment provider handles the checkout page, the card, the tax display, and the receipt. Your job is to receive a webhook and turn money into access. That sentence contains the entire risk.
A webhook is not a function call. It is a retried, possibly duplicated, possibly out-of-order message from someone else's system, delivered over the public internet, and it is the only signal you get that a stranger paid you.
This is the fulfillment design behind the annual pass on FundScope, and the failure modes it is built around.
The shape of the deal
The product is a single annual pass: twelve months of access, no auto-renewal, one price for domestic buyers and one for overseas buyers. There is no subscription object, no proration, no upgrade path.
That reduces fulfillment to four facts that must be true after a successful payment:
- An order exists with the provider's order id, the buyer's email, the amount, and a status.
- The order status is
paid, exactly once, even if three identical webhooks arrive. - An entitlement exists for that email, expiring one year after payment.
- A receipt or welcome email is sent, and sending it twice is acceptable while charging twice is not.
Everything below exists to make those four facts hold under replay.
Verify before you parse
The first rule is that no field from the request body is trusted until the signature is verified. A webhook endpoint is a public URL; anyone can POST to it, and the payload contains an email address and an amount.
If you parse first and verify later, a malformed-but-valid-looking body can create a pending order and pollute your reconciliation reports.
The verification is asymmetric: the provider signs with a private key, you verify with a public key pinned on disk.
const publicKey = fs.readFileSync(env.WEBHOOK_PUBLIC_KEY_PATH, 'utf8');
function verify(rawBody, signature) {
return crypto.verify('sha256', Buffer.from(rawBody, 'utf8'), { key: publicKey, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(signature, 'base64'));
}
Two implementation details that are easy to get wrong:
- Verify the raw bytes, not
JSON.stringify(req.body). Once Express parses the body, key order and whitespace are gone, and the signature will never match. Capture the raw body withexpress.raw({ type: 'application/json' })for that route only. - Fail closed. If the key file is missing, the process should refuse to start rather than accept unsigned callbacks. A payment endpoint that silently degrades to "no verification" is the worst possible availability.
There is one exception, and it must be explicit: test mode. When running against the provider's sandbox, callbacks may arrive without a valid production signature. Gate that behind an environment flag that cannot be set accidentally in production:
const allowUnsigned = env.NODE_ENV !== 'production' && env.PAYMENT_TEST_MODE === '1';
Not if (env.NODE_ENV === 'development') scattered in three places. One flag, one branch, one log line that says UNSIGNED_WEBHOOK_ACCEPTED every time it happens.
Make the order row the idempotency key
The provider retries. It retries on timeout, on a 5xx, and sometimes on a slow 2xx. It may also deliver the same event twice because of an internal replay. You do not get to opt out.
So the database, not the handler, enforces "once":
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
provider TEXT NOT NULL,
order_no TEXT NOT NULL UNIQUE, -- provider's id
email TEXT NOT NULL,
amount_cents INTEGER NOT NULL,
currency TEXT NOT NULL,
status TEXT NOT NULL, -- pending | paid | refunded | failed
paid_at TEXT,
raw_event TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
order_no UNIQUE is the whole trick. The handler does not check "have I seen this before?" in application code; it attempts an insert and lets the constraint decide. If the insert conflicts, the event is a duplicate by definition, and the handler returns 200 immediately.
But there is a subtlety: the first delivery may arrive before the checkout redirect completes, and the buyer's email may not yet be attached to the order row if you created it optimistically. Two patterns work:
- Create the order row only from the webhook. There is no local pending order. The webhook carries the email and the order id, so the first valid event creates the row as
paid. Simpler, and nothing to reconcile before payment. - Create a pending row at checkout, then update it. Needed if you want to show "waiting for payment" in the account page. Then the webhook must update by
order_noand must be safe when the pending row was created by a different request.
I use the first pattern. Fewer rows, fewer states, and the account page can show entitlements only, which is what users actually care about.
Fulfillment is a transaction, not a sequence of awaits
The handler that follows verification should do the minimum, then get out:
app.post('/api/payments/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const raw = req.body.toString('utf8');
const sig = req.get('X-Signature') || '';
if (!allowUnsigned && !verify(raw, sig)) return res.status(401).end();
let event;
try { event = JSON.parse(raw); } catch { return res.status(400).end(); }
if (event.type === 'order.completed') {
const r = db.prepare(
`INSERT INTO orders (provider, order_no, email, amount_cents, currency, status, paid_at, raw_event, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 'paid', ?, ?, datetime('now'), datetime('now'))
ON CONFLICT (order_no) DO NOTHING`
).run('provider', event.data.orderNo, event.data.email, event.data.amount, event.data.currency, event.data.paidAt, raw);
if (r.changes === 0) { return res.json({ ok: true, idempotent: true }); }
grantEntitlement(event.data.email, event.data.paidAt);
enqueueReceipt(event.data.orderNo);
}
return res.json({ ok: true });
});
Four deliberate choices:
- Return 200 for duplicates with
idempotent: true. Returning 409 or 500 for a duplicate teaches the provider to retry forever. The duplicate is a success from the provider's point of view; say so. - Do not call the email API inside the handler. Sending mail synchronously means a slow SMTP server turns into a webhook timeout, which turns into more retries, which turns into more duplicate deliveries. The handler writes an outbox row and returns; a worker sends the mail with its own retry and backoff.
- Grant the entitlement in the same transaction as the order insert. If the insert commits and the grant fails, you have a paid order with no access - the worst state to debug, because the money is real and the user is angry. SQLite gives you a real transaction; use it:
const tx = db.transaction((evt) => {
insertOrderOrThrow(evt);
upsertEntitlement(evt.email, addYears(evt.paidAt, 1));
});
- Store the raw event. Not for auditing vanity - for the day when a field means something different than you assumed.
raw_eventis the only ground truth you will have after the provider's dashboard rotates its retention window.
Entitlements are additive, not a boolean
A user who buys twice should end up with two years, not one. That is a product decision, and it is cheap to support if the entitlement table stores an end date rather than a flag:
CREATE TABLE entitlements (
email TEXT PRIMARY KEY,
expires_at TEXT NOT NULL,
source TEXT NOT NULL, -- order_no of the latest grant
updated_at TEXT NOT NULL
);
INSERT INTO entitlements (email, expires_at, source, updated_at)
VALUES (?, ?, ?, datetime('now'))
ON CONFLICT (email) DO UPDATE SET
expires_at = MAX(entitlements.expires_at, excluded.expires_at), -- never shorten
source = excluded.source,
updated_at = excluded.updated_at;
MAX is doing real work here: a duplicate webhook, a later partial refund, or a mistakenly replayed event must never be able to shorten access that was already granted. Extending is fine; taking away is only allowed through the explicit refund path.
Refunds have their own event and their own rule
A refund is not a negative payment. It is a state transition that must revoke access and be visible in the order history:
if (event.type === 'refund.succeeded') {
const tx = db.transaction(() => {
db.prepare(`UPDATE orders SET status='refunded', updated_at=datetime('now') WHERE order_no=?`).run(event.data.orderNo);
db.prepare(`UPDATE entitlements SET expires_at=datetime('now'), updated_at=datetime('now') WHERE source=?`).run(event.data.orderNo);
});
tx();
}
Note the WHERE source=?: only the entitlement created by that order is revoked. If the user bought a second year afterwards, the refund of the first order should not touch the second. Getting this wrong silently punishes your best customers, and they will find out.
Also note what is missing: no email is sent from here synchronously, and no attempt is made to "recalculate" usage. The next gated request will see the expired entitlement. Read-time checks make revocation instant and order-independent.
When the webhook never arrives
Webhooks are at-least-once in theory and occasionally zero-times in practice: a deploy window, a bad certificate, a provider-side outage. The user paid, the dashboard says so, and your database has nothing.
The answer is not "wait for the next webhook." It is a reconciliation command that can be run manually and scheduled daily:
GET /api/payments/orders?since=... (provider API, read-only) → for each order with status=paid and no local row: insert order, grant entitlement, enqueue receipt
Because the insert is guarded by order_no UNIQUE, running reconciliation twice is harmless. Because the grant uses MAX, granting twice is harmless. The same idempotency that protects the webhook protects the backfill, which is the main reason to build it this way instead of with "check if exists" logic.
The manual fallback matters too. Domestic buyers on the QR-code channel are fulfilled by a human reviewing a transfer screenshot, not by a provider callback. Both channels write to the same orders table with the same status vocabulary, so the account page and the entitlement logic do not know which channel was used. Different acquisition paths, one fulfillment model.
The test checklist I actually run
Before every release that touches the payment path:
- Valid event → one order, one entitlement, one queued email.
- Same event twice → second returns
idempotent: true, no second email, no date shift. - Bad signature → 401, no rows written.
- Missing public key → process refuses to start.
- Event with an unknown type → 200, ignored, logged.
- Refund after a second purchase → only the refunded order's grant is revoked.
- Reconciliation replay after a webhook → no duplicate orders.
- Email worker down for ten minutes → orders still fulfill, mail drains afterwards.
None of these are exotic. All of them have failed in production systems I have watched, usually because the handler checked "does this order exist?" before inserting, and two concurrent deliveries both got "no."
The part that does not change
Payment integrations come and go. Providers rename events, change signature schemes, and deprecate sandboxes. What survives is the local contract: an order row keyed by the provider's id, an entitlement with an end date, one transaction that writes both, and an outbox for everything with a side effect.
Build that, and swapping providers becomes a mapping exercise instead of a rewrite. Skip it, and every retry is a potential double charge.
More small-product engineering notes are at wuhuajin.com. Originally published on wuhuajin.com.
Comments
No comments yet. Start the discussion.