All articles
FinTech

Payment integrations: preventing losses from retries, webhooks, and refunds

How to avoid duplicate charges and lost refunds. Idempotency, webhook verification, event ordering, financial accounting, and reconciliation with a payment provider.

A customer paid for an order but did not see a confirmation. They clicked again, refreshed the page, or contacted support. Meanwhile, the payment system may already have charged them, even though your server never received the response.

Treating a missing response as a failure can turn a retry into a second payment. Treating a return to the success page as proof of payment can lead to delivering goods without a confirmed charge. Relying only on webhooks can leave some operations unnoticed after a delivery failure.

A reliable integration must work beyond the happy path of clicking and paying. It must withstand retries, delays, reordered events, and disagreements between systems.

We examine how to connect orders, payments, notifications, and refunds so that a technical failure does not become a duplicate charge or a lost obligation to the customer.

An order, a payment, and a payment attempt are different objects

An order may have several payment attempts. A customer might choose another card, fail an additional verification step, or return to the purchase the next day.

But several network requests do not necessarily mean several attempts. Sometimes they are retries of a single command after a connection was lost.

It is therefore useful to track the following separately:

  • the order and its current amount;
  • the payment intent or another settlement object provided by the payment API;
  • the specific attempt to perform an operation;
  • the provider's operation identifier;
  • events reporting changes to its state.

Object names depend on the payment API. What matters is preserving the distinction between a customer's intent to pay and the technical delivery of a command.

The server determines the amount, currency, payee, and order ownership from trusted data. A price sent by the browser must not become the basis for a charge, nor should knowing an order number grant access to someone else's order.

The link between a local attempt and the provider's object must survive application restarts. A value held only in process memory is not enough.

A timeout means uncertainty, not failure

Consider an order for 100 euros. The server sends a charge command, the provider executes it, but the response is lost in transit.

To the server, this is a timeout. To the provider, it is a successful operation. A new request with a new identifier may create another 100-euro charge.

The correct next step depends on the API contract: safely retry the same operation with the same idempotency key, query its status, or await confirmation through the prescribed mechanism.

If the outcome cannot yet be established, the operation must remain in an explicitly uncertain state. It needs to be checked again and made visible to support, rather than converted into an invented success or failure.

Automatically switching to another provider after any timeout is particularly dangerous. The first provider may already have charged the customer. The second knows nothing about that operation and is not required to prevent duplicating it.

Routing between providers requires separate rules: when the previous attempt is conclusively finished, when it can be canceled, and when another attempt is permissible. Having a backup gateway alone does not make a retry safe.

Idempotency starts with the business operation

When processed again, an idempotent request does not create another business effect for the same operation.

An idempotency key should be tied to a specific attempt, saved before contacting the provider, and reused when delivering that command again. Generating a new key for every button click or network retry does not solve the problem.

The application typically needs:

  • a stable operation identifier;
  • recorded request parameters;
  • a uniqueness constraint in storage;
  • a persisted processing state and any known result;
  • a check that a repeated key is not being used with a different amount, currency, or order.

Checking that a key does not exist and then inserting it as two independent actions leaves a race condition. Two processes can pass the check simultaneously. Protection must rely on storage guarantees and correct conflict handling, not just a conditional statement.

The provider's key protects within the boundaries of its contract: a particular method, account, parameter set, and retention period. Once that period expires, a retry cannot be assumed safe without checking.

The local operation history must therefore be retained according to your accounting requirements. External idempotency does not replace your own state model.

Returning to a success page does not confirm payment

A customer can close the tab before returning to the site. They can open a saved link later or change the URL parameters themselves.

Neither the existence of a success page nor a URL parameter is, by itself, proof that money was received.

The basis for fulfilling an order must come from trusted server-to-server interaction with the provider. Depending on the integration, that may be a verified notification, an operation-status query, or a combination of mechanisms.

At a minimum, confirmation must match the payment object, provider account, order, amount, currency, and expected settlement stage.

Successful card authorization does not always mean the charge has been captured. In a two-stage flow, funds may only be reserved until capture is confirmed. Rules for delivering goods or services must reflect the actual payment model used by the product.

The interface only needs to show a clear state: checking payment, paid, or unable to complete. Server-side uncertainty must not be hidden behind a green checkmark.

Verify a webhook before applying it

A public webhook endpoint receives HTTP requests from outside your network. A familiar field or payment identifier does not make a request authentic.

Verification must follow the provider's documented mechanism. If the scheme signs the raw request body, verify the original bytes, not JSON reconstructed afterward. Prefer a supported SDK or a vetted implementation of the protocol.

If the scheme includes a timestamp and an allowed time window, check those as well. Additional network restrictions may help, but are not a universal substitute for authenticity verification.

After verifying the source, check the event's meaning:

  • whether it belongs to the correct account and environment, rather than test mode;
  • whether the associated provider object is known;
  • whether the material operation parameters match;
  • whether this change is allowed under the product's rules;
  • whether the available data is sufficient to act, or the current state must be queried.

Webhook-verification secrets must never be sent to the browser or stored in a public repository. Rotation and any overlap between old and new secrets must follow the provider's supported procedure.

Acknowledge an event only after durable recording

A notification may arrive more than once, including after the application has performed the required action but failed to acknowledge receipt in time.

A practical approach is to verify the event, durably record it in an inbox, and then process it asynchronously.

Event uniqueness is usually defined within the context of a provider, account, and environment. The exact key depends on the notification format. A database constraint prevents the same event from being accepted concurrently by several processes.

If the integration contract permits it, a successful HTTP response can be returned after durable acceptance, without waiting for every business action to complete.

But if recording failed, do not claim that the event was accepted. Otherwise, the provider may stop retrying delivery while the application has lost the notification.

The queue worker must also tolerate retries. Recording an event in an inbox does not guarantee that a process will not stop between updating an order and marking the event as processed.

Duplicate events and duplicate credits need different protections

Checking a webhook identifier solves only part of the problem. Different events can refer to one payment, and a single business fact may be discovered through both a notification and background reconciliation.

Delivery of goods, balance increases, and other actions therefore need protection at the operation level. For example, confirming the same captured charge again must not create a second credit.

Where possible, update the accounting records, mark the operation as applied, and record an outgoing event in one local transaction.

If payment requires calling another service, an outbox is useful: the transaction stores both the state change and a task for later delivery.

Outbox delivery can still be repeated. The receiving service needs its own stable operation key. A queue alone does not guarantee execution exactly once throughout a distributed system.

The entire chain of business effects must be tested for retries: from payment confirmation to granting access, shipping an order, and awarding a partner commission.

Events may arrive out of order

A successful-payment notification can be followed by a delayed event describing an earlier processing stage.

Simply storing the status from the most recently received request can turn a paid order back into one awaiting payment.

You need explicit transition rules and, where the provider supplies versions or sequences, must respect their semantics. A delivery timestamp alone does not establish the order of state changes.

The answer is not to ignore everything after success. A refund, dispute, or adjustment can legitimately follow a payment.

It helps to separate payment, refund, dispute, and order-fulfillment states. They are related, but should not overwrite a single field without controlled rules.

When events conflict, preserve the evidence needed for investigation and check the object with the provider. An inconvenient event must not be discarded just to keep the interface looking tidy.

A refund is a separate financial operation

A refund needs its own identifier, parameters, idempotency key, and processing states.

A response saying that a request was accepted does not always mean the refund has completed. A timeout after the command was sent also does not mean it can safely be retried with a new key.

Partial refunds require particular care. If two employees simultaneously request refunds of 70 euros each against a 100-euro charge, validating each request independently is insufficient.

The available amount must account for completed refunds and active obligations from accepted operations. Limit checking and reservation of the amount must be consistent with the transaction and locking model.

An uncertain result must not automatically be treated as failure with the reserved amount released: the provider may have executed the operation.

Canceling an authorization, refunding captured funds, and disputing a payment have different meanings. They must not be merged simply because all three can result in money not remaining with the merchant.

Refund permissions, limits, and additional approval requirements must be separate from permission to view an order. The administration interface must leave an auditable history of actions.

Financial accounting must not depend on the order screen

A paid status is useful for the interface, but is not a complete financial record.

You must separately understand how much was authorized, captured, refunded, withheld in fees, and actually paid out to the company. These values need not match at a particular point in time.

Internal balances need a transaction journal with clear underlying reasons and reconciliation support. Posted entries should not be silently rewritten: corrections must preserve their connection to the original operation.

Amounts must use agreed precision. That may mean integers in a currency's smallest units or a suitable decimal type. Do not assume every currency has two decimal places or that ordinary floating-point calculations will produce exact financial results.

Rounding, conversion, and fee rules must be defined explicitly. Available-balance checks and the creation of obligations must remain consistent under concurrent processing.

Logs need identifiers that link events, but not full card details, API secrets, or unnecessary personal information. Retention and access are governed by security requirements, contracts, and applicable regulation.

Reconciliation is necessary even when webhooks work

A notification may never arrive, a handler may be unavailable for an extended period, or an application bug may prevent an already received event from being applied.

Independent reconciliation is therefore required: comparing local operations with the provider's available registers, APIs, and reports. Verifying actual receipt of money also requires links to payouts and bank records.

Comparisons must account for the period, currency, fees, refunds, holds, conversions, and the difference between the operation date and payout date.

Reconciliation must identify specific discrepancies, not just differences between total amounts:

  • the provider has a captured charge missing from local accounting;
  • an order was fulfilled without a confirmed charge;
  • a refund completed externally but was not recorded internally;
  • an operation has remained uncertain for too long;
  • one external object is linked to several local credits.

A discrepancy does not always mean an error: some differences follow from settlement timing. But every exception needs a reason, a recheck deadline, and an accountable owner.

If reconciliation fixes state automatically, it must use the same uniqueness constraints and accounting rules as the webhook handler. Otherwise, the recovery mechanism itself becomes a source of duplicates.

Scenarios to test before launch

A successful payment in a test environment confirms only one path. Test the following separately:

  • two simultaneous requests for the same payment attempt;
  • a response lost after the provider executed the operation;
  • the same key retried with changed parameters;
  • a repeated webhook and several different events concerning one operation;
  • events arriving in reverse order;
  • a process stopping after an accounting update but before processing is acknowledged;
  • queue unavailability and recovery after restart;
  • a missing webhook followed by discovery of the operation during reconciliation;
  • partial and concurrent refunds;
  • an uncertain refund outcome;
  • an invalid signature, test account, or amount mismatch;
  • an outgoing event retried after the order was successfully fulfilled.

Check the final outcome, not just API responses: the number of charges, credits, refunds, and granted access rights. An attractive screen does not reveal an extra transaction-journal entry.

Test environments have limitations. Real-operation tests require separate agreement: the amount, responsible person, refund conditions, and acceptable costs must be known in advance.

What to agree with developers

Before starting the integration, obtain answers to several questions:

  • What counts as a separate business operation, and what is a retry?
  • Where are idempotency keys and links to provider objects stored?
  • What does the system do after a timeout?
  • How are notifications verified and persisted?
  • Which actions are protected against duplicate execution?
  • How are late events, refunds, and disputes handled?
  • Who investigates discrepancies, and which tools does support have?
  • How can state be recovered after a failure without charging again?

Check the specific provider's conditions against its current documentation. Idempotency support, key retention, signatures, and retry policies are not identical across APIs.

Payment reliability is not achieved through a single button, queue, or ready-made SDK. It comes from consistent rules for commands, events, accounting, and recovery.

The goal of an integration is not to avoid every timeout. It is to establish what happened to the money even after a timeout, avoid unnecessary operations, and correctly fulfill obligations to the customer.

What do you want to do?

Explain the idea in a couple of sentences. We'll come back with an estimate, deadlines and a plan - free of charge and under NDA.