BT San Technology

22 May 2026

Connecting payments to a web app: handling paid, duplicate payments and refunds

28 min read · Websites and web apps

Illustration: a hand holding a phone with a green-check payment confirmation, beside a laptop listing orders with check marks and a retry icon
AI-generated illustration

A customer scans a PromptPay QR code and pays, but the shop still shows "awaiting payment". In another case, the system ships goods twice because it received the payment message twice. Or someone sends a forged request to the shop's endpoint and an order becomes paid with no money received. All three have the same root cause: the website has to trust messages from outside that may arrive late, arrive twice, arrive out of order, or not come from the real provider at all.

This article walks through a webhook endpoint that handles all of them. It uses TypeScript that Node 24 runs directly with nothing to install. It has code you can run yourself, real output, and SQL for a real database. A manager can read the explanations and tables and see the picture. An engineer can run the code and follow along.

The real problem: an order marked paid twice, not paid, or paid falsely

The thank-you page after payment (the redirect back to the website) cannot be trusted. The customer may close the tab before reaching it, lose their connection, or edit the URL. So payment providers offer webhooks: the provider calls a URL of ours when the payment status changes. This is more reliable, but it has its own conditions.

Consider three hypothetical scenarios. They are not any BT San customer's project.

  • An online shop accepting PromptPay QR: the provider sends a payment-succeeded event, does not get a reply in time, and sends it again. The system deducts stock and sends the receipt email twice.
  • A training course booking site: a "refund" event arrives before "payment succeeded" because the network reordered them. The system sees the course as paid even though the money has already been refunded. The learner gets a free link to the classroom.
  • A corporate customer paying an invoice into an ERP: someone sends a forged request to a publicly open endpoint. The invoice is closed with no money in the account. Accounting finds out at period close.

These three cases are fixed by three different mechanisms, and you need all of them: signature verification, duplicate-processing protection (idempotency), and status ordering. The fourth part is to acknowledge quickly and do the work afterwards.

How webhooks are delivered: what is known and what must not be assumed

The summary below comes from the provider documentation cited at the end of the article. Use it as the basis instead of assuming that a message arrives once and in order.

TopicWhat the documentation saysEffect on our code
Duplicate deliveryStripe states that a webhook endpoint may receive the same event more than once. Record the event IDs you have processed and skip ones you have already recorded.We need a table or a unique key on the event id.
OrderingStripe states that events may arrive in a different order than they occurred, and says not to use the created value to decide order.Do not tie the logic to arrival order. Use a state machine that only moves forward.
Retry on failureStripe retries for up to three days in live mode with exponential backoff. Omise states that it does not guarantee automatic redelivery and recommends polling the Events API to find missed events.Providers differ. A reconciliation job must always run alongside the webhook.
Reply quicklyStripe says to return a 2xx quickly before doing heavy work, and to process asynchronously with a queue.Receive, verify, record, reply, then continue the work.
SignatureStripe and Omise require verifying an HMAC-SHA256 over a message that combines the timestamp and the raw body. Stripe also requires checking that the timestamp is within an accepted window (the library default is 5 minutes).Keep the raw body before parsing JSON.
Summary of the Stripe and Omise documentation as of the access date, 2026-11-21. For the details, read the documentation of the provider you actually use.

The Standard Webhooks specification (an open project on GitHub) sets out consistent common guidance: the signature covers the id, timestamp and body; the receiver should check that the timestamp is within an accepted window; and the webhook id stays the same when it is redelivered. The receiver can therefore use it to prevent duplicate processing.

The examples in this article use hypothetical header names and event formats (x-demo-timestamp, x-demo-signature) so that they run without being tied to any one provider. When you adapt them, change them to match the real provider's documentation, for example Stripe-Signature for Stripe or Omise-Signature for Omise.

Overview of the example

All the code is in the folder examples/payment-webhook-order-status-idempotency/. It uses only Node 24 built-ins, with no npm install. TypeScript runs directly with the command node file.ts (Node just strips the types without type checking, and supports only syntax that can be erased, so we avoid enum and namespace, and import statements must include the .ts extension).

FileRole
verify.tsVerifies the signature and the time window
orders.tsThe order state machine, pure functions with no side effects
store.tsDuplicate protection by event id, and processing after the acknowledgment
server.tsThe endpoint, using node:http
schema.sqlTable definitions and production-style SQL for PostgreSQL
demo.ts / webhook.test.tsA script that fires 6 groups of events, and a node:test test suite

The order of work in the endpoint is: read the raw body, verify the signature, parse the JSON, reserve the right to process by event id, reply 200, and only then do the actual work. The steps follow.

Step 1: Verify the signature on the raw body and prevent replay

The provider computes an HMAC-SHA256 over the message: the timestamp, then a dot, then the raw body, using a shared secret as the key. We compute it again and compare. If they match, the message came from someone who knows the secret, and the content was not altered.

verify.ts
// Signature check for a webhook. Header names here are DEMO names, not a real provider's.
import { createHmac, timingSafeEqual } from "node:crypto";

export const DEMO_SECRET = "whsec_demo_only"; // fixed fake secret, never use in production

export type VerifyResult =
  | { ok: true }
  | { ok: false; reason: "malformed" | "bad_signature" | "stale" };

// signature = HMAC-SHA256(secret, "<timestamp>.<raw body bytes>"), hex encoded
export function sign(secret: string, timestamp: number, rawBody: Buffer): string {
  const h = createHmac("sha256", secret);
  h.update(`${timestamp}.`);
  h.update(rawBody); // the exact bytes received, not JSON.stringify(JSON.parse(body))
  return h.digest("hex");
}

export function verify(
  secret: string,
  rawBody: Buffer,
  timestampHeader: string | undefined,
  signatureHeader: string | undefined,
  nowSec: number,
  toleranceSec = 300,
): VerifyResult {
  const ts = Number(timestampHeader);
  if (!timestampHeader || !Number.isInteger(ts) || !signatureHeader) {
    return { ok: false, reason: "malformed" };
  }
  const expected = Buffer.from(sign(secret, ts, rawBody), "hex");
  const given = Buffer.from(signatureHeader, "hex");
  // timingSafeEqual throws when lengths differ, so compare lengths first
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
    return { ok: false, reason: "bad_signature" };
  }
  // the timestamp is covered by the signature, so it can be trusted once we get here
  if (Math.abs(nowSec - ts) > toleranceSec) return { ok: false, reason: "stale" };
  return { ok: true };
}
verify.ts verifies the signature and the time window

There are four points where mistakes are common.

  • Use the bytes you actually received. Never JSON.parse and then JSON.stringify to compute the signature, because whitespace and key order may change and the signature will not match. The Stripe documentation warns about this clearly: touching the raw body makes verification fail.
  • Compare with timingSafeEqual, not ===. The Node documentation says this function compares in constant time, which suits comparing HMAC digests.
  • Check the length first, because the Node documentation says timingSafeEqual throws an error if the two values have different lengths. An attacker who sends a short signature can crash the endpoint if you do not catch this.
  • Check the timestamp after the signature passes, because the timestamp is part of the signed message. An attacker cannot change the time value without breaking the signature. The example code allows a 300-second tolerance, matching the Stripe library default stated in its documentation, and you should not set it to 0, because Stripe says that disables the check.

The timestamp check prevents replay, which is when an attacker captures a genuine, correctly signed request and sends it again later. The time window makes old messages unusable. A message still inside the window that is resent is caught by the duplicate-processing layer in step 3. The two layers reinforce each other and are not redundant.

During secret rotation, some providers send several signatures in a single header. Some do this (see the documentation of the provider you use). Our example verifies a single signature to keep the code short. A real system must support this case too.

Step 2: The state machine: no going backwards, a mismatched amount is not paid

There are three statuses: pending, paid, refunded, in that order. An event that moves the status forward is applied. An event at the same level as the current status or lower, such as a late pending after paid or a second paid, changes nothing.

orders.ts · lines 20–33
// Pure function: same input, same result. `trusted` = the event came from a re-fetch
// of the provider's record, so it may skip a step (pending -> refunded).
export function applyEvent(order: Order, ev: PayEvent, trusted = false): { order: Order; outcome: Outcome } {
  if (ev.amount !== order.amount || ev.currency !== order.currency) {
    // never mark paid on a wrong amount: keep the status, raise a flag for a human
    return { order: { ...order, flag: `mismatch on ${ev.id}` }, outcome: "flagged_mismatch" };
  }
  const target = TARGET[ev.type];
  if (RANK[target] <= RANK[order.status]) return { order, outcome: "ignored_older" }; // late or repeated
  if (target === "refunded" && order.status !== "paid" && !trusted) {
    return { order, outcome: "needs_refetch" }; // refund before we saw "paid": ask the provider
  }
  return { order: { ...order, status: target }, outcome: "applied" };
}
orders.ts the applyEvent function is a pure function
  • Amount or currency does not match the order: do not change the status to paid, but set a flag for a person to review. Do not stay silent and do not trust it.
  • A refund arrives before we have seen the payment: we do not know what the truth is, so the outcome is needs_refetch and we ask the provider (see step 4).
  • This example assumes a full refund. A partial refund needs a separate column for the cumulative refunded amount.

The advantage of writing this as a pure function is that it is easy to test. It needs no server or database, and it answers a manager's question directly: what is the business rule? It can be read in under 15 lines.

Step 3: Idempotency: one event id, done once

Idempotency simply means that doing something many times has the same result as doing it once. The method the Stripe documentation recommends is to record the event ids you have processed and not process ones you have already recorded. The in-memory example looks like this.

store.ts
// Idempotent event processing (in memory). Production version: see schema.sql.
import { applyEvent } from "./orders.ts";
import type { Order, PayEvent } from "./orders.ts";

export type Charge = { status: "pending" | "paid" | "refunded"; amount: number; currency: string };

export function createStore(
  orders: Order[],
  fetchCharge: (orderId: string) => Promise<Charge>, // stands in for the provider API
  onPaid: (orderId: string) => void, // side effect that must run once (ship, send receipt)
) {
  const byId = new Map(orders.map((o) => [o.id, o]));
  const seen = new Set<string>(); // = unique index on webhook_events.event_id
  const running = new Set<Promise<void>>();
  const results: string[] = [];

  async function process(ev: PayEvent): Promise<void> {
    await new Promise((r) => setTimeout(r, 5)); // pretend to do I/O
    const order = byId.get(ev.orderId);
    if (!order) { results.push(`${ev.id} unknown_order`); return; }
    let r = applyEvent(order, ev);
    if (r.outcome === "needs_refetch") {
      const c = await fetchCharge(order.id); // provider is the source of truth
      r = applyEvent(order, { ...ev, ...c, type: `payment.${c.status}` }, true);
      results.push(`${ev.id} refetched provider says ${c.status}`);
    }
    byId.set(order.id, r.order);
    results.push(`${ev.id} ${r.outcome} -> ${r.order.status}`);
    if (r.outcome === "applied" && r.order.status === "paid") onPaid(order.id);
  }

  return {
    // The claim is synchronous: check and insert happen with no await in between.
    // With a database, INSERT ... ON CONFLICT DO NOTHING plays this role.
    receive(ev: PayEvent): "accepted" | "duplicate" {
      if (seen.has(ev.id)) return "duplicate";
      seen.add(ev.id);
      const p = process(ev).catch(() => { seen.delete(ev.id); }); // failed: let the retry in
      running.add(p);
      void p.finally(() => running.delete(p));
      return "accepted";
    },
    async idle() { while (running.size) await Promise.all([...running]); },
    order: (id: string) => byId.get(id),
    results,
  };
}
store.ts reserves the right by event id, then continues processing

The key point is that receive checks and records the event id in one step with no await in between. Even if the provider fires the same copy ten times at once, only the first gets accepted and the rest get duplicate. In Node, which is single-threaded, this part is safe on its own. But a real server usually runs several processes, so the database has to be the one that decides. See the database section below.

If processing fails partway, the example code gives the reservation back (deletes the id) so that the provider can resend and the work can be done again. In a real database this happens by itself: a failed transaction rolls back both the INSERT of the event and the UPDATE of the order, so there is no half-finished state left behind.

Step 4: Reply 2xx quickly, process later, and ask the provider when in doubt

server.ts
// HTTP endpoint: raw body -> verify -> parse -> claim -> answer 2xx -> process later.
import { createServer } from "node:http";
import { verify } from "./verify.ts";
import type { PayEvent } from "./orders.ts";

export function createWebhookServer(
  secret: string,
  receive: (ev: PayEvent) => "accepted" | "duplicate",
  now: () => number = () => Math.floor(Date.now() / 1000),
) {
  return createServer(async (req, res) => {
    const chunks: Buffer[] = [];
    for await (const c of req) chunks.push(c as Buffer);
    const raw = Buffer.concat(chunks); // keep the bytes; do not parse before verifying
    const send = (code: number, body: object) => {
      res.writeHead(code, { "content-type": "application/json" });
      res.end(JSON.stringify(body));
    };

    const v = verify(secret, raw, req.headers["x-demo-timestamp"] as string | undefined,
      req.headers["x-demo-signature"] as string | undefined, now());
    if (!v.ok) return send(401, { error: v.reason });

    let ev: PayEvent;
    try { ev = JSON.parse(raw.toString("utf8")); } catch { return send(400, { error: "bad_json" }); }
    if (!ev.id || !ev.orderId || !ev.type) return send(400, { error: "bad_event" });

    // 2xx right away; the real work continues in the background inside receive()
    send(200, { status: receive(ev) });
  });
}
server.ts keeps the raw body, verifies the signature, replies, then does the work

The order matters. Verify the signature before parsing JSON. If the signature is wrong, reply 401 right away. Once the event passes, reserve the right to process it and reply 200. Heavy work such as deducting stock, sending email or calling an ERP continues after the reply. This matches what Stripe says: return a 2xx before any complex logic, and use a queue to process. In a real system, the "continues" part should be a job in a queue that survives a process crash, not an in-memory promise as in the example.

When should you ask the provider? If the event contradicts what we know, for example a refund arriving before the payment succeeded, call the provider's API to fetch that charge or payment directly, and treat the fetched data as the truth. This approach is our own design, not a requirement of any provider. The Omise documentation also warns that fetching data to confirm alone does not protect against forged requests, so you must still verify the signature first. This example does not call a real API. It uses a fake fetchCharge function that returns values from a table in the code. A real system needs a server-side API key, kept in the environment and not in the code.

Do not confuse this with the idempotency key on the outbound API side. Stripe has a mechanism that lets us attach an Idempotency-Key when creating or updating an object, so that a request can be safely retried when the connection drops. That protects against our own commands being sent twice. The event id in this article protects against receiving an event twice. A real system usually needs both.

Running it: six groups of events fired at the endpoint

demo.ts starts a server on 127.0.0.1 with a random port, then sends real requests to that server using Node's fetch. It uses a fake secret, whsec_demo_only, which is for demonstration only.

demo.ts · lines 24–34
async function post(e: PayEvent, o: { age?: number; secret?: string; tamper?: boolean } = {}) {
  const body = JSON.stringify(e);
  const ts = Math.floor(Date.now() / 1000) - (o.age ?? 0);
  const sig = sign(o.secret ?? DEMO_SECRET, ts, Buffer.from(body));
  const sent = o.tamper ? body.replace(String(e.amount), "1") : body; // changed after signing
  const r = await fetch(`http://127.0.0.1:${port}/webhook`, {
    method: "POST", body: sent,
    headers: { "x-demo-timestamp": String(ts), "x-demo-signature": sig },
  });
  console.log(`  ${e.id} ${e.type} -> HTTP ${r.status} ${JSON.stringify(await r.json())}`);
}
demo.ts the post function signs with a configurable time and simulates altering the body after signing
output.txt
1) valid event, then the same event again
  evt_001 payment.paid -> HTTP 200 {"status":"accepted"}
  evt_001 payment.paid -> HTTP 200 {"status":"duplicate"}
   A-1001: paid
2) forged signature, tampered body, replayed old timestamp
  evt_010 payment.paid -> HTTP 401 {"error":"bad_signature"}
  evt_011 payment.paid -> HTTP 401 {"error":"bad_signature"}
  evt_012 payment.paid -> HTTP 401 {"error":"stale"}
   A-1002: pending
3) out of order: paid, late pending, second paid, refund, late paid
  evt_101 payment.paid -> HTTP 200 {"status":"accepted"}
  evt_100 payment.pending -> HTTP 200 {"status":"accepted"}
  evt_102 payment.paid -> HTTP 200 {"status":"accepted"}
   A-1002: paid
  evt_103 payment.refunded -> HTTP 200 {"status":"accepted"}
  evt_104 payment.paid -> HTTP 200 {"status":"accepted"}
   A-1002: refunded
4) wrong amount: paid event says 100.00 THB, order is 1,200.00 THB
  evt_201 payment.paid -> HTTP 200 {"status":"accepted"}
   A-1003: pending (flag: mismatch on evt_201)
5) 10 concurrent deliveries of the same event
  evt_301 payment.paid -> HTTP 200 {"status":"accepted"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
  evt_301 payment.paid -> HTTP 200 {"status":"duplicate"}
   A-1004: paid
6) refund arrives before we saw paid: re-fetch from provider
  evt_401 payment.refunded -> HTTP 200 {"status":"accepted"}
   A-1005: refunded

store log:
  evt_001 applied -> paid
  evt_101 applied -> paid
  evt_100 ignored_older -> paid
  evt_102 ignored_older -> paid
  evt_103 applied -> refunded
  evt_104 ignored_older -> refunded
  evt_201 flagged_mismatch -> pending
  evt_301 applied -> paid
  evt_401 refetched provider says refunded
  evt_401 applied -> refunded

shipments triggered: 3 (A-1001, A-1002, A-1004)
Output from the real run on 2026-11-21 with node demo.ts (Node 24). The nine repeated evt_301 lines are in the full file.

Reading the results one by one.

  1. A valid event gets accepted and the order becomes paid. Resending the same event gets duplicate and the order does not change.
  2. A forged signature, and a body altered after signing, get 401 bad_signature. An event with a correct signature but a timestamp one hour old gets 401 stale. The order stays pending.
  3. paid arrives first, then a late pending and a second paid change nothing (ignored_older). Then refunded arrives, and a late paid does not pull the status back. The final result is refunded.
  4. A paid with a mismatched amount gets flagged_mismatch. The order stays pending with a flag.
  5. Sending the same event 10 times at once gets accepted 1 time and duplicate 9 times.
  6. refunded arrives before the system has seen paid. The system queries the simulated provider, gets the answer refunded, and only then updates.

The last line of the output says there were 3 side effects (shipments), for orders A-1001, A-1002 and A-1004, one per order, even though A-1001 was sent twice and A-1004 was sent ten times. This number is what the business cares about.

The test suite

webhook.test.ts has 4 cases and runs with node --test webhook.test.ts, giving 4 pass. It tests the signature (valid, altered body, wrong secret, unequal length, too old), the state machine rules, the mismatched amount, and 20 simultaneous copies that must produce the side effect only once. If anyone edits the code and breaks any mechanism, the test suite fails.

A real database: a unique key and a single transaction

In-memory works because there is a single Node process. A real system has several processes and can restart, so let the database decide. Use a webhook_events table with event_id as the primary key and use INSERT ... ON CONFLICT DO NOTHING, which the PostgreSQL documentation describes as skipping the insert of a row when it conflicts with a unique constraint.

schema.sql
-- PostgreSQL. Production shape of the in-memory store in store.ts.
CREATE TABLE orders (
  id        text PRIMARY KEY,
  amount    bigint NOT NULL,                 -- minor units (satang)
  currency  text   NOT NULL,
  status    text   NOT NULL DEFAULT 'pending'
            CHECK (status IN ('pending','paid','refunded')),
  flag      text,                            -- set when amount/currency did not match
  updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE webhook_events (
  event_id    text PRIMARY KEY,              -- the provider's event id: the unique key
  type        text NOT NULL,
  order_id    text NOT NULL REFERENCES orders(id),
  payload     jsonb NOT NULL,                -- keep it for audit and replay
  received_at timestamptz NOT NULL DEFAULT now(),
  outcome     text                           -- applied / ignored_older / flagged_mismatch ...
);

-- One transaction per event. Parameters come from the verified event: $1 event_id, $2 type, $3 order_id, $4 payload, $5 amount, $6 currency.
BEGIN;

INSERT INTO webhook_events (event_id, type, order_id, payload)
VALUES ($1, $2, $3, $4)
ON CONFLICT (event_id) DO NOTHING;
-- 0 rows inserted = duplicate delivery: COMMIT and answer 200 without touching the order.

UPDATE orders
SET status = 'paid', updated_at = now()
WHERE id = $3
  AND status = 'pending'          -- state machine in SQL: only move forward
  AND amount = $5 AND currency = $6;  -- wrong amount updates 0 rows -> flag it instead
-- Run the UPDATE only when the INSERT above reported 1 row.

COMMIT;
schema.sql the table and the steps in a single transaction
  • If the INSERT affects 0 rows, the event has been received before. COMMIT and reply 200 without touching the order.
  • The order UPDATE has the conditions status = 'pending' and a matching amount, so it acts as the state machine at the SQL level. If no row is updated, record the outcome and then decide whether it was a late arrival or an amount mismatch.
  • Keep the raw payload in a jsonb column for later inspection and for replaying when a bug is fixed.
  • The two statements are in a single transaction. If it crashes midway, there is no recorded event with an order that has not moved.

External side effects, such as sending email or calling an ERP, cannot sit inside the transaction. The safe way is to write those jobs into a job table (an outbox) in the same transaction, and have a separate worker read it and do them. Work that can be repeated without harm survives a worker crash midway.

Hypothetical examples: applying this to three businesses

Online shop with PromptPay QR

An order starts as pending with a QR code that expires. When paid arrives, the system deducts stock, issues a receipt and calls the carrier, once each. So this queue should be tied to the event id or order id with a unique constraint. If the customer pays twice (one order, two payments), this example does not handle it. You need an extra rule on whether to refund automatically or have a person review it.

Course booking site

The damage from a paid arriving late after refunded is granting class access to someone who has already been refunded. The state machine in the example prevents this directly. Another issue is limited seats. If payment succeeds after the seats are full, you have to decide whether to refund or add seats. This is a business rule to discuss with the owner (see the related article on double booking).

B2B invoice payments into an ERP

Corporate customers often transfer an amount that does not match the invoice (withholding tax, bank fees, payment in installments). Flagging a mismatch instead of automatically closing the invoice is therefore more important than in the shop case. You may need extra statuses, such as partially paid, and a screen for accounting to handle flagged items before they are pushed into the ERP.

Where providers differ

TopicWhat to check in that provider's documentation
Header names and signature formatStripe uses the Stripe-Signature header, while Omise uses Omise-Signature and Omise-Signature-Timestamp. The format of the signed message also differs.
Secret formatThe format, and how the secret is used as a key, differ by provider. Follow that provider's documentation.
Retry policyCheck whether redelivery is guaranteed and for how long. If it is not guaranteed, you need a job that fetches data to reconcile.
Refunds and disputesThe event types and related objects differ. You must map them into your own state machine.
Test modeKeep the test and live secrets and endpoints clearly separate.

Common mistakes and a checklist

  • Trusting the redirect page after payment instead of a webhook or fetching the status from the provider
  • Using the framework's body parser to convert to JSON before verifying the signature (the raw body is lost)
  • Comparing signatures with === or not checking the length before timingSafeEqual
  • Not checking the timestamp, or setting the time window as long as days
  • Ordering events by their created value, even though the Stripe documentation says not to
  • Doing heavy processing before replying, which makes the provider time out and resend
  • Checking whether the event id has been seen and then writing, with no unique constraint (a race between two requests)
  • Not comparing the amount and currency against the order
  • Putting secrets or API keys in code or logs
  1. Verify the signature on the raw body with the timestamp before doing anything else
  2. The event id is a unique key, and the reservation happens in the same transaction as the order update
  3. The state machine only moves forward, and out-of-order events are skipped or sent to ask the provider
  4. The amount and currency must match before marking paid
  5. Reply 2xx quickly, with the heavy work in a queue
  6. There is a reconciliation job alongside
  7. There are tests for duplicate events, out-of-order events, forged signatures and mismatched amounts

Monitoring and reconciliation in a real system

A webhook that is correct on every point can still go wrong. For example, the endpoint may be down for longer than the provider's retry period, or the provider may not guarantee redelivery (the Omise case according to its documentation). So a reconciliation job is needed as a back-office process alongside it.

  • An hourly or daily job fetches the payment list from the provider's API, compares it with orders that have stayed pending too long, and pulls the real status to update them.
  • A report of flagged amount mismatches, and of orders that are paid but have no event in the webhook_events table.
  • Count the number of 401s per hour. A spike means someone is firing requests at you, or the secret in your system does not match the provider's (for example after a secret change).
  • Count duplicate and ignored_older to see the provider's real behavior. These numbers are normally not errors.
  • Alert when no webhook arrives at all during a period when there normally would be some.
  • Keep the server clock accurate with NTP, because the replay window depends on time.

Limitations of the example: no rate limit, no body size limit, no support for multiple signatures during secret rotation, no partial refunds, no crash-tolerant queue, and no calls to the provider's real API. Use it as a learning example, not as production-ready code.

References

  1. Stripe — Receive Stripe events in your webhook endpoint (signatures, duplicates, ordering, retries) (accessed 2026-11-21)
  2. Stripe API — Idempotent requests (accessed 2026-11-21)
  3. Omise — Webhooks (signature, retries, verifying via API) (accessed 2026-11-21)
  4. Standard Webhooks — specification (standard-webhooks/standard-webhooks) (accessed 2026-11-21)
  5. PostgreSQL — INSERT (ON CONFLICT clause) (accessed 2026-11-21)
  6. Node.js — crypto.timingSafeEqual(a, b) (accessed 2026-11-21)
  7. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer