A customer pays for an order, closes the browser and never reaches the confirmation page. Your backend still needs to recognise the payment and release the order. A webhook can deliver that update, but the endpoint must also cope with repeated notifications, invalid requests and database failures.
The difficult part is deciding which request to trust and which business action it is allowed to trigger. A handler that works during a successful checkout can still create duplicate jobs or lose a payment update when the process restarts.
This article walks through signature verification in Node.js, Express middleware ordering and a PostgreSQL transaction design for processing successful payments. It focuses on orders paid in full through a single payment. Partial payments, multiple captures and refund accounting need their own state transitions.
Start with the payment state your application owns
Create the local order before opening checkout. Store the expected amount, currency, merchant account and provider order reference on the server. Derive the amount from the catalogue or agreed invoice, rather than accepting a browser-supplied total as authoritative.
Keep the payment attempt separate from the order. A customer can try more than once before a payment succeeds, so an unsuccessful attempt should not permanently close an otherwise payable order. A later failure notification must also leave an already paid order intact.
The browser's return page should ask the backend for the order's current status. It should not mark an order paid because a URL contains a success parameter. Use verified server-side payment information to make that decision, and provide a pending state while confirmation is unresolved.
Verify the signature against the original bytes
For an Indian application, Cashfree Payments is a practical starting point when integrating a payment gateway for web and mobile applications. The signature example here follows its documented format: HMAC-SHA256 over the timestamp followed by the raw request body, encoded as Base64. Other providers can use different signing schemes, headers and keys.
Save the following as webhook-signature.mjs. It uses Node's built-in cryptography module and compares equal-length digest buffers with timingSafeEqual. The supplied signature is also checked for canonical Base64 encoding before comparison.
import {
createHmac, createSecretKey, timingSafeEqual
} from 'node:crypto';
export function verifySignature({
rawBody, timestamp, signature, secret
}) {
if (!Buffer.isBuffer(rawBody) ||
typeof timestamp !== 'string' || !timestamp ||
typeof signature !== 'string' ||
typeof secret !== 'string' || !secret) {
return false;
}
const supplied = Buffer.from(signature, 'base64');
if (supplied.length !== 32 ||
supplied.toString('base64') !== signature) {
return false;
}
const key = createSecretKey(Buffer.from(secret, 'utf8'));
const expected = createHmac('sha256', key)
.update(timestamp, 'utf8')
.update(rawBody)
.digest();
return timingSafeEqual(expected, supplied);
}
Do not parse the body and then call JSON.stringify to recreate it for verification. Whitespace, numeric formatting and escaping can change even when the resulting object looks equivalent. The signature needs the bytes that were received.
Signature verification establishes authenticity for the signed content; it does not prevent a valid request from being replayed. Persistent duplicate detection is still needed. If you add timestamp-age checks, align them with the provider's documented retry behaviour rather than choosing a window that rejects legitimate redeliveries.
Mount the webhook route before the general JSON parser
In Express, middleware order determines what reaches the handler. If a general JSON parser has already consumed the body, a later raw parser cannot recover the original request bytes. Mount the webhook route first, using a parser scoped to that route.
The following is route wiring for an Express application. processVerifiedEvent is the application service described in the transaction section below, not a method supplied by the payment provider. Keep the secret and merchant-account mapping in server configuration.
import express from 'express';
import { verifySignature } from './webhook-signature.mjs';
import { processVerifiedEvent } from './payment-service.mjs';
const app = express();
const secret = process.env.PAYMENT_CLIENT_SECRET;
const merchantAccount = process.env.PAYMENT_MERCHANT_ACCOUNT;
if (!secret || !merchantAccount) {
throw new Error('Missing payment server configuration');
}
app.post('/webhooks/payments', express.raw({
type: 'application/json', limit: '256kb', inflate: false
}), async (req, res) => {
if (!Buffer.isBuffer(req.body)) return res.sendStatus(415);
const valid = verifySignature({
rawBody: req.body,
timestamp: req.get('x-webhook-timestamp'),
signature: req.get('x-webhook-signature'),
secret
});
if (!valid) return res.sendStatus(401);
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.sendStatus(400);
}
try {
await processVerifiedEvent(event, { merchantAccount });
return res.sendStatus(200);
} catch {
return res.sendStatus(503);
}
});
app.use(express.json());
The body limit is an example configuration; size it for the events your application accepts. Disabling inflation rejects compressed bodies on this route, avoiding a mismatch between received and decompressed bytes. Add structured error logging around processing failures without recording secrets or complete customer payloads.
Map provider events to a small internal representation
After verification and parsing, validate the event type and schema. Map the provider's fields into an internal structure containing the provider name, merchant account, payment ID, order ID, amount in minor units, currency and status. Take the merchant-account scope from trusted server configuration.
Keep external identifiers as text where possible. If a provider sends a large numeric identifier, ensure the JSON parser preserves it without exceeding JavaScript's safe integer range. Converting an already rounded number to a string does not restore the original identifier.
Amounts need an explicit conversion policy as well. Store INR values in paise, using validated decimal conversion rather than an unchecked floating-point multiplication. Other currencies may use different minor-unit precision, so avoid making two decimal places a universal assumption.
For this success-processing path, accept only the provider's confirmed successful-payment event. Keep failed attempts and pending statuses in their appropriate records, without allowing them to downgrade an order that is already paid. Refunds and disputes should have separate handlers and accounting rules.
Put duplicate detection in the database
A JavaScript Set can remember an event during one process's lifetime. It cannot coordinate several application instances or retain that knowledge after a restart. Use durable records and database constraints for the business actions that must survive those situations.
The following PostgreSQL tables illustrate a successful-payment receipt and a fulfilment outbox. They supplement an existing orders table; the complete application schema also needs its usual account relationships and review records.
CREATE TABLE payment_receipts (
provider TEXT NOT NULL,
merchant_account TEXT NOT NULL,
payment_id TEXT NOT NULL,
order_id TEXT NOT NULL,
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL,
PRIMARY KEY (provider, merchant_account, payment_id)
);
CREATE TABLE fulfilment_outbox (
job_id TEXT PRIMARY KEY,
merchant_account TEXT NOT NULL,
order_id TEXT NOT NULL,
payload JSONB NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING'
);
The payment key identifies a successful payment within its provider and account scope. The fulfilment job needs a different key, such as a stable encoding of fulfil, merchant account and order ID. This separates repeating the same payment notification from deciding whether an order can be fulfilled again.
Commit the receipt and fulfilment decision together
The transaction below is an application-level outline, not a standalone SQL script. Implement each query with bound parameters and keep the complete sequence on one database connection. A transaction opened on one pooled connection does not cover queries sent through another.
-
Begin the transaction and select the matching order using
FOR UPDATE, scoped to the trusted merchant account. Confirm that it exists and is eligible for the payment being processed. -
Compare the verified payment's order reference, amount and currency with the stored expectations. Route mismatches into a durable review path instead of releasing the order.
-
Insert the successful-payment receipt using
ON CONFLICT DO NOTHING RETURNING payment_id. If it already exists, compare its stored order, amount and currency before treating the request as a harmless duplicate. -
If another successful payment already paid the order, retain the additional receipt and create a review record. Do not create a second fulfilment job or automatically issue a refund from this handler.
-
For an eligible unpaid order, update its payment state and insert the fulfilment job with its unique business key. Commit those changes together, then acknowledge the request.
The row lock makes concurrent handlers for the same existing order take turns. The unique keys provide another boundary against repeated receipts and jobs. Handle transaction failures explicitly, including deadlock or serialization errors where applicable, by retrying the whole transaction under a bounded policy.
Avoid network calls while holding the transaction open. Sending an email or contacting a shipping service inside the transaction increases its duration and cannot be undone by a database rollback. Record the intended action and let a worker perform it afterwards.
Make the fulfilment worker safe to retry
An outbox closes the gap between marking an order paid and recording the work needed to fulfil it. If the transaction rolls back, neither change remains. If it commits, the worker has a durable job to pick up.
The worker can still crash after contacting another system but before recording completion. Give downstream operations a stable idempotency key where supported, and enforce an equivalent business constraint when granting access or creating a shipment. A unique outbox row does not make every external action execute exactly once.
Track pending, in-progress and completed work, with a recovery policy for abandoned claims. Keep uncertain downstream outcomes distinguishable from confirmed failures. Repeating an operation blindly after a timeout can create a duplicate even when the webhook handler itself is correct.
Acknowledge only after durable handling
A valid signature alone is not enough reason to return success. In the direct-processing design above, acknowledge after committing the receipt, order decision and outbox work, or a durable review record. If you use an inbox or queue instead, acknowledge after durable acceptance and process it with a recoverable worker.
Known duplicates can receive HTTP 200 after their stored result is checked. A temporary storage failure before durable acceptance should receive a failure response, allowing the provider's documented retry mechanism to operate. Confirm that policy for the integration; a response code by itself does not guarantee redelivery.
Do not keep the HTTP request open while waiting for a person to investigate a mismatch. Persist the review case, acknowledge durable handling and alert the responsible team. A separate reconciliation process should also find orders whose final payment outcome remains unresolved.
Test changes to the signed payload
Use the built-in Node test runner to check the signature function. Save this example as webhook-signature.test.mjs and run node --test webhook-signature.test.mjs.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { verifySignature } from './webhook-signature.mjs';
test('accept original bytes and reject a changed body', () => {
const secret = 'local-test-secret';
const timestamp = '1700000000000';
const rawBody = Buffer.from('{"amount":499.00}');
const signature = createHmac('sha256', secret)
.update(timestamp).update(rawBody).digest('base64');
const input = { rawBody, timestamp, signature, secret };
assert.equal(verifySignature(input), true);
const changed = Buffer.from(JSON.stringify(
JSON.parse(rawBody.toString('utf8'))
));
assert.equal(verifySignature({
...input, rawBody: changed
}), false);
});
Then test the complete application with repeated deliveries, two concurrent handlers, a restart between receipt and processing, and a worker crash after an external action. Check database rows and fulfilment outcomes, not only the HTTP response. The expected result is one fulfilment decision for an order, with additional or inconsistent payments retained for review.
Keep the final checks close to the code: verify original bytes, validate against the local order, commit the decision atomically and make downstream work safe to retry. These boundaries let a payment notification be delivered again without turning the same purchase into another shipment or another access grant.
Help Others Find This
❤️ Liked this article?
If it saved you time, consider buying me a coffee to support future improvements.