Securing crypto payment webhooks: signatures, replays and retries

A practical guide to securing crypto payment webhooks with RSA-SHA256, exact signed bytes, replay protection, durable idempotency and correct retry handling.

Published , updated

Securing crypto payment webhooks illustrated by a laptop, padlock and neatly looped cable on a calm operations desk

Securing crypto payment webhooks means verifying the signed request before trusting it, binding the payment to the stored order and recording its effects exactly once. With Suawave, verify x-ca-signature using RSA-SHA256, preserve the original signed bytes and deduplicate event UUIDs durably. Return HTTP 200 with *ok* only after accepting the event into durable processing.

A webhook handler writes your payment records. It needs to behave correctly when a genuine request arrives twice, when two deposits arrive together and when the process stops after a database commit. A signature check handles only one part of that job.

1. Preserve the bytes before checking the signature

Suawave public callbacks use a base64 RSA-SHA256 signature with PKCS#1 v1.5 padding. Fetch the PKIX PUBLIC KEY PEM from GET /pubkey/ over HTTPS. Validate that it is an RSA key of at least 2048 bits, then cache it. The public verifier doesn’t need a shared HMAC secret or access to the signing private key.

The signed message depends on the callback transport:

Callback transport Signed message Common integration mistake
Default GET Full external URL with the original query order Sorting or re-encoding parameters
Form POST with post=1 Exact raw body Parsing and rebuilding the form
JSON POST with json=1 Exact raw body Serializing parsed JSON again

json=1 takes precedence over post=1. Those options are fixed by the first create call for the ticker and callback pair. Repeating create with different options doesn’t reconfigure an existing order. Choose the transport before creating checkout addresses.

For GET behind a proxy, combine a configured trusted external origin with the original encoded request target. Don’t trust a caller-supplied Host or forwarded-host header to select the origin. For POST, capture the raw body before JSON or form middleware transforms it. The signature verification documentation gives framework-specific input sources.

A short Node.js verifier

This function is the JavaScript example from docs/site/examples/js/verify.js. It is a verifier, not a complete HTTP handler. Load and validate the public key separately; pass the original request target and a Buffer containing the untouched POST body.

const crypto = require('crypto');

function verifyCallback({ method, requestUri, rawBody, signature }, publicKeyPem, trustedOrigin) {
  let signed;
  if (method === 'GET') {
    signed = Buffer.from(trustedOrigin + requestUri, 'utf8');
  } else if (method === 'POST') {
    if (!Buffer.isBuffer(rawBody) || rawBody.length > 65536) return false;
    signed = rawBody;
  } else {
    return false;
  }
  if (!signature || !/^[A-Za-z0-9+/]+={0,2}$/.test(signature)) return false;
  const verifier = crypto.createVerify('RSA-SHA256');
  verifier.update(signed);
  return verifier.verify(publicKeyPem, signature, 'base64');
}

module.exports = { verifyCallback };

In Express, use req.originalUrl for requestUri and capture POST input with express.raw before parsing. Apply a request size limit at the HTTP boundary as well. Catch malformed-key and verification exceptions there, and treat them as failure. A failed verification must produce HTTP 401 and no order changes.

For other languages and more detail on proxy handling, see verifying callback signatures with RSA-SHA256.

Securing crypto payment webhooks by verifying the original GET request target or raw POST body with RSA-SHA256; no timestamp is sent

2. Bind the verified payment to the order

After verification, parse the request and find the stored order. Compare its nonce and order reference, then check address_in and coin. A trc20/usdt order expects trc20_usdt in the callback’s coin field. Don’t infer the ticker from the amount or from a customer-provided label.

POST signs the body, while your custom callback query parameters remain in the URL. The signature doesn’t make an arbitrary order reference in that query trustworthy. Matching the verified deposit address and coin against the stored order prevents a genuine body from being assigned to an unrelated order.

Generate a fresh unguessable nonce for each order’s callback URL and retain the complete original URL on the server. It is also the capability used to retrieve public logs, so exclude it from analytics and customer-visible links. A nonce helps bind an order; it doesn’t make a captured signed event fresh.

Check pending before applying money. A genuine pending event still isn’t permission to fulfill. A confirmed event still needs an amount check. The guide to crypto payment underpayments covers gross amounts, net amounts and separate deposits.

3. Prevent replay with durable idempotency

Suawave public callbacks have no timestamp and no key ID. Don’t invent a five-minute timestamp check based on a header the gateway doesn’t send. A captured request can remain cryptographically valid. Your protection is to ensure that processing it again has no additional effect.

Persist each processed event UUID in the same database transaction as its payment record and order transition. Put a unique constraint on the UUID. A preliminary “does it exist?” query without that constraint can race when two requests arrive together.

A useful transaction sequence is:

  1. Insert the verified event UUID, treating a uniqueness conflict as an already accepted event.
  2. Lock the matching order and record this deposit’s confirmed amount when applicable.
  3. Apply only forward-moving order transitions and create any fulfillment job durably.
  4. Commit before sending the acknowledgement.

If the transaction fails, don’t acknowledge success. The retry can attempt the work again. If the transaction commits but the connection drops before the response arrives, the retry finds the saved UUID and acknowledges it without repeating the order change.

Is UUID deduplication enough to prevent duplicate shipments?

It prevents one event from being applied twice. Two genuine payments have different events, so fulfillment also needs an order-level guard. Create one durable shipment or entitlement action per order, with a unique database key. Workers consuming that action should preserve the same rule when talking to external systems.

Pending and confirmed callbacks for one deposit have different UUIDs. Keep a deposit-level state as well as event records, and never let a late pending event undo confirmation. Crypto payment finality explains what the two callback types establish.

Securing crypto payment webhooks: repeated deliveries share one UUID and one committed order action before HTTP 200 acknowledgement

4. Acknowledge correctly and expect retries

Suawave expects HTTP 200 with the plain body *ok* within 30 seconds. Plain ok is accepted too, without regard to letter case. Use the documented *ok* response consistently so framework defaults don’t turn an accepted event into another retry.

HTTP 204, a JSON success object or a redirect isn’t that acknowledgement. Redirects aren’t followed. Configure the final HTTPS callback path directly, including any path spelling your application requires.

There are eight delivery attempts. After the initial send, retry delays are 30 seconds, 2 minutes, 10 minutes, 30 minutes, 2 hours, 6 hours and 24 hours, each with up to 10 percent added jitter. The UUID remains the same. These are successive retry delays, not promises that delivery will occur at exact wall-clock times.

Keep slow work out of the request. Writing the event and a fulfillment job durably lets you acknowledge while packing, email delivery or entitlement work runs separately. An in-memory queue alone doesn’t establish durable acceptance: the process could exit after acknowledging and lose the job.

The callback guide documents acknowledgement, ordering and retries. Treat an already processed valid event as a normal success so the gateway can stop retrying it.

5. Handle key rotation without accepting arbitrary keys

Cache the key from the configured Suawave endpoint. When verification fails, refresh that key once and verify again before rejecting the request. Rotation switches retries of older events to the new signing key too; the event UUID still supplies the identity for deduplication.

Don’t fetch a verification key from a URL supplied by the callback. Don’t repeatedly refresh on the same request. Check the refreshed key’s type and size, and reject a request that still fails verification. If the key endpoint is unavailable, keep the order unchanged and let delivery retry rather than accepting unverified data.

Separate operational records for invalid signatures from valid events that couldn’t be committed. One suggests bad signed bytes or an untrusted request; the other suggests a processing outage. Avoid logging complete secret-bearing callback URLs while diagnosing either case.

6. Reconcile missed callbacks and check failure paths

Use GET /{ticker}/logs/ with the original callback URL to investigate delivery gaps. A sent result means forwarding confirmed but its confirmed callback hasn’t been acknowledged, including when retries are exhausted. done means the confirmed callback was acknowledged. Logs are a reconciliation fallback; your normal acceptance path remains verified callbacks.

Before release, send the same genuine signed event twice through your handler and verify that only one durable action exists. Change one signed byte and require rejection. Exercise a database failure before commit and a lost acknowledgement after commit. Deliver a confirmed event before its pending event and check that the order stays paid.

Finally, check the amount and network binding with two separate orders. A valid signature for one deposit mustn’t pay the other order. The USDT integration walkthrough shows how to store those order details, while USDT TRC20 vs BEP20 explains why the network belongs beside the amount in every checkout record.