'Proper implementation of using a idempotency key with another service like stripe
What is the proper way to handle idempotency in a rails application? I am using devise and need to make sure that each user doesn't get multiple duplicate PaymentIntents for the same purchase.
Since the idempotency key needs to be used with each subsequent failed request should it be something saved in the database, session, etc..?
Stripe suggests to use idempotency keys to prevent duplicate PaymentIntents for the same purchase: https://stripe.com/docs/payments/payment-intents#best-practices
Solution 1:[1]
You don't necessarily need to generate/save idempotency keys on your end. Stripe libraries can automatically generate idempotency keys and retry requests with an exponential backoff.
It is important to note that Idempotency keys are useful for preventing double charges in cases of poor network conditions only. They allow for safely retrying requests without accidentally performing the same operation twice. This is useful when an API call is disrupted in transit and you do not receive a response. For example, if a request to create a charge does not respond due to a network connection error, the request can be retried with the same idempotency key to guarantee that no more than one charge is created.
Idempotency keys do not prevent double charges which occur due to a button being pressed twice e.g. maybe a user clicked the button twice while a page was loading and it leads to making two API requests. You would want to use approaches like the disabled HTML attribute to prevent such occurrences.
Solution 2:[2]
an idempotency key is any id that helps you and stripe from creating duplicate work.
For example when your user starts to make a Purchase in your application, you want to use the purchase.id as your idempotency key.
Then you would pass that key to stripe for every PurchaseIntent request.
If the customer updates something on the purchase, you would then pass that data along to stripe with the same purchase.id
Once that purchase is complete, you would keep some more data like completed_at:datetime and completed_transaction_data:json
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alex |
| Solution 2 | Blair Anderson |
