Guides
Errors and retries
Every error has a stable code. Know which ones to fix, which to retry, and retry safely.
Errors use normal HTTP status codes and always carry the same JSON: success: false, a human message, a stable machine code, and a request_id. Branch on code, never on message β messages may get clearer over time; codes never change.
{
"success": false,
"message": "Validation failed",
"code": "VALIDATION_FAILED",
"error_sources": [{ "path": "amount", "message": "required" }],
"request_id": "7UDv-A9SxdKgCB0MyhP152eEZxZwsLQn4nbgSwSzsO0"
}error_sources points at each field that failed (customer.email, metadata, a query parameter). Some errors add data with details:
{
"success": false,
"message": "success_url must be on one of your websites (Settings βΊ Domains)",
"code": "RETURN_URL_NOT_ALLOWED",
"data": { "field": "success_url" },
"request_id": "PvMqENWBZPjtccwrdkUBJjUAiXvd_zlLkgFjutS4yok"
}Every code
| Status | code | Means | Retry? |
|---|---|---|---|
| 400 | IDEMPOTENCY_KEY_REQUIRED | A POST without an Idempotency-Key header. | No β add the header. |
| 400 | RETURN_URL_NOT_ALLOWED | success_url / cancel_url isn't on your websites (data.field says which). | No β add the domain in Settings βΊ Domains. |
| 400 | INVALID_BODY | The body isn't valid JSON (or form data). | No. |
| 401 | API_KEY_INVALID | No Authorization: Bearer β¦ header, or the key is wrong, revoked or from another account. | No β check the key. |
| 402 | PLAN_LIMIT | This month's live payment allowance is used up (data.limit_key, data.limit, data.used). Test mode keeps working. | No β upgrade, or wait for the 1st of the month (Bangladesh time). |
| 402 | SHOP_PAUSED | This shop is paused because the plan ended. Payments already started still complete. | No β renew. |
| 404 | PAYMENT_NOT_FOUND | No such payment in this mode (a test key can't see live payments). | No. |
| 404 | NOT_FOUND | No such endpoint β check the path. | No. |
| 409 | PAYMENT_STATE | The payment can't do that now (e.g. refunding one that isn't completed). | No. |
| 409 | IDEMPOTENCY_IN_PROGRESS | The first request with this key is still running. | Yes, same key. |
| 422 | VALIDATION_FAILED | A field is missing or wrong β see error_sources. | No. |
| 422 | IDEMPOTENCY_KEY_REUSED | This key was used with a different body. | No β a bug: one key per action. |
| 429 | RATE_LIMITED | More than 300 requests a minute on this key. | Yes, after Retry-After seconds. |
| 500 | INTERNAL | Our fault. Quote the request_id to support. | Yes, same key. |
| 503 | SERVICE_UNAVAILABLE | A short outage or deploy. | Yes, same key. |
Retrying safely
Because every POST has an idempotency key, retrying is always safe as long as you send the same key β the worst case is getting the first answer back. Retry network errors, timeouts, 429, 5xx and IDEMPOTENCY_IN_PROGRESS a few times with a growing wait; never retry other 4xx, they need a fix.
Here is all of that as one small function you can paste into your project β the key, JSON, safe retries and an error with code and request_id. It is what our own SDKs do.
# The rules every client follows β shown with curl:
# 1. Authorization: Bearer <secret key> on every request.
# 2. Idempotency-Key on every POST; reuse the SAME key when you retry.
# 3. Retry network errors, 429 (wait Retry-After seconds), 5xx and 409 IDEMPOTENCY_IN_PROGRESS.
# 4. Never retry other 4xx: fix the request (the "code" says what is wrong).
curl https://api.takaelo.com/v1/checkouts \
--retry 3 --retry-all-errors \
-H "Authorization: Bearer $TAKAELO_SECRET_KEY" \
-H "Idempotency-Key: order-4821-1" \
-H "Content-Type: application/json" \
-d '{"amount": 1250, "reference": "ORD-4821"}'<?php
// TakaElo.php β the whole client (PHP 8.1+). Usage:
// $checkout = takaelo('POST', '/checkouts', ['amount' => 1250, 'reference' => 'ORD-4821'], 'order-4821-1');
// $payment = takaelo('GET', '/payments/' . $checkout['id']);
final class TakaEloException extends RuntimeException
{
public function __construct(public readonly int $status, public readonly ?string $errorCode, string $message, public readonly ?string $requestId)
{
parent::__construct($message);
}
}
function takaelo(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
$headers = ['Authorization: Bearer ' . getenv('TAKAELO_SECRET_KEY'), 'Content-Type: application/json'];
if ($method === 'POST') {
$headers[] = 'Idempotency-Key: ' . ($idempotencyKey ?? bin2hex(random_bytes(16))); // same key on every retry
}
for ($attempt = 0; ; $attempt++) {
$ch = curl_init('https://api.takaelo.com/v1' . $path);
$retryAfter = 0;
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, 'Retry-After:') === 0) $retryAfter = (int) trim(substr($line, 12));
return strlen($line);
},
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body === null ? '' : json_encode($body));
}
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$json = is_string($raw) ? (json_decode($raw, true) ?? []) : [];
if (!empty($json['success'])) {
return $json['data'];
}
$retryable = $raw === false || $status === 429 || $status >= 500 || ($json['code'] ?? '') === 'IDEMPOTENCY_IN_PROGRESS';
if ($retryable && $attempt < 3) {
sleep($retryAfter ?: 2 ** $attempt);
continue;
}
throw new TakaEloException($status, $json['code'] ?? null, $json['message'] ?? curl_error($ch), $json['request_id'] ?? null);
}
}// takaelo.js β the whole client (Node 18+). Usage:
// const checkout = await takaelo("POST", "/checkouts", { amount: 1250, reference: "ORD-4821" }, "order-4821-1");
// const payment = await takaelo("GET", `/payments/${checkout.id}`);
import crypto from "node:crypto";
export class TakaEloError extends Error {
constructor(status, body) {
super(body.message ?? `HTTP ${status}`);
this.status = status;
this.code = body.code;
this.requestId = body.request_id;
}
}
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
export async function takaelo(method, path, body, idempotencyKey) {
const headers = { Authorization: `Bearer ${process.env.TAKAELO_SECRET_KEY}`, "Content-Type": "application/json" };
if (method === "POST") headers["Idempotency-Key"] = idempotencyKey ?? crypto.randomUUID(); // same key on every retry
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetch(`https://api.takaelo.com/v1${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
} catch (err) {
if (attempt < 3) { await sleep(2 ** attempt); continue; } // network blip: resending is safe
throw err;
}
const json = await res.json().catch(() => ({}));
if (json.success) return json.data;
const retryable = res.status === 429 || res.status >= 500 || json.code === "IDEMPOTENCY_IN_PROGRESS";
if (retryable && attempt < 3) {
await sleep(Number(res.headers.get("retry-after")) || 2 ** attempt);
continue;
}
throw new TakaEloError(res.status, json);
}
}# takaelo.py β the whole client (Python 3.10+). Usage:
# checkout = takaelo("POST", "/checkouts", {"amount": 1250, "reference": "ORD-4821"}, "order-4821-1")
# payment = takaelo("GET", f"/payments/{checkout['id']}")
import json
import os
import time
import urllib.error
import urllib.request
import uuid
class TakaEloError(Exception):
def __init__(self, status: int, body: dict):
super().__init__(body.get("message", f"HTTP {status}"))
self.status, self.code, self.request_id = status, body.get("code"), body.get("request_id")
def takaelo(method: str, path: str, body: dict | None = None, idempotency_key: str | None = None) -> dict:
headers = {"Authorization": "Bearer " + os.environ["TAKAELO_SECRET_KEY"], "Content-Type": "application/json"}
if method == "POST":
headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4()) # same key on every retry
data = None if body is None else json.dumps(body).encode()
for attempt in range(4):
request = urllib.request.Request("https://api.takaelo.com/v1" + path, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)["data"]
except urllib.error.HTTPError as e:
status, retry_after = e.code, int(e.headers.get("Retry-After") or 0)
try:
error = json.load(e)
except ValueError:
error = {}
retryable = status == 429 or status >= 500 or error.get("code") == "IDEMPOTENCY_IN_PROGRESS"
if not retryable or attempt == 3:
raise TakaEloError(status, error) from None
time.sleep(retry_after or 2**attempt)
except urllib.error.URLError:
if attempt == 3:
raise
time.sleep(2**attempt) # network blip: resending is safe// Package takaelo is the whole client. Usage:
//
// var checkout struct{ ID, URL string }
// err := takaelo.Do(ctx, "POST", "/checkouts", map[string]any{"amount": 1250, "reference": "ORD-4821"}, "order-4821-1", &checkout)
package takaelo
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
)
// Error is a TakaElo error reply.
type Error struct {
Status int
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
func (e *Error) Error() string { return fmt.Sprintf("takaelo %d %s: %s", e.Status, e.Code, e.Message) }
var client = &http.Client{Timeout: 30 * time.Second}
// Do calls the API and decodes "data" into out. POSTs keep the same Idempotency-Key across retries.
func Do(ctx context.Context, method, path string, body any, idempotencyKey string, out any) error {
var payload []byte
if body != nil {
payload, _ = json.Marshal(body)
}
if method == http.MethodPost && idempotencyKey == "" {
b := make([]byte, 16)
rand.Read(b)
idempotencyKey = hex.EncodeToString(b)
}
for attempt := 0; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, method, "https://api.takaelo.com/v1"+path, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("TAKAELO_SECRET_KEY"))
req.Header.Set("Content-Type", "application/json")
if method == http.MethodPost {
req.Header.Set("Idempotency-Key", idempotencyKey)
}
res, err := client.Do(req)
if err != nil {
if attempt < 3 {
time.Sleep(time.Duration(1<<attempt) * time.Second) // network blip: resending is safe
continue
}
return err
}
var reply struct {
Success bool `json:"success"`
Data json.RawMessage `json:"data"`
Error
}
json.NewDecoder(res.Body).Decode(&reply)
res.Body.Close()
if reply.Success {
if out == nil {
return nil
}
return json.Unmarshal(reply.Data, out)
}
reply.Error.Status = res.StatusCode
retryable := res.StatusCode == 429 || res.StatusCode >= 500 || reply.Code == "IDEMPOTENCY_IN_PROGRESS"
if !retryable || attempt == 3 {
return &reply.Error
}
wait, _ := strconv.Atoi(res.Header.Get("Retry-After"))
if wait == 0 {
wait = 1 << attempt
}
time.Sleep(time.Duration(wait) * time.Second)
}
}# takaelo.rb β the whole client. Usage:
# checkout = TakaElo.request(:post, "/checkouts", { amount: 1250, reference: "ORD-4821" }, idempotency_key: "order-4821-1")
# payment = TakaElo.request(:get, "/payments/#{checkout["id"]}")
require "json"
require "net/http"
require "securerandom"
module TakaElo
class Error < StandardError
attr_reader :status, :code, :request_id
def initialize(status, body)
super(body["message"] || "HTTP #{status}")
@status, @code, @request_id = status, body["code"], body["request_id"]
end
end
def self.request(method, path, body = nil, idempotency_key: nil)
uri = URI("https://api.takaelo.com/v1#{path}")
headers = { "Authorization" => "Bearer #{ENV.fetch("TAKAELO_SECRET_KEY")}", "Content-Type" => "application/json" }
headers["Idempotency-Key"] = idempotency_key || SecureRandom.uuid if method == :post # same key on every retry
4.times do |attempt|
begin
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 30) do |http|
http.send_request(method.to_s.upcase, uri.request_uri, body&.to_json, headers)
end
rescue IOError, SystemCallError, Timeout::Error
raise if attempt == 3
sleep(2**attempt) # network blip: resending is safe
next
end
json = JSON.parse(response.body) rescue {}
return json["data"] if json["success"]
status = response.code.to_i
retryable = status == 429 || status >= 500 || json["code"] == "IDEMPOTENCY_IN_PROGRESS"
raise Error.new(status, json) if !retryable || attempt == 3
sleep((response["Retry-After"] || 2**attempt).to_i)
end
end
end// TakaElo.java β the whole client (Java 11+, Jackson). Usage:
// JsonNode checkout = TakaElo.call("POST", "/checkouts", Map.of("amount", 1250, "reference", "ORD-4821"), "order-4821-1");
// JsonNode payment = TakaElo.call("GET", "/payments/" + checkout.get("id").asText(), null, null);
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;
public final class TakaElo {
public static final class ApiException extends RuntimeException {
public final int status;
public final String code;
public final String requestId;
ApiException(int status, JsonNode body) {
super(body.path("message").asText("HTTP " + status));
this.status = status;
this.code = body.path("code").asText(null);
this.requestId = body.path("request_id").asText(null);
}
}
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private static final ObjectMapper JSON = new ObjectMapper();
public static JsonNode call(String method, String path, Object body, String idempotencyKey) throws IOException, InterruptedException {
String payload = body == null ? "" : JSON.writeValueAsString(body);
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create("https://api.takaelo.com/v1" + path))
.timeout(Duration.ofSeconds(30))
.header("Authorization", "Bearer " + System.getenv("TAKAELO_SECRET_KEY"))
.header("Content-Type", "application/json")
.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(payload));
if (method.equals("POST")) {
builder.header("Idempotency-Key", idempotencyKey != null ? idempotencyKey : UUID.randomUUID().toString()); // same key on every retry
}
HttpRequest request = builder.build();
for (int attempt = 0; ; attempt++) {
HttpResponse<String> response;
try {
response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
if (attempt == 3) throw e;
Thread.sleep(1000L << attempt); // network blip: resending is safe
continue;
}
JsonNode json;
try { json = JSON.readTree(response.body()); } catch (IOException e) { json = JSON.createObjectNode(); }
if (json.path("success").asBoolean()) return json.get("data");
int status = response.statusCode();
boolean retryable = status == 429 || status >= 500 || "IDEMPOTENCY_IN_PROGRESS".equals(json.path("code").asText());
if (!retryable || attempt == 3) throw new ApiException(status, json);
long wait = response.headers().firstValueAsLong("Retry-After").orElse(1L << attempt);
Thread.sleep(wait * 1000);
}
}
}// TakaElo.cs β the whole client (.NET 8+). Usage:
// var checkout = await TakaElo.CallAsync(HttpMethod.Post, "/checkouts", new { amount = 1250, reference = "ORD-4821" }, "order-4821-1");
// var payment = await TakaElo.CallAsync(HttpMethod.Get, $"/payments/{checkout.GetProperty("id")}");
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
public sealed class TakaEloException(int status, string? code, string message, string? requestId) : Exception(message)
{
public int Status { get; } = status;
public string? Code { get; } = code;
public string? RequestId { get; } = requestId;
}
public static class TakaElo
{
static readonly HttpClient Http = new() { BaseAddress = new Uri("https://api.takaelo.com/v1/"), Timeout = TimeSpan.FromSeconds(30) };
public static async Task<JsonElement> CallAsync(HttpMethod method, string path, object? body = null, string? idempotencyKey = null)
{
if (method == HttpMethod.Post) idempotencyKey ??= Guid.NewGuid().ToString(); // same key on every retry
for (var attempt = 0; ; attempt++)
{
using var request = new HttpRequestMessage(method, path.TrimStart('/'));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("TAKAELO_SECRET_KEY"));
if (idempotencyKey != null) request.Headers.Add("Idempotency-Key", idempotencyKey);
if (body != null) request.Content = JsonContent.Create(body);
HttpResponseMessage response;
try { response = await Http.SendAsync(request); }
catch (HttpRequestException) when (attempt < 3)
{
await Task.Delay(TimeSpan.FromSeconds(1 << attempt)); // network blip: resending is safe
continue;
}
using (response)
{
JsonElement json;
try { json = await response.Content.ReadFromJsonAsync<JsonElement>(); }
catch (JsonException) { json = JsonDocument.Parse("{}").RootElement; }
if (json.TryGetProperty("success", out var ok) && ok.GetBoolean()) return json.GetProperty("data");
var status = (int)response.StatusCode;
string? Field(string name) => json.TryGetProperty(name, out var v) ? v.GetString() : null;
var retryable = status == 429 || status >= 500 || Field("code") == "IDEMPOTENCY_IN_PROGRESS";
if (!retryable || attempt == 3) throw new TakaEloException(status, Field("code"), Field("message") ?? $"HTTP {status}", Field("request_id"));
var wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(1 << attempt);
await Task.Delay(wait);
}
}
}
}request_id. Send it with your question and we can see exactly what happened.