How to prevent double charging on a repeated request (idempotency)?
sobes.tech AI
Answer from AI
To prevent double charging on repeated requests, idempotency is used — a guarantee that a repeated call with the same parameters will not lead to a repeated change of state.
Main approaches:
-
Using a unique transaction identifier (idempotency key). The client generates a unique key for each operation. The server saves the result of the operation with this key and, on a repeated request with the same key, returns the saved result without performing the charge again.
-
Checking the operation status. Before charging, it is checked whether the operation has already been completed (for example, by order or payment status).
Example in JavaScript (fetch):
const idempotencyKey = 'unique-transaction-id-123';
fetch('/api/charge', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey
},
body: JSON.stringify({ amount: 100 })
})
.then(response => response.json())
.then(data => console.log(data));
On the server, logic for saving and checking the key needs to be implemented.