Idempotency
Learn how to use idempotency keys to prevent duplicate charges when network errors occur or requests are retried.
What is Idempotency?
Idempotency ensures that making the same request multiple times has the same effect as making it once. This is crucial for payment processing to prevent duplicate charges when network errors occur or requests are retried.
1. Include Idempotency Key
Send a unique idempotency key in the Idempotency-Key header with your request.
2. First Request
The API processes the request normally and stores the idempotency key with the result.
3. Duplicate Request
If you send the same idempotency key again, the API returns the original response without processing a new payment.
Implementation
// Generate a unique idempotency key
function generateIdempotencyKey(orderId) {
return `order_${orderId}_${Date.now()}`;
}
// Use idempotency key in payment request
const response = await fetch('https://api.altafinex.com/v1/payments', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_SECRET_KEY',
'Content-Type': 'application/json',
'Idempotency-Key': generateIdempotencyKey(orderId),
},
body: JSON.stringify({
token_id: tokenId,
amount: amount,
currency: 'THB',
}),
});
// If request fails, retry with the same key
// The API will return the original response, not create a duplicate paymentBest Practices
Use a combination that ensures uniqueness:
- Order ID + timestamp
- UUID v4
- Customer ID + payment intent ID
Idempotency keys are valid for 24 hours. After that, you can reuse the same key value for a new request.
When retrying a failed request, always use the same idempotency key. This ensures you don't accidentally create duplicate payments.
Idempotency Key Format
Header Name:Idempotency-Key
Format:Any string up to 255 characters. Recommended: alphanumeric with hyphens or underscores
Examples:Error Handling
If you send a request with an idempotency key that was used for a different request (different parameters), you'll receive a 409 Conflict error. This prevents accidental duplicate charges with different amounts.
Important
If you receive a 409 error, check your idempotency key generation logic. Each unique payment should have a unique key.
Supported Endpoints
- •
POST /v1/payments- Create payment - •
POST /v1/refunds- Initiate refund
While idempotency keys are recommended for all POST requests, they're especially important for payment and refund operations to prevent duplicate charges.