Payment Webhooks: Handling Paid, Failed and Refunded Events — Integrations & APIs article by Rui Codex

Handle payment webhooks by verifying each event's signature, storing its ID before doing anything else, and updating order state idempotently for paid, failed and refunded events. Treat the webhook as a notification to re-check, not as the final truth, and let a reconciliation job catch what gets lost.

Key takeaways

  • Verify the signature of every webhook request before reading its payload.
  • Store each event ID so that a repeated delivery does not repeat the work.
  • Change order state only through transitions that are safe to run twice.
  • Treat a failed payment as a state to recover from, not as an automatic cancellation.
  • Run a scheduled reconciliation against the payment provider's records to catch missed events.

What is a payment webhook, and how does it differ from a redirect?

A payment webhook is an HTTP request that the payment provider sends to an endpoint on your server when something happens to a payment, such as a successful charge or a refund. It is a server-to-server message, so it does not depend on the customer's browser staying open after checkout.

The customer's return to your shop after paying is a browser redirect, and it cannot be trusted as proof of payment. A customer can close the tab before the redirect lands, or a network fault can drop it. The webhook is the more reliable channel, which is why order logic should be driven by it. The Stripe webhook documentation describes the event model and how endpoints receive events, which is a useful reference for the concepts in this article.

Keep the two channels separate in your code. The redirect page can say that the payment is being confirmed, while the state change itself happens only when the verified webhook is processed.

How do you verify and store incoming events safely?

Verify the signature on every request before parsing it, and store the raw event before running any business logic. Respond with a success status only after the event is saved, so that a crash after saving does not lose it.

Checklist for the receiving endpoint

  • Check the signature header against the raw request body, using the signing secret for that specific endpoint.
  • Reject requests with invalid signatures or timestamps that fall outside your accepted window.
  • Insert the event ID into a table with a unique constraint.
  • Acknowledge quickly and move heavy work, such as document generation, to a queue.

Use the unique constraint as the duplicate guard. If the insert fails because the ID already exists, return success and do nothing else. Signature verification needs the exact raw body, so if a framework parses and re-serialises JSON first, the check will fail. That mismatch is an easy mistake to make, so test verification with a signed sample payload from the provider's test mode.

Tip: Keep signing secrets in your secret store rather than in source code, and use separate secrets for test and live endpoints.

A paid event should move an order from pending to paid exactly once, and it should never overwrite a later state. Build the transition as a conditional update, for example 'set status to paid where status is pending', so that a repeated or late event has no effect.

Payment usually triggers side effects: stock reservation becomes a deduction, an invoice may be issued, and a fulfilment message goes to the warehouse. Each of these should follow from the state change, not from the arrival of the webhook. Record the state change and the pending side effects in the same database transaction, using an outbox table, so that they are either all recorded or none are. A worker then sends the messages, and a retry of the worker cannot ship the same order twice because each message carries the order's own identifier.

The main trade-off is complexity. An outbox adds a table and a worker, but it removes the window in which the order is marked paid while the warehouse message is lost. For a small shop with one warehouse, a simple transaction may be enough; for a portal connected to several systems, the outbox is usually worth the effort.

What should happen when a payment fails?

A failed payment should keep the order open in a payment-pending state and tell the customer how to retry, rather than cancelling it at once. A declined card is often recoverable, so a failure event is a signal to wait, not a final verdict.

Decide explicitly how long the order stays open and what happens when that window closes. Cancellation should be a separate step, triggered by a timeout job or by a final failure status, and it should release any reserved stock. Log each failure with the provider's reason code so that support staff can explain what the customer needs to do.

Cancelling on the first failure protects stock but loses sales, while holding the order indefinitely ties up stock and clutters operations. Neither extreme suits every catalogue. The window should be a business decision written into the code and tested, not a default that nobody chose.

How do refunds flow back into the order?

A refund event should record the refunded amount against the original payment and adjust accounting, without changing the fulfilment history of the order. Partial refunds mean that one payment can have several refund events, so store refunds as their own records rather than as a single flag on the order.

A refund must not silently reverse a shipment that has already left the warehouse, because physical returns need their own workflow. Treat a refund on an already-shipped order as a return case, and link it to the original shipment. Refund events may also arrive for orders your system does not recognise, perhaps because of a data migration. Log those for review rather than failing silently.

Do not assume events arrive in the order they were created. A refund notification can reach your endpoint before a related payment notification, so the handler should accept the refund, store it against the payment identifier, and resolve the link when the payment record exists.

Where do webhook pipelines fail in practice?

Webhook pipelines most often fail through duplicate deliveries, out-of-order events, endpoint outages and signature mismatches. Each failure has a recognisable symptom and a specific guard, as the table below shows.

FailureWhat you seeGuard
Duplicate deliveryThe same event is processed twiceUnique constraint on the event ID
Out-of-order eventsA refund is handled before its payment record existsStore first, resolve links later
Endpoint outageEvents are missing for a periodReconciliation against provider records
Signature mismatchAll requests are rejectedVerify against the raw request body

The guards are complementary rather than alternatives. The unique constraint does nothing for a missing event, and reconciliation does nothing for a duplicate that has already shipped an order. Design for all four.

Why do you still need reconciliation?

Reconciliation is needed because no webhook pipeline can guarantee that every event is received and processed on the first attempt. A scheduled job that compares your order records with the provider's payment records finds the gaps, and it repairs them through the same handlers the webhooks use.

Run the job at a fixed interval, match records by payment identifier, and log every mismatch with its cause. Treat reconciliation as a safety net rather than the primary path, because polling every order is slow and uses API calls. Keep the interval short enough that a missed event is noticed before a customer contacts support.

Tip: Make the reconciliation job call the same state transition functions as the webhook handler, so that there is only one set of rules to test.

If your shop or back office needs these flows connected to an ERP or CRM, our ERP and CRM integration service covers the data mapping. For the broader connection work between systems, see our system integration services, and for the storefront itself, our web development services.

Hypothetical examples of webhook handling

Here are two hypothetical scenarios:

Scenario one: A shop receives a paid event while its order service is restarting. The endpoint stored the event ID and returned success before the restart, so the event waits in the queue and is processed once the service is back. The order moves to paid once, and the shipment message is sent once.

Scenario two: A customer's card is declined, then succeeds on a second attempt. The failure event keeps the order open, and the later paid event completes it. Without the state guard, a late failure event processed after the payment could have overwritten the paid status.

Neither scenario describes a real client. They show how the rules in this article interact when events arrive at unexpected times.

Frequently Asked Questions

Should I trust the redirect after checkout or the webhook?

The webhook is the source of truth for payment state, and the redirect is only a display event. Show a pending page after the redirect until the verified webhook confirms the paid event. If the page cannot wait, confirm the status directly with the provider's API before changing the order.

Can the same webhook arrive twice?

Yes, so plan for duplicate deliveries. Duplicates are possible whenever a response is slow or lost, so every handler should be idempotent and keyed on the event ID. Store the ID with a unique constraint, return success for duplicates, and never repeat side effects such as shipping or invoicing.

Do I need a reconciliation job if my webhooks work?

Yes, a reconciliation job is still worth running. Events can be missed during outages, deployments or misconfiguration, and a periodic comparison with the provider's records finds the gaps. Repair them through the same handlers the webhooks use, so the business rules stay in one place.

Should a failed payment cancel the order?

Usually not immediately. A failed payment should leave the order open in a payment-pending state for a defined window, then cancel it and release stock if no successful payment arrives. The length of that window is a business decision rather than a technical default.

Conclusion

Payment webhooks are simple to receive and easy to get wrong once they change orders, stock and invoices. Verify every request, store every event before acting on it, make each transition safe to repeat, and run reconciliation as a safety net. These habits keep paid, failed and refunded events consistent even when the network, the provider or your own services fail.

If you are connecting a webshop or portal to a payment provider and want this handling reviewed or built, request a project consultation at the Rui Codex contact page, or email info@ruicodex.com to discuss your project. Rui Codex is led by a founder with 200+ projects delivered, and published case studies are at our case studies page.

Sources

Tags: payment webhooks webhook handling webshop integration idempotency order management refund handling API integration reconciliation

Need Help Implementing This?

Our team can help you put these insights into practice. From AI automation to custom software development, we build solutions that deliver real results.

Send a project request