Idempotency
Send an Idempotency-Key with every create request so retries are safe — same key and body replays the original response.
Networks fail. If a POST /v1/payments times out, you can't know whether ePay created the payment. An idempotency key makes the retry safe: ePay remembers the first response for that key and returns it again instead of creating a second payment or refund.
curl https://beta.api.epay.lk/v1/payments \
-H "Authorization: Bearer $EPAY_SECRET_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1042-attempt-1" \
-d '{ "amount": 125000, "order_id": "1042" }'Supported on POST /v1/payments and POST /v1/refunds. Keys are scoped to your account.
Semantics
| Situation | Result |
|---|---|
| First request with a key | Processed normally; the response is stored for 24 hours |
| Same key, same method, path and body | The stored response is replayed with the original status code and header Idempotent-Replayed: true |
| Same key, different body | 422 idempotency_error / idempotency_key_reused — nothing is created |
| Same key while the first request is still running | 409 idempotency_error / idempotency_key_in_use — retry shortly |
The first request failed with a 5xx | Not stored — retrying with the same key runs the request again |
| Key longer than 255 characters | 400 idempotency_key_invalid |
"Same body" means byte-for-byte: serialise the retry from the same data in the same way (don't add fields or change key order between attempts).
A replayed payment-create response includes the original checkout_url, so a retry after a timeout still gets you the link to redirect to.
Choosing keys
- Use something unique per intended operation that you'd regenerate identically on retry:
order-1042,refund-order-1042-item-3, or a UUID stored with your order before the first call. - Don't reuse a key for a different operation, even after 24 hours.
- If the order changes (new amount), it's a new operation — use a new key (and cancel the old payment).
async function createPayment(order: Order) {
const key = order.idempotencyKey ?? (order.idempotencyKey = await saveKey(order, crypto.randomUUID()));
for (let attempt = 0; attempt < 4; attempt++) {
try {
const res = await fetch(`${process.env.EPAY_API_URL}/v1/payments`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.EPAY_SECRET_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify({ amount: order.totalCents, order_id: order.id }),
});
if (res.ok) return await res.json();
if (res.status !== 409 && res.status !== 429 && res.status < 500) throw await res.json();
} catch (err) {
if (!(err instanceof TypeError)) throw err; // only network errors fall through to retry
}
await new Promise((r) => setTimeout(r, 500 * 2 ** attempt + Math.random() * 250));
}
throw new Error("ePay unavailable, try again later");
}
