KoviraPay

Payment Webhooks, Idempotency and Safe Order Fulfilment

Build trustworthy payment webhooks for WooCommerce or a custom API: signatures, retries, idempotency, order status and separate USDC settlement evidence.

The most expensive checkout bugs do not always happen on the payment screen. They happen after the buyer clicks Pay: an order is marked complete too early, a webhook is delivered twice, an entitlement is granted two times, or a settlement event is mistaken for proof that a customer paid an invoice. Those problems are particularly important when fiat payment collection and USDC settlement are separate stages.

This guide explains how to build a trustworthy payment lifecycle for WooCommerce, a custom SaaS backend or a hosted payment link. The goal is not to claim that a signature alone makes everything safe. It is to show how an engineering team can combine authenticated messages, evidence matching, state transitions, duplicate protection, logging and recovery into a dependable workflow.

A webhook is a server-to-server notification. It is not, by itself, an instruction to ship an item or transfer funds. Your application must determine whether the message is authentic, fresh, expected for that payment and consistent with the existing order state before it creates a business side effect.

The checkout redirect is not a payment receipt

Imagine a buyer orders a $49 membership from a WooCommerce store. Your checkout creates an external payment session and sends the browser to a provider. A few seconds later the browser returns to a thank-you URL. A naive integration sees the return and marks the order paid. That can grant membership access even when the customer never finished the provider's process.

A browser navigation does not prove that an acquiring bank settled a transaction, that an on-ramp completed conversion or that a stablecoin arrived. Browser redirects can be interrupted, revisited, bookmarked or spoofed. They are useful for user experience, but the backend needs authenticated evidence from the payment system.

A better implementation stores the order as pending while the browser shows a receipt-in-progress screen. The backend consumes a trusted webhook or performs an authenticated server-side status request. It then maps the result to the correct order and confirms that the amount, currency, provider session and expected merchant all match.

This separation also handles slow payment methods more gracefully. A buyer may finish one step, while the provider still needs additional verification or the crypto settlement chain still needs confirmations. Your customer message should describe that state accurately rather than saying the sale is completed too soon.

Define a payment state machine before coding callbacks

Not every gateway uses the same labels. A useful internal model may include created, pending, provider-confirmed, settlement-pending, settled, failed, expired, refunded and disputed. These are conceptual states; map them to the documented API status values rather than assuming the exact strings appear in every product.

Created means the merchant has issued a payment request. Pending means a route was chosen and confirmation has not completed. Provider-confirmed means an external payment provider reports success under its own rules. Settlement-pending means the required merchant payout still needs reconciliation. Settled means the route-specific destination and amount have been verified. Failed and expired should remain distinct, because a buyer may be able to retry an expired invoice but should not automatically reuse a failed provider authorization.

Decide which transitions are legal. A payment should not move from failed directly to paid because an old, delayed notification arrives. A refunded payment should not silently return to completed because someone replays the original success event. If a dispute occurs after fulfillment, the order history must retain that fact instead of erasing the earlier state.

State changes should be monotonic wherever the business model permits. If the gateway reports a more recent authoritative status, record it along with the source, timestamp and evidence reference. Never treat the arrival order of HTTP requests as proof that an event represents the newest state; networks reorder and retry messages.

A robust webhook receiving path

Think of the receiver as a short pipeline. First, accept only the expected HTTP method and enforce a small documented body-size limit. Second, identify the intended signing configuration for that endpoint without reading a secret from the payload. Third, authenticate the exact raw request bytes according to the publisher's current signing protocol. Fourth, check any authenticated timestamp, event ID and audience or endpoint identifier the protocol provides.

Only after these steps should you parse and validate the JSON schema. Confirm required fields have the expected types, amounts are well formed, currency codes belong to the expected set, payment references match your own records and external identifiers do not point to another merchant's transaction.

Finally, persist the authenticated event or its durable processing record before acknowledging it. Ideally, expensive downstream work goes into a bounded worker queue. When a legitimate duplicate arrives, respond successfully without repeating business side effects. If a message is malformed or unauthenticated, return the appropriate error and log a redacted reason.

The OWASP Webhook Security Cheat Sheet describes these controls and explains why signatures, replay defense and idempotency are separate safeguards. The WooCommerce payment gateway documentation explains when to use its own order-payment completion APIs.

Signature verification: what exactly is signed?

A common mistake is to decode the incoming JSON and then calculate an HMAC over newly serialized JSON. Even when the data looks identical, key order, whitespace and escaping can change the bytes, producing a different signature. When the provider signs the raw body, verify against the raw body using the documented algorithm and secret.

Never invent a universal X-Signature header or timestamp format and assume every upstream provider implements it. Provider protocols differ: one may sign the body only, another may combine timestamp and body, and another may use asymmetric signatures. Follow the specific provider's documentation, verify key rotation requirements, and use a constant-time comparison where applicable.

Store signing credentials in restricted server-side configuration rather than merchant-controlled HTML, WordPress templates or request parameters. Use a different secret per integration where supported. Redact secrets, authorization headers and full sensitive payloads from application logs. If a secret is exposed, revoke and replace it promptly; hiding the log line after publication does not undo the compromise.

When receiving a callback behind Cloudflare or a reverse proxy, do not confuse the proxy IP with a reliable authorization mechanism. A valid cryptographic signature, correct endpoint audience and server-side transaction match are stronger controls than a hard-coded list of apparent client IPs.

Replay protection and duplicate event delivery

Even a correctly signed message can be replayed. An attacker who obtains a previously valid event might send it again. Ordinary payment providers also retry when your server is slow or returns an error. Duplicate deliveries are therefore normal, not a rare edge case.

If a provider's protocol includes an authenticated timestamp, enforce a reasonable tolerance that fits the provider's documented rules and keep server clocks synchronized. If it includes a signed or authenticated unique event ID, persist that identifier and refuse to apply its side effects twice. Do not treat an unsigned timestamp as cryptographic freshness proof.

For a protocol that signs only the body, do not pretend that adding your own timestamp query parameter creates replay protection. In that case, deduplicate using durable event or payment identifiers, authorize the transition against the current authoritative payment state and use the provider's additional verification API if available.

Persisted idempotency matters longer than a five-minute timestamp tolerance. Providers may retry notifications over hours or days. A short replay cache and a durable order-event processing record solve different problems. Configure retention based on the real provider retry window and your audit obligations.

The database transaction that prevents duplicate fulfillment

Suppose two workers process the same legitimate success notification at almost the same time. Both read the order as pending. Both decide fulfillment is required. Without a concurrency control, each may send a download code or grant a subscription. HMAC verification did nothing to prevent this race.

A common solution uses a database transaction and a unique constraint on the provider event ID or the logical fulfillment key. In the transaction, claim the event, lock or conditionally update the expected order and record a single fulfillment job. Commit before the separate worker sends an irreversible email or external activation command.

Use an outbox pattern when possible: the same database transaction records both the new paid state and the outbound task. A worker later sends the task and marks the outbox row as delivered. If the worker crashes, it can retry without losing the task. The receiving system should also accept an idempotency key so the customer cannot receive multiple paid entitlements from repeated delivery attempts.

Illustrative pseudo-sequence: begin transaction; insert event ID into a unique inbox table; verify transaction identity; update order only if its current state allows it; insert one fulfillment outbox row with a unique order-action key; commit; acknowledge webhook; let the outbox worker perform fulfillment. The exact SQL and lock semantics depend on your database and application, so test the concurrency behavior instead of blindly copying pseudocode into production.

WooCommerce order statuses and payment completion

WooCommerce has its own order lifecycle. The gateway integration should not independently reduce inventory, email a paid receipt and invoke another order-payment routine unless those operations are deliberately coordinated. The documented payment_complete() method performs the payment completion transition and participates in WooCommerce stock and order behavior.

Before calling it, confirm that the authenticated event corresponds to the current order, amount and transaction. The same notification can arrive several times; build a durable guard to prevent reprocessing. WooCommerce's order object and stored transaction ID are preferable to relying on a browser cookie that may not exist during server-side callbacks.

For Checkout Blocks, the initial client-side result can differ from the ultimate server-side payment state. The order may exist before the redirect to an external provider, and the store still needs a callback or reconciliation path. Test both Blocks and Classic checkout because plugin registration, display and payment initiation may use different frontend mechanisms, while server-side payment authority should remain consistent.

Consult the WooCommerce gateway integration reference for the current API. For KoviraPay-specific route and API behavior, use the current developer documentation rather than mixing generic WooCommerce examples with undocumented local endpoints.

Fiat collection, USDC conversion and settlement are separate proofs

In a fiat-to-USDC system, the buyer may authorize a card payment in EUR or USD while the merchant expects a stablecoin transfer on a specific network. These are not one atomic transaction. Depending on the provider and route, fiat payment confirmation, conversion, payout initiation and on-chain receipt can happen at different times.

Record each proof separately. A provider callback might confirm an invoice, but not the final amount and chain destination. Conversely, observing an on-chain token transfer to a shared address is not enough to conclude that a particular buyer settled a specific order unless the route provides a verifiable invoice-to-transfer association.

For on-chain reconciliation, verify the chain ID, token contract address, destination address, amount in token base units, transaction receipt and required confirmation depth. On EVM networks, an address such as 0x... does not by itself tell you which chain was used. USDC on Polygon and USDC on Ethereum may share a familiar ticker but are not the same blockchain asset instance.

Provider-managed payout routes may expose authenticated reports or payout IDs instead of direct smart-contract events. The correct evidence requirements differ across routes. Do not force every method into a one-size-fits-all Polygon verification rule.

Amount matching without floating-point surprises

Payment amounts should be stored in integer minor units or exact decimal representations as dictated by the contract. For example, an invoice for $19.99 typically maps to 1,999 minor currency units for a two-decimal fiat currency. A USDC transfer commonly uses six decimal places in supported networks, which means its raw token amount has a different scale.

Never compare a PHP floating-point value of 19.99 to a blockchain integer and assume a string match is meaningful. Normalize each source to its declared currency or token unit and compare with the route's documented tolerance policy, if any. Reconciliation should explain why a discrepancy is accepted; it should not quietly round until the payment appears to match.

Also distinguish merchant net receipts from customer invoice gross. A 7% KoviraPay platform fee is not the same as all processing and conversion charges. The provider's quote may include its own fees or exchange-rate spread. A successful order can therefore have different gross, fee and settlement figures that must remain separately auditable.

A failure-and-recovery walkthrough

Consider a WooCommerce purchase of an annual software license. The buyer reaches the provider, payment is submitted, but your webhook endpoint returns a temporary 503 because the database is restarting. The provider retries later. The buyer refreshes the thank-you page several times in the meantime.

The order should remain unpaid until the backend has adequate verification. Each page refresh should show a safe pending or status-check response, not attempt to grant a license. When the valid event eventually arrives, it should match the existing payment reference and trigger one allowed state transition. If the event is delivered twice, the unique inbox key and order transition guard prevent duplicate fulfillment.

Next, suppose the email-service worker crashes after recording the paid order but before delivering the license. An outbox pattern preserves the pending license-delivery task. The worker can retry without reverting the financial state. If the license provider returns the same entitlement twice, a recipient-side idempotency key or deterministic entitlement ID can keep the customer from receiving duplicated service.

Finally, suppose the provider reports success but the expected USDC payout never reaches the configured wallet. Treat that as a settlement-reconciliation issue, not a reason to falsify the buyer payment state. Investigate the provider payout identifier, chain, network status and internal reconciliation queue. Inform the merchant with accurate status language while keeping the evidence trail intact.

Observability without leaking payment secrets

A usable payment log should include correlation identifiers, order ID, payment ID, provider ID, event category, verification outcome, transition result, retry count and timing. It generally should not include full PAN/card details, wallet private keys, signing secrets, raw authorization headers or unnecessary customer PII.

Use structured log fields so you can answer a concrete question: “Why did order 412 stay pending after the buyer returned?” A status timeline can show payment initiated, provider redirect issued, first callback rejected as missing a signature, second callback accepted, reconciliation queued and settlement confirmed. That is more actionable than a single ambiguous green “Paid” label.

Track operational metrics separately from commercial marketing metrics. Webhook failure rate, signature rejection rate, retries, queue age and payout reconciliation lag help keep the integration healthy. Google clicks and organic impressions help evaluate demand. Successful real merchant activations and confirmed orders help evaluate business traction. None of those numbers should be inflated with an owner's test account.

Testing scenarios worth automating

A basic success-path test is not enough. Build a test matrix covering authentic success, authentic failure, timeout, expiry, duplicate delivery, out-of-order events, unknown transaction reference, wrong amount, wrong currency, wrong merchant, missing signature, malformed JSON and oversized body.

Include security cases: wrong signing key, revoked signing key, stale timestamp where the protocol supports it, tampered body, secret leakage in logs and a callback containing another merchant's payment ID. The system should reject the attack safely and preserve sufficient diagnostics for an operator to investigate.

Include reliability cases: provider is temporarily unreachable, database transaction retries after deadlock, worker crashes before and after committing the outbox job, queue backlog develops, and the callback arrives during a deployment. Verify that retries are bounded, failures become visible and a support operator can initiate a controlled rescan that does not override evidence.

And include business cases: a completed payment arrives after a customer attempts cancellation, a refund is processed after fulfillment, an order has more than one payment attempt, and a buyer requests access after an original session expired. Decide the intended outcome for each one before the real customer asks.

Merchant-facing messages that reduce support burden

The customer should see useful, accurate status language. “Payment initiated” should not be displayed as “Payment received.” “Your provider payment is being verified” may be appropriate while waiting for an authenticated notification. “Order confirmed” should only appear when your order's documented confirmation conditions have been met.

The merchant dashboard should similarly distinguish awaiting customer action, awaiting provider confirmation, settlement in progress and verified settlement. A support link should include a safe correlation reference and guide staff through the relevant evidence. Avoid exposing internal database identifiers or customer-sensitive data in public error pages.

When an upstream provider has a temporary outage, explain that payment confirmation may be delayed rather than asserting that customer funds are lost or already paid. Give the user a retry or contact option appropriate to the current state. Good status messaging protects trust as effectively as a polished landing-page headline.

A practical deployment checklist

Before production, make sure you can answer yes to these questions:

  1. Does every payment have a unique merchant-scoped order and gateway reference?
  2. Is the webhook signature validated using the exact documented signing input?
  3. Are the method, endpoint and request body limits enforced?
  4. Is freshness verified when the upstream protocol supports authenticated timestamps?
  5. Are duplicate deliveries safely acknowledged without applying the same side effect twice?
  6. Can two concurrent workers process one payment without duplicate fulfillment?
  7. Are amount, currency, merchant, payment ID and provider route checked before completion?
  8. Are fiat confirmation and USDC settlement represented as distinct evidence stages?
  9. Does WooCommerce move to paid only after trusted payment confirmation?
  10. Can expired, failed and abandoned sessions be retried without generating duplicate entitlements?
  11. Are logs redacted and error cases visible in an operator dashboard?
  12. Have you tested the actual payout network and receiving wallet on the selected route?

If any answer is no, treat it as an engineering task rather than a marketing footnote. A low platform fee and a quick technical installation have little value if the store delivers goods before money is confirmed or cannot explain where a payment went.

Frequently asked questions

Can I mark the order paid when the customer returns to my website?

No. The browser return is not an authenticated payment confirmation. Use an appropriate verified server-to-server status or webhook mechanism and match its evidence to the order. The return page can show a pending state while the server catches up.

Is checking an HMAC enough to prevent duplicate delivery?

No. An HMAC helps confirm origin and integrity according to its protocol, but a legitimate delivery can arrive multiple times. You also need an idempotent processing path and, when supported, authenticated freshness and event deduplication.

When should WooCommerce call payment_complete()?

Only after the relevant payment has been verified for that order and the order is eligible for the paid transition. Use WooCommerce's established order APIs, not an independent inventory update combined with an untrusted redirect.

Does an on-chain USDC transfer prove my customer's fiat invoice is paid?

Not on its own. It proves an on-chain transfer occurred, subject to chain verification. The payment system still needs a defensible link between the correct buyer invoice, provider event, merchant, destination, token and amount.

What should happen if a webhook is delayed or missing?

Keep the order in an accurate pending state and use an authenticated status query or controlled reconciliation job. Provide a support reference and retry process; do not manually forge a final payment state to hide the outage.

Where to go next

If you are building a custom integration, start with the current KoviraPay API documentation and developer overview. WooCommerce merchants can explore the WooCommerce integration guide and the non-transactional checkout demonstration. Before going live, review fees and provider caveats and the service-role explanation. Those pages help you choose an appropriate route; the webhook checks in this guide help you make that choice reliable in production.