Skip to main content

What is an idempotency key?

Primer supports a request idempotency mechanism for our Payments API. This optional feature enables you to safely retry a request without risking the user being charged or refunded multiple times. This is particularly useful when an API call fails due to the request being invalid, due to a network issue, or if Primer is momentarily unavailable. If this is the case, make another request with the same idempotency key:
  • If a request with the same idempotency key has already been processed, the new request is ignored. Primer returns a 409 error with the errorId IdempotencyKeyAlreadyExists, and the response includes the paymentId and paymentStatus of the original payment.
  • If the original request is still being processed, Primer also returns 409 with IdempotencyKeyAlreadyExists, but paymentId and paymentStatus are null. This doesn’t mean the payment failed. Don’t create a new payment. Wait, then resend the same request with the same key to get the payment, or wait for the PAYMENT.STATUS webhook.
  • Otherwise, Primer will attempt to process the new request.

How to use an idempotency key

To make an idempotent request, generate an idempotency key and pass it to the header X-Idempotency-Key.
The way you generate the key is totally up to you, as long as it is unique per request attempt. Keep in mind that a payment request resulting in a declined or failed payment is still considered Successfully processed for the API. Therefore, if you want to allow the user to retry an unsuccessful payment, make sure to not use the same idempotency key. As a such, don’t use anything too restrictive like an orderId for the idempotency key as multiple payment attempts and refunds can be made for a single order.

Prevent duplicate payments from the checkout

An idempotency key only stops a repeat of the same request. A client session stays valid for 24 hours. After a decline, the checkout lets the customer try again, and a successful payment doesn’t close the session, so one session can create more than one payment for the same order. To prevent duplicate payments:
  • remove or disable the checkout as soon as the payment succeeds
  • before you create a client session or allow another payment, check on your server that the order isn’t already paid
  • pass an idempotency key for each payment attempt, for example built from the order ID and the attempt number. See Use idempotency keys.