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.

How It Works

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

Code Example
How to implement idempotency in your payment requests
// 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 payment

Best Practices

Generate Unique Keys

Use a combination that ensures uniqueness:

  • Order ID + timestamp
  • UUID v4
  • Customer ID + payment intent ID
Key Lifetime

Idempotency keys are valid for 24 hours. After that, you can reuse the same key value for a new request.

Retry Logic

When retrying a failed request, always use the same idempotency key. This ensures you don't accidentally create duplicate payments.

Idempotency Key Format

Requirements
Header Name:

Idempotency-Key

Format:

Any string up to 255 characters. Recommended: alphanumeric with hyphens or underscores

Examples:
order_12345_1705312200000
550e8400-e29b-41d4-a716-446655440000
payment_cust_123_2024-01-15

Error Handling

Idempotency Conflicts
409 Conflict

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

Endpoints That Support Idempotency
  • 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.