POST /api/v1/withdrawals and your own idempotency_key, sending the same body on every retry, so a retry never asks twice. 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: keep a limit and a pause.
Prerequisites
MART_API_KEY: your API key, with thewithdrawals:writescope.MART_API_BASE:https://sandbox.mart.pswhile you build,https://mart.pswhen you go live.- A saved payout method, in the panel or with
PUT /api/v1/payout-method: cash at the office, or bank transfer where Mart offers it. Withdrawals must also be enabled for your account. MART_WITHDRAW_AMOUNT: shekels, at most two decimals, no more thanavailable. It is sent as a decimal string, never rounded.MART_IDEMPOTENCY_KEY: your own name for this one request, up to 64 letters, digits, dots, underscores or hyphens.
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
# Ask Mart to pay out part of what is available, safely retried with the same idempotency key.
# Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at most two decimals) and
# MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is answered.
set -euo pipefail
export LC_NUMERIC=C # printf reads and writes amounts with a decimal point
idempotency_key=${MART_IDEMPOTENCY_KEY:?set MART_IDEMPOTENCY_KEY to your own name for this request}
# The amount as a decimal string, such as "125.50": exact, never rounded on the way.
request=$(jq -n --arg key "$idempotency_key" --arg amount "$MART_WITHDRAW_AMOUNT" '{amount: $amount, idempotency_key: $key}')
echo "idempotency key: $idempotency_key" # 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. The same key answers the original request, so a retry never asks twice.
for attempt in 1 2 3 4 5; do
response=$(curl --silent --show-error --max-time 30 --request POST \
--header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
--data "$request" --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE/api/v1/withdrawals") || 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_IDEMPOTENCY_KEY=$idempotency_key" >&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}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=$idempotency_key" >&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
jq -r '.data.withdrawal | "withdrawal: \(.withdrawal_id)\nstatus: \(.status)"' <<<"$body"
printf 'amount: %.2f ILS\n' "$(jq -r '.data.withdrawal.amount' <<<"$body")"
echo "replay: $(jq -r '.meta.idempotency_replay' <<<"$body")"
// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.
// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE, MART_API_KEY,
// MART_WITHDRAW_AMOUNT (shekels, at most two decimals) and MART_IDEMPOTENCY_KEY: your own name for
// this one request, kept until it is answered.
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
const idempotencyKey = process.env.MART_IDEMPOTENCY_KEY;
if (!base || !key || !idempotencyKey) throw new Error('Set MART_API_BASE, MART_API_KEY and MART_IDEMPOTENCY_KEY');
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: the same key answers the original request. The amount is a
// decimal string, such as "125.50": exact, never rounded on the way.
const request = JSON.stringify({ amount: String(process.env.MART_WITHDRAW_AMOUNT), idempotency_key: idempotencyKey });
console.log(`idempotency key: ${idempotencyKey}`); // written down before the first attempt
const response = await send('/api/v1/withdrawals', request, 30_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` : ''}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=${idempotencyKey}`);
process.exit(1);
}
if (!response.ok || body === null) {
console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}`);
process.exit(1);
}
console.log(`withdrawal: ${body.data.withdrawal.withdrawal_id}`);
console.log(`status: ${body.data.withdrawal.status}`);
console.log(`amount: ${body.data.withdrawal.amount.toFixed(2)} ILS`);
console.log(`replay: ${body.meta.idempotency_replay}`);
"""Ask Mart to pay out part of what is available, safely retried with the same idempotency key.
Python 3.9 or later, with httpx. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels,
at most two decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it
is answered.
"""
import os
import random
import sys
import time
import httpx
TIMEOUT = 30
client = httpx.Client(
base_url=os.environ["MART_API_BASE"],
headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
timeout=TIMEOUT,
)
idempotency_key = os.environ["MART_IDEMPOTENCY_KEY"]
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: the same key answers the original request. The amount is a
# decimal string, such as "125.50": exact, never rounded on the way.
request = {"amount": os.environ["MART_WITHDRAW_AMOUNT"], "idempotency_key": idempotency_key}
print(f"idempotency key: {idempotency_key}", flush=True) # written down before the first attempt
response = send("/api/v1/withdrawals", request)
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)}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY={idempotency_key}")
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)}")
withdrawal = body["data"]["withdrawal"]
print(f"withdrawal: {withdrawal['withdrawal_id']}")
print(f"status: {withdrawal['status']}")
print(f"amount: {withdrawal['amount']:.2f} ILS")
print(f"replay: {str(body['meta']['idempotency_replay']).lower()}")
<?php
// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.
// PHP 7.4 or later, with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT
// (shekels, at most two decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept
// until it is answered.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');
$idempotencyKey = (string) getenv('MART_IDEMPOTENCY_KEY');
if ($idempotencyKey === '') {
fwrite(STDERR, "error: set MART_IDEMPOTENCY_KEY to your own name for this request\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: the same key answers the original request. The amount is a
// decimal string, such as "125.50": exact, never rounded on the way.
$request = json_encode(['amount' => (string) getenv('MART_WITHDRAW_AMOUNT'), 'idempotency_key' => $idempotencyKey]);
echo "idempotency key: $idempotencyKey\n"; // written down before the first attempt
[$status, $headers, $raw] = send("$base/api/v1/withdrawals", $key, $request, 30);
if ($status === 0 || $status === 429 || $status >= 500) {
fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status) . when($headers) . "; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=$idempotencyKey\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);
}
$withdrawal = $body['data']['withdrawal'];
echo "withdrawal: {$withdrawal['withdrawal_id']}\n";
echo "status: {$withdrawal['status']}\n";
printf("amount: %.2f ILS\n", $withdrawal['amount']);
echo 'replay: ' . ($body['meta']['idempotency_replay'] ? 'true' : 'false') . "\n";
//go:build ignore
// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.
// Go 1.22 or later. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at most two
// decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is answered.
// Run it with: go run request-a-withdrawal.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"strconv"
"time"
)
var client = &http.Client{Timeout: 30 * time.Second}
func main() {
idempotencyKey := os.Getenv("MART_IDEMPOTENCY_KEY")
if idempotencyKey == "" {
fail(fmt.Errorf("set MART_IDEMPOTENCY_KEY to your own name for this request"))
}
// Decided once, before any attempt: the same key answers the original request. The amount is a
// decimal string, such as "125.50": exact, never rounded on the way.
request, err := json.Marshal(map[string]string{
"amount": os.Getenv("MART_WITHDRAW_AMOUNT"),
"idempotency_key": idempotencyKey,
})
if err != nil {
fail(err)
}
fmt.Println("idempotency key:", idempotencyKey) // written down before the first attempt
resp := send("/api/v1/withdrawals", request)
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; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=%s", status, idempotencyKey))
}
var answer struct {
Data struct {
Withdrawal struct {
ID string `json:"withdrawal_id"`
Status string `json:"status"`
Amount float64 `json:"amount"`
} `json:"withdrawal"`
} `json:"data"`
Meta struct {
IdempotencyReplay bool `json:"idempotency_replay"`
} `json:"meta"`
}
decode(resp, &answer)
fmt.Println("withdrawal:", answer.Data.Withdrawal.ID)
fmt.Println("status:", answer.Data.Withdrawal.Status)
fmt.Printf("amount: %.2f ILS\n", answer.Data.Withdrawal.Amount)
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)
}
// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.
// Java 17 or later, with Jackson. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at
// most two decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is
// answered. Run it as a single file: java -cp <the Jackson jars> request-a-withdrawal.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.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
class RequestAWithdrawal {
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 idempotencyKey = System.getenv("MART_IDEMPOTENCY_KEY");
if (idempotencyKey == null || idempotencyKey.isEmpty()) {
fail("set MART_IDEMPOTENCY_KEY to your own name for this request");
}
// Decided once, before any attempt: the same key answers the original request. The amount is a
// decimal string, such as "125.50": exact, never rounded on the way.
String payload = JSON.writeValueAsString(Map.of(
"amount", System.getenv("MART_WITHDRAW_AMOUNT"),
"idempotency_key", idempotencyKey));
HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/withdrawals"))
.header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(30))
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
System.out.println("idempotency key: " + idempotencyKey); // 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 + "; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=" + idempotencyKey);
}
JsonNode body = parse(response.body());
if (response.statusCode() >= 300 || body == null) {
fail(response.statusCode() + " " + code(body) + when(response));
}
JsonNode withdrawal = body.path("data").path("withdrawal");
System.out.println("withdrawal: " + withdrawal.path("withdrawal_id").asText());
System.out.println("status: " + withdrawal.path("status").asText());
System.out.printf(Locale.ROOT, "amount: %.2f ILS%n", withdrawal.path("amount").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("");
}
}
Verify the result
Run it twice with the same key and amount:idempotency key: wd-2026-11-01-001
withdrawal: MQ
status: requested
amount: <amount> ILS
replay: false
replay: true: the same request, not a second one. Mart reviews it before paying: see Payout and withdrawals.
Troubleshooting
| What you see | What to do |
|---|---|
403 withdrawals_disabled | Withdrawals are off for your account. Ask Mart. |
409 payout_method_missing | Save a payout method first. |
409 withdrawals_locked | Wait until details.locked_until. |
422 amount_below_minimum | Ask for at least details.minimum. |
409 insufficient_available | Ask for at most details.available. |
409 too_many_open_withdrawals | Wait for a request to finish, or cancel one still requested. |
422 bank_transfer_not_allowed | Bank transfer is no longer offered to you: save cash at the office, then ask again. |
403 cash_not_allowed | Cash is no longer offered to you: save a bank account where Mart offers it, or ask Mart. |
422 amount_above_cash_maximum | Ask for at most details.maximum, or switch to bank transfer. |
409 idempotency_conflict | This key was used with another amount. A new request needs a new key. |
422 invalid_amount | Shekels with at most two decimals, for example 125.50. |
503 withdrawal_busy | The recipe waits and sends the same request again. |
503 ledger_unavailable | Run it again later with the same key. |
| 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. |
