Building reliable payment webhooks
Payment webhooks retry, so verify signatures on raw bytes, claim each event once, and enforce idempotency on both event IDs and transaction IDs before you mark an order paid. Return 2xx when work is done or permanently rejected; queue customer notifications after commit.
A payment webhook is a POST to your server that says a transfer arrived, or that an earlier event should be retried. Treated like a normal form handler, it fails in familiar ways: the same event pays two orders, a timeout retry sends a second Telegram message, or a forged body ships an order. I build hosted payment gateways for Syriatel Cash and Sham Cash. The shops that stay out of trouble do the same checks on every request: verify the signature, record the event once, and only then apply the transaction ID.
This article is a pattern for your backend. Header and field names below are examples; map them to the values from setup. Do not copy a made-up path into production.
What payment webhooks have to get right
In a Syrian checkout the customer usually pays from a wallet, then enters the transaction ID (رقم العملية) on your site. Your app can also receive a server-to-server notice when the gateway has something new for you. Either way, the decision is the same as in How to Automate Payment Confirmation for Syrian Wallets: match on the transaction ID, check the amount, reject a reused ID, and store the sender number as extra information. The sender number is always returned; it is not the matching key.
The webhook path adds delivery on top of matching. Providers retry when they do not get a timely success. Your process can crash after a write but before it replies, and two workers can handle the same POST at once. Those retries must not create a second shipment or a second message.
I keep email, Telegram, and n8n off the write that marks the order paid. The write is idempotent. The notification retries from a queue if it fails. Mixing the two is how a paid order gets several messages, or how a failed Telegram send rolls back a payment the customer already made.
Verify the signature before you parse the body
Read the raw bytes of the body and check a signature header against a signing secret that never ships in the repository. If you run express.json() first, you lose the exact bytes the sender signed, and verification becomes guesswork. Mount express.raw() on the webhook route only.
A common header shape is t=<unix-seconds>,v1=<hex hmac>. The signed payload is the timestamp, a period, then the raw body. Compare digests with crypto.timingSafeEqual, and reject timestamps older than a short window (I use five minutes) so a captured request cannot be replayed a day later.
```javascript import crypto from "node:crypto"; import express from "express";
export function verifySignature(rawBody, header, secret, maxAgeSec = 300) { if (!header || !secret) return { ok: false, reason: "missing_signature" };
const parts = Object.fromEntries( header.split(",").map((piece) => { const index = piece.indexOf("="); return [piece.slice(0, index).trim(), piece.slice(index + 1).trim()]; }) );
const timestamp = parts.t; const expectedHex = parts.v1; if (!timestamp || !expectedHex) return { ok: false, reason: "malformed_header" };
const ageSec = Math.abs(Date.now() / 1000 - Number(timestamp)); if (!Number.isFinite(Number(timestamp)) || ageSec > maxAgeSec) { return { ok: false, reason: "timestamp_out_of_range" }; }
const raw = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody); const signed = Buffer.concat([Buffer.from(${timestamp}.), raw]); const digest = crypto.createHmac("sha256", secret).update(signed).digest();
let expected; try { expected = Buffer.from(expectedHex, "hex"); } catch { return { ok: false, reason: "malformed_header" }; }
if (expected.length !== digest.length || !crypto.timingSafeEqual(digest, expected)) { return { ok: false, reason: "bad_signature" }; } return { ok: true }; }
export function webhookBodyParser(req, res, next) { express.raw({ type: "application/json", limit: "64kb" })(req, res, next); } ```
A bad signature is a client error. I return 400 or 401 and I do not retry the business logic. Returning 500 here only asks the sender to send the same forged or truncated request again. Log the reason and the request id, not the secret and not a full wallet payload if you can avoid it.
If the gateway you use signs a different string (the body alone, or a list of fields), keep this structure and change only the bytes that go into createHmac. The rule that matters is: verify first, parse after.
Idempotency: the same event will arrive twice
Webhook idempotency means a second delivery of the same event does not change the world again. The event ID from the payload (or a header) is the first key. The transaction ID you apply to an order is the second. You need both. Two different events can, in a bug or a replay, try to spend the same transfer. A single event can also be delivered twice with the same event ID.
Do not insert the event row only after a successful payment write. If you crash between the write and the insert, the retry looks new and you process it again. Do not insert a "done" row before you start, either, unless you can recover: a retry would then see the row and skip work that never finished.
The pattern I use is a claim:
- Insert the event with
processed_atempty. If a row already exists and is processed, return 200 and stop. - If a row exists and is still unprocessed, take it only if it is stale (the previous worker died), otherwise return 409 so the sender retries later.
- Apply the payment in the same database transaction as the final
processed_atstamp, with a unique constraint on the transaction ID. - After commit, enqueue notifications.
```sql CREATE TABLE webhook_events ( event_id TEXT PRIMARY KEY, event_type TEXT NOT NULL, payload JSONB NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now(), claimed_at TIMESTAMPTZ, processed_at TIMESTAMPTZ );
CREATE TABLE used_transaction_ids ( transaction_id TEXT PRIMARY KEY, order_id TEXT NOT NULL, amount INTEGER NOT NULL, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() ); ```
```javascript import express from "express"; import pg from "pg"; import { verifySignature, webhookBodyParser } from "./webhook-signature.js";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const app = express();
function toIntAmount(value) { const n = Number(value); if (!Number.isFinite(n)) throw new Error("bad_amount"); return Math.round(n); }
app.post("/webhooks/payments", webhookBodyParser, async (req, res) => { const secret = process.env.WEBHOOK_SIGNING_SECRET; const header = req.get("x-webhook-signature") || ""; const check = verifySignature(req.body, header, secret); if (!check.ok) { return res.status(400).json({ ok: false, reason: check.reason }); }
let event; try { event = JSON.parse(Buffer.from(req.body).toString("utf8")); } catch { return res.status(400).json({ ok: false, reason: "invalid_json" }); }
// Placeholder field names. Replace with the names you get at gateway setup. const eventId = event.eventId || event.id; const eventType = event.type || "payment.received"; if (!eventId) return res.status(400).json({ ok: false, reason: "missing_event_id" });
const client = await pool.connect(); try { await client.query("BEGIN");
const claim = await client.query( INSERT INTO webhook_events (event_id, event_type, payload, claimed_at) VALUES ($1, $2, $3::jsonb, now()) ON CONFLICT (event_id) DO UPDATE SET claimed_at = now() WHERE webhook_events.processed_at IS NULL AND ( webhook_events.claimed_at IS NULL OR webhook_events.claimed_at < now() - interval '2 minutes' ) RETURNING event_id, processed_at, [eventId, eventType, Buffer.from(req.body).toString("utf8")] );
if (claim.rowCount === 0) { const existing = await client.query( SELECT processed_at FROM webhook_events WHERE event_id = $1, [eventId] ); await client.query("COMMIT"); if (existing.rows[0]?.processed_at) { return res.status(200).json({ ok: true, duplicate: true }); } return res.status(409).json({ ok: false, reason: "in_progress" }); }
const result = await applyPaymentEvent(client, event); if (!result.ok && result.retry) { await client.query("ROLLBACK"); return res.status(503).json({ ok: false, reason: result.reason }); } if (!result.ok) { // Non-retryable: keep the claim so a later delivery does not try the same work again. await client.query( UPDATE webhook_events SET processed_at = now() WHERE event_id = $1, [eventId] ); await client.query("COMMIT"); return res.status(200).json({ ok: false, reason: result.reason }); }
await client.query( UPDATE webhook_events SET processed_at = now() WHERE event_id = $1, [eventId] ); await client.query("COMMIT");
await enqueueNotify(result.orderId); return res.status(200).json({ ok: true, orderId: result.orderId }); } catch (err) { try { await client.query("ROLLBACK"); } catch {} console.error("webhook_failed", err.message); return res.status(500).json({ ok: false, reason: "internal" }); } finally { client.release(); } });
async function applyPaymentEvent(client, event) { const transactionId = event.transactionId; const orderId = event.orderId; if (!transactionId || !orderId) { return { ok: false, retry: false, reason: "missing_ids" }; }
const orderRes = await client.query( SELECT id, amount, status FROM orders WHERE id = $1 FOR UPDATE, [orderId] ); const order = orderRes.rows[0]; if (!order) return { ok: false, retry: false, reason: "order_not_found" }; if (order.status === "paid") { const used = await client.query( SELECT order_id FROM used_transaction_ids WHERE transaction_id = $1, [transactionId] ); if (used.rows[0]?.order_id === order.id) return { ok: true, orderId: order.id }; return { ok: false, retry: false, reason: "order_already_paid" }; }
const paidAmount = toIntAmount(event.amount); const expected = toIntAmount(order.amount); if (paidAmount !== expected) { await client.query( INSERT INTO used_transaction_ids (transaction_id, order_id, amount) VALUES ($1, $2, $3) ON CONFLICT (transaction_id) DO NOTHING, [transactionId, order.id, paidAmount] ); await client.query( UPDATE orders SET status = 'review', transaction_id = $2, sender_number = $3 WHERE id = $1 AND status <> 'paid', [order.id, transactionId, event.senderNumber || null] ); return { ok: true, orderId: order.id, flagged: true }; }
try { await client.query( INSERT INTO used_transaction_ids (transaction_id, order_id, amount) VALUES ($1, $2, $3), [transactionId, order.id, paidAmount] ); } catch (err) { if (err.code === "23505") { return { ok: false, retry: false, reason: "transaction_already_used" }; } throw err; }
await client.query( UPDATE orders SET status = 'paid', transaction_id = $2, sender_number = $3, paid_at = now() WHERE id = $1, [order.id, transactionId, event.senderNumber || null] ); return { ok: true, orderId: order.id }; }
app.listen(Number(process.env.PORT || 3000), "0.0.0.0"); ```
Amounts are compared as integers, so 85000 and "85000.00" agree. A wrong amount still binds the transaction ID to that order so it cannot close a different one. FOR UPDATE on the order row stops two events paying the same unpaid order in parallel. enqueueNotify runs after commit; if it throws, I still return 200 and a job retries the message.
Syriatel Cash transfers have no memo field. Do not expect the webhook to carry a customer-typed reference from the wallet itself. The order ID in the payload has to come from your system (you created the order before the customer paid, or the customer typed the transaction ID against an order). I walk through that matching rule for the hosted gateway in Syriatel Cash API: Accept Payments on Your Site.
What to return when the sender retries
Return 2xx when you have finished the event or decided it will never be applied (unknown order, reused transaction ID, amount already flagged). Return 5xx or 409 when a later retry might succeed: database down, a claim still held, or a lock you could not take.
Do not return 500 for a signature failure or invalid JSON, and do not return 200 before the payment write is committed. A timeout after commit is fine; the duplicate should hit the processed_at path and stop.
Outgoing retries to n8n or Telegram are yours, not the provider's. The payment row does not roll back because a chat message failed. Fanning a paid event out to Telegram is a separate workflow in أتمتة شغل متجرك بـ n8n.
Go-live checks
- The webhook URL is HTTPS only. The signing secret is in the environment, not in git.
- You have sent a signed test event, a replay of the same event ID, and an event with a bad signature. The first pays once, the second returns 200 without a second write, the third returns 400.
- Two events with the same transaction ID cannot pay two orders. The unique constraint is the last line of defence, not a log line.
- A wrong amount flags the order and still consumes the transaction ID.
- Notifications can fail and retry without changing the order status.
- A manual confirm button still exists in the dashboard for the cases the webhook will not settle.
I would not point a live wallet at a handler that has not seen those cases in a sandbox.
Frequently asked questions
Is a webhook required if the customer already types the transaction ID?
No. Typed IDs are enough to confirm a payment. A webhook helps when the customer pays and never comes back to the page, or when you want your own systems notified without polling. Many shops start with the form and add a webhook later.
Does this replace the Syriatel Cash or Sham Cash gateway?
No. The gateway looks up the transfer. This article is how your server receives and records that news without double spending an ID. Syriatel Cash API is $2 per number per month; Sham Cash API is $5 per account per month. Both are hosted, with same-day setup and no source-code handover.
What if two open orders have the same amount?
That is fine if matching starts from the transaction ID. Do not pick an unpaid order by amount when an event is missing an ID. The Arabic setup walkthrough is كيف تربط سيريتل كاش بمتجرك الإلكتروني.
Where should this process run?
On a server you control, behind Nginx and TLS. A practical publish path is in نشر مشروع Node.js على VPS.
If you want the hosted gateway and a handler wired with these rules, write through the form on fayezalshami.com or email fayezalshami.dev@gmail.com. Say which wallet you use, how many numbers or accounts, and whether confirmation today is a form, a bot, or a webhook you already have.