PAY-14Required
Create each charge with an idempotency key
Send an idempotency key, built from your own stable IDs, on every provider request that creates a payment, a refund or a payout.
How to do it
A request can time out after the provider has charged the card. A retry with the same key returns the first result instead of charging again. Build the key from the order and attempt, such as order-ord_8f2k-attempt-1, and reuse it for every retry of that request. Make a new key only when the amount or payment method changes. Providers forget keys after a while, after 24 hours at Stripe. After that, look the payment up by your order ID instead of retrying. The server side of the same idea is idempotency keys, and the attack test is race conditions.
Examples
JavaScript example
const idempotencyKey = `order-${order.id}-attempt-${order.attempt}`
const intent = await withRetries(() => stripe.paymentIntents.create(
{ amount: order.totalMinor, currency: order.currency.toLowerCase(), metadata: { orderId: order.id } },
{ idempotencyKey },
))
Python example
idempotency_key = f"order-{order.id}-attempt-{order.attempt}"
intent = with_retries(lambda: stripe.PaymentIntent.create(
amount=order.total_minor,
currency=order.currency.lower(),
metadata={"order_id": order.id},
idempotency_key=idempotency_key,
))
How to check
In a test, make the provider call time out after the request was sent, then retry. The provider shows one payment, and the order shows one charge.
Sources
Related rules
- API-76 Send the same idempotency key when you retry a write in API design
- API-32 Accept idempotency keys on POST that creates or charges in API design
- APS-53 Make each change happen exactly once in Application security
- USG-1 Give every usage event a key and count it once in Usage-based billing
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/payments/amounts-and-orders/idempotent-charge-creation">Agent Wranglers payments and billing playbook</a>. In code you write, add a comment next to it with the same link.