silvercloudStudio home ↗
EN

SILVERCLOUD / Technical article

Payment confirmation you can trust: a server-side checklist for apps and websites

8 min read

A customer taps Pay, sees a green tick and closes the app. Was the order paid? Probably, and with money that is not enough. The tick only shows that one device reached the end of a flow. Whether money moved is known to the payment provider, and your server must learn it from the provider, through a channel nobody else can fake.

This checklist covers payment states, server-side confirmation, safe retries, refunds, reconciliation and testing, for cards, e-wallets and QR bank transfers alike.

A success screen is not a confirmation

After paying, the customer returns to your site or app, often with parameters such as ?status=success&order=1042. Treating that as proof fails in three ways:

  • Anyone can edit it. Changing failed to success in a browser takes seconds.
  • It may never load. The tab closes, the signal drops or the banking app never switches back, and your server never hears about a successful payment.
  • It can arrive before the money. Some methods, bank transfers in particular, stay pending after the customer has finished.

The return page should show "Confirming your payment" and ask your own server, which trusts only verified sources. The client never decides an order is paid.

The states of a payment

Model the payment explicitly, not as a single paid flag:

  • Created: registered with the provider, not yet paid.
  • Pending: the customer has acted or a transfer is under way; the result is not final.
  • Succeeded: the provider confirms the funds.
  • Failed: declined, canceled or rejected.
  • Expired: the payment window closed without a result.
  • Partially refunded and refunded: money returned after success, in part or in full.

Cards can add an authorized-but-not-captured state and, later, disputes. Write the allowed transitions in code: created may become pending; created or pending may become succeeded, failed or expired; succeeded may become partially refunded or refunded, and a partially refunded payment may be refunded further; nothing returns to created or pending. Any other change is a bug or a case for review.

Confirm on the server, from a source you can verify

Two sources are trustworthy, and solid integrations use both.

Signed webhooks. The provider calls your endpoint when something happens, and most providers sign each request with a shared secret: typically an HMAC-SHA256 of the raw body, often with a timestamp. Your handler should:

  1. Read the raw body exactly as received. Parsing and re-serializing JSON can change whitespace, escaping or key order, and the signature stops matching.
  2. Compute the HMAC and compare it with the header in constant time. An ordinary string comparison stops at the first differing character, and that timing can leak information about the expected value.
  3. Reject timestamps outside a short window, often five minutes, so a captured request cannot be replayed later; a replay inside the window is caught by the event-ID check.
  4. Check amount, currency and order reference against the order you created. A valid signature proves who sent the message, not that the right amount was paid for the right order. Store amounts as integers in the smallest currency unit, never as floating point.

The provider's API. Your server looks up the payment by ID with your secret key. This covers late or lost webhooks; some teams treat every webhook only as a signal to fetch the current state.

Keys and webhook secrets stay on the server, outside the app and the repository, and can be rotated without downtime.

Idempotency: the same event twice changes nothing

Most providers deliver webhooks at least once: if your endpoint times out or returns an error, the event comes again, sometimes repeatedly. Duplicates are normal, so processing must be idempotent.

  • Deduplicate by event ID. Store processed event IDs under a unique constraint, so a repeated delivery changes nothing.
  • One transaction, one update. Record the event ID and change the order in the same database transaction; a failure rolls back both, and the retry starts clean. Make the update conditional (WHERE status = 'pending'), so a webhook and an API check arriving together cannot both fulfill the order.
  • Idempotency keys for new payments and refunds. If the provider supports them, derive the key from your own attempt ID, so a retry after a timeout returns the original result instead of charging twice. If not, save your own record with a unique reference first and look it up before retrying.
  • Out-of-order events. Delivery order is generally not guaranteed; a success event can arrive after a refund event. Apply your transition map, not the latest event, and fetch the current state when unsure.
  • Backoff. Retry timeouts, connection errors, 429 and 5xx responses with exponential backoff, jitter and a cap on attempts. Do not retry validation errors.
  • A timeout means unknown, not failed. The charge may have gone through; resolve it by querying.
  • Scheduled expiry. A job finds payments pending past their window, checks with the provider, and only then marks them expired. A success after expiry, which happens with bank transfers, goes to review or refund under a rule agreed in advance.

Answer webhooks quickly: store, commit, return 2xx, and queue slow work like emails and fulfillment. Slow handlers cause timeouts, and timeouts cause duplicates.

What it looks like in code

A minimal handler in TypeScript for Node.js and PostgreSQL. Header names, signature encoding and the signed string vary by provider; the shape does not.

TypeScript
import { createHmac, timingSafeEqual } from "node:crypto";
import { Pool } from "pg";

const pool = new Pool(); // reads the PG* environment variables
const SECRET = process.env.PAYMENT_WEBHOOK_SECRET!; // server-side only, never in the app

export async function handlePaymentWebhook(req: Request): Promise<Response> {
  const raw = Buffer.from(await req.arrayBuffer()); // the exact bytes, before any JSON parsing
  const timestamp = req.headers.get("x-signature-timestamp") ?? "";
  const received = Buffer.from(req.headers.get("x-signature") ?? "", "hex");
  const expected = createHmac("sha256", SECRET).update(`${timestamp}.`).update(raw).digest();
  const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300; // Unix seconds, 5 minutes
  if (!fresh || received.length !== expected.length || !timingSafeEqual(received, expected)) {
    return new Response("invalid signature", { status: 400 });
  }
  const event = JSON.parse(raw.toString("utf8"));
  const db = await pool.connect();
  try {
    await db.query("BEGIN");
    // event_id is the primary key: a repeated delivery inserts nothing.
    const inserted = await db.query(
      "INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING", [event.id]);
    if (inserted.rowCount === 1 && event.type === "payment.succeeded") {
      // Only pending -> paid, and only if amount and currency match the order.
      const paid = await db.query(
        `UPDATE orders SET status = 'paid', paid_at = now()
          WHERE id = $1 AND status = 'pending' AND amount = $2 AND currency = $3`,
        [event.data.order_id, event.data.amount, event.data.currency]);
      if (paid.rowCount === 0) await db.query("INSERT INTO payment_review (event_id) VALUES ($1)", [event.id]);
    }
    await db.query("COMMIT");
    return new Response("ok");
  } catch {
    await db.query("ROLLBACK");
    return new Response("retry later", { status: 500 }); // the provider retries
  } finally {
    db.release();
  }
}

If no pending order matches (already paid, expired, or a different amount), the event goes to a review table instead of disappearing.

Refunds, reconciliation and the audit trail

Refunds are separate records linked to the payment, with their own states: a refund can also be pending or fail. Partial refunds must never exceed the captured amount in total. Send refund requests with idempotency keys, and change the order status only when the provider confirms.

Daily reconciliation catches what everything else misses. Load the provider's transaction or settlement report for the previous day, match each line to your records by provider transaction ID, and compare amount, currency and status. Typical mismatches:

  • Paid at the provider, pending in your system: a lost webhook, and a customer who paid and is still waiting.
  • Paid in your system, unknown to the provider: a bug or abuse, the most urgent kind.
  • Different amount or status: an unrecorded partial refund, or gross amounts confused with fees and net settlement.

Mismatches go to a discrepancy queue with an owner and a resolution note; nothing is fixed silently. Mind the report's cut-off time: a payment near midnight can fall on different days on each side.

Audit trail. Keep every raw webhook with its headers and verification result, so you can replay it, plus an append-only history of status changes: from, to, when, and which event, job or person caused it. Never log secrets or full card numbers; with a hosted checkout or embedded payment fields, card numbers never reach your servers.

Alerts fire on spikes in signature failures, processing errors, payments stuck in pending, failed refunds, reconciliation mismatches and drops in the success rate.

Test the failures, not only the happy path

Use the provider's sandbox or test mode with test credentials, then:

  • Replay webhooks. Save real sandbox events as fixtures; send one twice, reverse the order, change one byte of the body, use an old timestamp.
  • Inject faults. Stop the process after the commit but before the 2xx response; the provider resends, and nothing may happen twice. Take the database away for a minute. Add latency to provider calls until your timeouts fire.
  • Misuse the client. Double-tap Pay, close the browser before the redirect, open the return URL with forged parameters.

Go-live checklist

  1. Paid status comes only from a verified webhook or a server-side API query.
  2. Signatures are checked over the raw body in constant time; stale timestamps are rejected.
  3. Amount, currency and order reference are matched against the order.
  4. Event IDs are unique; duplicates return 2xx with no side effects.
  5. The event record and the status change commit in one transaction, with a conditional update.
  6. Creating payments and refunds uses idempotency keys or a lookup by your own reference.
  7. Transitions are defined in code; late events cannot move an order backwards.
  8. The webhook answers within the provider's timeout; slow work is queued.
  9. Outgoing calls have timeouts and capped retries with backoff and jitter.
  10. Pending payments expire on a schedule after a status check; late successes have a defined path.
  11. Partial refunds cannot exceed the captured amount.
  12. Reconciliation runs daily, and every mismatch has an owner.
  13. Raw webhooks and status history are kept; logs hold no secrets or full card numbers.
  14. Alerts cover signature failures, processing errors, stuck payments and reconciliation mismatches.

silvercloud is an outsourced development team. For partner businesses, we build this layer into apps and websites, from checkout and webhooks to refunds and reconciliation, and build payment gateway systems to their requirements, then hand the work over for their teams to run. If you are planning a payment integration, send us a brief at silvercloud.city.

Send a payment integration brief