Verify payment webhooks in Node.js: nine offline checks
A valid signature proves that the body matches the shared secret. It does not prove that an order is fully paid, that a delivery is new, or that fulfilment may run again.
For OmniWallet IPN, verify the HMAC-SHA512 signature in x-omni-sig before using payment data. The sender signs and sends the same serialized JSON body. You can verify its raw bytes, or use the exact canonical JSON procedure in the API reference. Arbitrary JSON formatting is not that procedure.
This offline lab separates signature verification, exact redelivery detection and business validation. It needs no account, network calls, API key or real payment.
1. Run the experiment locally
Download the complete Node.js lab (.mjs). No signup or package installation is required. You can inspect the same source below before running it.
Save the complete code below as ipn-raw-body-lab.mjs and run node ipn-raw-body-lab.mjs. It uses only built-in Node.js modules. The nine assertions were checked with Node.js v26.1.0; the output also prints your runtime version.
The sample secret and payment identifiers are public, synthetic fixtures. The receiver() function is a teaching model, not an HTTP server or a production payment handler.
// Offline teaching lab, NOT a production receiver or fulfilment policy.
// Run: node docs/growth/examples/ipn-raw-body-lab.mjs
// All payloads and the secret below are synthetic public fixtures.
import { createHmac, createHash, timingSafeEqual } from 'node:crypto';
import assert from 'node:assert/strict';
const secret = 'public-lab-fixture-not-a-production-secret';
const sign = raw => createHmac('sha512', secret).update(raw).digest('hex');
const rows = [];
function receiver() {
const seen = new Set(); // Demonstrates the restart limitation; never a durable inbox.
return (raw, signature) => {
if (typeof signature !== 'string' || !/^[a-f0-9]{128}$/i.test(signature)) return 'reject_signature';
const expected = Buffer.from(sign(raw), 'hex');
if (!timingSafeEqual(Buffer.from(signature, 'hex'), expected)) return 'reject_signature';
let event;
try { event = JSON.parse(raw.toString('utf8')); } catch { return 'reject_json'; }
if (!event || typeof event !== 'object' || Array.isArray(event) || !event.payment_id || !event.payment_status) return 'reject_shape';
const deliveryHash = createHash('sha256').update(raw).digest('hex');
if (seen.has(deliveryHash)) return 'exact_redelivery';
seen.add(deliveryHash);
// No order update, funds movement or fulfilment is performed by this lab.
return 'record_for_business_validation';
};
}
const receive = receiver();
const raw = Buffer.from('{"actually_paid":"1","order_id":"注文-例","payment_id":"demo-1","payment_status":"partially_paid"}');
function check(name, result, expected) { assert.equal(result, expected, name); rows.push({ name, result }); }
check('UTF-8 raw body', receive(raw, sign(raw)), 'record_for_business_validation');
check('Same bytes redelivered', receive(raw, sign(raw)), 'exact_redelivery');
const altered = Buffer.from(raw.toString().replace('"1"', '"9"'));
check('Changed amount with old signature', receive(altered, sign(raw)), 'reject_signature');
const pretty = Buffer.from(JSON.stringify(JSON.parse(raw), null, 2));
check('Reserialized JSON with old signature', receive(pretty, sign(raw)), 'reject_signature');
check('Short signature', receive(raw, 'abcd'), 'reject_signature');
check('Non-hex signature', receive(raw, 'z'.repeat(128)), 'reject_signature');
check('Updated amount, same payment/status, new valid signature', receive(altered, sign(altered)), 'record_for_business_validation');
const malformed = Buffer.from('{');
check('Signed malformed JSON', receive(malformed, sign(malformed)), 'reject_json');
check('Receiver restart loses memory deduplication', receiver()(raw, sign(raw)), 'record_for_business_validation');
console.log(JSON.stringify({ runtime: process.version, cases: rows, passed: rows.length, productionReady: false, limitation: 'Exact-byte deduplication only. Use a durable inbox and transactional business idempotency; independently validate payment/order/currency/amount and authoritative status. A valid signature is not proof that an order may be fulfilled.' }, null, 2));
2. Compare the nine expected results
A successful run prints passed: 9 and productionReady: false. These result labels belong to this experiment; they are not OmniWallet API status values.
| Case | Expected lab result |
|---|---|
| UTF-8 raw body | record_for_business_validation |
| Same bytes redelivered | exact_redelivery |
| Changed amount with old signature | reject_signature |
| Reserialized JSON with old signature | reject_signature |
| Short signature | reject_signature |
| Non-hex signature | reject_signature |
| Updated amount, same payment/status, new valid signature | record_for_business_validation |
| Signed malformed JSON | reject_json |
| Receiver restart loses memory deduplication | record_for_business_validation |
3. Verify bytes before parsing or formatting JSON
Whitespace, key order and character encoding affect the signed bytes. The experiment changes compact JSON into pretty-printed JSON, while keeping the original signature. The fields still mean the same thing, but the signature check fails because the bytes changed.
Capture the raw request body before middleware transforms it. Validate the signature encoding and length, calculate HMAC-SHA512 with your actual IPN secret, and compare equal-length buffers. The lab checks for 128 hexadecimal characters before calling timingSafeEqual; Node.js requires the compared buffers to have the same byte length.
Only after verification does the lab parse JSON and perform its minimal shape check. That check is intentionally incomplete: a real integration must validate the documented schema and business fields too. A signed malformed JSON body is rejected separately from an invalid signature.
4. Separate redelivery from a new payment update
The in-memory Set recognizes identical body bytes using a hash. Restarting the receiver loses that memory, as the final case demonstrates. Even a valid signature does not establish freshness or stop replay by itself.
Do not discard every later message with the same payment_id and payment_status. In the seventh case, a partially paid payment has a changed actually_paid amount and a new valid signature, while its payment ID and status remain the same. That update still needs business validation.
Use a durable inbox and transactional order processing. Make fulfilment idempotent independently of delivery deduplication. Match the payment to your stored order, currency, network, expected amount and authoritative payment state before deciding what to do. The experiment deliberately performs no order update or fulfilment.
5. HTTP 200 is an acknowledgement, not proof of fulfilment
Your endpoint returns 200, then the process stops before saving the payment. The sender has recorded a successful delivery, but your order still looks unpaid. The missing step is durable acceptance before acknowledgement.

For example, fictional order ORDER-2052 expects 49.00 USDT. First verify the raw body signature and validate the payload shape. Save the accepted delivery and its processing state in a durable inbox transaction. Only acknowledge after the commit succeeds, or after confirming that the exact delivery was already stored. Keep customer data and secrets out of public logs.
A separate worker can then match the payment to the stored order, network, currency, amount and current authoritative state. Record the order decision with an independent business idempotency key. Mark the inbox item processed only when that work is safely recorded. If fulfilment calls another service, such as a hosting control panel, pass a stable operation key and reconcile uncertain results; a database transaction alone cannot make that external action atomic.
| Failure point | Receiver decision | Recovery |
|---|---|---|
| Signature does not match | Reject; do not enqueue, credit or fulfil. | Check the endpoint secret and unchanged body bytes. Never accept an invalid signature to silence retries. |
| Inbox write or commit fails | Do not return a success acknowledgement. | Return an appropriate failure response and alert your team. Sender retries are bounded, so reconcile later if the retry budget runs out. |
| Process stops after commit, before acknowledgement | A later exact redelivery can acknowledge the stored record. | The durable worker resumes pending work. Do not treat an already stored delivery as a reason to run fulfilment again. |
| HTTP 200 returned, then fulfilment fails | The inbox remains pending or failed internally. | Retry your worker or investigate from the durable record. Do not depend on the sender to resend an acknowledged notification. |
In OmniWallet's current sender implementation, any 2xx response records successful delivery; a response outside that range is eligible for bounded retries. A redirect is not followed. This describes transport delivery, not a promise of exactly-once business processing. Test a database failure, a receiver restart, a duplicate and a downstream timeout before connecting automatic fulfilment.
The nine-check lab above verifies signatures and exact-body redelivery only. It does not implement this inbox, a database transaction or a fulfilment worker. For a real inbox, use your database's transaction guarantees and your HTTP server's response lifecycle: SQLite transaction control and Node.js response.end().
6. An older payment notification arrives last. Should the order go backwards?
A webhook's arrival time is not the payment's business state. In a fictional order ORDER-2056 for 30 USDT, a worker has already validated the complete receipt and recorded fulfilment. Another worker then processes an earlier, validly signed partial-payment notification. Blindly copying that older payload into the order could reopen the order or request money the customer has already paid.

- Keep the evidence, not just the latest arrival. Verify and durably accept each relevant delivery using the earlier inbox checklist. Keep its payload reference and processing outcome. An exact duplicate and a distinct, older update are different cases.
- Reconcile before changing the order. Read the current payment through the authenticated API or have an authorized operator inspect it. Match the stored order, network, token, expected amount and payment state. If that read fails or contradicts earlier evidence, leave the case pending for investigation; do not automatically ask for another payment.
- Protect the decision from concurrent workers. Serialize decisions for the same order, or use your database's documented conditional-write and transaction controls. A second worker must recheck the stored decision before changing it. An API read alone does not make a later local write atomic.
- Check the fulfilment ledger separately. Repeated or reordered notifications must not run the same renewal, credit or shipment again. Use a stable business operation key; reconcile uncertain external results instead of assuming a timeout means nothing happened.
| Evidence received | Safe next step |
|---|---|
| Earlier partial snapshot after a recorded fulfilment | Retain and investigate the snapshot against current payment evidence; do not reopen the order merely because this delivery arrived last. |
| A new review or conflicting current state | Route to the authorized exception process. An earlier fulfilment is not permission to ignore a genuine later risk, refund or accounting event. |
| Another worker has already claimed the same service action | Read the recorded operation result. Resume or reconcile that operation rather than creating a second action. |
Do not invent a numeric ranking for payment statuses or assume that a delivery timestamp is a guaranteed sequence number. Use only ordering or version fields whose meaning is explicitly documented for your API. The nine-check lab does not implement ordered delivery, current-state reconciliation or concurrent database workers; test this scenario separately in your test environment. See the payment API reference for actual fields and SQLite isolation documentation for the limits of concurrent transactions.
7. Rehearse a real receiver before enabling fulfilment
Nine passing offline assertions are a starting point, not a launch approval. They do not exercise your HTTP endpoint, database, worker or supplier. Run the following rehearsal against your separate test environment, using fictional order RECEIVER-2058 and synthetic fixtures. This is a test plan for your integration, not additional tests implemented by the downloadable lab.

| Test you arrange | Observe and record | Acceptance condition |
|---|---|---|
| Send an altered body with its old signature | HTTP response, inbox entry count and order-operation count. | No accepted inbox item, credit or fulfilment for the invalid signature. |
| Make the inbox transaction fail | Response status and whether any success acknowledgement escaped before commit. | No success acknowledgement for an unstored delivery. The failure remains visible to operations. |
| Stop the receiver after commit, before acknowledgement; then replay the exact fixture | Durable inbox identity, pending work and business operation reference after restart. | The stored work can resume; the replay does not create a second business action. |
| Process an earlier partial snapshot after a newer accepted payment decision | Current authoritative payment check and the recorded order decision. | The last arrival alone does not reopen a fulfilled order or prompt another full payment. Conflicting evidence goes to review. |
| Let two workers claim the same service action | Both claim results, stable business key and downstream operation result. | One intended action is recorded. A downstream timeout remains uncertain until reconciled, not a reason to issue again blindly. |
For each row, keep a small review record: test date, environment, synthetic order reference, expected result, actual result, redacted evidence location and reviewer. A failed or untested row stays open. Do not put secrets, customer payloads, voucher codes or wallet credentials in screenshots or public issue trackers.
Test under HTTPS with a bounded request body and the actual documented signature contract. Use only public fixtures in shared examples and test-only credentials in your own test service. Do not deliberately fail a production database or replay live customer deliveries to complete this worksheet. If a test fails, disable automatic fulfilment in your integration until the issue is understood; do not disable signature verification.
Return to durable acceptance before acknowledgement and out-of-order reconciliation for the reasoning behind these checks. A local transaction does not make an external service action atomic, and this worksheet is not an exactly-once delivery guarantee. The Node.js response lifecycle and your database's transaction guarantees determine what your implementation can prove.
For the complete merchant workflow, see accepting USDT payments. For exact API fields, signature rules and supported payment states, use the API reference and integration guide.
Sources and authorship
Published by the OmniWallet team. The acknowledgement and failure-recovery section was added on 3 November 2026; the out-of-order reconciliation example was added on 6 November 2026. The production rehearsal worksheet was expanded on 8 November 2026. AI assisted with drafting and editing; the executable lab and its nine assertions were checked locally. The Japanese version of the original experiment is available on our official Zenn account.
Node.js references: createHmac and timingSafeEqual.