POST /api/v1/orders and sends the very same body, under the same partner_reference, on every retry, so a retry can never create a second order. After no answer, a 429 or a 5xx, it waits Retry-After, or 1, 2, 4, then 8 seconds with jitter, at most five times. Those numbers are the recipe’s choice: change them, but keep a limit and a pause.
The Next.js, FastAPI, Laravel and Spring forms take the reference from your own order_id. Never open such a route to your shop’s visitors: anyone who can call it places orders on your account. Each form refuses a call without the secret in INTERNAL_ROUTE_SECRET (sent as X-Internal-Secret); keep the route behind your app’s own authentication too. It returns the reference, the status and the replay flag, never the order’s money.
Prerequisites
MART_API_KEY: your API key, with theorders:writescope.MART_API_BASE:https://sandbox.mart.pswhile you build,https://mart.pswhen you go live.MART_PRODUCT_IDandMART_STATE_ID: a product your key is offered and a town’sstates[].id.MART_PARTNER_REFERENCE: your own id for this order, up to 64 letters, digits, dots, underscores or hyphens. Keep it with the order.
jq; Node 22.18 or later, which runs the .ts file as it is; Python 3.9 or later with httpx; PHP 7.4 or later with its curl extension; Go 1.22 or later; or Java 17 or later with Jackson (jackson-databind). Each file reads its variables from the environment and sets a timeout on every call. Run it on your own server: a browser or an app never holds the key.
Run the recipe
#!/usr/bin/env bash
# Create an order that survives a timeout: retry with the same partner_reference and read the replay.
# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and MART_PARTNER_REFERENCE:
# your own id for this order, from your own system, so that running this again can never make a
# second order.
set -euo pipefail
export LC_NUMERIC=C # printf reads and writes amounts with a decimal point
reference=${MART_PARTNER_REFERENCE:?set MART_PARTNER_REFERENCE to your own id for this order}
order=$(jq -n --arg ref "$reference" --argjson product "$MART_PRODUCT_ID" --argjson state "$MART_STATE_ID" '{
partner_reference: $ref,
payment_type: "cod",
products: [{product_id: $product, quantity: 1}],
shipping_address: {customer_name: "Test Buyer", phone: "0599000000", state_id: $state, address: "Main street 1"}
}')
echo "reference: $reference" # written down before the first attempt
# Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
# what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
# is final. Every attempt sends the SAME body, so a retry can never create a second order.
for attempt in 1 2 3 4 5; do
response=$(curl --silent --show-error --max-time 60 --request POST \
--header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
--data "$order" --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE/api/v1/orders") || response=$'\n000'
read -r status retry_after <<<"${response##*$'\n'}"
body=${response%$'\n'*}
case $status in 000 | 429 | 500 | 502 | 503 | 504) ;; *) break ;; esac
[ "$attempt" = 5 ] && break
if [[ $retry_after =~ ^[0-9]+$ ]]; then
if [ "$retry_after" -gt 60 ]; then
echo "error: $status, try again after $retry_after s with MART_PARTNER_REFERENCE=$reference" >&2
exit 1
fi
wait_ms=$((retry_after * 1000))
else
wait_ms=$((1000 << (attempt - 1)))
[ "$wait_ms" -gt 30000 ] && wait_ms=30000
wait_ms=$((wait_ms / 2 + RANDOM % (wait_ms / 2 + 1)))
fi
printf 'retry: attempt %d %s, waiting %d.%d s\n' "$attempt" \
"$([ "$status" = 000 ] && echo 'got no answer' || echo "answered $status")" $((wait_ms / 1000)) $((wait_ms % 1000 / 100)) >&2
sleep "$((wait_ms / 1000)).$(printf '%03d' $((wait_ms % 1000)))"
done
if [ "$status" = 000 ] || [ "$status" -ge 500 ] || [ "$status" = 429 ]; then
echo "error: ${status/000/no answer}${retry_after:+, try again after $retry_after s}; the order may exist: run again later with MART_PARTNER_REFERENCE=$reference" >&2
exit 1
fi
if [ "$status" -ge 300 ]; then
echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')" >&2
exit 1
fi
# 201: created now. 200 with meta.idempotency_replay true: this order already existed.
echo "order: $(jq -r '.data.order.partner_reference' <<<"$body")"
echo "status: $(jq -r '.data.order.status' <<<"$body")"
printf 'order total: %.2f\n' "$(jq -r '.data.order.order_total' <<<"$body")"
echo "replay: $(jq -r '.meta.idempotency_replay' <<<"$body")"
// Create an order that survives a timeout: retry with the same partner_reference and read the replay.
// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID,
// MART_STATE_ID and MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that
// running this again can never make a second order.
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
const reference = process.env.MART_PARTNER_REFERENCE;
if (!base || !key || !reference) throw new Error('Set MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE');
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
// what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
// is final. Every attempt sends the same bytes.
async function send(path: string, payload: string, timeoutMs: number): Promise<Response | null> {
for (let attempt = 1; ; attempt++) {
let response: Response | null = null;
try {
response = await fetch(`${base}${path}`, {
method: 'POST',
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
if (!RETRYABLE.has(response.status) || attempt === 5) return response;
} catch {
if (attempt === 5) return null; // no answer at all
}
let wait: number;
const retryAfter = Number(response?.headers.get('retry-after'));
if (response && Number.isInteger(retryAfter) && retryAfter > 0) {
if (retryAfter > 60) return response; // too long to wait here: the caller says when to come back
wait = retryAfter;
} else {
const backoff = Math.min(30, 2 ** (attempt - 1));
wait = backoff / 2 + (Math.random() * backoff) / 2;
}
console.error(`retry: attempt ${attempt} ${response ? `answered ${response.status}` : 'got no answer'}, waiting ${wait.toFixed(1)} s`);
await sleep(wait * 1000);
}
}
// Decided once, before any attempt: every retry sends this same body.
const order = JSON.stringify({
partner_reference: reference,
payment_type: 'cod',
products: [{ product_id: Number(process.env.MART_PRODUCT_ID), quantity: 1 }],
shipping_address: {
customer_name: 'Test Buyer',
phone: '0599000000',
state_id: Number(process.env.MART_STATE_ID),
address: 'Main street 1',
},
});
console.log(`reference: ${reference}`); // written down before the first attempt
const response = await send('/api/v1/orders', order, 60_000);
const body = response ? await response.json().catch(() => null) : null;
if (response === null || response.status === 429 || response.status >= 500) {
const when = response?.headers.get('retry-after');
console.error(`error: ${response ? response.status : 'no answer'}${when ? `, try again after ${when} s` : ''}; the order may exist: run again later with MART_PARTNER_REFERENCE=${reference}`);
process.exit(1);
}
if (!response.ok || body === null) {
console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}`);
process.exit(1);
}
// 201: created now. 200 with meta.idempotency_replay true: this order already existed.
console.log(`order: ${body.data.order.partner_reference}`);
console.log(`status: ${body.data.order.status}`);
console.log(`order total: ${body.data.order.order_total.toFixed(2)}`);
console.log(`replay: ${body.meta.idempotency_replay}`);
"""Create an order that survives a timeout: retry with the same partner_reference and read the replay.
Python 3.9 or later, with httpx. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and
MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that running this again
can never make a second order.
"""
import os
import random
import sys
import time
import httpx
TIMEOUT = 60
client = httpx.Client(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=TIMEOUT,
)
reference = os.environ["MART_PARTNER_REFERENCE"]
def body_of(response: httpx.Response):
"""The JSON body, or None for an answer that is not JSON (an edge error page)."""
try:
return response.json()
except ValueError:
return None
RETRYABLE = {429, 500, 502, 503, 504}
def send(path: str, payload: dict):
"""POST the same payload until it is answered for good.
Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
is final. Returns None when no attempt got an answer.
"""
for attempt in range(1, 6):
response = None
try:
response = client.post(path, json=payload)
if response.status_code not in RETRYABLE or attempt == 5:
return response
except httpx.TransportError:
if attempt == 5:
return None
retry_after = response.headers.get("Retry-After", "") if response is not None else ""
if retry_after.isdigit() and int(retry_after) > 0:
if int(retry_after) > 60:
return response # too long to wait here: the caller says when to come back
wait = float(retry_after)
else:
backoff = min(30, 2 ** (attempt - 1))
wait = backoff / 2 + random.uniform(0, backoff / 2)
what = f"answered {response.status_code}" if response is not None else "got no answer"
print(f"retry: attempt {attempt} {what}, waiting {wait:.1f} s", file=sys.stderr)
time.sleep(wait)
def when(response) -> str:
"""", try again after N s" when the answer says how long to wait (Retry-After), else nothing."""
retry_after = response.headers.get("Retry-After") if response is not None else None
return f", try again after {retry_after} s" if retry_after else ""
# Decided once, before any attempt: every retry sends this same body.
order = {
"partner_reference": reference,
"payment_type": "cod",
"products": [{"product_id": int(os.environ["MART_PRODUCT_ID"]), "quantity": 1}],
"shipping_address": {
"customer_name": "Test Buyer",
"phone": "0599000000",
"state_id": int(os.environ["MART_STATE_ID"]),
"address": "Main street 1",
},
}
print(f"reference: {reference}", flush=True) # written down before the first attempt
response = send("/api/v1/orders", order)
if response is None or response.status_code == 429 or response.status_code >= 500:
status = response.status_code if response is not None else "no answer"
sys.exit(f"error: {status}{when(response)}; the order may exist: run again later with MART_PARTNER_REFERENCE={reference}")
body = body_of(response)
if response.is_error or body is None:
sys.exit(f"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}{when(response)}")
# 201: created now. 200 with meta.idempotency_replay true: this order already existed.
created = body["data"]["order"]
print(f"order: {created['partner_reference']}")
print(f"status: {created['status']}")
print(f"order total: {created['order_total']:.2f}")
print(f"replay: {str(body['meta']['idempotency_replay']).lower()}")
<?php
// Create an order that survives a timeout: retry with the same partner_reference and read the replay.
// PHP 7.4 or later, with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID,
// MART_STATE_ID and MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that
// running this again can never make a second order.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');
$reference = (string) getenv('MART_PARTNER_REFERENCE');
if ($reference === '') {
fwrite(STDERR, "error: set MART_PARTNER_REFERENCE to your own id for this order\n");
exit(1);
}
/**
* One request with the curl extension. Returns [status, headers (lower-case name => value), body];
* status 0 when there was no answer at all.
*/
function request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array
{
$headers = [];
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
$parts = explode(':', $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($payload !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
}
$body = curl_exec($curl);
$status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
return [$status, $headers, (string) $body];
}
/** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
function when(array $headers): string
{
return isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
}
/**
* POST the same payload until it is answered for good. Retries are your choice of numbers: at most
* 5 attempts; after no answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8
* seconds (capped at 30) with jitter. Any other answer is final.
*/
function send(string $url, string $key, string $payload, int $timeout): array
{
for ($attempt = 1; ; $attempt++) {
[$status, $headers, $raw] = request('POST', $url, $key, $payload, $timeout);
if (!in_array($status, [0, 429, 500, 502, 503, 504], true) || $attempt === 5) {
return [$status, $headers, $raw];
}
$retryAfter = $headers['retry-after'] ?? '';
if (ctype_digit($retryAfter) && (int) $retryAfter > 0) {
if ((int) $retryAfter > 60) {
return [$status, $headers, $raw]; // too long to wait here: the caller says when to come back
}
$wait = (float) $retryAfter;
} else {
$backoff = min(30, 2 ** ($attempt - 1));
$wait = $backoff / 2 + mt_rand() / mt_getrandmax() * $backoff / 2;
}
fwrite(STDERR, sprintf("retry: attempt %d %s, waiting %.1f s\n", $attempt, $status === 0 ? 'got no answer' : "answered $status", $wait));
usleep((int) ($wait * 1000000));
}
}
// Decided once, before any attempt: every retry sends this same body.
$order = json_encode([
'partner_reference' => $reference,
'payment_type' => 'cod',
'products' => [['product_id' => (int) getenv('MART_PRODUCT_ID'), 'quantity' => 1]],
'shipping_address' => [
'customer_name' => 'Test Buyer',
'phone' => '0599000000',
'state_id' => (int) getenv('MART_STATE_ID'),
'address' => 'Main street 1',
],
]);
echo "reference: $reference\n"; // written down before the first attempt
[$status, $headers, $raw] = send("$base/api/v1/orders", $key, $order, 60);
if ($status === 0 || $status === 429 || $status >= 500) {
fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status) . when($headers) . "; the order may exist: run again later with MART_PARTNER_REFERENCE=$reference\n");
exit(1);
}
$body = json_decode($raw, true);
if ($status >= 300 || !is_array($body)) {
fwrite(STDERR, "error: $status " . ($body['error']['code'] ?? '(not JSON)') . when($headers) . "\n");
exit(1);
}
// 201: created now. 200 with meta.idempotency_replay true: this order already existed.
echo "order: {$body['data']['order']['partner_reference']}\n";
echo "status: {$body['data']['order']['status']}\n";
printf("order total: %.2f\n", $body['data']['order']['order_total']);
echo 'replay: ' . ($body['meta']['idempotency_replay'] ? 'true' : 'false') . "\n";
//go:build ignore
// Create an order that survives a timeout: retry with the same partner_reference and read the replay.
// Go 1.22 or later. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and
// MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that running this again
// can never make a second order. Run it with: go run create-an-order.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"strconv"
"time"
)
var client = &http.Client{Timeout: 60 * time.Second}
func main() {
reference := os.Getenv("MART_PARTNER_REFERENCE")
if reference == "" {
fail(fmt.Errorf("set MART_PARTNER_REFERENCE to your own id for this order"))
}
productID, _ := strconv.Atoi(os.Getenv("MART_PRODUCT_ID"))
stateID, _ := strconv.Atoi(os.Getenv("MART_STATE_ID"))
// Decided once, before any attempt: every retry sends these same bytes.
order, err := json.Marshal(map[string]any{
"partner_reference": reference,
"payment_type": "cod",
"products": []map[string]any{{"product_id": productID, "quantity": 1}},
"shipping_address": map[string]any{
"customer_name": "Test Buyer", "phone": "0599000000", "state_id": stateID, "address": "Main street 1",
},
})
if err != nil {
fail(err)
}
fmt.Println("reference:", reference) // written down before the first attempt
resp := send("/api/v1/orders", order)
if resp == nil || resp.StatusCode == 429 || resp.StatusCode >= 500 {
status := "no answer"
if resp != nil {
status = strconv.Itoa(resp.StatusCode)
if after := resp.Header.Get("Retry-After"); after != "" {
status += ", try again after " + after + " s"
}
}
fail(fmt.Errorf("%s; the order may exist: run again later with MART_PARTNER_REFERENCE=%s", status, reference))
}
var answer struct {
Data struct {
Order struct {
PartnerReference string `json:"partner_reference"`
Status string `json:"status"`
OrderTotal float64 `json:"order_total"`
} `json:"order"`
} `json:"data"`
Meta struct {
IdempotencyReplay bool `json:"idempotency_replay"`
} `json:"meta"`
}
decode(resp, &answer)
// 201: created now. 200 with meta.idempotency_replay true: this order already existed.
fmt.Println("order:", answer.Data.Order.PartnerReference)
fmt.Println("status:", answer.Data.Order.Status)
fmt.Printf("order total: %.2f\n", answer.Data.Order.OrderTotal)
fmt.Println("replay:", answer.Meta.IdempotencyReplay)
}
var retryable = map[int]bool{429: true, 500: true, 502: true, 503: true, 504: true}
// send POSTs the same bytes until they are answered for good, and returns the last answer, or
// nil when no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no
// answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)
// with jitter. Any other answer is final.
func send(path string, payload []byte) *http.Response {
for attempt := 1; ; attempt++ {
req, err := http.NewRequest(http.MethodPost, os.Getenv("MART_API_BASE")+path, bytes.NewReader(payload))
if err != nil {
fail(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil && attempt == 5 {
return nil
}
if err == nil && (!retryable[resp.StatusCode] || attempt == 5) {
return resp
}
what := "got no answer"
backoff := math.Min(30, math.Pow(2, float64(attempt-1)))
wait := backoff/2 + rand.Float64()*backoff/2
if err == nil {
what = fmt.Sprintf("answered %d", resp.StatusCode)
if seconds, convErr := strconv.Atoi(resp.Header.Get("Retry-After")); convErr == nil && seconds > 0 {
if seconds > 60 {
return resp // too long to wait here: the caller says when to come back
}
wait = float64(seconds)
}
resp.Body.Close()
}
fmt.Fprintf(os.Stderr, "retry: attempt %d %s, waiting %.1f s\n", attempt, what, wait)
time.Sleep(time.Duration(wait * float64(time.Second)))
}
}
// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
fail(err)
}
var envelope struct {
Error *struct {
Code string `json:"code"`
} `json:"error"`
}
if resp.StatusCode >= 300 {
code := "(not JSON)"
if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
code = envelope.Error.Code
}
wait := ""
if after := resp.Header.Get("Retry-After"); after != "" {
wait = ", try again after " + after + " s"
}
fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
}
if err := json.Unmarshal(raw, out); err != nil {
fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
}
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
// Create an order that survives a timeout: retry with the same partner_reference and read the replay.
// Java 17 or later, with Jackson. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and
// MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that running this again
// can never make a second order. Run it as a single file: java -cp <the Jackson jars> create-an-order.java
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.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
class CreateAnOrder {
static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
String reference = System.getenv("MART_PARTNER_REFERENCE");
if (reference == null || reference.isEmpty()) {
fail("set MART_PARTNER_REFERENCE to your own id for this order");
}
// Decided once, before any attempt: every retry sends this same body.
String order = JSON.writeValueAsString(Map.of(
"partner_reference", reference,
"payment_type", "cod",
"products", List.of(Map.of("product_id", Integer.parseInt(System.getenv("MART_PRODUCT_ID")), "quantity", 1)),
"shipping_address", Map.of("customer_name", "Test Buyer", "phone", "0599000000",
"state_id", Integer.parseInt(System.getenv("MART_STATE_ID")), "address", "Main street 1")));
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/orders"))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofString(order))
.build();
System.out.println("reference: " + reference); // written down before the first attempt
HttpResponse<String> response = send(request);
if (response == null || response.statusCode() == 429 || response.statusCode() >= 500) {
String status = response == null ? "no answer" : response.statusCode() + when(response);
fail(status + "; the order may exist: run again later with MART_PARTNER_REFERENCE=" + reference);
}
JsonNode body = parse(response.body());
if (response.statusCode() >= 300 || body == null) {
fail(response.statusCode() + " " + code(body) + when(response));
}
// 201: created now. 200 with meta.idempotency_replay true: this order already existed.
JsonNode created = body.path("data").path("order");
System.out.println("order: " + created.path("partner_reference").asText());
System.out.println("status: " + created.path("status").asText());
System.out.printf(Locale.ROOT, "order total: %.2f%n", created.path("order_total").asDouble());
System.out.println("replay: " + body.path("meta").path("idempotency_replay").asBoolean());
}
static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);
/**
* Sends the same request until it is answered for good, and returns the last answer, or null when
* no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no answer, a
* 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter.
* Any other answer is final.
*/
static HttpResponse<String> send(HttpRequest request) throws InterruptedException {
for (int attempt = 1; ; attempt++) {
HttpResponse<String> response = null;
try {
response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
if (!RETRYABLE.contains(response.statusCode()) || attempt == 5) {
return response;
}
} catch (IOException e) {
if (attempt == 5) {
return null;
}
}
double backoff = Math.min(30, Math.pow(2, attempt - 1));
double wait = backoff / 2 + ThreadLocalRandom.current().nextDouble() * backoff / 2;
String what = "got no answer";
if (response != null) {
what = "answered " + response.statusCode();
String after = response.headers().firstValue("Retry-After").orElse("");
if (after.matches("[0-9]+") && Long.parseLong(after) > 0) {
if (Long.parseLong(after) > 60) {
return response; // too long to wait here: the caller says when to come back
}
wait = Long.parseLong(after);
}
}
System.err.printf(Locale.ROOT, "retry: attempt %d %s, waiting %.1f s%n", attempt, what, wait);
Thread.sleep((long) (wait * 1000));
}
}
/** The JSON body, or null for an answer that is not JSON (an edge error page). */
static JsonNode parse(String text) {
try {
return JSON.readTree(text);
} catch (IOException e) {
return null;
}
}
static void fail(String message) {
System.err.println("error: " + message);
System.exit(1);
}
static String code(JsonNode body) {
return body == null ? "(not JSON)" : body.path("error").path("code").asText();
}
/** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
static String when(HttpResponse<String> response) {
return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
}
}
// app/api/orders/route.ts: place the Mart order for one of your own orders, safe to retry.
// NEVER OPEN TO YOUR SHOP'S VISITORS: anyone who can call it places cash-on-delivery orders on your
// account. Call it from your own server code (your checkout, once an order is confirmed), never from
// a browser. It refuses any call without the secret in INTERNAL_ROUTE_SECRET (sent as the
// X-Internal-Secret header); put it behind your app's own authentication as well.
// POST {"order_id": "your-order-id", "product_id": 123, "quantity": 1, "customer_name": "...",
// "phone": "...", "state_id": 45, "address": "..."}. Needs MART_API_BASE and MART_API_KEY.
import { NextResponse } from 'next/server';
import { createHash, timingSafeEqual } from 'node:crypto';
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
/** The caller holds the secret, compared in constant time. No secret configured: nobody does. */
function authorised(request: Request): boolean {
const secret = process.env.INTERNAL_ROUTE_SECRET;
if (!secret) return false;
const given = createHash('sha256').update(request.headers.get('x-internal-secret') ?? '').digest();
return timingSafeEqual(given, createHash('sha256').update(secret).digest());
}
export async function POST(request: Request) {
if (!authorised(request)) {
return NextResponse.json({ error: 'unauthorised' }, { status: 401 });
}
const input = await request.json().catch(() => ({}));
// Your own order id is the partner_reference: never made up here, the same on every attempt.
if (typeof input.order_id !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(input.order_id)) {
return NextResponse.json({ error: 'order_id is required: your own id for this order' }, { status: 422 });
}
const order = JSON.stringify({
partner_reference: input.order_id,
payment_type: 'cod',
products: [{ product_id: Number(input.product_id), quantity: Number(input.quantity ?? 1) }],
shipping_address: {
customer_name: String(input.customer_name ?? ''),
phone: String(input.phone ?? ''),
state_id: Number(input.state_id),
address: String(input.address ?? ''),
},
});
// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
// what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
// is final. The same partner_reference means a retry can never create a second order.
for (let attempt = 1; ; attempt++) {
let response: Response | null = null;
try {
response = await fetch(`${base}/api/v1/orders`, {
method: 'POST',
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: order,
signal: AbortSignal.timeout(60_000),
cache: 'no-store',
});
} catch {
response = null;
}
const retryAfter = Number(response?.headers.get('retry-after'));
const retry = (response === null || RETRYABLE.has(response.status)) && attempt < 5 && !(retryAfter > 60);
if (!retry) {
if (response === null || response.status === 429 || response.status >= 500) {
// The order may exist: send the same order_id again later, after Retry-After when Mart gave one.
const after = response?.headers.get('retry-after');
return NextResponse.json({ error: 'mart_unavailable', order_id: input.order_id }, { status: 503, headers: after ? { 'Retry-After': after } : {} });
}
const body = await response.json().catch(() => null);
if (response.status >= 300 || body === null) {
return NextResponse.json({ error: body?.error?.code ?? 'unavailable' }, { status: response.status === 422 ? 422 : 502 });
}
// What your server needs, and nothing of your money. replay true: this order already existed.
return NextResponse.json({
partner_reference: body.data.order.partner_reference,
status: body.data.order.status,
replay: body.meta.idempotency_replay,
});
}
const backoff = Math.min(30, 2 ** (attempt - 1));
const wait = Number.isInteger(retryAfter) && retryAfter > 0 ? retryAfter : backoff / 2 + (Math.random() * backoff) / 2;
await sleep(wait * 1000);
}
}
"""Place the Mart order for one of your own orders, safe to retry.
NEVER OPEN TO YOUR SHOP'S VISITORS: anyone who can call it places cash-on-delivery orders on your
account. Call it from your own server code (your checkout, once an order is confirmed), never from a
browser. It refuses any call without the secret in INTERNAL_ROUTE_SECRET (sent as the
X-Internal-Secret header); put it behind your app's own authentication as well.
POST /orders with your order id, the product and the delivery address. Run: uvicorn create_an_order:app
Needs MART_API_BASE and MART_API_KEY in the server's environment.
"""
import asyncio
import hmac
import os
import random
import httpx
from fastapi import Depends, FastAPI, Header, HTTPException
from pydantic import BaseModel, Field
app = FastAPI()
mart = httpx.AsyncClient(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=60,
)
RETRYABLE = {429, 500, 502, 503, 504}
def json_of(response: httpx.Response) -> dict:
"""The JSON body, or a 502 for an answer that is not JSON (an edge error page)."""
try:
return response.json()
except ValueError:
raise HTTPException(502, "Mart answered with something that is not JSON")
def require_secret(x_internal_secret: str = Header(default="")) -> None:
"""The caller holds the secret, compared in constant time. No secret configured: nobody does."""
secret = os.environ.get("INTERNAL_ROUTE_SECRET", "")
if not secret or not hmac.compare_digest(x_internal_secret.encode(), secret.encode()):
raise HTTPException(401, "unauthorised")
class OrderRequest(BaseModel):
order_id: str = Field(pattern=r"^[A-Za-z0-9._-]{1,64}$") # your own id for this order
product_id: int
quantity: int = 1
customer_name: str
phone: str
state_id: int
address: str
@app.post("/orders", dependencies=[Depends(require_secret)])
async def create_order(request: OrderRequest) -> dict:
# Your own order id is the partner_reference: never made up here, the same on every attempt.
order = {
"partner_reference": request.order_id,
"payment_type": "cod",
"products": [{"product_id": request.product_id, "quantity": request.quantity}],
"shipping_address": {
"customer_name": request.customer_name,
"phone": request.phone,
"state_id": request.state_id,
"address": request.address,
},
}
# Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
# what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
# is final. The same partner_reference means a retry can never create a second order.
response = None
for attempt in range(1, 6):
try:
response = await mart.post("/api/v1/orders", json=order)
except httpx.TransportError:
response = None
retry_after = response.headers.get("Retry-After", "") if response is not None else ""
too_long = retry_after.isdigit() and int(retry_after) > 60
if (response is not None and response.status_code not in RETRYABLE) or attempt == 5 or too_long:
break
if retry_after.isdigit() and int(retry_after) > 0:
wait = float(retry_after)
else:
backoff = min(30, 2 ** (attempt - 1))
wait = backoff / 2 + random.uniform(0, backoff / 2)
await asyncio.sleep(wait)
if response is None or response.status_code == 429 or response.status_code >= 500:
# The order may exist: send the same order_id again later, after Retry-After when Mart gave one.
after = response.headers.get("Retry-After") if response is not None else None
raise HTTPException(503, f"Mart did not answer; send order {request.order_id} again later",
headers={"Retry-After": after} if after else None)
if response.is_error:
raise HTTPException(422 if response.status_code == 422 else 502, "order refused")
body = json_of(response)
# What your server needs, and nothing of your money. replay true: this order already existed.
return {
"partner_reference": body["data"]["order"]["partner_reference"],
"status": body["data"]["order"]["status"],
"replay": body["meta"]["idempotency_replay"],
}
<?php
// app/Http/Controllers/MartOrderController.php: place the Mart order for one of your own orders, safe to retry.
// NEVER OPEN TO YOUR SHOP'S VISITORS: anyone who can call it places cash-on-delivery orders on your
// account. Call it from your own server code (your checkout, once an order is confirmed), never from a
// browser. It refuses any call without the secret in INTERNAL_ROUTE_SECRET (sent as the
// X-Internal-Secret header); put it behind your app's own authentication as well.
// routes/api.php: Route::post('/mart/orders', MartOrderController::class);
// config/services.php: 'mart' => ['base' => env('MART_API_BASE'), 'key' => env('MART_API_KEY'),
// 'route_secret' => env('INTERNAL_ROUTE_SECRET')],
namespace App\Http\Controllers;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Throwable;
class MartOrderController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
// The caller holds the secret, compared in constant time. No secret configured: nobody does.
$secret = (string) config('services.mart.route_secret');
if ($secret === '' || ! hash_equals($secret, (string) $request->header('X-Internal-Secret'))) {
return response()->json(['error' => 'unauthorised'], 401);
}
$input = $request->validate([
'order_id' => ['required', 'string', 'regex:/^[A-Za-z0-9._-]{1,64}$/'], // your own id for this order
'product_id' => 'required|integer',
'quantity' => 'integer|min:1',
'customer_name' => 'required|string',
'phone' => 'required|string',
'state_id' => 'required|integer',
'address' => 'required|string',
]);
// Your own order id is the partner_reference: never made up here, the same on every attempt.
$order = [
'partner_reference' => $input['order_id'],
'payment_type' => 'cod',
'products' => [['product_id' => (int) $input['product_id'], 'quantity' => (int) ($input['quantity'] ?? 1)]],
'shipping_address' => [
'customer_name' => $input['customer_name'],
'phone' => $input['phone'],
'state_id' => (int) $input['state_id'],
'address' => $input['address'],
],
];
try {
// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx,
// wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any
// other answer is final. The same partner_reference can never create a second order.
$response = Http::withToken(config('services.mart.key'))
->timeout(60)
->retry(5, function (int $attempt, Throwable $e): int {
$after = $e instanceof RequestException ? (string) $e->response->header('Retry-After') : '';
if (ctype_digit($after) && (int) $after > 0) {
return (int) $after * 1000;
}
$backoff = min(30, 2 ** ($attempt - 1));
return (int) (($backoff / 2 + mt_rand() / mt_getrandmax() * $backoff / 2) * 1000);
}, function (Throwable $e): bool {
if ($e instanceof ConnectionException) {
return true;
}
if (! $e instanceof RequestException) {
return false;
}
$after = (string) $e->response->header('Retry-After');
return in_array($e->response->status(), [429, 500, 502, 503, 504], true) && ! (ctype_digit($after) && (int) $after > 60);
}, throw: false)
->post(config('services.mart.base').'/api/v1/orders', $order);
} catch (ConnectionException $e) {
$response = null;
}
if ($response === null || $response->status() === 429 || $response->serverError()) {
// The order may exist: send the same order_id again later, after Retry-After when Mart gave one.
$after = $response?->header('Retry-After');
return response()->json(['error' => 'mart_unavailable', 'order_id' => $input['order_id']], 503, $after ? ['Retry-After' => $after] : []);
}
if ($response->failed()) {
return response()->json(['error' => $response->json('error.code')], $response->status() === 422 ? 422 : 502);
}
// What your server needs, and nothing of your money. replay true: this order already existed.
return response()->json([
'partner_reference' => $response->json('data.order.partner_reference'),
'status' => $response->json('data.order.status'),
'replay' => $response->json('meta.idempotency_replay'),
]);
}
}
package com.example.martrecipes;
import com.fasterxml.jackson.databind.JsonNode;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClient;
/**
* Place the Mart order for one of your own orders, safe to retry. NEVER OPEN TO YOUR SHOP'S VISITORS:
* anyone who can call it places cash-on-delivery orders on your account. Call it from your own server
* code (your checkout, once an order is confirmed), never from a browser. It refuses any call without
* the secret in INTERNAL_ROUTE_SECRET (sent as the X-Internal-Secret header); put it behind your app's
* own authentication (Spring Security) as well. POST /mart/orders with your order id, the product and
* the delivery address.
*/
@RestController
public class OrderController {
record OrderRequest(String order_id, Integer product_id, Integer quantity, String customer_name, String phone,
Integer state_id, String address) {}
private static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);
private final RestClient mart;
private final String secret;
// MART_API_BASE and MART_API_KEY come from the environment; every call has a timeout.
public OrderController(@Value("${MART_API_BASE}") String base, @Value("${MART_API_KEY}") String key,
@Value("${INTERNAL_ROUTE_SECRET:}") String secret) {
SimpleClientHttpRequestFactory timeouts = new SimpleClientHttpRequestFactory();
timeouts.setConnectTimeout(Duration.ofSeconds(10));
timeouts.setReadTimeout(Duration.ofSeconds(60));
this.mart = RestClient.builder()
.baseUrl(base)
.defaultHeader("Authorization", "Bearer " + key)
.requestFactory(timeouts)
.build();
this.secret = secret;
}
/** The caller holds the secret, compared in constant time. No secret configured: nobody does. */
private boolean authorised(String given) {
return !secret.isEmpty() && given != null
&& MessageDigest.isEqual(given.getBytes(StandardCharsets.UTF_8), secret.getBytes(StandardCharsets.UTF_8));
}
@PostMapping("/mart/orders")
public ResponseEntity<Object> create(@RequestHeader(name = "X-Internal-Secret", required = false) String given,
@RequestBody OrderRequest input) throws InterruptedException {
if (!authorised(given)) {
return ResponseEntity.status(401).body(Map.of("error", "unauthorised"));
}
// Your own order id is the partner_reference: never made up here, the same on every attempt.
if (input.order_id() == null || !input.order_id().matches("[A-Za-z0-9._-]{1,64}") || input.product_id() == null
|| input.state_id() == null || input.customer_name() == null || input.phone() == null || input.address() == null) {
return ResponseEntity.status(422).body(Map.of("error", "order_id, product_id, customer_name, phone, state_id and address are required"));
}
Map<String, Object> order = Map.of(
"partner_reference", input.order_id(),
"payment_type", "cod",
"products", List.of(Map.of("product_id", input.product_id(), "quantity", input.quantity() == null ? 1 : input.quantity())),
"shipping_address", Map.of("customer_name", input.customer_name(), "phone", input.phone(),
"state_id", input.state_id(), "address", input.address()));
// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait
// what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer
// is final. The same partner_reference means a retry can never create a second order.
ResponseEntity<JsonNode> response = null;
for (int attempt = 1; ; attempt++) {
try {
response = mart.post().uri("/api/v1/orders").body(order).retrieve()
.onStatus(HttpStatusCode::isError, (request, answer) -> {})
.toEntity(JsonNode.class);
} catch (RestClientException e) {
response = null; // no answer, or one that is not JSON: the same order is sent again
}
String after = response == null ? "" : String.valueOf(response.getHeaders().getFirst("Retry-After"));
boolean tooLong = after.matches("[0-9]+") && Long.parseLong(after) > 60;
if ((response != null && !RETRYABLE.contains(response.getStatusCode().value())) || attempt == 5 || tooLong) {
break;
}
double backoff = Math.min(30, Math.pow(2, attempt - 1));
double wait = after.matches("[0-9]+") && Long.parseLong(after) > 0 ? Long.parseLong(after)
: backoff / 2 + ThreadLocalRandom.current().nextDouble() * backoff / 2;
Thread.sleep((long) (wait * 1000));
}
if (response == null || response.getStatusCode().value() == 429 || response.getStatusCode().is5xxServerError()) {
// The order may exist: send the same order_id again later, after Retry-After when Mart gave one.
String after = response == null ? null : response.getHeaders().getFirst("Retry-After");
return ResponseEntity.status(503).header("Retry-After", after == null ? new String[0] : new String[] {after})
.body(Map.of("error", "mart_unavailable", "order_id", input.order_id()));
}
JsonNode body = response.getBody();
if (response.getStatusCode().isError() || body == null) {
return ResponseEntity.status(response.getStatusCode().value() == 422 ? 422 : 502).body(Map.of("error", "order refused"));
}
// What your server needs, and nothing of your money. replay true: this order already existed.
return ResponseEntity.ok(Map.of(
"partner_reference", body.path("data").path("order").path("partner_reference").asText(),
"status", body.path("data").path("order").path("status").asText(),
"replay", body.path("meta").path("idempotency_replay").asBoolean()));
}
}
Verify the result
Run it twice with the sameMART_PARTNER_REFERENCE:
reference: 100245
order: 100245
status: processing
order total: <amount>
replay: false
replay: true: the same order, as a retry after a lost answer receives it. A retry first prints a line on stderr, for example retry: attempt 1 answered 429, waiting 2.0 s.
Troubleshooting
| What you see | What to do |
|---|---|
409 idempotency_conflict | The reference already names a different order. Give each order its own reference. |
422 with a product or address code | Nothing was created. Fix what error.code names, then run it again with the same reference. |
422 orders_not_enabled | Ask Mart to enable orders for your key. |
error: no answer or a 5xx after the last attempt | The order may exist. Run it again later with the same MART_PARTNER_REFERENCE, never a new one. |
| Any recipe | What to do |
|---|---|
401 missing_api_key or invalid_api_key | Check that MART_API_KEY holds the whole key. A key still refused needs a replacement from Mart. |
401 key_environment_mismatch | Point MART_API_BASE at the environment that issued the key. |
403 insufficient_scope | Ask Mart to add the scope in details.required_scope. |
429 rate_limit_exceeded | Wait the Retry-After the error line shows, then run it again. |
error: no answer, or a timeout | Check MART_API_BASE and your network. |
error: with (not JSON) | A proxy or firewall answered, not the API. Check MART_API_BASE and your network. |
