Reliable payment processing depends on more than accepting a webhook request. This checklist explains how to validate payment events, reject forged or stale messages, prevent duplicate fulfillment with idempotency, handle retries and out-of-order delivery, and reconcile provider records with your internal transaction state.
Overview
Payment webhooks are notifications, not automatically trusted instructions. A gateway may send the same event more than once, deliver events after a delay, retry a request after a timeout, or deliver related events in an unexpected order. Network failures can also leave the provider and your application with different views of the same payment.
A resilient webhook handler therefore performs several distinct checks:
- Authenticity: Was the message signed by the expected payment provider, and was it received within an acceptable time window?
- Integrity: Has the payload changed since it was signed, and does it conform to the expected event schema?
- Uniqueness: Has this event already been processed, or is it a legitimate retry?
- Business validity: Is the event consistent with the order, invoice, customer, and amount stored by your system?
- State safety: Can this event move the transaction to a new state without incorrectly reversing or duplicating a previous decision?
Keep these concerns separate in both code and monitoring. A valid signature does not prove that the amount is correct, and a correctly shaped payload does not prove that the event should be allowed to fulfill an order. Teams building a broader validation layer can also use the API Contract Validation Playbook to apply schema and compatibility checks consistently across payment integrations.
What to track
1. Event identity and delivery metadata
Store the provider event ID as a durable, uniquely indexed value. Also record the event type, provider account or environment, delivery timestamp, received timestamp, signature result, schema version when available, and processing outcome. Do not rely only on a local request ID: it identifies an HTTP attempt, not necessarily the underlying payment event.
A useful event record includes:
- Provider event ID and related payment or charge ID
- Event type and payload version
- First-seen and last-seen timestamps
- Attempt count and retry reason, if supplied
- Signature verification result
- Schema validation result
- Idempotency decision: processed, duplicate, deferred, rejected, or quarantined
- Internal order ID and current transaction state
- Redacted error details and operator actions
Retain enough evidence to explain a decision without storing unnecessary payment or personal data. The Validation Audit Trails guide provides a useful framework for separating decision evidence from sensitive payload content.
2. Signature and timestamp validation
Use the provider's official signature construction and verification method. Common patterns include an HMAC over a timestamp and raw request body, but the exact header names, delimiter, encoding, digest algorithm, and secret-handling requirements vary. Verify the signature against the untouched raw body before parsing or normalizing JSON.
A provider-neutral implementation pattern looks like this:
rawBody = readRequestBodyExactlyOnce()
received = parseProviderSignatureHeader(request.headers)
if received.timestamp is missing:
reject("missing signature timestamp")
if abs(currentTime - received.timestamp) > allowedSkew:
reject("stale webhook")
signedData = received.timestamp + "." + rawBody
expected = HMAC_SHA256(webhookSecret, signedData)
if !constantTimeEqual(expected, received.signature):
reject("invalid signature")
payload = parseJSON(rawBody)
validateSchema(payload)
Do not log secrets or complete payment payloads by default. During secret rotation, support the documented overlap pattern: test the active secret first, then a previous secret only when the provider's rotation process requires it. Alert on unexpected use of an old secret rather than silently accepting it indefinitely.
3. Idempotency keys and durable deduplication
Webhook idempotency has two related parts. The first is the provider's idempotency key for an outbound API request, such as creating a payment or refund. The second is your inbound event deduplication key, usually the provider's event ID. Track both when available.
For outbound operations, generate an idempotency key that represents one intended business action and persist it before making the request. Reusing the same key for a retry can prevent a timeout from becoming a second charge. Do not reuse a key for a different order, amount, or business action.
For inbound events, make the uniqueness check and processing claim durable. A typical flow is:
- Verify the signature and basic request limits.
- Insert the provider event ID into an events table with a unique constraint.
- If the insert conflicts, return a safe acknowledgment for a previously completed event or resume according to its recorded status.
- Validate the payload and business relationships.
- Apply the permitted state transition and record the outcome in one transaction where practical.
A memory cache can reduce repeated work, but it should not be the only deduplication mechanism. Restarts, multiple workers, and delayed retries make a durable store necessary.
4. State transitions, not isolated event labels
Compare each event with the transaction state already held internally. The following table is a starting model; provider terminology and permitted transitions must be adapted to the gateway and payment method.
| Incoming condition | Expected internal response | Validation concern |
|---|---|---|
| Payment authorized | Move from pending to authorized | Match order, currency, amount, and provider payment ID. |
| Payment captured or succeeded | Mark paid and permit one fulfillment decision | Ensure fulfillment has not already occurred. |
| Payment failed | Record failure and keep the order unpaid | Do not overwrite a later successful state without a defined rule. |
| Refund completed | Record the refund against the original payment | Validate refund amount and prevent duplicate accounting entries. |
| Dispute or chargeback opened | Flag for risk or operations review | Do not treat the event as an ordinary payment reversal unless defined. |
Use an explicit state machine where possible. Terminal states should not be casually overwritten by an older event. If a late event conflicts with the current state, preserve the event, mark it for review or reconciliation, and avoid making an irreversible business decision from an ambiguous message.
Cadence and checkpoints
Webhook validation should be tested continuously in development and reviewed on a recurring operational schedule. A practical cadence is:
Every release
- Run signature tests with valid, altered, missing, and stale headers.
- Replay the same event several times concurrently and confirm one business outcome.
- Test malformed JSON, unknown fields, missing required fields, incorrect types, and oversized bodies.
- Verify that an event cannot change an unrelated order by altering an order ID, amount, or customer reference.
- Confirm that acknowledgment behavior matches the retry strategy: transient processing failures should not be mistaken for successful handling.
Monthly or quarterly
- Review duplicate, rejected, delayed, and quarantined event rates by provider and event type.
- Sample completed payments and compare provider event history with internal ledger, order, refund, and fulfillment records.
- Test replay and reconciliation procedures using a controlled environment.
- Review webhook secrets, access permissions, endpoint exposure, alert routes, and retention settings.
- Check whether schema versions, event names, retry windows, timestamp rules, or payment-state terminology have changed.
Before a gateway migration or provider change
Build a contract comparison for event names, identifiers, signature headers, timestamp formats, retry behavior, amount units, currency representation, and status transitions. Run old and new handlers against captured, redacted fixtures where permitted. Treat migration testing as a transaction validation exercise, not only an integration test.
How to interpret changes
Metrics are most useful when grouped by failure mode. A rise in duplicate events may indicate provider retries caused by slow responses, but it may also reveal that your handler acknowledges too late. An increase in invalid signatures may reflect secret rotation, a proxy altering the body, an incorrect environment secret, or an actual spoofing attempt. Investigate the pattern before changing validation rules.
Use these interpretation questions:
- Are events arriving late? Compare provider event time with receipt time and identify whether delays affect only one event type or payment method.
- Are state conflicts increasing? Look for out-of-order delivery, asynchronous authorization and capture, or a code change that assumes event order.
- Are duplicates producing side effects? Inspect fulfillment, email, inventory, ledger, and refund operations separately. A deduplicated webhook can still trigger duplicate work in a downstream queue.
- Are rejected events recoverable? Distinguish invalid or forged requests from temporary database, timeout, and dependency failures. These categories require different retry and alerting behavior.
- Do internal records reconcile? Compare immutable provider IDs, gross and net amounts, currency, refunds, fees where relevant to your ledger, and final status. Do not reconcile on display names alone.
For higher-risk flows, connect webhook outcomes with a risk scoring or step-up process rather than treating every valid payment event as sufficient evidence. The Transaction Risk Scoring API Integration Guide covers how risk decisions can fit alongside manual review and additional checks.
Replay and recovery test cases
Maintain a small regression suite that includes:
- The same signed event delivered twice with identical payloads.
- Two workers processing the same event at the same time.
- An event received after the signature timestamp falls outside the accepted window.
- A valid event with an amount or currency that differs from the internal order.
- A success event received before an earlier pending event.
- A refund event delivered twice or with an amount greater than the remaining refundable amount.
- A provider timeout after the application commits the state but before it returns an acknowledgment.
- A replay of an old event after a secret rotation or schema migration.
When to revisit
Revisit this checklist at least monthly or quarterly, depending on transaction volume and operational risk. A recurring review should not merely confirm that the endpoint is reachable. It should verify that current provider behavior, internal state transitions, evidence retention, and reconciliation controls still agree.
Update the implementation and test fixtures immediately when a payment platform changes its signature requirements, event schemas, retry windows, timestamp rules, API version, or payment-state terminology. Also revisit the design after a duplicate charge, missed fulfillment, unexplained refund, disputed transaction, webhook outage, secret rotation, database migration, or gateway replacement.
Use this short runbook during each review:
- Choose a representative sample of successful, failed, refunded, and disputed transactions.
- Compare provider event IDs and timelines with internal payment, order, ledger, and fulfillment records.
- List duplicate, delayed, rejected, and state-conflict events from the review period.
- Replay safe test fixtures and confirm signature, schema, idempotency, and state-transition behavior.
- Investigate every unreconciled item, assign an owner, and record the resolution without altering historical evidence.
- Update provider-specific documentation, fixtures, alerts, and this checklist when behavior changes.
The practical goal is not to eliminate every unusual event. It is to ensure that unusual events become visible, repeatable, and recoverable without creating a second charge or an incorrect transaction record.