Stablecoin Payment API Idempotency: Retry Orders Safely
Implement stablecoin payment API idempotency with durable keys, unchanged requests, conflict handling, and recovery checks that prevent duplicate orders.
Stablecoin payment API idempotency lets your application retry one payment-creation operation without intentionally creating another order. Persist an operation key and its original request before the first call, then reuse both after a timeout or restart. Keep a separate business reference to prevent competing requests from assigning multiple payment orders to the same purchase.
StableOps is a stablecoin payment operations platform for software developers and businesses. It connects payment orders to on-chain monitoring, confirmation tracking, and signed webhooks while merchants control their receiving addresses and funds. Its payment API requires an explicit Idempotency-Key when creating a payment order.
This guide focuses on the uncertain moment between submitting an order and receiving its response. For the complete customer payment flow, start with how to accept stablecoin payments.
Why does a timeout make payment creation ambiguous?
A timeout means your application did not receive a usable response. It does not prove that the payment order was never created.
Consider a hypothetical SaaS purchase for 49 USDC. Your server submits the payment request, the provider creates an order, and the connection closes before the response reaches your server. If your recovery code generates a new operation identity, it may either create a second order or receive a business-reference conflict. Neither outcome automatically recovers the missing payment instructions.
Disabling the browser button helps the interface, but two tabs, concurrent requests, or a restarted application can bypass that protection. A durable operation record keeps those callers attached to one intended attempt.
HTTP does not make every POST safe to retry automatically. RFC 9110, section 9.2.2 describes the conditions needed to retry a non-idempotent request. A payment API's explicit idempotency contract supplies application-level behavior beyond the method alone.
Which identifiers protect which part of a payment?
Use separate identifiers for request replay, purchase identity, event delivery, and fulfillment. They answer different questions.
| Identifier | Question it answers | StableOps integration behavior |
|---|---|---|
Idempotency-Key | Is this the same creation operation? | The same key and identical body replay the original completed response while its record remains valid |
merchantOrderId | Which merchant payment reference owns this order? | Unique within an organization and environment |
| Payment Order ID | Which provider resource should we inspect? | Use it to retrieve current payment status |
X-Event-Id | Have we accepted this webhook event already? | Persist and deduplicate it in your application |
| Internal purchase ID | Have we already delivered this purchase? | Enforce fulfillment idempotency in your business system |
In StableOps, a new key with an already-used merchantOrderId returns 409 merchant_order_id already used. It does not replay the original order. A reused key with a changed body also produces a conflict. The idempotency documentation explains this distinction.
If your purchase supports multiple deliberate payment attempts, model the purchase and its attempts separately. Each new attempt needs its own merchant reference and operation key. Keep them linked to the same purchase, whose fulfillment must still occur only once.
How do you implement stablecoin payment API idempotency?
Create and store an immutable payment attempt before making the remote request. Every caller handling that attempt must load the same stored key and payload.
1. Reserve one attempt in your own application
Store the internal purchase ID, attempt number, environment, merchant reference, idempotency key, original SDK input, and eventual Payment Order ID. Include your organization context if your application serves multiple merchants.
Enforce uniqueness at the database level for the context, purchase, and attempt number. An application-level “check, then insert” can race when two requests arrive together. PostgreSQL's unique constraints provide a database-enforced rule across one column or a group of columns.
Commit the attempt before calling the payment API. If the process stops after the remote order is created, the next process can recover the stored request instead of inventing another one.
2. Generate the key and expiration once
The following server-side TypeScript uses the current SDK interface. The example purchase ID and amount are illustrative. Your database adapter must atomically insert this attempt or return the existing record, and must commit before any API call.
import { StableOps, type CreatePaymentOrderInput } from '@stableops/api-sdk'
const stableops = new StableOps({
apiKey: process.env.STABLEOPS_API_KEY!,
})
type PaymentAttempt = {
idempotencyKey: string
input: CreatePaymentOrderInput
}
// Run only when reserving a genuinely new attempt.
function prepareAttempt(merchantOrderId: string): PaymentAttempt {
return {
idempotencyKey: `${merchantOrderId}:create-payment-order`,
input: {
merchantOrderId,
amount: '49.00',
acceptedAssets: [{ chain: 'base-sepolia', asset: 'USDC' }],
expiresAt: new Date(Date.now() + 25 * 60 * 1000).toISOString(),
metadata: { purchaseId: 'purchase_123' },
},
}
}
// Call with the committed attempt loaded from your database.
async function submitStoredAttempt(attempt: PaymentAttempt) {
const order = await stableops.paymentOrders.create(attempt.input, {
idempotencyKey: attempt.idempotencyKey,
})
// Persist order.id against this attempt before returning to the payer.
return order
}The two functions show preparation and submission, not a complete persistence layer. Connect them through your committed database record. Derive the merchant reference on the server from the authenticated purchase and attempt number, such as purchase_123:attempt_1. Verify ownership and calculate the payable amount from your own catalog rather than trusting browser input.
Use a Sandbox key and an imported Base Sepolia USDC receiving address for this example. The SDK quickstart covers setup. Choose supported chain and asset pairs for your actual environment rather than assuming every network supports every token.
3. Replay the saved input without rebuilding it
After a recoverable failure, call submitStoredAttempt with the original database record. Do not call prepareAttempt again. Recomputing expiresAt, changing metadata, or reordering the accepted-assets array can change the request body and trigger a conflict.
Preserve decimal amounts as strings. Do not silently convert '49.00' to '49' while reconstructing a retry. The practical rule is to preserve the original input, not to guess which changes the provider might consider equivalent.
The SDK maps camelCase fields to the HTTP API's snake_case fields. For teams using direct HTTP, the create payment order reference documents the request and response. For example, SDK merchantOrderId maps to API merchant_order_id, while idempotencyKey is sent as a header.
4. Retrieve current status after recovering an order
A replay recovers the original creation response. It is not a fresh payment-status query. Once you have the Payment Order ID, retrieve the resource before deciding what the customer should see:
const recovered = await submitStoredAttempt(storedAttempt)
const current = await stableops.paymentOrders.retrieve(recovered.id)
// Render current.amount, current.expiresAt, and current.paymentInstructions.
// Route terminal states to your completion or recovery screen.
console.log(current.id, current.status)Here storedAttempt means your previously committed PaymentAttempt record. If you already saved the order ID, retrieve it directly. An order may have finalized, expired, or been canceled since creation. Replaying creation does not extend its payment window or reopen it.
Which failures should be retried or investigated?
Retry transient failures within a bounded recovery policy. Investigate conflicts instead of generating a replacement key automatically.
The current TypeScript SDK retries reads and explicitly retryable payment-order and checkout-session creation for network errors, timeouts, 429, and 5xx responses. It does not automatically retry 409 responses. Its in-call retries reuse the request, but durable storage remains your responsibility across separate calls and process restarts.
| Result | Meaning | Next action |
|---|---|---|
| Network timeout or connection failure | The result may be unknown | Retry the saved operation with bounded backoff, then escalate unresolved attempts |
429 or 5xx | The request encountered a potentially temporary failure | Allow bounded SDK retries, retaining the same key and body |
409 with a changed-body message | A key was reused for different input | Compare with the saved payload and correct the caller |
409 with an in-progress message | The original operation has not completed within the concurrent wait | Schedule a later check using the same saved operation |
409 merchant_order_id already used | That merchant reference already belongs to an order | Recover the saved mapping or investigate existing orders, without inventing a new reference |
| Missing key, invalid input, or invalid credentials | The request needs correction | Fix the cause before another submission |
A 409 by itself is not proof that a valid payment resource is available to your application. Inspect the error details. If your mapping is missing, use the Dashboard or order listing API to locate and verify the existing order. Do not assume that endpoint supports filtering by merchant reference.
StableOps currently retains idempotency records for 24 hours. That replay window is separate from the order's payment expiration. After the replay record expires, the merchant-reference uniqueness rule still prevents another order from claiming the same reference, but the original response is no longer guaranteed to replay. Store the order mapping durably and investigate unresolved attempts before that window closes.
Does request idempotency prevent duplicate USDC transfers?
No. Request idempotency protects order creation. It cannot stop a payer from signing two transfers or make a repeated transfer disappear.
Similarly, one correctly created order can produce multiple lifecycle events and repeated webhook deliveries. Verify signatures and deduplicate events, then fulfill only from verified payment.finalized evidence with a separate purchase-level guard. The webhook duplicate-fulfillment guide covers that downstream design.
For payment reconciliation, retain the purchase ID, attempt reference, Payment Order ID, event IDs, and transaction hashes. These links explain whether two observed transactions belong to a retry, a deliberate new attempt, or an exception requiring review. Order creation alone is never evidence that funds arrived.
What should a payment API proof of concept verify?
Test recovery behavior before connecting the flow to paid access or shipping. These are acceptance criteria for your integration, not claims that every possible failure is automatically resolved.
| Test | Expected result |
|---|---|
| Submit the same stored key and body twice | Recover the same Payment Order ID |
| Submit concurrently from two application requests | Both use one committed local attempt, with no second provider order |
Change expiresAt while keeping the key | Receive a conflict rather than a silent update |
| Use a new key with the same merchant reference | Receive a merchant-reference conflict |
| Lose the response, then restart the application | Recover using the stored operation and save its order mapping |
| Replay creation after the payment changes state | Retrieve the resource and show its current state |
| Simulate recovery beyond the replay window | Use the durable mapping or investigate, without blindly creating another attempt |
| Deliver a finalized webhook twice | Apply the purchase's fulfillment once |
Use Sandbox payment testing for the application workflow and targeted fault injection for response loss and restarts. Sandbox does not prove every mainnet failure mode. If a customer needs a genuinely new attempt after expiration, follow the expired-payment recovery guide, retaining the original attempt and checking for transfers before asking them to pay again.
Frequently asked questions
Can I use the merchant order ID as the idempotency key?
You can derive a key from the merchant reference and operation name. The roles remain separate: the key identifies a replayable request, while the merchant reference uniquely associates the payment order with your business record.
Should every retry get a new random key?
No. Generate or derive a key once per intended operation, persist it, and reuse it for retries. A new key identifies a different operation, even if the HTTP request looks similar.
Does idempotency guarantee exactly-once payment processing?
No. A request replay contract has a defined scope and retention period. Wallet transfers, event acceptance, and business fulfillment require their own controls and reconciliation.
Can the same pattern be assumed for AI agent payments?
The principle applies, but the interfaces and recovery rules differ. StableOps AI Agent Payments uses its own intent and authorization flow. Follow the Agent Payments quickstart rather than applying this merchant-order example to outgoing agent spending.
Validate recovery before choosing your payment integration
StableOps provides explicit creation keys, merchant-reference uniqueness, retrievable order state, on-chain monitoring, and signed event delivery. Your application supplies durable attempt storage, customer authorization, and purchase-level fulfillment controls. This division lets a team evaluate payment infrastructure against a concrete recovery workflow.
Start with the StableOps payment API quickstart, then run the acceptance table against your own application. If you prefer a hosted payment page, review Checkout Sessions. Compare the current pricing plans, or create a StableOps account to test the integration in Sandbox.
Technical behavior and official references checked on November 14, 2026. All purchase examples are hypothetical.
Related articles
Build reliable crypto payment webhook handling with raw-body signature verification, event deduplication, idempotent fulfillment, and replay-safe recovery.
Recover unpaid stablecoin subscription renewals with invoice checks, payment tracking, grace-period policies, and verified events before restoring access.
Learn why production stablecoin payments need explicit order states, deterministic transfer matching, finality tracking, idempotency, and reliable webhooks.
Learn how to refund finalized stablecoin payments with verified addresses, exact amounts, signed transactions, idempotent webhooks, and on-chain reconciliation.