Idempotency and retries
Networks fail in the worst place: after we did the work, before you got the answer. Two mechanisms make every money request safe to send again.
The idempotency key
Every request that creates or moves money — createPayin, createPayout, createSettlement — needs an Idempotency-Key header (at most 128 visible ASCII characters).
A key is remembered for 72 hours, per project and mode.
- Same key, same request within 72 hours: you get the stored response again, byte for byte, with the header
NP-Idempotent-Replay: true. Nothing is done twice. - Same key, different request (another body, path or query):
409 idempotency_key_reused. Never change a retry's body. - Same key while the first request is still running:
409 request_in_progress. Wait a moment and send it again. - A request that failed (any error) did nothing and stored nothing; sending it again runs it again.
Use your own id as the key: your order id for a pay-in, your withdrawal id for a payout. Then a retry from another process, after a deploy, or by a colleague clicking "retry" in your back office, can never create a second object.
Your reference is unique forever
Independently of the key, merchant_order_id (pay-ins) and merchant_payout_id (payouts) are unique per project forever. Creating a second object with the same reference gives 409 duplicate_merchant_reference with existing_id, the id of the one that exists. This is what stops a double payout when someone retries after the 72-hour window.
samples/ts/payins.ts// Pay-ins: create one per order exactly once, read it back, list, cancel.
// bun payins.ts DEP-48213
import { NicePay, NicePayError, type Payin } from "@nicepay/sdk-ts";
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
secret: process.env["NICEPAY_KEY_SECRET"] ?? "",
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
/**
* The pay-in for one of your orders: created the first time, the same one every time
* after — whether you retry a second later (idempotency key) or a week later
* (merchant_order_id is unique per project forever).
*/
async function payinForOrder(orderId: string, amount: string): Promise<Payin> {
try {
return await nicepay.createPayin(
{ merchant_order_id: orderId, amount, currency: "INR", method: "upi", customer: { ref: "player-7591035" }, metadata: { cart: "c-1" } },
{ idempotencyKey: orderId },
);
} catch (error) {
if (error instanceof NicePayError && error.code === "duplicate_merchant_reference") {
return nicepay.getPayin(String(error.problem["existing_id"]));
}
throw error;
}
}
const orderId = process.argv[2] ?? `DEP-${String(Date.now())}`;
const first = await payinForOrder(orderId, "750.00");
const again = await payinForOrder(orderId, "750.00");
console.log(`order ${orderId} → ${first.id} (again: ${again.id}, same: ${String(first.id === again.id)})`);
// Read it back. checkout_url is only in the create response; store it if you need it.
const fetched = await nicepay.getPayin(first.id);
console.log(`status ${fetched.status}, amount ${fetched.amount} ${fetched.currency}, rail ${fetched.rail}`);
// Find it by your own id.
const found = await nicepay.listPayins({ merchant_order_id: orderId });
console.log(`found by merchant_order_id: ${String(found.data.length)}`);
// The customer gave up: cancel. (If money still arrives, the pay-in succeeds anyway — "late money wins".)
if (fetched.status === "pending") {
const cancelled = await nicepay.cancelPayin(first.id);
console.log(`cancelled: ${cancelled.status}`);
}What the SDKs retry
The SDKs generate an idempotency key when you do not pass one, and reuse it on every retry. They retry at most 3 times, with exponential back-off and jitter, and only when it is safe:
| Situation | GET | Money POST (has an idempotency key) | Other POST, PATCH, DELETE |
|---|---|---|---|
| No answer (network error, timeout) | retried | retried, same key | not retried |
429 rate_limited | retried after Retry-After | retried after Retry-After | retried after Retry-After |
409 request_in_progress | — | retried, same key | — |
5xx | retried | retried, same key | not retried |
Any other 4xx | not retried | not retried | not retried |
Every attempt is signed again with a new nonce.
When nobody knows what happened
If every attempt went unanswered, the SDK raises a connection error with outcomeUnknown: true (PHP: $e->outcomeUnknown) for anything but a GET, and gives you the idempotency key it used.
Money: an unknown outcome is not a failure. Do not mark the withdrawal failed, do not refund the customer's balance, do not pay them another way. Keep it "processing", and later send the same request with the same idempotency key — or look the object up by your
merchant_payout_id— and act on what you find.
Mistakes that lose money
- A random idempotency key generated inside your retry loop: every retry is a new request, so a timeout can become two payouts. Generate it once per withdrawal — better, use the withdrawal's own id.
- Treating a timeout as "failed" and giving the player their money back while the payout is in fact on its way.
- Reusing one
merchant_payout_idfor two different withdrawals: the second is refused as a duplicate, and if you then give up on it, that player is never paid.