{
  "openapi": "3.0.3",
  "info": {
    "title": "Mart Partner API",
    "version": "1.1.0",
    "description": "REST API for Mart reseller partners: the product catalog (with per-product and per-combination stock), delivery destinations, and order creation — cash on delivery or card.\n\nEvery response, success or failure, uses the envelope `{status, status_code, message, data, meta, error}`; branch on `error.code`, never on `message`. Response keys are structurally stable: absent objects are `null`, absent collections are `[]`; the only caller-controlled structural variance is the products listing's `include=` parameter.\n\nAuthenticate with `Authorization: Bearer <key>` (preferred) or `X-Api-Key`. A key holds scopes, each operation names the one it needs in `x-required-scope`, and a key without it is answered `403` `insufficient_scope` (`details.required_scope` names it) without using any quota; keys made before scopes existed keep exactly the access they had. Rate limits are per key on fixed minute/day windows; the `X-RateLimit-*` headers are authoritative.\n\n**Environments** — build against the sandbox first. `https://sandbox.mart.ps` is a separate installation with its own keys (`mk_test_…`), a periodically refreshed copy of the catalog, synthetic customers and orders, and Lahza's test gateway: nothing placed there is fulfilled or charged, and its data is reset on a published schedule. Production keys are `mk_live_…` and work only against `https://mart.ps`; a key sent to the wrong environment answers `401` `key_environment_mismatch` before anything else is checked. Every response carries `X-Mart-Environment: production|sandbox` — assert it in your client so a misconfigured base URL fails loudly.\n\nThis document is the machine contract. The human documentation — onboarding, sync guidance, pricing semantics, idempotent retries, the full error catalogue with remedies — is at https://mart.ps/api/docs."
  },
  "servers": [
    {
      "url": "https://mart.ps",
      "description": "Production"
    },
    {
      "url": "https://sandbox.mart.ps",
      "description": "Sandbox"
    }
  ],
  "security": [
    {
      "bearerAuth": []
    },
    {
      "apiKeyHeader": []
    }
  ],
  "paths": {
    "/api/v1/products": {
      "get": {
        "summary": "List products",
        "description": "One page of the catalog, priced for your account, with stock and combinations on every row. Returns both active and inactive products (each row carries `status`); zero-stock rows remain with `in_stock: false`. Sync guidance — including why incremental syncs can never detect price changes: https://mart.ps/api/docs#catalog.",
        "tags": [
          "Products"
        ],
        "operationId": "listProducts",
        "x-required-scope": "catalog:read",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Default 500, maximum 1000 (both back-office configurable).",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 1000,
              "default": 500
            }
          },
          {
            "name": "include",
            "in": "query",
            "description": "Comma-separated opt-in heavy fields. Supported: `description` (adds description and description_short to every item — same content as the detail endpoint). Unknown values return 422.",
            "schema": {
              "type": "string",
              "example": "description"
            }
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "active",
                "inactive",
                "all"
              ],
              "default": "all"
            }
          },
          {
            "name": "updated_after",
            "in": "query",
            "description": "ISO 8601 datetime; filters on the product's last edit time (`date_upd`).",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "example": "2026-07-01T00:00:00+03:00"
          },
          {
            "name": "in_stock",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "true",
                "false"
              ]
            }
          },
          {
            "name": "category_id",
            "in": "query",
            "description": "Product category id (Meta product taxonomy) — see `category.category_id`. Products without a category mapping do not match; an unknown id matches nothing (200, empty page).",
            "schema": {
              "type": "integer"
            }
          },
          {
            "name": "brand_id",
            "in": "query",
            "description": "Brand (manufacturer) id — see `brand.id` on any product row. Must be a positive integer; `0`, a non-numeric value or a repeated `brand_id[]=` answer 422 `invalid_parameter`. Products with no brand never match, and an unknown id matches nothing (200, empty page).",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "name": "product_ids",
            "in": "query",
            "description": "Comma-separated product ids, 1 to 100, to fetch exactly those products (for example ones that entered your offer, see `GET /products/ids`). Combines with the other filters. Products you are not offered never appear. Anything else, including an empty value, answers 422 `invalid_parameter`.",
            "schema": {
              "type": "string",
              "example": "9597,12402"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "One page of products.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "products": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/ProductListItem"
                              }
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "products": [
                      {
                        "product_id": 9597,
                        "reference": "1005118",
                        "name": "Hebron Rock and Star Men's Bustar",
                        "status": "active",
                        "brand": {
                          "id": 100,
                          "name": "Rock"
                        },
                        "category": {
                          "category_id": 429,
                          "category_name": "clothing & accessories > shoes & footwear",
                          "gender": "men"
                        },
                        "price": {
                          "group_price": 54.99,
                          "public_price": 59.99,
                          "base_price": 129.99
                        },
                        "currency": "ILS",
                        "total_quantity": 3,
                        "in_stock": true,
                        "cover_image": "https://cdn.mart.ps/28359-thickbox_default/product.jpg",
                        "images": [
                          "https://cdn.mart.ps/28359-thickbox_default/product.jpg"
                        ],
                        "combinations": [
                          {
                            "id": 41206,
                            "available_quantity": 3,
                            "attributes": [
                              {
                                "id": 16,
                                "name": "بني",
                                "group": "اللون"
                              }
                            ]
                          }
                        ],
                        "updated_at": "2026-07-20T14:03:00+03:00"
                      }
                    ]
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 500,
                      "total": 15297,
                      "total_pages": 31,
                      "has_next": true
                    }
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Sync the catalogue: read every page of the products your key is offered.\n# Needs MART_API_BASE and MART_API_KEY.\nset -euo pipefail\n\n# api PATH: sets $body, or prints the status and error code and stops.\napi() {\n  local response status retry_after\n  response=$(curl --silent --show-error --max-time 30 \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") \\\n    --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE$1\") || { echo \"error: no answer\" >&2; exit 1; }\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  if [ \"$status\" -ge 300 ]; then\n    echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n    exit 1\n  fi\n}\n\npage=1\ntotal=0\nwhile true; do\n  api \"/api/v1/products?limit=100&page=$page\"\n  count=$(jq '.data.products | length' <<<\"$body\")\n  # Store the products here: jq -c '.data.products[]' prints one per line.\n  total=$((total + count))\n  echo \"page $page: $count products\"\n  [ \"$(jq -r '.meta.pagination.has_next' <<<\"$body\")\" = true ] || break\n  page=$((page + 1))\n  sleep 1 # a pause between pages, so a full sync never arrives as one burst\ndone\necho \"products: $total\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Sync the catalogue: read every page of the products your key is offered.\n// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE and MART_API_KEY.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nif (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function get(path: string): Promise<any> {\n  const response = await fetch(`${base}${path}`, {\n    headers: { Authorization: `Bearer ${key}` },\n    signal: AbortSignal.timeout(30_000),\n  });\n  const body = await response.json().catch(() => null); // an edge error page is not JSON\n  if (!response.ok || body === null) {\n    const retryAfter = response.headers.get('retry-after');\n    console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);\n    process.exit(1);\n  }\n  return body;\n}\n\nlet page = 1;\nlet total = 0;\nwhile (true) {\n  const body = await get(`/api/v1/products?limit=100&page=${page}`);\n  const products: any[] = body.data.products;\n  // Store the products here.\n  total += products.length;\n  console.log(`page ${page}: ${products.length} products`);\n  if (!body.meta.pagination.has_next) break;\n  page++;\n  await sleep(1000); // a pause between pages, so a full sync never arrives as one burst\n}\nconsole.log(`products: ${total}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Sync the catalogue: read every page of the products your key is offered. Python 3.9+, httpx.\n\nNeeds MART_API_BASE and MART_API_KEY.\n\"\"\"\nimport os\nimport sys\nimport time\n\nimport httpx\n\nTIMEOUT = 30\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\n\ndef check(response: httpx.Response) -> dict:\n    body = body_of(response)\n    if response.is_error or body is None:\n        code = body[\"error\"][\"code\"] if body else \"(not JSON)\"\n        retry_after = response.headers.get(\"Retry-After\")\n        sys.exit(f\"error: {response.status_code} {code}\" + (f\", try again after {retry_after} s\" if retry_after else \"\"))\n    return body\n\n\npage = 1\ntotal = 0\nwhile True:\n    body = check(client.get(\"/api/v1/products\", params={\"limit\": 100, \"page\": page}))\n    products = body[\"data\"][\"products\"]\n    # Store the products here.\n    total += len(products)\n    print(f\"page {page}: {len(products)} products\")\n    if not body[\"meta\"][\"pagination\"][\"has_next\"]:\n        break\n    page += 1\n    time.sleep(1)  # a pause between pages, so a full sync never arrives as one burst\nprint(f\"products: {total}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Sync the catalogue: read every page of the products your key is offered. PHP 7.4 or later, with\n// the curl extension. Needs MART_API_BASE and MART_API_KEY.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** A GET that must succeed: the decoded body, or the status and error code, and stop. */\nfunction get(string $url, string $key): array\n{\n    [$status, $headers, $raw] = request('GET', $url, $key);\n    $body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)\n    if ($status < 200 || $status >= 300 || !is_array($body)) {\n        $code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');\n        $wait = isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n        fwrite(STDERR, \"error: $code$wait\\n\");\n        exit(1);\n    }\n\n    return $body;\n}\n\n$page = 1;\n$total = 0;\nwhile (true) {\n    $body = get(\"$base/api/v1/products?limit=100&page=$page\", $key);\n    $products = $body['data']['products'];\n    // Store the products here.\n    $total += count($products);\n    echo \"page $page: \" . count($products) . \" products\\n\";\n    if (!$body['meta']['pagination']['has_next']) {\n        break;\n    }\n    $page++;\n    sleep(1); // a pause between pages, so a full sync never arrives as one burst\n}\necho \"products: $total\\n\";\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Sync the catalogue: read every page of the products your key is offered. Go 1.22 or later.\n// Needs MART_API_BASE and MART_API_KEY. Run it with: go run sync-the-catalogue.go\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tpage, total := 1, 0\n\tfor {\n\t\tvar body struct {\n\t\t\tData struct {\n\t\t\t\tProducts []json.RawMessage `json:\"products\"`\n\t\t\t} `json:\"data\"`\n\t\t\tMeta struct {\n\t\t\t\tPagination struct {\n\t\t\t\t\tHasNext bool `json:\"has_next\"`\n\t\t\t\t} `json:\"pagination\"`\n\t\t\t} `json:\"meta\"`\n\t\t}\n\t\tget(fmt.Sprintf(\"/api/v1/products?limit=100&page=%d\", page), &body)\n\t\t// Store the products here: decode each json.RawMessage into your own type.\n\t\ttotal += len(body.Data.Products)\n\t\tfmt.Printf(\"page %d: %d products\\n\", page, len(body.Data.Products))\n\t\tif !body.Meta.Pagination.HasNext {\n\t\t\tbreak\n\t\t}\n\t\tpage++\n\t\ttime.Sleep(time.Second) // a pause between pages, so a full sync never arrives as one burst\n\t}\n\tfmt.Println(\"products:\", total)\n}\n\n// get sends one GET and decodes its answer into out.\nfunc get(path string, out any) {\n\treq, err := http.NewRequest(http.MethodGet, os.Getenv(\"MART_API_BASE\")+path, nil)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tdecode(resp, out)\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Sync the catalogue: read every page of the products your key is offered. Java 17 or later, with Jackson.\n// Needs MART_API_BASE and MART_API_KEY. Run it as a single file: java -cp <the Jackson jars> sync-the-catalogue.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.Locale;\n\nclass SyncTheCatalogue {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        int page = 1;\n        int total = 0;\n        while (true) {\n            JsonNode body = get(\"/api/v1/products?limit=100&page=\" + page);\n            JsonNode products = body.path(\"data\").path(\"products\");\n            // Store the products here.\n            total += products.size();\n            System.out.println(\"page \" + page + \": \" + products.size() + \" products\");\n            if (!body.path(\"meta\").path(\"pagination\").path(\"has_next\").asBoolean()) {\n                break;\n            }\n            page++;\n            Thread.sleep(1000); // a pause between pages, so a full sync never arrives as one burst\n        }\n        System.out.println(\"products: \" + total);\n    }\n\n    /** One GET that must succeed: the decoded body, or the status and error code, and stop. */\n    static JsonNode get(String path) throws InterruptedException {\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + path))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .timeout(Duration.ofSeconds(30))\n                .GET()\n                .build();\n        HttpResponse<String> response;\n        try {\n            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        } catch (IOException e) {\n            fail(\"no answer: \" + e.getMessage());\n            return null;\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        return body;\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/products/ids": {
      "get": {
        "summary": "List offered product ids",
        "description": "The ids of the products your account is offered, ascending, and nothing else. Use it to notice what entered or left your offer: pull the ids now and then (or when `meta.offer_changed_at` moves), compare them with the ids you hold, drop the ones that are gone, and fetch the new ones with `GET /products?product_ids=...`. The set is the one `GET /products` lists for the same key, and `status` works as it does there. `meta.snapshot_at` is when the read started (UTC). `meta.offer_changed_at` appears only when your account has its own offer, and moves when that offer is edited. Full behaviour: https://mart.ps/api/docs#catalog/product-ids.",
        "tags": [
          "Products"
        ],
        "operationId": "listProductIds",
        "x-required-scope": "catalog:read",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Default and maximum are the same number, set by Mart (20000 unless changed).",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "active",
                "inactive",
                "all"
              ],
              "default": "all"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "One page of product ids.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "product_ids": {
                              "type": "array",
                              "items": {
                                "type": "integer"
                              }
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            },
                            "snapshot_at": {
                              "type": "string",
                              "format": "date-time"
                            },
                            "offer_changed_at": {
                              "type": "string",
                              "nullable": true,
                              "format": "date-time",
                              "description": "Only when your account has its own offer."
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "product_ids": [
                      9597,
                      12402,
                      12410
                    ]
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 20000,
                      "total": 3,
                      "total_pages": 1,
                      "has_next": false
                    },
                    "snapshot_at": "2026-11-06T09:00:00+00:00"
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/products/{product_id}": {
      "get": {
        "summary": "Get product details",
        "description": "The full product record: text fields and every combination with its stock and images. Pricing is product-level — the single `price` object applies to every combination. A malformed id never matches the route (`route_not_found`); a well-formed id with no such product answers `product_not_found`.",
        "tags": [
          "Products"
        ],
        "operationId": "getProduct",
        "x-required-scope": "catalog:read",
        "parameters": [
          {
            "name": "product_id",
            "in": "path",
            "required": true,
            "description": "Stable product identifier used in catalog synchronization and order creation. Positive integer; leading zeros are rejected so each product has exactly one URL.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "example": 9597
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The product document, combinations included.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "product": {
                              "$ref": "#/components/schemas/ProductDetail"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "product": {
                      "product_id": 9597,
                      "reference": "1005118",
                      "name": "Hebron Rock and Star Men's Bustar",
                      "description": "<p>Leather upper, rubber sole.</p>",
                      "description_short": "Men's shoe.",
                      "status": "active",
                      "brand": {
                        "id": 100,
                        "name": "Rock"
                      },
                      "category": {
                        "category_id": 429,
                        "category_name": "clothing & accessories > shoes & footwear",
                        "gender": "men"
                      },
                      "price": {
                        "group_price": 54.99,
                        "public_price": 59.99,
                        "base_price": 129.99
                      },
                      "currency": "ILS",
                      "total_quantity": 3,
                      "in_stock": true,
                      "cover_image": "https://cdn.mart.ps/28359-thickbox_default/product.jpg",
                      "images": [
                        "https://cdn.mart.ps/28359-thickbox_default/product.jpg"
                      ],
                      "combinations": [
                        {
                          "id": 41206,
                          "available_quantity": 3,
                          "attributes": [
                            {
                              "id": 16,
                              "name": "بني",
                              "group": "اللون"
                            }
                          ],
                          "default": true,
                          "images": []
                        }
                      ],
                      "updated_at": "2026-07-20T14:03:00+03:00"
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/categories": {
      "get": {
        "summary": "List product categories",
        "description": "The category vocabulary behind the products endpoints (Meta's product taxonomy), flat, ordered by `category_name` — no pagination (`meta` is `null`). `category_id` is the exact value the products `category_id` filter accepts.",
        "tags": [
          "Categories"
        ],
        "operationId": "listCategories",
        "x-required-scope": "catalog:read",
        "parameters": [],
        "responses": {
          "200": {
            "description": "The full category list.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "categories": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/CategoryItem"
                              }
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "categories": [
                      {
                        "category_id": 528,
                        "category_name": "clothing & accessories > clothing",
                        "gender": null
                      },
                      {
                        "category_id": 455,
                        "category_name": "clothing & accessories > clothing > women's clothing",
                        "gender": "women"
                      }
                    ]
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/attributes": {
      "get": {
        "summary": "List attribute groups and values",
        "description": "The attribute vocabulary behind combination `attributes`, grouped by attribute group; only values actually in use are served — no pagination (`meta` is `null`). `values[].attribute_id` equals the `id` the products endpoints emit in `combinations[].attributes[]`; join by that id.",
        "tags": [
          "Attributes"
        ],
        "operationId": "listAttributes",
        "x-required-scope": "catalog:read",
        "parameters": [],
        "responses": {
          "200": {
            "description": "The full attribute-group list.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "attributes": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/AttributeGroupItem"
                              }
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "attributes": [
                      {
                        "attribute_group_id": 1,
                        "attribute_group_name": "اللون",
                        "values": [
                          {
                            "attribute_id": 1,
                            "attribute_name": "أحمر"
                          },
                          {
                            "attribute_id": 16,
                            "attribute_name": "بني"
                          }
                        ]
                      }
                    ]
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/states": {
      "get": {
        "summary": "List delivery destinations",
        "description": "All delivery destinations as a two-level tree: cities, each holding its deliverable states — no pagination (`meta` is `null`). Only a leaf `states[].id` is a valid `shipping_address.state_id`; names are not unique, so match on `id`. Every state carries `delivery`: the fee brackets, by products total, that an order of yours to it is priced with, so you can show delivery prices before an order exists. They are your account's own prices: another key can see other brackets. Details: https://mart.ps/api/docs#catalog/states.",
        "tags": [
          "Delivery"
        ],
        "operationId": "listStates",
        "x-required-scope": "catalog:read",
        "parameters": [],
        "responses": {
          "200": {
            "description": "The full city → states tree, with each state's delivery brackets.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "cities": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/CityItem"
                              }
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "cities": [
                      {
                        "id": 255,
                        "name": "الخليل",
                        "states": [
                          {
                            "id": 774,
                            "name": "أبو الغزلان",
                            "delivery": {
                              "available": true,
                              "fees": [
                                {
                                  "from_total": 0.0,
                                  "to_total": 300.0,
                                  "fee": 35.0
                                },
                                {
                                  "from_total": 300.0,
                                  "to_total": null,
                                  "fee": 20.0
                                }
                              ]
                            }
                          },
                          {
                            "id": 726,
                            "name": "إذنا",
                            "delivery": {
                              "available": true,
                              "fees": [
                                {
                                  "from_total": 0.0,
                                  "to_total": 300.0,
                                  "fee": 35.0
                                },
                                {
                                  "from_total": 300.0,
                                  "to_total": null,
                                  "fee": 20.0
                                }
                              ]
                            }
                          }
                        ]
                      }
                    ]
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Show what delivery costs to one town, then quote an order without placing it.\n# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\nset -euo pipefail\nexport LC_NUMERIC=C # printf reads and writes amounts with a decimal point\n\n# api METHOD PATH [JSON]: sets $body, or prints the status and error code and stops.\napi() {\n  local response status retry_after\n  response=$(curl --silent --show-error --max-time 30 --request \"$1\" \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") --header 'Content-Type: application/json' \\\n    ${3:+--data \"$3\"} --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE$2\") || { echo \"error: no answer\" >&2; exit 1; }\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  if [ \"$status\" -ge 300 ]; then\n    echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n    exit 1\n  fi\n}\n\n# 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n#    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n#    on its own schedule, never once per visitor.\napi GET /api/v1/states\nfees=$(jq -c --argjson state \"$MART_STATE_ID\" '[.data.cities[].states[] | select(.id == $state)] | first | .delivery.fees' <<<\"$body\")\nif [ \"$fees\" = null ]; then\n  echo \"error: state $MART_STATE_ID is not a delivery town\" >&2\n  exit 1\nfi\necho \"delivery fees for state $MART_STATE_ID:\"\njq -r '.[] | \"\\(.from_total) \\(.to_total) \\(.fee)\"' <<<\"$fees\" |\n  while read -r from to fee; do\n    if [ \"$to\" != null ]; then\n      printf '  from %.2f, less than %.2f: %.2f\\n' \"$from\" \"$to\" \"$fee\"\n    else\n      printf '  from %.2f: %.2f\\n' \"$from\" \"$fee\"\n    fi\n  done\n\n# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n#    reserved, but it counts against the same per-minute budget as creating orders.\norder=$(jq -n --arg ref \"quote-$(date +%s)\" --argjson product \"$MART_PRODUCT_ID\" --argjson state \"$MART_STATE_ID\" '{\n  partner_reference: $ref,\n  payment_type: \"cod\",\n  products: [{product_id: $product, quantity: 1}],\n  shipping_address: {customer_name: \"Test Buyer\", phone: \"0599000000\", state_id: $state, address: \"Main street 1\"}\n}')\napi POST /api/v1/orders/validate \"$order\"\njq -r '\"valid: \\(.data.validation.valid)\"' <<<\"$body\"\nread -r products fee total < <(jq -r '.data.validation.quote | \"\\(.products_total) \\(.shipping_fee) \\(.order_total)\"' <<<\"$body\")\nprintf 'products total: %.2f\\ndelivery fee: %.2f\\norder total: %.2f\\n' \"$products\" \"$fee\" \"$total\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Show what delivery costs to one town, then quote an order without placing it.\n// Node 22.18 or later runs this .ts file as it is.\n// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nif (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');\nconst productId = Number(process.env.MART_PRODUCT_ID);\nconst stateId = Number(process.env.MART_STATE_ID);\n\nasync function api(method: string, path: string, payload?: unknown): Promise<any> {\n  const response = await fetch(`${base}${path}`, {\n    method,\n    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },\n    body: payload === undefined ? undefined : JSON.stringify(payload),\n    signal: AbortSignal.timeout(30_000),\n  });\n  const body = await response.json().catch(() => null); // an edge error page is not JSON\n  if (!response.ok || body === null) {\n    const retryAfter = response.headers.get('retry-after');\n    console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);\n    process.exit(1);\n  }\n  return body;\n}\n\n// 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n//    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n//    on its own schedule, never once per visitor.\nconst states = await api('GET', '/api/v1/states');\nconst town = states.data.cities.flatMap((city: any) => city.states).find((state: any) => state.id === stateId);\nif (!town) {\n  console.error(`error: state ${stateId} is not a delivery town`);\n  process.exit(1);\n}\nconsole.log(`delivery fees for state ${stateId}:`);\nfor (const bracket of town.delivery.fees) {\n  const upper = bracket.to_total === null ? '' : `, less than ${bracket.to_total.toFixed(2)}`;\n  console.log(`  from ${bracket.from_total.toFixed(2)}${upper}: ${bracket.fee.toFixed(2)}`);\n}\n\n// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n//    reserved, but it counts against the same per-minute budget as creating orders.\nconst result = await api('POST', '/api/v1/orders/validate', {\n  partner_reference: `quote-${Date.now()}`,\n  payment_type: 'cod',\n  products: [{ product_id: productId, quantity: 1 }],\n  shipping_address: { customer_name: 'Test Buyer', phone: '0599000000', state_id: stateId, address: 'Main street 1' },\n});\nconst quote = result.data.validation.quote;\nconsole.log(`valid: ${result.data.validation.valid}`);\nconsole.log(`products total: ${quote.products_total.toFixed(2)}`);\nconsole.log(`delivery fee: ${quote.shipping_fee.toFixed(2)}`);\nconsole.log(`order total: ${quote.order_total.toFixed(2)}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Show what delivery costs to one town, then quote an order without placing it. Python 3.9+, httpx.\n\nNeeds MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\n\"\"\"\nimport os\nimport sys\nimport time\n\nimport httpx\n\nTIMEOUT = 30\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\nproduct_id = int(os.environ[\"MART_PRODUCT_ID\"])\nstate_id = int(os.environ[\"MART_STATE_ID\"])\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\n\ndef check(response: httpx.Response) -> dict:\n    body = body_of(response)\n    if response.is_error or body is None:\n        code = body[\"error\"][\"code\"] if body else \"(not JSON)\"\n        retry_after = response.headers.get(\"Retry-After\")\n        sys.exit(f\"error: {response.status_code} {code}\" + (f\", try again after {retry_after} s\" if retry_after else \"\"))\n    return body\n\n\n# 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n#    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n#    on its own schedule, never once per visitor.\ncities = check(client.get(\"/api/v1/states\"))[\"data\"][\"cities\"]\ntown = next((state for city in cities for state in city[\"states\"] if state[\"id\"] == state_id), None)\nif town is None:\n    sys.exit(f\"error: state {state_id} is not a delivery town\")\nprint(f\"delivery fees for state {state_id}:\")\nfor bracket in town[\"delivery\"][\"fees\"]:\n    upper = \"\" if bracket[\"to_total\"] is None else f\", less than {bracket['to_total']:.2f}\"\n    print(f\"  from {bracket['from_total']:.2f}{upper}: {bracket['fee']:.2f}\")\n\n# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n#    reserved, but it counts against the same per-minute budget as creating orders.\nresult = check(client.post(\"/api/v1/orders/validate\", json={\n    \"partner_reference\": f\"quote-{int(time.time())}\",\n    \"payment_type\": \"cod\",\n    \"products\": [{\"product_id\": product_id, \"quantity\": 1}],\n    \"shipping_address\": {\"customer_name\": \"Test Buyer\", \"phone\": \"0599000000\", \"state_id\": state_id, \"address\": \"Main street 1\"},\n}))[\"data\"][\"validation\"]\nprint(f\"valid: {str(result['valid']).lower()}\")\nprint(f\"products total: {result['quote']['products_total']:.2f}\")\nprint(f\"delivery fee: {result['quote']['shipping_fee']:.2f}\")\nprint(f\"order total: {result['quote']['order_total']:.2f}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Show what delivery costs to one town, then quote an order without placing it. PHP 7.4 or later,\n// with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n$productId = (int) getenv('MART_PRODUCT_ID');\n$stateId = (int) getenv('MART_STATE_ID');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** A GET that must succeed: the decoded body, or the status and error code, and stop. */\nfunction get(string $url, string $key): array\n{\n    [$status, $headers, $raw] = request('GET', $url, $key);\n    $body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)\n    if ($status < 200 || $status >= 300 || !is_array($body)) {\n        $code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');\n        $wait = isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n        fwrite(STDERR, \"error: $code$wait\\n\");\n        exit(1);\n    }\n\n    return $body;\n}\n\n// 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n//    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n//    on its own schedule, never once per visitor.\n$states = get(\"$base/api/v1/states\", $key);\n$town = null;\nforeach ($states['data']['cities'] as $city) {\n    foreach ($city['states'] as $state) {\n        if ($state['id'] === $stateId) {\n            $town = $state;\n        }\n    }\n}\nif ($town === null) {\n    fwrite(STDERR, \"error: state $stateId is not a delivery town\\n\");\n    exit(1);\n}\necho \"delivery fees for state $stateId:\\n\";\nforeach ($town['delivery']['fees'] as $bracket) {\n    $upper = $bracket['to_total'] === null ? '' : sprintf(', less than %.2f', $bracket['to_total']);\n    printf(\"  from %.2f%s: %.2f\\n\", $bracket['from_total'], $upper, $bracket['fee']);\n}\n\n// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n//    reserved, but it counts against the same per-minute budget as creating orders.\n[$status, $headers, $raw] = request('POST', \"$base/api/v1/orders/validate\", $key, json_encode([\n    'partner_reference' => 'quote-' . time(),\n    'payment_type' => 'cod',\n    'products' => [['product_id' => $productId, 'quantity' => 1]],\n    'shipping_address' => ['customer_name' => 'Test Buyer', 'phone' => '0599000000', 'state_id' => $stateId, 'address' => 'Main street 1'],\n]));\n$result = json_decode($raw, true);\nif ($status !== 200 || !is_array($result)) {\n    $wait = isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($result['error']['code'] ?? '(not JSON)')) . \"$wait\\n\");\n    exit(1);\n}\n$validation = $result['data']['validation'];\necho 'valid: ' . ($validation['valid'] ? 'true' : 'false') . \"\\n\";\nprintf(\"products total: %.2f\\n\", $validation['quote']['products_total']);\nprintf(\"delivery fee: %.2f\\n\", $validation['quote']['shipping_fee']);\nprintf(\"order total: %.2f\\n\", $validation['quote']['order_total']);\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Show what delivery costs to one town, then quote an order without placing it. Go 1.22 or later.\n// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\n// Run it with: go run delivery-prices-and-quote.go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tproductID, _ := strconv.Atoi(os.Getenv(\"MART_PRODUCT_ID\"))\n\tstateID, _ := strconv.Atoi(os.Getenv(\"MART_STATE_ID\"))\n\n\t// 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n\t//    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n\t//    on its own schedule, never once per visitor.\n\tvar tree struct {\n\t\tData struct {\n\t\t\tCities []struct {\n\t\t\t\tStates []struct {\n\t\t\t\t\tID       int `json:\"id\"`\n\t\t\t\t\tDelivery struct {\n\t\t\t\t\t\tFees []struct {\n\t\t\t\t\t\t\tFrom float64  `json:\"from_total\"`\n\t\t\t\t\t\t\tTo   *float64 `json:\"to_total\"` // null: no upper end\n\t\t\t\t\t\t\tFee  float64  `json:\"fee\"`\n\t\t\t\t\t\t} `json:\"fees\"`\n\t\t\t\t\t} `json:\"delivery\"`\n\t\t\t\t} `json:\"states\"`\n\t\t\t} `json:\"cities\"`\n\t\t} `json:\"data\"`\n\t}\n\tget(\"/api/v1/states\", &tree)\n\tfound := false\n\tfor _, city := range tree.Data.Cities {\n\t\tfor _, state := range city.States {\n\t\t\tif state.ID != stateID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfound = true\n\t\t\tfmt.Printf(\"delivery fees for state %d:\\n\", stateID)\n\t\t\tfor _, b := range state.Delivery.Fees {\n\t\t\t\tif b.To != nil {\n\t\t\t\t\tfmt.Printf(\"  from %.2f, less than %.2f: %.2f\\n\", b.From, *b.To, b.Fee)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"  from %.2f: %.2f\\n\", b.From, b.Fee)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !found {\n\t\tfail(fmt.Errorf(\"state %d is not a delivery town\", stateID))\n\t}\n\n\t// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n\t//    reserved, but it counts against the same per-minute budget as creating orders.\n\torder, err := json.Marshal(map[string]any{\n\t\t\"partner_reference\": fmt.Sprintf(\"quote-%d\", time.Now().Unix()),\n\t\t\"payment_type\":      \"cod\",\n\t\t\"products\":          []map[string]any{{\"product_id\": productID, \"quantity\": 1}},\n\t\t\"shipping_address\": map[string]any{\n\t\t\t\"customer_name\": \"Test Buyer\", \"phone\": \"0599000000\", \"state_id\": stateID, \"address\": \"Main street 1\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq, err := http.NewRequest(http.MethodPost, os.Getenv(\"MART_API_BASE\")+\"/api/v1/orders/validate\", bytes.NewReader(order))\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tvar result struct {\n\t\tData struct {\n\t\t\tValidation struct {\n\t\t\t\tValid bool `json:\"valid\"`\n\t\t\t\tQuote struct {\n\t\t\t\t\tProductsTotal float64 `json:\"products_total\"`\n\t\t\t\t\tShippingFee   float64 `json:\"shipping_fee\"`\n\t\t\t\t\tOrderTotal    float64 `json:\"order_total\"`\n\t\t\t\t} `json:\"quote\"`\n\t\t\t} `json:\"validation\"`\n\t\t} `json:\"data\"`\n\t}\n\tdecode(resp, &result)\n\tv := result.Data.Validation\n\tfmt.Println(\"valid:\", v.Valid)\n\tfmt.Printf(\"products total: %.2f\\ndelivery fee: %.2f\\norder total: %.2f\\n\",\n\t\tv.Quote.ProductsTotal, v.Quote.ShippingFee, v.Quote.OrderTotal)\n}\n\n// get sends one GET and decodes its answer into out.\nfunc get(path string, out any) {\n\treq, err := http.NewRequest(http.MethodGet, os.Getenv(\"MART_API_BASE\")+path, nil)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tdecode(resp, out)\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Show what delivery costs to one town, then quote an order without placing it. Java 17 or later, with Jackson.\n// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\n// Run it as a single file: java -cp <the Jackson jars> delivery-prices-and-quote.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\n\nclass DeliveryPricesAndQuote {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        int productId = Integer.parseInt(System.getenv(\"MART_PRODUCT_ID\"));\n        int stateId = Integer.parseInt(System.getenv(\"MART_STATE_ID\"));\n\n        // 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n        //    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n        //    on its own schedule, never once per visitor.\n        JsonNode town = null;\n        for (JsonNode city : get(\"/api/v1/states\").path(\"data\").path(\"cities\")) {\n            for (JsonNode state : city.path(\"states\")) {\n                if (state.path(\"id\").asInt() == stateId) {\n                    town = state;\n                }\n            }\n        }\n        if (town == null) {\n            fail(\"state \" + stateId + \" is not a delivery town\");\n        }\n        System.out.println(\"delivery fees for state \" + stateId + \":\");\n        for (JsonNode bracket : town.path(\"delivery\").path(\"fees\")) {\n            String upper = bracket.path(\"to_total\").isNull() ? \"\"\n                    : String.format(Locale.ROOT, \", less than %.2f\", bracket.path(\"to_total\").asDouble());\n            System.out.printf(Locale.ROOT, \"  from %.2f%s: %.2f%n\", bracket.path(\"from_total\").asDouble(), upper,\n                    bracket.path(\"fee\").asDouble());\n        }\n\n        // 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n        //    reserved, but it counts against the same per-minute budget as creating orders.\n        String order = JSON.writeValueAsString(Map.of(\n                \"partner_reference\", \"quote-\" + System.currentTimeMillis(),\n                \"payment_type\", \"cod\",\n                \"products\", List.of(Map.of(\"product_id\", productId, \"quantity\", 1)),\n                \"shipping_address\", Map.of(\"customer_name\", \"Test Buyer\", \"phone\", \"0599000000\",\n                        \"state_id\", stateId, \"address\", \"Main street 1\")));\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + \"/api/v1/orders/validate\"))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .header(\"Content-Type\", \"application/json\")\n                .timeout(Duration.ofSeconds(30))\n                .POST(HttpRequest.BodyPublishers.ofString(order))\n                .build();\n        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        JsonNode result = parse(response.body());\n        if (response.statusCode() >= 300 || result == null) {\n            fail(response.statusCode() + \" \" + code(result) + when(response));\n        }\n        JsonNode validation = result.path(\"data\").path(\"validation\");\n        JsonNode quote = validation.path(\"quote\");\n        System.out.println(\"valid: \" + validation.path(\"valid\").asBoolean());\n        System.out.printf(Locale.ROOT, \"products total: %.2f%n\", quote.path(\"products_total\").asDouble());\n        System.out.printf(Locale.ROOT, \"delivery fee: %.2f%n\", quote.path(\"shipping_fee\").asDouble());\n        System.out.printf(Locale.ROOT, \"order total: %.2f%n\", quote.path(\"order_total\").asDouble());\n    }\n\n    /** One GET that must succeed: the decoded body, or the status and error code, and stop. */\n    static JsonNode get(String path) throws InterruptedException {\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + path))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .timeout(Duration.ofSeconds(30))\n                .GET()\n                .build();\n        HttpResponse<String> response;\n        try {\n            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        } catch (IOException e) {\n            fail(\"no answer: \" + e.getMessage());\n            return null;\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        return body;\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/orders": {
      "get": {
        "summary": "List orders",
        "description": "One page of your own orders, as summaries: the order's status, payment type, dates and totals, the same values `GET /api/v1/orders/{partner_reference}` returns for that order. Lines, delivery address, payment reference, cancellation and money stay on that single read. Ownership is your key: you never see another account's orders. Paging by offset can repeat a row when orders arrive between calls, so de-duplicate on `partner_reference`; to follow changes, use `updated_since` with `order=asc`. Full behaviour: https://mart.ps/api/docs#orders/list.",
        "tags": [
          "Orders"
        ],
        "operationId": "listOrders",
        "x-required-scope": "orders:read",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "description": "Comma-separated status ids, as `status.id` is returned on an order, for example `5,7`. Matches the status shown on each row, which is the status the single order read shows. At most 50 ids. A non-numeric value answers 422 `invalid_parameter`.",
            "schema": {
              "type": "string"
            },
            "example": "5,7"
          },
          {
            "name": "payment_type",
            "in": "query",
            "description": "Only orders paid this way.",
            "schema": {
              "type": "string",
              "enum": [
                "cod",
                "card"
              ]
            }
          },
          {
            "name": "created_from",
            "in": "query",
            "description": "ISO 8601 datetime; orders created at or after this instant.",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "example": "2026-07-01T00:00:00+03:00"
          },
          {
            "name": "created_to",
            "in": "query",
            "description": "ISO 8601 datetime; orders created strictly before this instant, so consecutive windows never overlap.",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "example": "2026-08-01T00:00:00+03:00"
          },
          {
            "name": "updated_since",
            "in": "query",
            "description": "ISO 8601 datetime; orders last modified at or after this instant (`updated_at`). With `order=asc` this is the way to follow changes.",
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "example": "2026-07-01T00:00:00+03:00"
          },
          {
            "name": "order",
            "in": "query",
            "description": "Sort by creation time, with the order's creation sequence breaking a tie, so a page boundary never repeats or skips a row.",
            "schema": {
              "type": "string",
              "enum": [
                "desc",
                "asc"
              ],
              "default": "desc"
            }
          },
          {
            "name": "page",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Default 50, maximum 100.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "One page of your own orders, newest first by default. An empty result is a normal 200 with `orders: []`.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "orders": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/OrderListItem"
                              }
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "orders": [
                      {
                        "partner_reference": "100245",
                        "status": {
                          "id": 5,
                          "name": "تم التوصيل"
                        },
                        "payment_type": "cod",
                        "created_at": "2026-08-01T10:15:00+00:00",
                        "updated_at": "2026-08-03T09:40:12+03:00",
                        "order_total": 275.0,
                        "cod_total": 275.0,
                        "shipping_fee": 35.0,
                        "free_shipping": true
                      }
                    ]
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 50,
                      "total": 1,
                      "total_pages": 1,
                      "has_next": false
                    }
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      },
      "post": {
        "summary": "Create order",
        "description": "Creates an order priced at your selling prices. Atomic: any single line failure rejects the whole order with 422 and nothing is created. Idempotent by `partner_reference`: an identical retry answers 200 with `meta.idempotency_replay: true`, different content answers 409. `payment_type` is REQUIRED (`cod` or `card`); with `card` the saved card is charged synchronously for the server-computed total (402 `card_declined` / 503 `payment_gateway_unavailable`; allow a 60s client timeout). Read the order back with `GET /api/v1/orders/{partner_reference}`. Full behaviour: https://mart.ps/api/docs#orders.",
        "tags": [
          "Orders"
        ],
        "operationId": "createOrder",
        "x-required-scope": "orders:write",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OrderCreateRequest"
              },
              "example": {
                "partner_reference": "100245",
                "payment_type": "cod",
                "shipping_address": {
                  "customer_name": "محمد علي",
                  "phone": "0599123456",
                  "extra_phone": "022345678",
                  "state_id": 386,
                  "address": "شارع الإرسال، عمارة 12",
                  "notes": null
                },
                "products": [
                  {
                    "product_id": 9597,
                    "combination_id": 41206,
                    "quantity": 2,
                    "price": 120.0
                  }
                ],
                "free_shipping": true
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Order created. `meta.idempotency_replay` is false.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "order": {
                              "$ref": "#/components/schemas/Order"
                            }
                          }
                        },
                        "meta": {
                          "$ref": "#/components/schemas/OrderMeta"
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 201,
                  "message": "Created",
                  "data": {
                    "order": {
                      "id": 100311,
                      "partner_reference": "100245",
                      "status": "processing",
                      "payment_type": "cod",
                      "created_at": "2026-08-01T10:15:00+00:00",
                      "cod_total": 240.0,
                      "shipping_fee": 35.0,
                      "free_shipping": true,
                      "reward": {
                        "gross_product_reward": 130.02,
                        "shipping_deduction": 35.0,
                        "net_reward": 95.02
                      },
                      "money": {
                        "gross": 130.02,
                        "shipping_deduction": 35.0,
                        "net": 95.02,
                        "earning_state": "pending",
                        "available_at": null
                      },
                      "products": [
                        {
                          "product_id": 9597,
                          "combination_id": 41206,
                          "quantity": 2,
                          "price": 120.0,
                          "group_price": 54.99
                        }
                      ],
                      "shipping_address": {
                        "customer_name": "محمد علي",
                        "phone": "0599123456",
                        "extra_phone": "022345678",
                        "state_id": 386,
                        "address": "شارع الإرسال، عمارة 12",
                        "notes": null
                      }
                    }
                  },
                  "meta": {
                    "idempotency_replay": false
                  },
                  "error": null
                }
              }
            }
          },
          "200": {
            "description": "Idempotent replay: the ORIGINAL response, byte-for-byte, frozen at creation (`meta.idempotency_replay: true`) — a record of what was created, not a live view. One shape exception: an order created before `payment_type` existed replays its frozen body without that key.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "order": {
                              "$ref": "#/components/schemas/Order"
                            }
                          }
                        },
                        "meta": {
                          "$ref": "#/components/schemas/OrderMeta"
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 201,
                  "message": "Created",
                  "data": {
                    "order": {
                      "id": 100311,
                      "partner_reference": "100245",
                      "status": "processing",
                      "payment_type": "cod",
                      "created_at": "2026-08-01T10:15:00+00:00",
                      "cod_total": 240.0,
                      "shipping_fee": 35.0,
                      "free_shipping": true,
                      "reward": {
                        "gross_product_reward": 130.02,
                        "shipping_deduction": 35.0,
                        "net_reward": 95.02
                      },
                      "money": {
                        "gross": 130.02,
                        "shipping_deduction": 35.0,
                        "net": 95.02,
                        "earning_state": "pending",
                        "available_at": null
                      },
                      "products": [
                        {
                          "product_id": 9597,
                          "combination_id": 41206,
                          "quantity": 2,
                          "price": 120.0,
                          "group_price": 54.99
                        }
                      ],
                      "shipping_address": {
                        "customer_name": "محمد علي",
                        "phone": "0599123456",
                        "extra_phone": "022345678",
                        "state_id": 386,
                        "address": "شارع الإرسال، عمارة 12",
                        "notes": null
                      }
                    }
                  },
                  "meta": {
                    "idempotency_replay": true
                  },
                  "error": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "402": {
            "$ref": "#/components/responses/CardDeclined"
          },
          "403": {
            "$ref": "#/components/responses/ForbiddenGroup"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyConflict"
          },
          "422": {
            "$ref": "#/components/responses/OrderUnprocessable"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/PaymentGatewayUnavailable"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Create an order that survives a timeout: retry with the same partner_reference and read the replay.\n# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and MART_PARTNER_REFERENCE:\n# your own id for this order, from your own system, so that running this again can never make a\n# second order.\nset -euo pipefail\nexport LC_NUMERIC=C # printf reads and writes amounts with a decimal point\n\nreference=${MART_PARTNER_REFERENCE:?set MART_PARTNER_REFERENCE to your own id for this order}\norder=$(jq -n --arg ref \"$reference\" --argjson product \"$MART_PRODUCT_ID\" --argjson state \"$MART_STATE_ID\" '{\n  partner_reference: $ref,\n  payment_type: \"cod\",\n  products: [{product_id: $product, quantity: 1}],\n  shipping_address: {customer_name: \"Test Buyer\", phone: \"0599000000\", state_id: $state, address: \"Main street 1\"}\n}')\necho \"reference: $reference\" # written down before the first attempt\n\n# Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n# what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n# is final. Every attempt sends the SAME body, so a retry can never create a second order.\nfor attempt in 1 2 3 4 5; do\n  response=$(curl --silent --show-error --max-time 60 --request POST \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") --header 'Content-Type: application/json' \\\n    --data \"$order\" --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE/api/v1/orders\") || response=$'\\n000'\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  case $status in 000 | 429 | 500 | 502 | 503 | 504) ;; *) break ;; esac\n  [ \"$attempt\" = 5 ] && break\n  if [[ $retry_after =~ ^[0-9]+$ ]]; then\n    if [ \"$retry_after\" -gt 60 ]; then\n      echo \"error: $status, try again after $retry_after s with MART_PARTNER_REFERENCE=$reference\" >&2\n      exit 1\n    fi\n    wait_ms=$((retry_after * 1000))\n  else\n    wait_ms=$((1000 << (attempt - 1)))\n    [ \"$wait_ms\" -gt 30000 ] && wait_ms=30000\n    wait_ms=$((wait_ms / 2 + RANDOM % (wait_ms / 2 + 1)))\n  fi\n  printf 'retry: attempt %d %s, waiting %d.%d s\\n' \"$attempt\" \\\n    \"$([ \"$status\" = 000 ] && echo 'got no answer' || echo \"answered $status\")\" $((wait_ms / 1000)) $((wait_ms % 1000 / 100)) >&2\n  sleep \"$((wait_ms / 1000)).$(printf '%03d' $((wait_ms % 1000)))\"\ndone\n\nif [ \"$status\" = 000 ] || [ \"$status\" -ge 500 ] || [ \"$status\" = 429 ]; then\n  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\n  exit 1\nfi\nif [ \"$status\" -ge 300 ]; then\n  echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')\" >&2\n  exit 1\nfi\n\n# 201: created now. 200 with meta.idempotency_replay true: this order already existed.\necho \"order: $(jq -r '.data.order.partner_reference' <<<\"$body\")\"\necho \"status: $(jq -r '.data.order.status' <<<\"$body\")\"\nprintf 'order total: %.2f\\n' \"$(jq -r '.data.order.order_total' <<<\"$body\")\"\necho \"replay: $(jq -r '.meta.idempotency_replay' <<<\"$body\")\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Create an order that survives a timeout: retry with the same partner_reference and read the replay.\n// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID,\n// MART_STATE_ID and MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that\n// running this again can never make a second order.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nconst reference = process.env.MART_PARTNER_REFERENCE;\nif (!base || !key || !reference) throw new Error('Set MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE');\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\nconst RETRYABLE = new Set([429, 500, 502, 503, 504]);\n\n// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n// what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n// is final. Every attempt sends the same bytes.\nasync function send(path: string, payload: string, timeoutMs: number): Promise<Response | null> {\n  for (let attempt = 1; ; attempt++) {\n    let response: Response | null = null;\n    try {\n      response = await fetch(`${base}${path}`, {\n        method: 'POST',\n        headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },\n        body: payload,\n        signal: AbortSignal.timeout(timeoutMs),\n      });\n      if (!RETRYABLE.has(response.status) || attempt === 5) return response;\n    } catch {\n      if (attempt === 5) return null; // no answer at all\n    }\n    let wait: number;\n    const retryAfter = Number(response?.headers.get('retry-after'));\n    if (response && Number.isInteger(retryAfter) && retryAfter > 0) {\n      if (retryAfter > 60) return response; // too long to wait here: the caller says when to come back\n      wait = retryAfter;\n    } else {\n      const backoff = Math.min(30, 2 ** (attempt - 1));\n      wait = backoff / 2 + (Math.random() * backoff) / 2;\n    }\n    console.error(`retry: attempt ${attempt} ${response ? `answered ${response.status}` : 'got no answer'}, waiting ${wait.toFixed(1)} s`);\n    await sleep(wait * 1000);\n  }\n}\n\n// Decided once, before any attempt: every retry sends this same body.\nconst order = JSON.stringify({\n  partner_reference: reference,\n  payment_type: 'cod',\n  products: [{ product_id: Number(process.env.MART_PRODUCT_ID), quantity: 1 }],\n  shipping_address: {\n    customer_name: 'Test Buyer',\n    phone: '0599000000',\n    state_id: Number(process.env.MART_STATE_ID),\n    address: 'Main street 1',\n  },\n});\nconsole.log(`reference: ${reference}`); // written down before the first attempt\n\nconst response = await send('/api/v1/orders', order, 60_000);\nconst body = response ? await response.json().catch(() => null) : null;\nif (response === null || response.status === 429 || response.status >= 500) {\n  const when = response?.headers.get('retry-after');\n  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}`);\n  process.exit(1);\n}\nif (!response.ok || body === null) {\n  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}`);\n  process.exit(1);\n}\n// 201: created now. 200 with meta.idempotency_replay true: this order already existed.\nconsole.log(`order: ${body.data.order.partner_reference}`);\nconsole.log(`status: ${body.data.order.status}`);\nconsole.log(`order total: ${body.data.order.order_total.toFixed(2)}`);\nconsole.log(`replay: ${body.meta.idempotency_replay}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Create an order that survives a timeout: retry with the same partner_reference and read the replay.\n\nPython 3.9 or later, with httpx. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and\nMART_PARTNER_REFERENCE: your own id for this order, from your own system, so that running this again\ncan never make a second order.\n\"\"\"\nimport os\nimport random\nimport sys\nimport time\n\nimport httpx\n\nTIMEOUT = 60\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\nreference = os.environ[\"MART_PARTNER_REFERENCE\"]\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\nRETRYABLE = {429, 500, 502, 503, 504}\n\n\ndef send(path: str, payload: dict):\n    \"\"\"POST the same payload until it is answered for good.\n\n    Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n    what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n    is final. Returns None when no attempt got an answer.\n    \"\"\"\n    for attempt in range(1, 6):\n        response = None\n        try:\n            response = client.post(path, json=payload)\n            if response.status_code not in RETRYABLE or attempt == 5:\n                return response\n        except httpx.TransportError:\n            if attempt == 5:\n                return None\n        retry_after = response.headers.get(\"Retry-After\", \"\") if response is not None else \"\"\n        if retry_after.isdigit() and int(retry_after) > 0:\n            if int(retry_after) > 60:\n                return response  # too long to wait here: the caller says when to come back\n            wait = float(retry_after)\n        else:\n            backoff = min(30, 2 ** (attempt - 1))\n            wait = backoff / 2 + random.uniform(0, backoff / 2)\n        what = f\"answered {response.status_code}\" if response is not None else \"got no answer\"\n        print(f\"retry: attempt {attempt} {what}, waiting {wait:.1f} s\", file=sys.stderr)\n        time.sleep(wait)\n\n\ndef when(response) -> str:\n    \"\"\"\", try again after N s\" when the answer says how long to wait (Retry-After), else nothing.\"\"\"\n    retry_after = response.headers.get(\"Retry-After\") if response is not None else None\n    return f\", try again after {retry_after} s\" if retry_after else \"\"\n\n\n# Decided once, before any attempt: every retry sends this same body.\norder = {\n    \"partner_reference\": reference,\n    \"payment_type\": \"cod\",\n    \"products\": [{\"product_id\": int(os.environ[\"MART_PRODUCT_ID\"]), \"quantity\": 1}],\n    \"shipping_address\": {\n        \"customer_name\": \"Test Buyer\",\n        \"phone\": \"0599000000\",\n        \"state_id\": int(os.environ[\"MART_STATE_ID\"]),\n        \"address\": \"Main street 1\",\n    },\n}\nprint(f\"reference: {reference}\", flush=True)  # written down before the first attempt\n\nresponse = send(\"/api/v1/orders\", order)\nif response is None or response.status_code == 429 or response.status_code >= 500:\n    status = response.status_code if response is not None else \"no answer\"\n    sys.exit(f\"error: {status}{when(response)}; the order may exist: run again later with MART_PARTNER_REFERENCE={reference}\")\nbody = body_of(response)\nif response.is_error or body is None:\n    sys.exit(f\"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}{when(response)}\")\n# 201: created now. 200 with meta.idempotency_replay true: this order already existed.\ncreated = body[\"data\"][\"order\"]\nprint(f\"order: {created['partner_reference']}\")\nprint(f\"status: {created['status']}\")\nprint(f\"order total: {created['order_total']:.2f}\")\nprint(f\"replay: {str(body['meta']['idempotency_replay']).lower()}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Create an order that survives a timeout: retry with the same partner_reference and read the replay.\n// PHP 7.4 or later, with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID,\n// MART_STATE_ID and MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that\n// running this again can never make a second order.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n$reference = (string) getenv('MART_PARTNER_REFERENCE');\nif ($reference === '') {\n    fwrite(STDERR, \"error: set MART_PARTNER_REFERENCE to your own id for this order\\n\");\n    exit(1);\n}\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\nfunction when(array $headers): string\n{\n    return isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n}\n\n/**\n * POST the same payload until it is answered for good. Retries are your choice of numbers: at most\n * 5 attempts; after no answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8\n * seconds (capped at 30) with jitter. Any other answer is final.\n */\nfunction send(string $url, string $key, string $payload, int $timeout): array\n{\n    for ($attempt = 1; ; $attempt++) {\n        [$status, $headers, $raw] = request('POST', $url, $key, $payload, $timeout);\n        if (!in_array($status, [0, 429, 500, 502, 503, 504], true) || $attempt === 5) {\n            return [$status, $headers, $raw];\n        }\n        $retryAfter = $headers['retry-after'] ?? '';\n        if (ctype_digit($retryAfter) && (int) $retryAfter > 0) {\n            if ((int) $retryAfter > 60) {\n                return [$status, $headers, $raw]; // too long to wait here: the caller says when to come back\n            }\n            $wait = (float) $retryAfter;\n        } else {\n            $backoff = min(30, 2 ** ($attempt - 1));\n            $wait = $backoff / 2 + mt_rand() / mt_getrandmax() * $backoff / 2;\n        }\n        fwrite(STDERR, sprintf(\"retry: attempt %d %s, waiting %.1f s\\n\", $attempt, $status === 0 ? 'got no answer' : \"answered $status\", $wait));\n        usleep((int) ($wait * 1000000));\n    }\n}\n\n// Decided once, before any attempt: every retry sends this same body.\n$order = json_encode([\n    'partner_reference' => $reference,\n    'payment_type' => 'cod',\n    'products' => [['product_id' => (int) getenv('MART_PRODUCT_ID'), 'quantity' => 1]],\n    'shipping_address' => [\n        'customer_name' => 'Test Buyer',\n        'phone' => '0599000000',\n        'state_id' => (int) getenv('MART_STATE_ID'),\n        'address' => 'Main street 1',\n    ],\n]);\necho \"reference: $reference\\n\"; // written down before the first attempt\n\n[$status, $headers, $raw] = send(\"$base/api/v1/orders\", $key, $order, 60);\nif ($status === 0 || $status === 429 || $status >= 500) {\n    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status) . when($headers) . \"; the order may exist: run again later with MART_PARTNER_REFERENCE=$reference\\n\");\n    exit(1);\n}\n$body = json_decode($raw, true);\nif ($status >= 300 || !is_array($body)) {\n    fwrite(STDERR, \"error: $status \" . ($body['error']['code'] ?? '(not JSON)') . when($headers) . \"\\n\");\n    exit(1);\n}\n\n// 201: created now. 200 with meta.idempotency_replay true: this order already existed.\necho \"order: {$body['data']['order']['partner_reference']}\\n\";\necho \"status: {$body['data']['order']['status']}\\n\";\nprintf(\"order total: %.2f\\n\", $body['data']['order']['order_total']);\necho 'replay: ' . ($body['meta']['idempotency_replay'] ? 'true' : 'false') . \"\\n\";\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Create an order that survives a timeout: retry with the same partner_reference and read the replay.\n// Go 1.22 or later. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and\n// MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that running this again\n// can never make a second order. Run it with: go run create-an-order.go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 60 * time.Second}\n\nfunc main() {\n\treference := os.Getenv(\"MART_PARTNER_REFERENCE\")\n\tif reference == \"\" {\n\t\tfail(fmt.Errorf(\"set MART_PARTNER_REFERENCE to your own id for this order\"))\n\t}\n\tproductID, _ := strconv.Atoi(os.Getenv(\"MART_PRODUCT_ID\"))\n\tstateID, _ := strconv.Atoi(os.Getenv(\"MART_STATE_ID\"))\n\n\t// Decided once, before any attempt: every retry sends these same bytes.\n\torder, err := json.Marshal(map[string]any{\n\t\t\"partner_reference\": reference,\n\t\t\"payment_type\":      \"cod\",\n\t\t\"products\":          []map[string]any{{\"product_id\": productID, \"quantity\": 1}},\n\t\t\"shipping_address\": map[string]any{\n\t\t\t\"customer_name\": \"Test Buyer\", \"phone\": \"0599000000\", \"state_id\": stateID, \"address\": \"Main street 1\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tfmt.Println(\"reference:\", reference) // written down before the first attempt\n\n\tresp := send(\"/api/v1/orders\", order)\n\tif resp == nil || resp.StatusCode == 429 || resp.StatusCode >= 500 {\n\t\tstatus := \"no answer\"\n\t\tif resp != nil {\n\t\t\tstatus = strconv.Itoa(resp.StatusCode)\n\t\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\t\tstatus += \", try again after \" + after + \" s\"\n\t\t\t}\n\t\t}\n\t\tfail(fmt.Errorf(\"%s; the order may exist: run again later with MART_PARTNER_REFERENCE=%s\", status, reference))\n\t}\n\tvar answer struct {\n\t\tData struct {\n\t\t\tOrder struct {\n\t\t\t\tPartnerReference string  `json:\"partner_reference\"`\n\t\t\t\tStatus           string  `json:\"status\"`\n\t\t\t\tOrderTotal       float64 `json:\"order_total\"`\n\t\t\t} `json:\"order\"`\n\t\t} `json:\"data\"`\n\t\tMeta struct {\n\t\t\tIdempotencyReplay bool `json:\"idempotency_replay\"`\n\t\t} `json:\"meta\"`\n\t}\n\tdecode(resp, &answer)\n\t// 201: created now. 200 with meta.idempotency_replay true: this order already existed.\n\tfmt.Println(\"order:\", answer.Data.Order.PartnerReference)\n\tfmt.Println(\"status:\", answer.Data.Order.Status)\n\tfmt.Printf(\"order total: %.2f\\n\", answer.Data.Order.OrderTotal)\n\tfmt.Println(\"replay:\", answer.Meta.IdempotencyReplay)\n}\n\nvar retryable = map[int]bool{429: true, 500: true, 502: true, 503: true, 504: true}\n\n// send POSTs the same bytes until they are answered for good, and returns the last answer, or\n// nil when no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no\n// answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)\n// with jitter. Any other answer is final.\nfunc send(path string, payload []byte) *http.Response {\n\tfor attempt := 1; ; attempt++ {\n\t\treq, err := http.NewRequest(http.MethodPost, os.Getenv(\"MART_API_BASE\")+path, bytes.NewReader(payload))\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tif err != nil && attempt == 5 {\n\t\t\treturn nil\n\t\t}\n\t\tif err == nil && (!retryable[resp.StatusCode] || attempt == 5) {\n\t\t\treturn resp\n\t\t}\n\t\twhat := \"got no answer\"\n\t\tbackoff := math.Min(30, math.Pow(2, float64(attempt-1)))\n\t\twait := backoff/2 + rand.Float64()*backoff/2\n\t\tif err == nil {\n\t\t\twhat = fmt.Sprintf(\"answered %d\", resp.StatusCode)\n\t\t\tif seconds, convErr := strconv.Atoi(resp.Header.Get(\"Retry-After\")); convErr == nil && seconds > 0 {\n\t\t\t\tif seconds > 60 {\n\t\t\t\t\treturn resp // too long to wait here: the caller says when to come back\n\t\t\t\t}\n\t\t\t\twait = float64(seconds)\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"retry: attempt %d %s, waiting %.1f s\\n\", attempt, what, wait)\n\t\ttime.Sleep(time.Duration(wait * float64(time.Second)))\n\t}\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Create an order that survives a timeout: retry with the same partner_reference and read the replay.\n// Java 17 or later, with Jackson. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID, MART_STATE_ID and\n// MART_PARTNER_REFERENCE: your own id for this order, from your own system, so that running this again\n// can never make a second order. Run it as a single file: java -cp <the Jackson jars> create-an-order.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ThreadLocalRandom;\n\nclass CreateAnOrder {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        String reference = System.getenv(\"MART_PARTNER_REFERENCE\");\n        if (reference == null || reference.isEmpty()) {\n            fail(\"set MART_PARTNER_REFERENCE to your own id for this order\");\n        }\n\n        // Decided once, before any attempt: every retry sends this same body.\n        String order = JSON.writeValueAsString(Map.of(\n                \"partner_reference\", reference,\n                \"payment_type\", \"cod\",\n                \"products\", List.of(Map.of(\"product_id\", Integer.parseInt(System.getenv(\"MART_PRODUCT_ID\")), \"quantity\", 1)),\n                \"shipping_address\", Map.of(\"customer_name\", \"Test Buyer\", \"phone\", \"0599000000\",\n                        \"state_id\", Integer.parseInt(System.getenv(\"MART_STATE_ID\")), \"address\", \"Main street 1\")));\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + \"/api/v1/orders\"))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .header(\"Content-Type\", \"application/json\")\n                .timeout(Duration.ofSeconds(60))\n                .POST(HttpRequest.BodyPublishers.ofString(order))\n                .build();\n        System.out.println(\"reference: \" + reference); // written down before the first attempt\n\n        HttpResponse<String> response = send(request);\n        if (response == null || response.statusCode() == 429 || response.statusCode() >= 500) {\n            String status = response == null ? \"no answer\" : response.statusCode() + when(response);\n            fail(status + \"; the order may exist: run again later with MART_PARTNER_REFERENCE=\" + reference);\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        // 201: created now. 200 with meta.idempotency_replay true: this order already existed.\n        JsonNode created = body.path(\"data\").path(\"order\");\n        System.out.println(\"order: \" + created.path(\"partner_reference\").asText());\n        System.out.println(\"status: \" + created.path(\"status\").asText());\n        System.out.printf(Locale.ROOT, \"order total: %.2f%n\", created.path(\"order_total\").asDouble());\n        System.out.println(\"replay: \" + body.path(\"meta\").path(\"idempotency_replay\").asBoolean());\n    }\n\n    static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);\n\n    /**\n     * Sends the same request until it is answered for good, and returns the last answer, or null when\n     * no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no answer, a\n     * 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter.\n     * Any other answer is final.\n     */\n    static HttpResponse<String> send(HttpRequest request) throws InterruptedException {\n        for (int attempt = 1; ; attempt++) {\n            HttpResponse<String> response = null;\n            try {\n                response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n                if (!RETRYABLE.contains(response.statusCode()) || attempt == 5) {\n                    return response;\n                }\n            } catch (IOException e) {\n                if (attempt == 5) {\n                    return null;\n                }\n            }\n            double backoff = Math.min(30, Math.pow(2, attempt - 1));\n            double wait = backoff / 2 + ThreadLocalRandom.current().nextDouble() * backoff / 2;\n            String what = \"got no answer\";\n            if (response != null) {\n                what = \"answered \" + response.statusCode();\n                String after = response.headers().firstValue(\"Retry-After\").orElse(\"\");\n                if (after.matches(\"[0-9]+\") && Long.parseLong(after) > 0) {\n                    if (Long.parseLong(after) > 60) {\n                        return response; // too long to wait here: the caller says when to come back\n                    }\n                    wait = Long.parseLong(after);\n                }\n            }\n            System.err.printf(Locale.ROOT, \"retry: attempt %d %s, waiting %.1f s%n\", attempt, what, wait);\n            Thread.sleep((long) (wait * 1000));\n        }\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/orders/validate": {
      "post": {
        "summary": "Validate an order without creating it",
        "description": "The dry-run twin of `POST /api/v1/orders`: same body, same validation pipeline, byte-identical error envelopes — but nothing is written, reserved or consumed. Idempotency is predicted, not processed. A valid order answers a `quote`: its products total, delivery fee, totals and reward exactly as a create with the same body would freeze them right now. A 200 is point-in-time: stock, prices and delivery fees can still move before the real create, and the create answer is the binding one. Details: https://mart.ps/api/docs#orders.",
        "tags": [
          "Orders"
        ],
        "operationId": "validateOrder",
        "x-required-scope": "orders:write",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OrderCreateRequest"
              },
              "example": {
                "partner_reference": "100245",
                "payment_type": "cod",
                "shipping_address": {
                  "customer_name": "محمد علي",
                  "phone": "0599123456",
                  "extra_phone": "022345678",
                  "state_id": 386,
                  "address": "شارع الإرسال، عمارة 12",
                  "notes": null
                },
                "products": [
                  {
                    "product_id": 9597,
                    "combination_id": 41206,
                    "quantity": 2,
                    "price": 120.0
                  }
                ],
                "free_shipping": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The order would be accepted, and this is what it would cost and earn. Point-in-time verdict — nothing was created or reserved.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "validation": {
                              "$ref": "#/components/schemas/Validation"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "Order is valid",
                  "data": {
                    "validation": {
                      "valid": true,
                      "quote": {
                        "products_total": 240.0,
                        "shipping_fee": 35.0,
                        "free_shipping": true,
                        "order_total": 240.0,
                        "cod_total": 240.0,
                        "reward": {
                          "gross": 130.02,
                          "shipping_deduction": 35.0,
                          "net": 95.02
                        }
                      }
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/ForbiddenGroup"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/IdempotencyConflict"
          },
          "422": {
            "$ref": "#/components/responses/OrderUnprocessable"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Show what delivery costs to one town, then quote an order without placing it.\n# Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\nset -euo pipefail\nexport LC_NUMERIC=C # printf reads and writes amounts with a decimal point\n\n# api METHOD PATH [JSON]: sets $body, or prints the status and error code and stops.\napi() {\n  local response status retry_after\n  response=$(curl --silent --show-error --max-time 30 --request \"$1\" \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") --header 'Content-Type: application/json' \\\n    ${3:+--data \"$3\"} --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE$2\") || { echo \"error: no answer\" >&2; exit 1; }\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  if [ \"$status\" -ge 300 ]; then\n    echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n    exit 1\n  fi\n}\n\n# 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n#    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n#    on its own schedule, never once per visitor.\napi GET /api/v1/states\nfees=$(jq -c --argjson state \"$MART_STATE_ID\" '[.data.cities[].states[] | select(.id == $state)] | first | .delivery.fees' <<<\"$body\")\nif [ \"$fees\" = null ]; then\n  echo \"error: state $MART_STATE_ID is not a delivery town\" >&2\n  exit 1\nfi\necho \"delivery fees for state $MART_STATE_ID:\"\njq -r '.[] | \"\\(.from_total) \\(.to_total) \\(.fee)\"' <<<\"$fees\" |\n  while read -r from to fee; do\n    if [ \"$to\" != null ]; then\n      printf '  from %.2f, less than %.2f: %.2f\\n' \"$from\" \"$to\" \"$fee\"\n    else\n      printf '  from %.2f: %.2f\\n' \"$from\" \"$fee\"\n    fi\n  done\n\n# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n#    reserved, but it counts against the same per-minute budget as creating orders.\norder=$(jq -n --arg ref \"quote-$(date +%s)\" --argjson product \"$MART_PRODUCT_ID\" --argjson state \"$MART_STATE_ID\" '{\n  partner_reference: $ref,\n  payment_type: \"cod\",\n  products: [{product_id: $product, quantity: 1}],\n  shipping_address: {customer_name: \"Test Buyer\", phone: \"0599000000\", state_id: $state, address: \"Main street 1\"}\n}')\napi POST /api/v1/orders/validate \"$order\"\njq -r '\"valid: \\(.data.validation.valid)\"' <<<\"$body\"\nread -r products fee total < <(jq -r '.data.validation.quote | \"\\(.products_total) \\(.shipping_fee) \\(.order_total)\"' <<<\"$body\")\nprintf 'products total: %.2f\\ndelivery fee: %.2f\\norder total: %.2f\\n' \"$products\" \"$fee\" \"$total\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Show what delivery costs to one town, then quote an order without placing it.\n// Node 22.18 or later runs this .ts file as it is.\n// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nif (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');\nconst productId = Number(process.env.MART_PRODUCT_ID);\nconst stateId = Number(process.env.MART_STATE_ID);\n\nasync function api(method: string, path: string, payload?: unknown): Promise<any> {\n  const response = await fetch(`${base}${path}`, {\n    method,\n    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },\n    body: payload === undefined ? undefined : JSON.stringify(payload),\n    signal: AbortSignal.timeout(30_000),\n  });\n  const body = await response.json().catch(() => null); // an edge error page is not JSON\n  if (!response.ok || body === null) {\n    const retryAfter = response.headers.get('retry-after');\n    console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);\n    process.exit(1);\n  }\n  return body;\n}\n\n// 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n//    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n//    on its own schedule, never once per visitor.\nconst states = await api('GET', '/api/v1/states');\nconst town = states.data.cities.flatMap((city: any) => city.states).find((state: any) => state.id === stateId);\nif (!town) {\n  console.error(`error: state ${stateId} is not a delivery town`);\n  process.exit(1);\n}\nconsole.log(`delivery fees for state ${stateId}:`);\nfor (const bracket of town.delivery.fees) {\n  const upper = bracket.to_total === null ? '' : `, less than ${bracket.to_total.toFixed(2)}`;\n  console.log(`  from ${bracket.from_total.toFixed(2)}${upper}: ${bracket.fee.toFixed(2)}`);\n}\n\n// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n//    reserved, but it counts against the same per-minute budget as creating orders.\nconst result = await api('POST', '/api/v1/orders/validate', {\n  partner_reference: `quote-${Date.now()}`,\n  payment_type: 'cod',\n  products: [{ product_id: productId, quantity: 1 }],\n  shipping_address: { customer_name: 'Test Buyer', phone: '0599000000', state_id: stateId, address: 'Main street 1' },\n});\nconst quote = result.data.validation.quote;\nconsole.log(`valid: ${result.data.validation.valid}`);\nconsole.log(`products total: ${quote.products_total.toFixed(2)}`);\nconsole.log(`delivery fee: ${quote.shipping_fee.toFixed(2)}`);\nconsole.log(`order total: ${quote.order_total.toFixed(2)}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Show what delivery costs to one town, then quote an order without placing it. Python 3.9+, httpx.\n\nNeeds MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\n\"\"\"\nimport os\nimport sys\nimport time\n\nimport httpx\n\nTIMEOUT = 30\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\nproduct_id = int(os.environ[\"MART_PRODUCT_ID\"])\nstate_id = int(os.environ[\"MART_STATE_ID\"])\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\n\ndef check(response: httpx.Response) -> dict:\n    body = body_of(response)\n    if response.is_error or body is None:\n        code = body[\"error\"][\"code\"] if body else \"(not JSON)\"\n        retry_after = response.headers.get(\"Retry-After\")\n        sys.exit(f\"error: {response.status_code} {code}\" + (f\", try again after {retry_after} s\" if retry_after else \"\"))\n    return body\n\n\n# 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n#    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n#    on its own schedule, never once per visitor.\ncities = check(client.get(\"/api/v1/states\"))[\"data\"][\"cities\"]\ntown = next((state for city in cities for state in city[\"states\"] if state[\"id\"] == state_id), None)\nif town is None:\n    sys.exit(f\"error: state {state_id} is not a delivery town\")\nprint(f\"delivery fees for state {state_id}:\")\nfor bracket in town[\"delivery\"][\"fees\"]:\n    upper = \"\" if bracket[\"to_total\"] is None else f\", less than {bracket['to_total']:.2f}\"\n    print(f\"  from {bracket['from_total']:.2f}{upper}: {bracket['fee']:.2f}\")\n\n# 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n#    reserved, but it counts against the same per-minute budget as creating orders.\nresult = check(client.post(\"/api/v1/orders/validate\", json={\n    \"partner_reference\": f\"quote-{int(time.time())}\",\n    \"payment_type\": \"cod\",\n    \"products\": [{\"product_id\": product_id, \"quantity\": 1}],\n    \"shipping_address\": {\"customer_name\": \"Test Buyer\", \"phone\": \"0599000000\", \"state_id\": state_id, \"address\": \"Main street 1\"},\n}))[\"data\"][\"validation\"]\nprint(f\"valid: {str(result['valid']).lower()}\")\nprint(f\"products total: {result['quote']['products_total']:.2f}\")\nprint(f\"delivery fee: {result['quote']['shipping_fee']:.2f}\")\nprint(f\"order total: {result['quote']['order_total']:.2f}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Show what delivery costs to one town, then quote an order without placing it. PHP 7.4 or later,\n// with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n$productId = (int) getenv('MART_PRODUCT_ID');\n$stateId = (int) getenv('MART_STATE_ID');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** A GET that must succeed: the decoded body, or the status and error code, and stop. */\nfunction get(string $url, string $key): array\n{\n    [$status, $headers, $raw] = request('GET', $url, $key);\n    $body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)\n    if ($status < 200 || $status >= 300 || !is_array($body)) {\n        $code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');\n        $wait = isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n        fwrite(STDERR, \"error: $code$wait\\n\");\n        exit(1);\n    }\n\n    return $body;\n}\n\n// 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n//    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n//    on its own schedule, never once per visitor.\n$states = get(\"$base/api/v1/states\", $key);\n$town = null;\nforeach ($states['data']['cities'] as $city) {\n    foreach ($city['states'] as $state) {\n        if ($state['id'] === $stateId) {\n            $town = $state;\n        }\n    }\n}\nif ($town === null) {\n    fwrite(STDERR, \"error: state $stateId is not a delivery town\\n\");\n    exit(1);\n}\necho \"delivery fees for state $stateId:\\n\";\nforeach ($town['delivery']['fees'] as $bracket) {\n    $upper = $bracket['to_total'] === null ? '' : sprintf(', less than %.2f', $bracket['to_total']);\n    printf(\"  from %.2f%s: %.2f\\n\", $bracket['from_total'], $upper, $bracket['fee']);\n}\n\n// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n//    reserved, but it counts against the same per-minute budget as creating orders.\n[$status, $headers, $raw] = request('POST', \"$base/api/v1/orders/validate\", $key, json_encode([\n    'partner_reference' => 'quote-' . time(),\n    'payment_type' => 'cod',\n    'products' => [['product_id' => $productId, 'quantity' => 1]],\n    'shipping_address' => ['customer_name' => 'Test Buyer', 'phone' => '0599000000', 'state_id' => $stateId, 'address' => 'Main street 1'],\n]));\n$result = json_decode($raw, true);\nif ($status !== 200 || !is_array($result)) {\n    $wait = isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($result['error']['code'] ?? '(not JSON)')) . \"$wait\\n\");\n    exit(1);\n}\n$validation = $result['data']['validation'];\necho 'valid: ' . ($validation['valid'] ? 'true' : 'false') . \"\\n\";\nprintf(\"products total: %.2f\\n\", $validation['quote']['products_total']);\nprintf(\"delivery fee: %.2f\\n\", $validation['quote']['shipping_fee']);\nprintf(\"order total: %.2f\\n\", $validation['quote']['order_total']);\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Show what delivery costs to one town, then quote an order without placing it. Go 1.22 or later.\n// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\n// Run it with: go run delivery-prices-and-quote.go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tproductID, _ := strconv.Atoi(os.Getenv(\"MART_PRODUCT_ID\"))\n\tstateID, _ := strconv.Atoi(os.Getenv(\"MART_STATE_ID\"))\n\n\t// 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n\t//    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n\t//    on its own schedule, never once per visitor.\n\tvar tree struct {\n\t\tData struct {\n\t\t\tCities []struct {\n\t\t\t\tStates []struct {\n\t\t\t\t\tID       int `json:\"id\"`\n\t\t\t\t\tDelivery struct {\n\t\t\t\t\t\tFees []struct {\n\t\t\t\t\t\t\tFrom float64  `json:\"from_total\"`\n\t\t\t\t\t\t\tTo   *float64 `json:\"to_total\"` // null: no upper end\n\t\t\t\t\t\t\tFee  float64  `json:\"fee\"`\n\t\t\t\t\t\t} `json:\"fees\"`\n\t\t\t\t\t} `json:\"delivery\"`\n\t\t\t\t} `json:\"states\"`\n\t\t\t} `json:\"cities\"`\n\t\t} `json:\"data\"`\n\t}\n\tget(\"/api/v1/states\", &tree)\n\tfound := false\n\tfor _, city := range tree.Data.Cities {\n\t\tfor _, state := range city.States {\n\t\t\tif state.ID != stateID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfound = true\n\t\t\tfmt.Printf(\"delivery fees for state %d:\\n\", stateID)\n\t\t\tfor _, b := range state.Delivery.Fees {\n\t\t\t\tif b.To != nil {\n\t\t\t\t\tfmt.Printf(\"  from %.2f, less than %.2f: %.2f\\n\", b.From, *b.To, b.Fee)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"  from %.2f: %.2f\\n\", b.From, b.Fee)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !found {\n\t\tfail(fmt.Errorf(\"state %d is not a delivery town\", stateID))\n\t}\n\n\t// 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n\t//    reserved, but it counts against the same per-minute budget as creating orders.\n\torder, err := json.Marshal(map[string]any{\n\t\t\"partner_reference\": fmt.Sprintf(\"quote-%d\", time.Now().Unix()),\n\t\t\"payment_type\":      \"cod\",\n\t\t\"products\":          []map[string]any{{\"product_id\": productID, \"quantity\": 1}},\n\t\t\"shipping_address\": map[string]any{\n\t\t\t\"customer_name\": \"Test Buyer\", \"phone\": \"0599000000\", \"state_id\": stateID, \"address\": \"Main street 1\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq, err := http.NewRequest(http.MethodPost, os.Getenv(\"MART_API_BASE\")+\"/api/v1/orders/validate\", bytes.NewReader(order))\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tvar result struct {\n\t\tData struct {\n\t\t\tValidation struct {\n\t\t\t\tValid bool `json:\"valid\"`\n\t\t\t\tQuote struct {\n\t\t\t\t\tProductsTotal float64 `json:\"products_total\"`\n\t\t\t\t\tShippingFee   float64 `json:\"shipping_fee\"`\n\t\t\t\t\tOrderTotal    float64 `json:\"order_total\"`\n\t\t\t\t} `json:\"quote\"`\n\t\t\t} `json:\"validation\"`\n\t\t} `json:\"data\"`\n\t}\n\tdecode(resp, &result)\n\tv := result.Data.Validation\n\tfmt.Println(\"valid:\", v.Valid)\n\tfmt.Printf(\"products total: %.2f\\ndelivery fee: %.2f\\norder total: %.2f\\n\",\n\t\tv.Quote.ProductsTotal, v.Quote.ShippingFee, v.Quote.OrderTotal)\n}\n\n// get sends one GET and decodes its answer into out.\nfunc get(path string, out any) {\n\treq, err := http.NewRequest(http.MethodGet, os.Getenv(\"MART_API_BASE\")+path, nil)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tdecode(resp, out)\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Show what delivery costs to one town, then quote an order without placing it. Java 17 or later, with Jackson.\n// Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID (a town's state id).\n// Run it as a single file: java -cp <the Jackson jars> delivery-prices-and-quote.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\n\nclass DeliveryPricesAndQuote {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        int productId = Integer.parseInt(System.getenv(\"MART_PRODUCT_ID\"));\n        int stateId = Integer.parseInt(System.getenv(\"MART_STATE_ID\"));\n\n        // 1. The town's fee brackets: a products total of at least \"from\" and less than \"to\" pays \"fee\".\n        //    The towns and their fees change rarely: a storefront keeps this answer and reads it again\n        //    on its own schedule, never once per visitor.\n        JsonNode town = null;\n        for (JsonNode city : get(\"/api/v1/states\").path(\"data\").path(\"cities\")) {\n            for (JsonNode state : city.path(\"states\")) {\n                if (state.path(\"id\").asInt() == stateId) {\n                    town = state;\n                }\n            }\n        }\n        if (town == null) {\n            fail(\"state \" + stateId + \" is not a delivery town\");\n        }\n        System.out.println(\"delivery fees for state \" + stateId + \":\");\n        for (JsonNode bracket : town.path(\"delivery\").path(\"fees\")) {\n            String upper = bracket.path(\"to_total\").isNull() ? \"\"\n                    : String.format(Locale.ROOT, \", less than %.2f\", bracket.path(\"to_total\").asDouble());\n            System.out.printf(Locale.ROOT, \"  from %.2f%s: %.2f%n\", bracket.path(\"from_total\").asDouble(), upper,\n                    bracket.path(\"fee\").asDouble());\n        }\n\n        // 2. The quote, for a real cart only: the same body as a real order. Nothing is created or\n        //    reserved, but it counts against the same per-minute budget as creating orders.\n        String order = JSON.writeValueAsString(Map.of(\n                \"partner_reference\", \"quote-\" + System.currentTimeMillis(),\n                \"payment_type\", \"cod\",\n                \"products\", List.of(Map.of(\"product_id\", productId, \"quantity\", 1)),\n                \"shipping_address\", Map.of(\"customer_name\", \"Test Buyer\", \"phone\", \"0599000000\",\n                        \"state_id\", stateId, \"address\", \"Main street 1\")));\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + \"/api/v1/orders/validate\"))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .header(\"Content-Type\", \"application/json\")\n                .timeout(Duration.ofSeconds(30))\n                .POST(HttpRequest.BodyPublishers.ofString(order))\n                .build();\n        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        JsonNode result = parse(response.body());\n        if (response.statusCode() >= 300 || result == null) {\n            fail(response.statusCode() + \" \" + code(result) + when(response));\n        }\n        JsonNode validation = result.path(\"data\").path(\"validation\");\n        JsonNode quote = validation.path(\"quote\");\n        System.out.println(\"valid: \" + validation.path(\"valid\").asBoolean());\n        System.out.printf(Locale.ROOT, \"products total: %.2f%n\", quote.path(\"products_total\").asDouble());\n        System.out.printf(Locale.ROOT, \"delivery fee: %.2f%n\", quote.path(\"shipping_fee\").asDouble());\n        System.out.printf(Locale.ROOT, \"order total: %.2f%n\", quote.path(\"order_total\").asDouble());\n    }\n\n    /** One GET that must succeed: the decoded body, or the status and error code, and stop. */\n    static JsonNode get(String path) throws InterruptedException {\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + path))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .timeout(Duration.ofSeconds(30))\n                .GET()\n                .build();\n        HttpResponse<String> response;\n        try {\n            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        } catch (IOException e) {\n            fail(\"no answer: \" + e.getMessage());\n            return null;\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        return body;\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/orders/cancel/{partner_reference}": {
      "post": {
        "summary": "Cancel an order by partner reference",
        "description": "Cancels an order you created, addressed by YOUR reference. Same permission as creation. Mart's configuration decides which states are cancellable (409 `order_not_cancellable` past that point). Repeating is safe and IS the retry procedure: an already-cancelled order answers 200 with `already_cancelled: true`. Not a refund. Details: https://mart.ps/api/docs#orders.",
        "tags": [
          "Orders"
        ],
        "operationId": "cancelOrderByPartnerReference",
        "x-required-scope": "orders:write",
        "parameters": [
          {
            "name": "partner_reference",
            "in": "path",
            "required": true,
            "description": "The reference you submitted to POST /api/v1/orders, exactly as you sent it. Letters, digits, dot, underscore, hyphen; max 64 characters. A reference outside that shape does not match this route at all and answers 404 `route_not_found`.",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9._-]{1,64}$",
              "maxLength": 64,
              "example": "PARTNER-ORDER-100245"
            }
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OrderCancelRequest"
              },
              "example": {
                "reason": "Customer requested cancellation"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The order is cancelled. `already_cancelled` says whether THIS call did it (`false`) or found it already done (`true`) — both are successes.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "order": {
                              "$ref": "#/components/schemas/CancelledOrder"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "Order cancelled",
                  "data": {
                    "order": {
                      "partner_reference": "PARTNER-ORDER-100245",
                      "status": {
                        "id": 6,
                        "name": "Cancelled"
                      },
                      "cancelled_at": "2026-08-04T08:15:00+00:00",
                      "already_cancelled": false
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/ForbiddenGroup"
          },
          "404": {
            "$ref": "#/components/responses/OrderNotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/OrderNotCancellable"
          },
          "422": {
            "$ref": "#/components/responses/OrderUnprocessable"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/OrderCancellationNotConfigured"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Cancel an order you created, by your own reference. Repeating it is safe.\n# Needs MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE.\nset -euo pipefail\n\nreference=${MART_PARTNER_REFERENCE:?set MART_PARTNER_REFERENCE to the order\\'s reference}\n\n# A cancel that already happened answers 200 with already_cancelled true, so after no answer, a\n# 429 or a 5xx the recovery is to send it again. Retries are your choice of numbers: at most 5\n# attempts, waiting what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter.\nfor attempt in 1 2 3 4 5; do\n  response=$(curl --silent --show-error --max-time 30 --request POST \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") --header 'Content-Type: application/json' \\\n    --data '{\"reason\": \"The customer changed their mind\"}' --write-out '\\n%{http_code} %header{retry-after}' \\\n    \"$MART_API_BASE/api/v1/orders/cancel/$(jq -rn --arg r \"$reference\" '$r | @uri')\") || response=$'\\n000'\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  case $status in 000 | 429 | 500 | 502 | 503 | 504) ;; *) break ;; esac\n  [ \"$attempt\" = 5 ] && break\n  if [[ $retry_after =~ ^[0-9]+$ ]]; then\n    if [ \"$retry_after\" -gt 60 ]; then\n      echo \"error: $status, try again after $retry_after s\" >&2\n      exit 1\n    fi\n    wait_ms=$((retry_after * 1000))\n  else\n    wait_ms=$((1000 << (attempt - 1)))\n    [ \"$wait_ms\" -gt 30000 ] && wait_ms=30000\n    wait_ms=$((wait_ms / 2 + RANDOM % (wait_ms / 2 + 1)))\n  fi\n  printf 'retry: attempt %d %s, waiting %d.%d s\\n' \"$attempt\" \\\n    \"$([ \"$status\" = 000 ] && echo 'got no answer' || echo \"answered $status\")\" $((wait_ms / 1000)) $((wait_ms % 1000 / 100)) >&2\n  sleep \"$((wait_ms / 1000)).$(printf '%03d' $((wait_ms % 1000)))\"\ndone\n\nif [ \"$status\" = 000 ]; then\n  echo \"error: no answer; send the cancel again later\" >&2\n  exit 1\nfi\nif [ \"$status\" -ge 300 ]; then\n  echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n  exit 1\nfi\njq -r '.data.order | \"order: \\(.partner_reference)\\nstatus id: \\(.status.id)\\nalready cancelled: \\(.already_cancelled)\"' <<<\"$body\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Cancel an order you created, by your own reference. Repeating it is safe.\n// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nconst reference = process.env.MART_PARTNER_REFERENCE;\nif (!base || !key || !reference) throw new Error('Set MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE');\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\nconst RETRYABLE = new Set([429, 500, 502, 503, 504]);\n\n// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n// what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n// is final. Every attempt sends the same bytes.\nasync function send(path: string, payload: string, timeoutMs: number): Promise<Response | null> {\n  for (let attempt = 1; ; attempt++) {\n    let response: Response | null = null;\n    try {\n      response = await fetch(`${base}${path}`, {\n        method: 'POST',\n        headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },\n        body: payload,\n        signal: AbortSignal.timeout(timeoutMs),\n      });\n      if (!RETRYABLE.has(response.status) || attempt === 5) return response;\n    } catch {\n      if (attempt === 5) return null; // no answer at all\n    }\n    let wait: number;\n    const retryAfter = Number(response?.headers.get('retry-after'));\n    if (response && Number.isInteger(retryAfter) && retryAfter > 0) {\n      if (retryAfter > 60) return response; // too long to wait here: the caller says when to come back\n      wait = retryAfter;\n    } else {\n      const backoff = Math.min(30, 2 ** (attempt - 1));\n      wait = backoff / 2 + (Math.random() * backoff) / 2;\n    }\n    console.error(`retry: attempt ${attempt} ${response ? `answered ${response.status}` : 'got no answer'}, waiting ${wait.toFixed(1)} s`);\n    await sleep(wait * 1000);\n  }\n}\n\n// A cancel that already happened answers 200 with already_cancelled true, so sending it again\n// after no answer is the recovery.\nconst response = await send(`/api/v1/orders/cancel/${encodeURIComponent(reference)}`,\n  JSON.stringify({ reason: 'The customer changed their mind' }), 30_000);\nconst body = response ? await response.json().catch(() => null) : null;\nif (response === null) {\n  console.error('error: no answer; send the cancel again later');\n  process.exit(1);\n}\nif (!response.ok || body === null) {\n  const when = response.headers.get('retry-after');\n  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${when ? `, try again after ${when} s` : ''}`);\n  process.exit(1);\n}\nconsole.log(`order: ${body.data.order.partner_reference}`);\nconsole.log(`status id: ${body.data.order.status.id}`);\nconsole.log(`already cancelled: ${body.data.order.already_cancelled}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Cancel an order you created, by your own reference. Repeating it is safe. Python 3.9+, httpx.\n\nNeeds MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE.\n\"\"\"\nimport os\nimport random\nimport sys\nimport time\nfrom urllib.parse import quote\n\nimport httpx\n\nTIMEOUT = 30\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\nreference = os.environ[\"MART_PARTNER_REFERENCE\"]\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\nRETRYABLE = {429, 500, 502, 503, 504}\n\n\ndef send(path: str, payload: dict):\n    \"\"\"POST the same payload until it is answered for good.\n\n    Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n    what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n    is final. Returns None when no attempt got an answer.\n    \"\"\"\n    for attempt in range(1, 6):\n        response = None\n        try:\n            response = client.post(path, json=payload)\n            if response.status_code not in RETRYABLE or attempt == 5:\n                return response\n        except httpx.TransportError:\n            if attempt == 5:\n                return None\n        retry_after = response.headers.get(\"Retry-After\", \"\") if response is not None else \"\"\n        if retry_after.isdigit() and int(retry_after) > 0:\n            if int(retry_after) > 60:\n                return response  # too long to wait here: the caller says when to come back\n            wait = float(retry_after)\n        else:\n            backoff = min(30, 2 ** (attempt - 1))\n            wait = backoff / 2 + random.uniform(0, backoff / 2)\n        what = f\"answered {response.status_code}\" if response is not None else \"got no answer\"\n        print(f\"retry: attempt {attempt} {what}, waiting {wait:.1f} s\", file=sys.stderr)\n        time.sleep(wait)\n\n\ndef when(response) -> str:\n    \"\"\"\", try again after N s\" when the answer says how long to wait (Retry-After), else nothing.\"\"\"\n    retry_after = response.headers.get(\"Retry-After\") if response is not None else None\n    return f\", try again after {retry_after} s\" if retry_after else \"\"\n\n\n# A cancel that already happened answers 200 with already_cancelled true, so sending it again\n# after no answer is the recovery.\nresponse = send(f\"/api/v1/orders/cancel/{quote(reference, safe='')}\", {\"reason\": \"The customer changed their mind\"})\nif response is None:\n    sys.exit(\"error: no answer; send the cancel again later\")\nbody = body_of(response)\nif response.is_error or body is None:\n    sys.exit(f\"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}{when(response)}\")\ncancelled = body[\"data\"][\"order\"]\nprint(f\"order: {cancelled['partner_reference']}\")\nprint(f\"status id: {cancelled['status']['id']}\")\nprint(f\"already cancelled: {str(cancelled['already_cancelled']).lower()}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Cancel an order you created, by your own reference. Repeating it is safe. PHP 7.4 or later, with\n// the curl extension. Needs MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n$reference = (string) getenv('MART_PARTNER_REFERENCE');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\nfunction when(array $headers): string\n{\n    return isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n}\n\n/**\n * POST the same payload until it is answered for good. Retries are your choice of numbers: at most\n * 5 attempts; after no answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8\n * seconds (capped at 30) with jitter. Any other answer is final.\n */\nfunction send(string $url, string $key, string $payload, int $timeout): array\n{\n    for ($attempt = 1; ; $attempt++) {\n        [$status, $headers, $raw] = request('POST', $url, $key, $payload, $timeout);\n        if (!in_array($status, [0, 429, 500, 502, 503, 504], true) || $attempt === 5) {\n            return [$status, $headers, $raw];\n        }\n        $retryAfter = $headers['retry-after'] ?? '';\n        if (ctype_digit($retryAfter) && (int) $retryAfter > 0) {\n            if ((int) $retryAfter > 60) {\n                return [$status, $headers, $raw]; // too long to wait here: the caller says when to come back\n            }\n            $wait = (float) $retryAfter;\n        } else {\n            $backoff = min(30, 2 ** ($attempt - 1));\n            $wait = $backoff / 2 + mt_rand() / mt_getrandmax() * $backoff / 2;\n        }\n        fwrite(STDERR, sprintf(\"retry: attempt %d %s, waiting %.1f s\\n\", $attempt, $status === 0 ? 'got no answer' : \"answered $status\", $wait));\n        usleep((int) ($wait * 1000000));\n    }\n}\n\n// A cancel that already happened answers 200 with already_cancelled true, so sending it again\n// after no answer is the recovery.\n[$status, $headers, $raw] = send(\"$base/api/v1/orders/cancel/\" . rawurlencode($reference), $key,\n    json_encode(['reason' => 'The customer changed their mind']), 30);\nif ($status === 0) {\n    fwrite(STDERR, \"error: no answer; send the cancel again later\\n\");\n    exit(1);\n}\n$body = json_decode($raw, true);\nif ($status >= 300 || !is_array($body)) {\n    fwrite(STDERR, \"error: $status \" . ($body['error']['code'] ?? '(not JSON)') . when($headers) . \"\\n\");\n    exit(1);\n}\n$cancelled = $body['data']['order'];\necho \"order: {$cancelled['partner_reference']}\\n\";\necho \"status id: {$cancelled['status']['id']}\\n\";\necho 'already cancelled: ' . ($cancelled['already_cancelled'] ? 'true' : 'false') . \"\\n\";\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Cancel an order you created, by your own reference. Repeating it is safe. Go 1.22 or later.\n// Needs MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE. Run it with: go run cancel-an-order.go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\treference := os.Getenv(\"MART_PARTNER_REFERENCE\")\n\t// A cancel that already happened answers 200 with already_cancelled true, so sending it again\n\t// after no answer is the recovery.\n\tresp := send(\"/api/v1/orders/cancel/\"+url.PathEscape(reference), []byte(`{\"reason\": \"The customer changed their mind\"}`))\n\tif resp == nil {\n\t\tfail(fmt.Errorf(\"no answer; send the cancel again later\"))\n\t}\n\tvar answer struct {\n\t\tData struct {\n\t\t\tOrder struct {\n\t\t\t\tPartnerReference string `json:\"partner_reference\"`\n\t\t\t\tStatus           struct {\n\t\t\t\t\tID int `json:\"id\"`\n\t\t\t\t} `json:\"status\"`\n\t\t\t\tAlreadyCancelled bool `json:\"already_cancelled\"`\n\t\t\t} `json:\"order\"`\n\t\t} `json:\"data\"`\n\t}\n\tdecode(resp, &answer)\n\tfmt.Println(\"order:\", answer.Data.Order.PartnerReference)\n\tfmt.Println(\"status id:\", answer.Data.Order.Status.ID)\n\tfmt.Println(\"already cancelled:\", answer.Data.Order.AlreadyCancelled)\n}\n\nvar retryable = map[int]bool{429: true, 500: true, 502: true, 503: true, 504: true}\n\n// send POSTs the same bytes until they are answered for good, and returns the last answer, or\n// nil when no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no\n// answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)\n// with jitter. Any other answer is final.\nfunc send(path string, payload []byte) *http.Response {\n\tfor attempt := 1; ; attempt++ {\n\t\treq, err := http.NewRequest(http.MethodPost, os.Getenv(\"MART_API_BASE\")+path, bytes.NewReader(payload))\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tif err != nil && attempt == 5 {\n\t\t\treturn nil\n\t\t}\n\t\tif err == nil && (!retryable[resp.StatusCode] || attempt == 5) {\n\t\t\treturn resp\n\t\t}\n\t\twhat := \"got no answer\"\n\t\tbackoff := math.Min(30, math.Pow(2, float64(attempt-1)))\n\t\twait := backoff/2 + rand.Float64()*backoff/2\n\t\tif err == nil {\n\t\t\twhat = fmt.Sprintf(\"answered %d\", resp.StatusCode)\n\t\t\tif seconds, convErr := strconv.Atoi(resp.Header.Get(\"Retry-After\")); convErr == nil && seconds > 0 {\n\t\t\t\tif seconds > 60 {\n\t\t\t\t\treturn resp // too long to wait here: the caller says when to come back\n\t\t\t\t}\n\t\t\t\twait = float64(seconds)\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"retry: attempt %d %s, waiting %.1f s\\n\", attempt, what, wait)\n\t\ttime.Sleep(time.Duration(wait * float64(time.Second)))\n\t}\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Cancel an order you created, by your own reference. Repeating it is safe. Java 17 or later, with Jackson.\n// Needs MART_API_BASE, MART_API_KEY and MART_PARTNER_REFERENCE.\n// Run it as a single file: java -cp <the Jackson jars> cancel-an-order.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URLEncoder;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.time.Duration;\nimport java.util.Locale;\nimport java.util.Set;\nimport java.util.concurrent.ThreadLocalRandom;\n\nclass CancelAnOrder {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        String reference = URLEncoder.encode(System.getenv(\"MART_PARTNER_REFERENCE\"), StandardCharsets.UTF_8);\n        HttpRequest request = HttpRequest.newBuilder(\n                        URI.create(System.getenv(\"MART_API_BASE\") + \"/api/v1/orders/cancel/\" + reference))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .header(\"Content-Type\", \"application/json\")\n                .timeout(Duration.ofSeconds(30))\n                .POST(HttpRequest.BodyPublishers.ofString(\"{\\\"reason\\\": \\\"The customer changed their mind\\\"}\"))\n                .build();\n\n        // A cancel that already happened answers 200 with already_cancelled true, so sending it again\n        // after no answer is the recovery.\n        HttpResponse<String> response = send(request);\n        if (response == null) {\n            fail(\"no answer; send the cancel again later\");\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        JsonNode cancelled = body.path(\"data\").path(\"order\");\n        System.out.println(\"order: \" + cancelled.path(\"partner_reference\").asText());\n        System.out.println(\"status id: \" + cancelled.path(\"status\").path(\"id\").asInt());\n        System.out.println(\"already cancelled: \" + cancelled.path(\"already_cancelled\").asBoolean());\n    }\n\n    static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);\n\n    /**\n     * Sends the same request until it is answered for good, and returns the last answer, or null when\n     * no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no answer, a\n     * 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter.\n     * Any other answer is final.\n     */\n    static HttpResponse<String> send(HttpRequest request) throws InterruptedException {\n        for (int attempt = 1; ; attempt++) {\n            HttpResponse<String> response = null;\n            try {\n                response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n                if (!RETRYABLE.contains(response.statusCode()) || attempt == 5) {\n                    return response;\n                }\n            } catch (IOException e) {\n                if (attempt == 5) {\n                    return null;\n                }\n            }\n            double backoff = Math.min(30, Math.pow(2, attempt - 1));\n            double wait = backoff / 2 + ThreadLocalRandom.current().nextDouble() * backoff / 2;\n            String what = \"got no answer\";\n            if (response != null) {\n                what = \"answered \" + response.statusCode();\n                String after = response.headers().firstValue(\"Retry-After\").orElse(\"\");\n                if (after.matches(\"[0-9]+\") && Long.parseLong(after) > 0) {\n                    if (Long.parseLong(after) > 60) {\n                        return response; // too long to wait here: the caller says when to come back\n                    }\n                    wait = Long.parseLong(after);\n                }\n            }\n            System.err.printf(Locale.ROOT, \"retry: attempt %d %s, waiting %.1f s%n\", attempt, what, wait);\n            Thread.sleep((long) (wait * 1000));\n        }\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/orders/{partner_reference}": {
      "get": {
        "summary": "Get order by partner reference",
        "description": "Returns YOUR order, addressed by the reference you submitted at creation. Key-scoped: an unknown or foreign reference answers the identical 404 `order_not_found`. Live view with frozen prices: `status`, quantities and `cod_total` are current; each item's `price` and the `shipping_fee` stay the creation-time figures. Details: https://mart.ps/api/docs#orders.",
        "tags": [
          "Orders"
        ],
        "operationId": "getOrderByPartnerReference",
        "x-required-scope": "orders:read",
        "parameters": [
          {
            "name": "partner_reference",
            "in": "path",
            "required": true,
            "description": "The reference you submitted to POST /api/v1/orders, exactly as you sent it (references are stored byte-for-byte). Letters, digits, dot, underscore, hyphen; max 64 characters.",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9._-]{1,64}$",
              "maxLength": 64,
              "example": "100245"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The partner's order: live status and quantities, frozen prices.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "order": {
                              "$ref": "#/components/schemas/PartnerOrder"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "order": {
                      "partner_reference": "100245",
                      "status": {
                        "id": 5,
                        "name": "تم التوصيل"
                      },
                      "payment_type": "cod",
                      "created_at": "2026-08-01T10:15:00+00:00",
                      "updated_at": "2026-08-03T09:40:12+03:00",
                      "cod_total": 240.0,
                      "shipping_fee": 35.0,
                      "free_shipping": true,
                      "products": [
                        {
                          "product_id": 9597,
                          "combination_id": 41206,
                          "quantity": 2,
                          "price": 120.0,
                          "line_total": 240.0
                        }
                      ],
                      "shipping_address": {
                        "customer_name": "محمد علي",
                        "phone": "0599123456",
                        "extra_phone": null,
                        "state_id": 386,
                        "state_name": "الخليل",
                        "address": "شارع الإرسال، عمارة 12",
                        "notes": null
                      },
                      "cancellation": null
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/OrderNotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/events": {
      "get": {
        "summary": "Events",
        "description": "What happened to your account, oldest first, as a feed with a cursor: orders, earnings and other ledger movements, withdrawals and your payout method. Store `meta.next_cursor` and ask again with `after=<it>`; a replay from any cursor shows every later event, in the same order, with no gaps. `next_cursor` is there even on an empty page, and on a page with nothing beyond it, it moves up to the head of the feed, which can be past your last event, so store it rather than an event's `cursor`. **Delivery is at least once:** after a lost response you read the same events again, so de-duplicate on `cursor`. **Feed order is visibility order:** an event takes its place when it is committed, so one that took longer to commit can follow a later one, and you use `occurred_at` for cause and effect. An event written late carries the original `occurred_at` and a new place, and a late `order.created` shows the order as it is when written. A `payload` is the matching read's row: `order.*` is a `GET /orders` item, `ledger.entry_posted` a `GET /ledger` item, `withdrawal.*` a `GET /withdrawals` item without `iban`, and `payout_method.changed` is `{version, updated_at}` and nothing of what it holds. The feed starts when the events feature was switched on for this store, and an order status that is not customer-visible is not an event. Full behaviour: https://mart.ps/api/docs#money/events.",
        "tags": [
          "Money"
        ],
        "operationId": "listEvents",
        "x-required-scope": "events:read",
        "parameters": [
          {
            "name": "after",
            "in": "query",
            "description": "The `cursor` of the last event you have, or a `next_cursor`, exactly as returned: you get what comes after it. Omitted: from the oldest event kept. A value this feed did not issue answers 422 `invalid_cursor`, a blank one included, so a lost cursor can never silently replay or skip. A cursor older than what the feed still keeps answers 410 `cursor_expired`.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Events per page, 1 to 500 (default 100). Anything else answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 500,
              "default": 100
            }
          },
          {
            "name": "start",
            "in": "query",
            "description": "`latest`: an empty page whose `next_cursor` is the head of the feed, to start from now. Cannot be combined with `after`. Any other value answers 422 `invalid_parameter`.",
            "schema": {
              "type": "string",
              "enum": [
                "latest"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "One page, oldest first. An account with nothing new gets `events: []`, with `next_cursor` still there.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "events": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/Event"
                              }
                            }
                          }
                        },
                        "meta": {
                          "$ref": "#/components/schemas/EventFeedMeta"
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "events": [
                      {
                        "cursor": "djE6NDI",
                        "type": "order.status_changed",
                        "reference": "100245",
                        "occurred_at": "2026-08-03T09:40:12+00:00",
                        "payload": {
                          "partner_reference": "100245",
                          "status": {
                            "id": 5,
                            "name": "Delivered"
                          },
                          "payment_type": "cod",
                          "created_at": "2026-08-01T07:00:00+00:00",
                          "updated_at": "2026-08-03T12:40:12+03:00",
                          "order_total": 120.5,
                          "cod_total": 120.5,
                          "shipping_fee": 20.0,
                          "free_shipping": false
                        }
                      }
                    ]
                  },
                  "meta": {
                    "next_cursor": "djE6NDI",
                    "has_more": false
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "410": {
            "$ref": "#/components/responses/EventFeedExpired"
          },
          "422": {
            "$ref": "#/components/responses/EventFeedInvalid"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Catch up on your account's events, then print the cursor to store for the next run.\n# Run it on a schedule (every minute, say). Needs MART_API_BASE and MART_API_KEY.\n# MART_EVENTS_CURSOR is the cursor the previous run printed; without it, reading starts at the oldest event.\nset -euo pipefail\n\n# api PATH: sets $body, or prints the status and error code and stops.\napi() {\n  local response status retry_after\n  response=$(curl --silent --show-error --max-time 30 \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") \\\n    --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE$1\") || { echo \"error: no answer\" >&2; exit 1; }\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  if [ \"$status\" -ge 300 ]; then\n    echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n    exit 1\n  fi\n}\n\ncursor=${MART_EVENTS_CURSOR:-}\ncount=0\n# At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.\nfor page in $(seq 1 100); do\n  api \"/api/v1/events?limit=100${cursor:+&after=$cursor}\"\n  # Delivery is at least once: skip an event whose cursor you already handled.\n  jq -r '.data.events[] | \"event \\(.cursor) \\(.type)\\(if .reference then \" \" + .reference else \"\" end)\"' <<<\"$body\"\n  count=$((count + $(jq '.data.events | length' <<<\"$body\")))\n  cursor=$(jq -r '.meta.next_cursor' <<<\"$body\")\n  [ \"$(jq -r '.meta.has_more' <<<\"$body\")\" = true ] || break\n  sleep 1 # a pause between pages\ndone\necho \"events: $count\"\necho \"cursor: $cursor\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Catch up on your account's events, then print the cursor to store for the next run.\n// Run it on a schedule (every minute, say). Node 22.18 or later runs this .ts file as it is.\n// Needs MART_API_BASE and MART_API_KEY. MART_EVENTS_CURSOR is the cursor the previous run printed;\n// without it, reading starts at the oldest event.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nif (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function get(path: string): Promise<any> {\n  const response = await fetch(`${base}${path}`, {\n    headers: { Authorization: `Bearer ${key}` },\n    signal: AbortSignal.timeout(30_000),\n  });\n  const body = await response.json().catch(() => null); // an edge error page is not JSON\n  if (!response.ok || body === null) {\n    const retryAfter = response.headers.get('retry-after');\n    console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);\n    process.exit(1);\n  }\n  return body;\n}\n\nlet cursor = process.env.MART_EVENTS_CURSOR ?? '';\nlet count = 0;\n// At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.\nfor (let page = 1; page <= 100; page++) {\n  const after = cursor ? `&after=${encodeURIComponent(cursor)}` : '';\n  const body = await get(`/api/v1/events?limit=100${after}`);\n  for (const event of body.data.events) {\n    // Delivery is at least once: skip an event whose cursor you already handled.\n    console.log(`event ${event.cursor} ${event.type}${event.reference ? ` ${event.reference}` : ''}`);\n    count++;\n  }\n  cursor = body.meta.next_cursor;\n  if (!body.meta.has_more) break;\n  await sleep(1000); // a pause between pages\n}\nconsole.log(`events: ${count}`);\nconsole.log(`cursor: ${cursor}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Catch up on your account's events, then print the cursor to store for the next run.\n\nRun it on a schedule (every minute, say). Python 3.9 or later, with httpx.\nNeeds MART_API_BASE and MART_API_KEY. MART_EVENTS_CURSOR is the cursor the previous run printed;\nwithout it, reading starts at the oldest event.\n\"\"\"\nimport os\nimport sys\nimport time\n\nimport httpx\n\nTIMEOUT = 30\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\n\ndef check(response: httpx.Response) -> dict:\n    body = body_of(response)\n    if response.is_error or body is None:\n        code = body[\"error\"][\"code\"] if body else \"(not JSON)\"\n        retry_after = response.headers.get(\"Retry-After\")\n        sys.exit(f\"error: {response.status_code} {code}\" + (f\", try again after {retry_after} s\" if retry_after else \"\"))\n    return body\n\n\ncursor = os.environ.get(\"MART_EVENTS_CURSOR\", \"\")\ncount = 0\n# At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.\nfor page in range(100):\n    params = {\"limit\": 100}\n    if cursor:\n        params[\"after\"] = cursor\n    body = check(client.get(\"/api/v1/events\", params=params))\n    for event in body[\"data\"][\"events\"]:\n        # Delivery is at least once: skip an event whose cursor you already handled.\n        reference = f\" {event['reference']}\" if event[\"reference\"] else \"\"\n        print(f\"event {event['cursor']} {event['type']}{reference}\")\n        count += 1\n    cursor = body[\"meta\"][\"next_cursor\"]\n    if not body[\"meta\"][\"has_more\"]:\n        break\n    time.sleep(1)  # a pause between pages\nprint(f\"events: {count}\")\nprint(f\"cursor: {cursor}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Catch up on your account's events, then print the cursor to store for the next run.\n// Run it on a schedule (every minute, say). PHP 7.4 or later, with the curl extension.\n// Needs MART_API_BASE and MART_API_KEY. MART_EVENTS_CURSOR is the cursor the previous run printed;\n// without it, reading starts at the oldest event.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** A GET that must succeed: the decoded body, or the status and error code, and stop. */\nfunction get(string $url, string $key): array\n{\n    [$status, $headers, $raw] = request('GET', $url, $key);\n    $body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)\n    if ($status < 200 || $status >= 300 || !is_array($body)) {\n        $code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');\n        $wait = isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n        fwrite(STDERR, \"error: $code$wait\\n\");\n        exit(1);\n    }\n\n    return $body;\n}\n\n$cursor = (string) getenv('MART_EVENTS_CURSOR');\n$count = 0;\n// At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.\nfor ($page = 1; $page <= 100; $page++) {\n    $query = http_build_query(array_filter(['limit' => 100, 'after' => $cursor]));\n    $body = get(\"$base/api/v1/events?$query\", $key);\n    foreach ($body['data']['events'] as $event) {\n        // Delivery is at least once: skip an event whose cursor you already handled.\n        echo \"event {$event['cursor']} {$event['type']}\" . ($event['reference'] ? \" {$event['reference']}\" : '') . \"\\n\";\n        $count++;\n    }\n    $cursor = $body['meta']['next_cursor'];\n    if (!$body['meta']['has_more']) {\n        break;\n    }\n    sleep(1); // a pause between pages\n}\necho \"events: $count\\n\";\necho \"cursor: $cursor\\n\";\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Catch up on your account's events, then print the cursor to store for the next run.\n// Run it on a schedule (every minute, say). Go 1.22 or later. Needs MART_API_BASE and MART_API_KEY.\n// MART_EVENTS_CURSOR is the cursor the previous run printed; without it, reading starts at the oldest event.\n// Run it with: go run follow-events.go\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tcursor := os.Getenv(\"MART_EVENTS_CURSOR\")\n\tcount := 0\n\t// At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.\n\tfor page := 1; page <= 100; page++ {\n\t\tquery := url.Values{\"limit\": {\"100\"}}\n\t\tif cursor != \"\" {\n\t\t\tquery.Set(\"after\", cursor)\n\t\t}\n\t\tvar body struct {\n\t\t\tData struct {\n\t\t\t\tEvents []struct {\n\t\t\t\t\tCursor    string  `json:\"cursor\"`\n\t\t\t\t\tType      string  `json:\"type\"`\n\t\t\t\t\tReference *string `json:\"reference\"`\n\t\t\t\t} `json:\"events\"`\n\t\t\t} `json:\"data\"`\n\t\t\tMeta struct {\n\t\t\t\tNextCursor string `json:\"next_cursor\"`\n\t\t\t\tHasMore    bool   `json:\"has_more\"`\n\t\t\t} `json:\"meta\"`\n\t\t}\n\t\tget(\"/api/v1/events?\"+query.Encode(), &body)\n\t\tfor _, event := range body.Data.Events {\n\t\t\t// Delivery is at least once: skip an event whose cursor you already handled.\n\t\t\tline := \"event \" + event.Cursor + \" \" + event.Type\n\t\t\tif event.Reference != nil {\n\t\t\t\tline += \" \" + *event.Reference\n\t\t\t}\n\t\t\tfmt.Println(line)\n\t\t\tcount++\n\t\t}\n\t\tcursor = body.Meta.NextCursor\n\t\tif !body.Meta.HasMore {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second) // a pause between pages\n\t}\n\tfmt.Println(\"events:\", count)\n\tfmt.Println(\"cursor:\", cursor)\n}\n\n// get sends one GET and decodes its answer into out.\nfunc get(path string, out any) {\n\treq, err := http.NewRequest(http.MethodGet, os.Getenv(\"MART_API_BASE\")+path, nil)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tdecode(resp, out)\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Catch up on your account's events, then print the cursor to store for the next run.\n// Run it on a schedule (every minute, say). Java 17 or later, with Jackson. Needs MART_API_BASE and\n// MART_API_KEY. MART_EVENTS_CURSOR is the cursor the previous run printed; without it, reading starts\n// at the oldest event. Run it as a single file: java -cp <the Jackson jars> follow-events.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URLEncoder;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.time.Duration;\nimport java.util.Locale;\nimport java.util.Objects;\n\nclass FollowEvents {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        String cursor = Objects.requireNonNullElse(System.getenv(\"MART_EVENTS_CURSOR\"), \"\");\n        int count = 0;\n        // At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.\n        for (int page = 1; page <= 100; page++) {\n            String after = cursor.isEmpty() ? \"\" : \"&after=\" + URLEncoder.encode(cursor, StandardCharsets.UTF_8);\n            JsonNode body = get(\"/api/v1/events?limit=100\" + after);\n            for (JsonNode event : body.path(\"data\").path(\"events\")) {\n                // Delivery is at least once: skip an event whose cursor you already handled.\n                String reference = event.path(\"reference\").isNull() ? \"\" : \" \" + event.path(\"reference\").asText();\n                System.out.println(\"event \" + event.path(\"cursor\").asText() + \" \" + event.path(\"type\").asText() + reference);\n                count++;\n            }\n            cursor = body.path(\"meta\").path(\"next_cursor\").asText();\n            if (!body.path(\"meta\").path(\"has_more\").asBoolean()) {\n                break;\n            }\n            Thread.sleep(1000); // a pause between pages\n        }\n        System.out.println(\"events: \" + count);\n        System.out.println(\"cursor: \" + cursor);\n    }\n\n    /** One GET that must succeed: the decoded body, or the status and error code, and stop. */\n    static JsonNode get(String path) throws InterruptedException {\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + path))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .timeout(Duration.ofSeconds(30))\n                .GET()\n                .build();\n        HttpResponse<String> response;\n        try {\n            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        } catch (IOException e) {\n            fail(\"no answer: \" + e.getMessage());\n            return null;\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        return body;\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/account": {
      "get": {
        "summary": "Your account",
        "description": "Your own account in one read: the shop name, whether it is active, paused or closed, what your key may do, your request limits, whether a payout method is saved, the withdrawal rules and whether the money endpoints can be read right now. The shape is the same for every partner. It always answers `200` once you are authenticated: a paused or closed account still reads it, and when the ledger cannot be read only `money.available` is `false` (the money endpoints answer `503` `ledger_unavailable` for that). `orders_enabled` is the effective value, your key's flag and the account being active. Withdrawal numbers are `null` when withdrawals are off or no number has been set. Full behaviour: https://mart.ps/api/docs#account/account.",
        "tags": [
          "Account"
        ],
        "operationId": "getAccount",
        "x-required-scope": null,
        "responses": {
          "200": {
            "description": "Your account.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "account": {
                              "$ref": "#/components/schemas/Account"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "account": {
                      "shop_display_name": "Al Noor Shop",
                      "status": "active",
                      "orders_enabled": true,
                      "card_enabled": false,
                      "price_override_allowed": true,
                      "free_shipping_allowed": false,
                      "rate_limits": {
                        "per_minute": 120,
                        "per_day": 20000
                      },
                      "payout_method_saved": false,
                      "withdrawals": {
                        "enabled": false,
                        "minimum": null,
                        "max_open_requests": null
                      },
                      "money": {
                        "available": true
                      }
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/ForbiddenGroup"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Make your first call: read your own account.\n# Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.\nset -euo pipefail\n\n# The key goes to curl through a file descriptor, so it never shows in the process list.\nresponse=$(curl --silent --show-error --max-time 30 \\\n  --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") \\\n  --write-out '\\n%{http_code} %header{x-mart-environment} %header{retry-after}' \\\n  \"$MART_API_BASE/api/v1/account\") || { echo \"error: no answer\" >&2; exit 1; }\nbody=${response%$'\\n'*}\nread -r status environment retry_after <<<\"${response##*$'\\n'}\"\n\nif [ \"$status\" != 200 ]; then\n  echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n  exit 1\nfi\n\n# Every answer names the installation that served it: check it before anything else.\necho \"environment: $environment\"\njq -r '.data.account | \"account status: \\(.status)\\norders enabled: \\(.orders_enabled)\"' <<<\"$body\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Make your first call: read your own account. Node 22.18 or later runs this .ts file as it is.\n// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nif (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');\n\nconst response = await fetch(`${base}/api/v1/account`, {\n  headers: { Authorization: `Bearer ${key}` },\n  signal: AbortSignal.timeout(30_000),\n});\nconst body = await response.json().catch(() => null); // an edge error page is not JSON\nif (!response.ok || body === null) {\n  const retryAfter = response.headers.get('retry-after');\n  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);\n  process.exit(1);\n}\n\n// Every answer names the installation that served it: check it before anything else.\nconsole.log(`environment: ${response.headers.get('x-mart-environment')}`);\nconsole.log(`account status: ${body.data.account.status}`);\nconsole.log(`orders enabled: ${body.data.account.orders_enabled}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Make your first call: read your own account. Python 3.9 or later, with httpx.\n\nNeeds MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.\n\"\"\"\nimport os\nimport sys\n\nimport httpx\n\nbase = os.environ[\"MART_API_BASE\"]\nkey = os.environ[\"MART_API_KEY\"]\n\nresponse = httpx.get(f\"{base}/api/v1/account\", headers={\"Authorization\": f\"Bearer {key}\"}, timeout=30)\ntry:\n    body = response.json()\nexcept ValueError:  # an edge error page is not JSON\n    body = None\nif response.is_error or body is None:\n    retry_after = response.headers.get(\"Retry-After\")\n    sys.exit(f\"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}\"\n             + (f\", try again after {retry_after} s\" if retry_after else \"\"))\n\n# Every answer names the installation that served it: check it before anything else.\nprint(f\"environment: {response.headers['X-Mart-Environment']}\")\naccount = body[\"data\"][\"account\"]\nprint(f\"account status: {account['status']}\")\nprint(f\"orders enabled: {str(account['orders_enabled']).lower()}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Make your first call: read your own account. PHP 7.4 or later, with the curl extension.\n// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\nfunction when(array $headers): string\n{\n    return isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n}\n\n[$status, $headers, $raw] = request('GET', \"$base/api/v1/account\", $key);\n$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)\nif ($status !== 200 || !is_array($body)) {\n    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)')) . when($headers) . \"\\n\");\n    exit(1);\n}\n\n// Every answer names the installation that served it: check it before anything else.\necho \"environment: {$headers['x-mart-environment']}\\n\";\n$account = $body['data']['account'];\necho \"account status: {$account['status']}\\n\";\necho 'orders enabled: ' . ($account['orders_enabled'] ? 'true' : 'false') . \"\\n\";\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Make your first call: read your own account. Go 1.22 or later, standard library only.\n// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.\n// Run it with: go run first-call.go\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\treq, err := http.NewRequest(http.MethodGet, os.Getenv(\"MART_API_BASE\")+\"/api/v1/account\", nil)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tenvironment := resp.Header.Get(\"X-Mart-Environment\")\n\n\tvar body struct {\n\t\tData struct {\n\t\t\tAccount struct {\n\t\t\t\tStatus        string `json:\"status\"`\n\t\t\t\tOrdersEnabled bool   `json:\"orders_enabled\"`\n\t\t\t} `json:\"account\"`\n\t\t} `json:\"data\"`\n\t}\n\tdecode(resp, &body)\n\n\t// Every answer names the installation that served it: check it before anything else.\n\tfmt.Println(\"environment:\", environment)\n\tfmt.Println(\"account status:\", body.Data.Account.Status)\n\tfmt.Println(\"orders enabled:\", body.Data.Account.OrdersEnabled)\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Make your first call: read your own account. Java 17 or later, with Jackson (jackson-databind).\n// Needs MART_API_BASE (https://sandbox.mart.ps while you build, https://mart.ps live) and MART_API_KEY.\n// Run it as a single file: java -cp <the Jackson jars> first-call.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.Locale;\n\nclass FirstCall {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + \"/api/v1/account\"))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .timeout(Duration.ofSeconds(30))\n                .GET()\n                .build();\n        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n\n        // Every answer names the installation that served it: check it before anything else.\n        System.out.println(\"environment: \" + response.headers().firstValue(\"X-Mart-Environment\").orElse(\"\"));\n        JsonNode account = body.path(\"data\").path(\"account\");\n        System.out.println(\"account status: \" + account.path(\"status\").asText());\n        System.out.println(\"orders enabled: \" + account.path(\"orders_enabled\").asBoolean());\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/reports/summary": {
      "get": {
        "summary": "Reports summary",
        "description": "Your own order totals over a recent range: the number and value of orders, the average order value, a breakdown by calendar month (shop-local months, newest first) with the cash-on-delivery and card split and the number cancelled, and the products you order most. Values are order totals, nothing else. Ownership is your key: you never see another account's orders. An account with no orders in the range gets a normal 200 with zeros and empty lists. `months` is one of 3, 6 or 12 (default 12); any other value answers 422 `invalid_parameter`. The range starts on the first day of the earliest month, so `months=3` covers this month and the two before it. Full behaviour: https://mart.ps/api/docs#reports/summary.",
        "tags": [
          "Reports"
        ],
        "operationId": "getReportsSummary",
        "x-required-scope": "reports:read",
        "parameters": [
          {
            "name": "months",
            "in": "query",
            "description": "How many calendar months to cover, counting the current one. Exactly 3, 6 or 12; anything else, including 03 or 12.0, answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "enum": [
                3,
                6,
                12
              ],
              "default": 12
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The summary for the range. Zeros and empty lists when there are no orders.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "summary": {
                              "$ref": "#/components/schemas/ReportsSummary"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "summary": {
                      "order_count": 3,
                      "order_value": 350.55,
                      "average_order_value": 116.85,
                      "by_month": [
                        {
                          "month": "2026-08",
                          "orders": 2,
                          "value": 300.0,
                          "cod_orders": 1,
                          "card_orders": 1,
                          "cancelled": 1
                        },
                        {
                          "month": "2026-07",
                          "orders": 1,
                          "value": 50.55,
                          "cod_orders": 1,
                          "card_orders": 0,
                          "cancelled": 0
                        }
                      ],
                      "top_products": [
                        {
                          "product_id": 9597,
                          "combination_id": 41206,
                          "name": "Example product",
                          "quantity": 4,
                          "orders": 1
                        },
                        {
                          "product_id": 12402,
                          "combination_id": null,
                          "name": "Another product",
                          "quantity": 3,
                          "orders": 2
                        }
                      ]
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/balance": {
      "get": {
        "summary": "Balance",
        "description": "Your account's money in one read: the balance, what is available now, what is held until it matures, the next maturity, and any amount you owe. `available` is what may be taken out now. `held` is earned but not yet matured; `next_maturity` says when the next part of it becomes available and how much. `owed` is a debt the account carries, 0 when there is none. `under_review` is earned money held back while its order is not delivered (for example during a ticket or an exchange): it is never in `available`, and it becomes available again once the order is back to delivered. `pending` is what your orders not delivered yet will earn once they are, with `pending_state` saying whether that figure is exact; it is not money yet and never in `balance`, `available` or a withdrawal. Every figure is its own read, so under concurrent posting they can differ by a moment: do not add them up. Amounts are in ILS, as numbers with 2 decimals. An account with no entries gets a normal 200 of zeros. When the balance cannot be read the answer is `503` `ledger_unavailable`, never zeros. Ownership is your key. Full behaviour: https://mart.ps/api/docs#money/balance.",
        "tags": [
          "Money"
        ],
        "operationId": "getBalance",
        "x-required-scope": "money:read",
        "responses": {
          "200": {
            "description": "Your balance.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "balance": {
                              "$ref": "#/components/schemas/Balance"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "balance": {
                      "currency": "ILS",
                      "balance": 210.0,
                      "available": 160.0,
                      "held": 50.0,
                      "next_maturity": {
                        "at": "2026-08-10T09:40:12+00:00",
                        "amount": 50.0
                      },
                      "owed": 0.0,
                      "pending": 75.0,
                      "pending_state": "ok",
                      "under_review": 0.0
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/LedgerUnavailable"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Read your balance: what is available now, what is still held, and what you owe.\n# Needs MART_API_BASE and MART_API_KEY.\nset -euo pipefail\nexport LC_NUMERIC=C # printf reads and writes amounts with a decimal point\n\nresponse=$(curl --silent --show-error --max-time 30 \\\n  --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") \\\n  --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE/api/v1/balance\") || { echo \"error: no answer\" >&2; exit 1; }\nread -r status retry_after <<<\"${response##*$'\\n'}\"\nbody=${response%$'\\n'*}\nif [ \"$status\" -ge 300 ]; then\n  # 503 ledger_unavailable: show the balance as unavailable, never as 0.00.\n  echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}\" >&2\n  exit 1\nfi\n\n# Each figure is its own read: show them, never add them up.\nread -r currency balance available held owed < <(jq -r \\\n  '.data.balance | \"\\(.currency) \\(.balance) \\(.available) \\(.held) \\(.owed)\"' <<<\"$body\")\nprintf 'balance: %.2f %s\\navailable: %.2f %s\\nheld: %.2f %s\\nowed: %.2f %s\\n' \\\n  \"$balance\" \"$currency\" \"$available\" \"$currency\" \"$held\" \"$currency\" \"$owed\" \"$currency\"\nread -r next_amount next_at < <(jq -r '.data.balance.next_maturity | if . then \"\\(.amount) \\(.at)\" else \"none\" end' <<<\"$body\")\nif [ \"$next_amount\" = none ]; then\n  echo \"next maturity: none\"\nelse\n  printf 'next maturity: %.2f %s on %s\\n' \"$next_amount\" \"$currency\" \"$next_at\"\nfi\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Read your balance: what is available now, what is still held, and what you owe.\n// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE and MART_API_KEY.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nif (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');\n\nconst response = await fetch(`${base}/api/v1/balance`, {\n  headers: { Authorization: `Bearer ${key}` },\n  signal: AbortSignal.timeout(30_000),\n});\nconst body = await response.json().catch(() => null); // an edge error page is not JSON\nif (!response.ok || body === null) {\n  // 503 ledger_unavailable: show the balance as unavailable, never as 0.00.\n  const retryAfter = response.headers.get('retry-after');\n  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);\n  process.exit(1);\n}\n\n// Each figure is its own read: show them, never add them up.\nconst balance = body.data.balance;\nconst money = (amount: number) => `${amount.toFixed(2)} ${balance.currency}`;\nconsole.log(`balance: ${money(balance.balance)}`);\nconsole.log(`available: ${money(balance.available)}`);\nconsole.log(`held: ${money(balance.held)}`);\nconsole.log(`owed: ${money(balance.owed)}`);\nconst next = balance.next_maturity;\nconsole.log(next ? `next maturity: ${money(next.amount)} on ${next.at}` : 'next maturity: none');\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Read your balance: what is available now, what is still held, and what you owe. Python 3.9+, httpx.\n\nNeeds MART_API_BASE and MART_API_KEY.\n\"\"\"\nimport os\nimport sys\n\nimport httpx\n\nbase = os.environ[\"MART_API_BASE\"]\nkey = os.environ[\"MART_API_KEY\"]\n\nresponse = httpx.get(f\"{base}/api/v1/balance\", headers={\"Authorization\": f\"Bearer {key}\"}, timeout=30)\ntry:\n    body = response.json()\nexcept ValueError:  # an edge error page is not JSON\n    body = None\nif response.is_error or body is None:\n    # 503 ledger_unavailable: show the balance as unavailable, never as 0.00.\n    retry_after = response.headers.get(\"Retry-After\")\n    sys.exit(f\"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}\"\n             + (f\", try again after {retry_after} s\" if retry_after else \"\"))\n\n# Each figure is its own read: show them, never add them up.\nbalance = body[\"data\"][\"balance\"]\ncurrency = balance[\"currency\"]\nfor name in (\"balance\", \"available\", \"held\", \"owed\"):\n    print(f\"{name}: {balance[name]:.2f} {currency}\")\nupcoming = balance[\"next_maturity\"]\nif upcoming:\n    print(f\"next maturity: {upcoming['amount']:.2f} {currency} on {upcoming['at']}\")\nelse:\n    print(\"next maturity: none\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Read your balance: what is available now, what is still held, and what you owe. PHP 7.4 or later,\n// with the curl extension. Needs MART_API_BASE and MART_API_KEY.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\nfunction when(array $headers): string\n{\n    return isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n}\n\n[$status, $headers, $raw] = request('GET', \"$base/api/v1/balance\", $key);\n$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)\nif ($status !== 200 || !is_array($body)) {\n    // 503 ledger_unavailable: show the balance as unavailable, never as 0.00.\n    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)')) . when($headers) . \"\\n\");\n    exit(1);\n}\n\n// Each figure is its own read: show them, never add them up.\n$balance = $body['data']['balance'];\nforeach (['balance', 'available', 'held', 'owed'] as $name) {\n    printf(\"%s: %.2f %s\\n\", $name, $balance[$name], $balance['currency']);\n}\n$next = $balance['next_maturity'];\necho $next === null\n    ? \"next maturity: none\\n\"\n    : sprintf(\"next maturity: %.2f %s on %s\\n\", $next['amount'], $balance['currency'], $next['at']);\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Read your balance: what is available now, what is still held, and what you owe. Go 1.22 or later.\n// Needs MART_API_BASE and MART_API_KEY. Run it with: go run read-your-balance.go\npackage main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tvar body struct {\n\t\tData struct {\n\t\t\tBalance struct {\n\t\t\t\tCurrency     string  `json:\"currency\"`\n\t\t\t\tBalance      float64 `json:\"balance\"`\n\t\t\t\tAvailable    float64 `json:\"available\"`\n\t\t\t\tHeld         float64 `json:\"held\"`\n\t\t\t\tOwed         float64 `json:\"owed\"`\n\t\t\t\tNextMaturity *struct {\n\t\t\t\t\tAt     string  `json:\"at\"`\n\t\t\t\t\tAmount float64 `json:\"amount\"`\n\t\t\t\t} `json:\"next_maturity\"`\n\t\t\t} `json:\"balance\"`\n\t\t} `json:\"data\"`\n\t}\n\t// 503 ledger_unavailable stops here: show the balance as unavailable, never as 0.00.\n\tget(\"/api/v1/balance\", &body)\n\n\t// Each figure is its own read: show them, never add them up.\n\tb := body.Data.Balance\n\tfmt.Printf(\"balance: %.2f %s\\n\", b.Balance, b.Currency)\n\tfmt.Printf(\"available: %.2f %s\\n\", b.Available, b.Currency)\n\tfmt.Printf(\"held: %.2f %s\\n\", b.Held, b.Currency)\n\tfmt.Printf(\"owed: %.2f %s\\n\", b.Owed, b.Currency)\n\tif b.NextMaturity != nil {\n\t\tfmt.Printf(\"next maturity: %.2f %s on %s\\n\", b.NextMaturity.Amount, b.Currency, b.NextMaturity.At)\n\t} else {\n\t\tfmt.Println(\"next maturity: none\")\n\t}\n}\n\n// get sends one GET and decodes its answer into out.\nfunc get(path string, out any) {\n\treq, err := http.NewRequest(http.MethodGet, os.Getenv(\"MART_API_BASE\")+path, nil)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfail(fmt.Errorf(\"no answer: %v\", err))\n\t}\n\tdecode(resp, out)\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Read your balance: what is available now, what is still held, and what you owe. Java 17 or later,\n// with Jackson. Needs MART_API_BASE and MART_API_KEY.\n// Run it as a single file: java -cp <the Jackson jars> read-your-balance.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.Locale;\n\nclass ReadYourBalance {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        // 503 ledger_unavailable stops here: show the balance as unavailable, never as 0.00.\n        JsonNode balance = get(\"/api/v1/balance\").path(\"data\").path(\"balance\");\n\n        // Each figure is its own read: show them, never add them up.\n        String currency = balance.path(\"currency\").asText();\n        for (String name : new String[] {\"balance\", \"available\", \"held\", \"owed\"}) {\n            System.out.printf(Locale.ROOT, \"%s: %.2f %s%n\", name, balance.path(name).asDouble(), currency);\n        }\n        JsonNode next = balance.path(\"next_maturity\");\n        if (next.isNull()) {\n            System.out.println(\"next maturity: none\");\n        } else {\n            System.out.printf(Locale.ROOT, \"next maturity: %.2f %s on %s%n\", next.path(\"amount\").asDouble(), currency, next.path(\"at\").asText());\n        }\n    }\n\n    /** One GET that must succeed: the decoded body, or the status and error code, and stop. */\n    static JsonNode get(String path) throws InterruptedException {\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + path))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .timeout(Duration.ofSeconds(30))\n                .GET()\n                .build();\n        HttpResponse<String> response;\n        try {\n            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n        } catch (IOException e) {\n            fail(\"no answer: \" + e.getMessage());\n            return null;\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        return body;\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/ledger": {
      "get": {
        "summary": "Ledger",
        "description": "Your account's movements, newest first, one page at a time. `amount` is signed: a credit to you is positive, a payment to you or a deduction is negative. `type` is `earning`, `reversal`, `payment`, `adjustment` or `charge`; a type this document does not list yet may appear as `other`, so treat an unknown value as informational. A `charge` is a cost billed to your account for an order, such as a parcel refused at the door, and a positive one is such a charge undone. `partner_reference` is your own reference for the order an earning, a reversal or a charge belongs to, and null for anything else. `state` is `held` until `available_at` and `available` after it for earnings and reversals, and null for the rest. `entry_id` is opaque. Entries that arrive between two page reads can repeat a row on the next page and never skip one, so de-duplicate on `entry_id`. `meta.pagination.total` is the number of entries on the account. When the ledger cannot be read the answer is `503` `ledger_unavailable`, never an empty list. Full behaviour: https://mart.ps/api/docs#money/ledger.",
        "tags": [
          "Money"
        ],
        "operationId": "listLedger",
        "x-required-scope": "money:read",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "One page of movements, newest first. An account with none gets `entries: []`.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "entries": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/LedgerEntry"
                              }
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "entries": [
                      {
                        "entry_id": "MTIz",
                        "type": "earning",
                        "amount": 18.0,
                        "partner_reference": "100245",
                        "payment_method": null,
                        "occurred_at": "2026-08-03T09:40:12+00:00",
                        "recorded_at": "2026-08-03T09:40:13+00:00",
                        "available_at": "2026-08-10T09:40:12+00:00",
                        "state": "held"
                      }
                    ]
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 50,
                      "total": 1,
                      "total_pages": 1,
                      "has_next": false
                    }
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/LedgerUnavailable"
          }
        }
      }
    },
    "/api/v1/statements": {
      "get": {
        "summary": "List statements",
        "description": "Your finalized statements, newest first, one page at a time. A statement is a balance snapshot for a period: `opening` and `closing` are the balance at the start and at the end of it, and they include earnings that were still held. They are not an amount that could be paid out; read `available` on the balance for that. A statement that is still being prepared is not listed. `number` is the statement's number, used to read it. An account with none gets `statements: []`. When the ledger cannot be read the answer is `503` `ledger_unavailable`. Full behaviour: https://mart.ps/api/docs#money/statements.",
        "tags": [
          "Money"
        ],
        "operationId": "listStatements",
        "x-required-scope": "money:read",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "One page of statements, newest first.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "statements": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/Statement"
                              }
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "statements": [
                      {
                        "number": 12,
                        "period_start": "2026-07-01T00:00:00+00:00",
                        "period_end": "2026-08-01T00:00:00+00:00",
                        "opening": 120.5,
                        "closing": 210.0,
                        "finalized_at": "2026-08-01T02:00:00+00:00"
                      }
                    ]
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 50,
                      "total": 1,
                      "total_pages": 1,
                      "has_next": false
                    }
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/LedgerUnavailable"
          }
        }
      }
    },
    "/api/v1/statements/{statement_number}": {
      "get": {
        "summary": "Get statement",
        "description": "One finalized statement and the movements that belong to it. `movements` are the entries recorded in the statement's period, from `period_start` up to but not including `period_end`, oldest first, in the same shape as the ledger. A movement belongs to the period in which it was recorded, which can differ from `occurred_at`. The movements are paged: `meta.pagination.total` counts the period. A number your account does not have, and a number that does not exist, answer the same `404` `statement_not_found`. Statements are balance snapshots, including held earnings, not a payout entitlement. Full behaviour: https://mart.ps/api/docs#money/statement.",
        "tags": [
          "Money"
        ],
        "operationId": "getStatement",
        "x-required-scope": "money:read",
        "parameters": [
          {
            "name": "statement_number",
            "in": "path",
            "required": true,
            "description": "The statement's `number`: digits only, no leading zero.",
            "schema": {
              "type": "integer",
              "minimum": 1
            },
            "example": 12
          },
          {
            "name": "page",
            "in": "query",
            "description": "Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The statement with one page of its movements.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "statement": {
                              "$ref": "#/components/schemas/StatementDetail"
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "statement": {
                      "number": 12,
                      "period_start": "2026-07-01T00:00:00+00:00",
                      "period_end": "2026-08-01T00:00:00+00:00",
                      "opening": 120.5,
                      "closing": 210.0,
                      "finalized_at": "2026-08-01T02:00:00+00:00",
                      "movements": [
                        {
                          "entry_id": "MTIz",
                          "type": "earning",
                          "amount": 18.0,
                          "partner_reference": "100245",
                          "payment_method": null,
                          "occurred_at": "2026-08-03T09:40:12+00:00",
                          "recorded_at": "2026-08-03T09:40:13+00:00",
                          "available_at": "2026-08-10T09:40:12+00:00",
                          "state": "held"
                        }
                      ]
                    }
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 50,
                      "total": 1,
                      "total_pages": 1,
                      "has_next": false
                    }
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/StatementNotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/LedgerUnavailable"
          }
        }
      }
    },
    "/api/v1/payout-method": {
      "get": {
        "summary": "Your payout method",
        "description": "How your money is paid, in full: it is yours, and only your key reads it. `method` is `bank` (the IBAN and account holder) or `cash` (collected at Mart's office by the person named in `account_holder_name`, with `pickup_instructions` saying where and when; `iban` is `null`). A withdrawal is paid by the method saved here, and only once one is saved. A bank transfer is offered only where Mart allows it for your account: while it is not, an IBAN you saved before is kept and shown here, but a withdrawal on it is refused until you save cash. `status` is `not_set` (everything else is `null`), `active`, or `locked`, which means withdrawals are locked until `withdrawals_locked_until` because the payout method was saved or changed. `national_id` is `null` when none was saved. `updated_at` is the last change. When the ledger cannot be read the answer is `503` `ledger_unavailable`, never `not_set`. A paused account can read it. Full behaviour: https://mart.ps/api/docs#money/payout-method.",
        "tags": [
          "Money"
        ],
        "operationId": "getPayoutMethod",
        "x-required-scope": "money:read",
        "responses": {
          "200": {
            "description": "Your payout method.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "payout_method": {
                              "$ref": "#/components/schemas/PayoutMethod"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "payout_method": {
                      "status": "locked",
                      "iban": "PS92PALS000000000400123456702",
                      "iban_country": "PS",
                      "account_holder_name": "Al Noor Shop",
                      "national_id": null,
                      "updated_at": "2026-11-06T09:30:00+00:00",
                      "withdrawals_locked_until": "2026-11-08T09:30:00+00:00",
                      "method": "bank",
                      "pickup_instructions": null
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/LedgerUnavailable"
          }
        }
      },
      "put": {
        "summary": "Save your payout method",
        "description": "Saves how your money is paid. For a bank transfer send `iban` and `account_holder_name`, and optionally `national_id`; `method` may be left out, as before cash existed. For cash at Mart's office send `\"method\": \"cash\"`, the collector's full name as `account_holder_name` and optionally their ID number as `national_id`; no IBAN. Cash is offered only where Mart allows it for your account (`403` `cash_not_allowed`): save it once before your first cash withdrawal, naming who collects (yourself, or someone with their ID number). A bank transfer is offered only where Mart allows it for your account: elsewhere an IBAN is refused with `422` `bank_transfer_not_allowed` and nothing is saved. Switching between bank and cash is refused while a withdrawal is open (`409` `payout_method_change_blocked`: cancel it first). A request without `method` on a cash account switches it back to bank, so it needs an IBAN. Leaving `national_id` out keeps the one already saved; sending `null` or an empty string clears it. **A switch between bank and cash never carries the ID number over:** leaving `national_id` out on a switch clears it, so send it whenever the collector (or, back to bank, the account holder) has one. The IBAN may be typed with spaces or in lower case: it is stored without them, in upper case. Its check digits, its length for the country and its country are checked: only the countries Mart has enabled for your account are accepted. **Saving or changing the IBAN locks withdrawals for a number of hours set for your account** (`withdrawals_locked_until`); a change never shortens a lock that is still running. A switch between bank and cash, and for cash a change of the collector's name or ID number, locks the same way. For a bank transfer, changing only the name or the national ID does not lock. Saving what is already saved changes nothing and starts no lock. Every change is recorded with who made it. `403` `withdrawals_disabled` when withdrawals are not enabled for your account. `422` `invalid_payout_method` when `method` is neither `bank` nor `cash`. `422` `bank_transfer_not_allowed` for a bank transfer where it is not offered, before the IBAN is checked. `422` `invalid_iban` says why in `error.details.reason` (`format`, `country_not_allowed`, `length`, `checksum`, `bban`) with `country` and `expected_length` where they apply; no error ever repeats what you sent. A paused account can save. When the ledger cannot be read the answer is `503` `ledger_unavailable`, and nothing is saved. Full behaviour: https://mart.ps/api/docs#money/payout-method-save.",
        "tags": [
          "Money"
        ],
        "operationId": "putPayoutMethod",
        "x-required-scope": "iban:write",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PayoutMethodRequest"
              },
              "example": {
                "iban": "PS92 PALS 0000 0000 0400 1234 5670 2",
                "account_holder_name": "Al Noor Shop",
                "national_id": "123456789"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Saved. The same object `GET` returns. Also `200` when nothing changed.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "payout_method": {
                              "$ref": "#/components/schemas/PayoutMethod"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "payout_method": {
                      "status": "locked",
                      "iban": "PS92PALS000000000400123456702",
                      "iban_country": "PS",
                      "account_holder_name": "Al Noor Shop",
                      "national_id": null,
                      "updated_at": "2026-11-06T09:30:00+00:00",
                      "withdrawals_locked_until": "2026-11-08T09:30:00+00:00",
                      "method": "bank",
                      "pickup_instructions": null
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/WithdrawalsDisabled"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/PayoutMethodChangeBlocked"
          },
          "422": {
            "$ref": "#/components/responses/PayoutMethodInvalid"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/LedgerUnavailable"
          }
        }
      }
    },
    "/api/v1/withdrawals": {
      "get": {
        "summary": "List your withdrawals",
        "description": "Your withdrawal requests, newest first, one page at a time. Filter with `status`. Each item is `{withdrawal_id, amount, status, iban, reject_reason, requested_at, approved_at, paid_at, method, requested_amount}`. `iban` is the one fixed when the request was approved and is null before, and always for cash. `method` is how the request is paid; `requested_amount` is what you asked for, and differs from `amount` only when a cash request was paid at another amount at the office. Another account's requests are never listed. Works whether or not withdrawals are currently enabled for your account, and while it is paused. When the ledger cannot be read the answer is `503` `ledger_unavailable`, never an empty list. Full behaviour: https://mart.ps/api/docs#money/withdrawals.",
        "tags": [
          "Money"
        ],
        "operationId": "listWithdrawals",
        "x-required-scope": "money:read",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "description": "Only requests in this status: `requested`, `approved`, `paid`, `rejected` or `cancelled`. Anything else answers 422 `invalid_parameter`.",
            "schema": {
              "type": "string",
              "enum": [
                "requested",
                "approved",
                "paid",
                "rejected",
                "cancelled"
              ]
            }
          },
          {
            "name": "page",
            "in": "query",
            "description": "Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "A page of your withdrawal requests.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "withdrawals": {
                              "type": "array",
                              "items": {
                                "$ref": "#/components/schemas/Withdrawal"
                              }
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "pagination": {
                              "$ref": "#/components/schemas/ListPaginationMeta"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "withdrawals": [
                      {
                        "withdrawal_id": "NDE",
                        "amount": 125.0,
                        "status": "approved",
                        "iban": "PS92PALS000000000400123456702",
                        "reject_reason": null,
                        "requested_at": "2026-11-01T08:30:00+00:00",
                        "approved_at": "2026-11-02T09:00:00+00:00",
                        "paid_at": null,
                        "method": "bank",
                        "requested_amount": 125.0
                      }
                    ]
                  },
                  "meta": {
                    "pagination": {
                      "page": 1,
                      "limit": 50,
                      "total": 1,
                      "total_pages": 1,
                      "has_next": false
                    }
                  },
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/WithdrawalsDisabled"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/WithdrawalInvalid"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/WithdrawalUnavailable"
          }
        }
      },
      "post": {
        "summary": "Ask to withdraw",
        "description": "Asks Mart to pay out part of what is available. Send `amount` (shekels, at most two decimals) and your own `idempotency_key`. The request is checked in this order: a repeat of an earlier request is answered first, whatever has changed since; then withdrawals must be enabled for your account (`403` `withdrawals_disabled`), a payout method must be saved (`409` `payout_method_missing`: cash too is saved once) and not locked (`409` `withdrawals_locked`); a saved IBAN is paid to only where a bank transfer is offered to your account (`422` `bank_transfer_not_allowed`: save cash instead); when it is cash, cash must still be offered to your account (`403` `cash_not_allowed`: switch to bank) and the amount must not exceed the maximum for one cash payout when Mart has set one (`422` `amount_above_cash_maximum`, `details.maximum`); the amount must reach the minimum when your account has one (`422` `amount_below_minimum`), you must be under the limit of open requests (`409` `too_many_open_withdrawals`), and the amount must not exceed `GET /balance`'s `available` (`409` `insufficient_available`). A request holds its amount back from `available` until it is paid, rejected or cancelled. Mart reviews it by hand; nothing is paid at this call. A request is paid by your payout method at the time you make it (`method`). A cash request is collected at Mart's office: the office may pay a different amount within what is available, and `requested_amount` keeps what you asked for. **Retrying:** send the same `idempotency_key` and amount and you get the original request back with `200` and `meta.idempotency_replay: true`; never a second request. Keys are compared without regard to case. If the answer is `503` `withdrawal_busy`, wait `Retry-After` seconds and retry with the same key. A paused account can ask. Full behaviour: https://mart.ps/api/docs#money/withdrawal-create.",
        "tags": [
          "Money"
        ],
        "operationId": "createWithdrawal",
        "x-required-scope": "withdrawals:write",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WithdrawalRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "The request was recorded. `meta.idempotency_replay` is false.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "withdrawal": {
                              "$ref": "#/components/schemas/Withdrawal"
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "idempotency_replay": {
                              "type": "boolean"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 201,
                  "message": "Created",
                  "data": {
                    "withdrawal": {
                      "withdrawal_id": "NDE",
                      "amount": 125.0,
                      "status": "requested",
                      "iban": null,
                      "reject_reason": null,
                      "requested_at": "2026-11-01T08:30:00+00:00",
                      "approved_at": null,
                      "paid_at": null,
                      "method": "bank",
                      "requested_amount": 125.0
                    }
                  },
                  "meta": {
                    "idempotency_replay": false
                  },
                  "error": null
                }
              }
            }
          },
          "200": {
            "description": "A repeat of an earlier request: the original, as it stands now (`meta.idempotency_replay` is true). Nothing new was recorded.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "withdrawal": {
                              "$ref": "#/components/schemas/Withdrawal"
                            }
                          }
                        },
                        "meta": {
                          "type": "object",
                          "properties": {
                            "idempotency_replay": {
                              "type": "boolean"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "withdrawal": {
                      "withdrawal_id": "NDE",
                      "amount": 125.0,
                      "status": "requested",
                      "iban": null,
                      "reject_reason": null,
                      "requested_at": "2026-11-01T08:30:00+00:00",
                      "approved_at": null,
                      "paid_at": null,
                      "method": "bank",
                      "requested_amount": 125.0
                    }
                  },
                  "meta": {
                    "idempotency_replay": true
                  },
                  "error": null
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/WithdrawalsDisabled"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/WithdrawalRefused"
          },
          "422": {
            "$ref": "#/components/responses/WithdrawalInvalid"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/WithdrawalUnavailable"
          }
        },
        "x-codeSamples": [
          {
            "lang": "bash",
            "label": "cURL recipe",
            "source": "#!/usr/bin/env bash\n# Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n# Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at most two decimals) and\n# MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is answered.\nset -euo pipefail\nexport LC_NUMERIC=C # printf reads and writes amounts with a decimal point\n\nidempotency_key=${MART_IDEMPOTENCY_KEY:?set MART_IDEMPOTENCY_KEY to your own name for this request}\n# The amount as a decimal string, such as \"125.50\": exact, never rounded on the way.\nrequest=$(jq -n --arg key \"$idempotency_key\" --arg amount \"$MART_WITHDRAW_AMOUNT\" '{amount: $amount, idempotency_key: $key}')\necho \"idempotency key: $idempotency_key\" # written down before the first attempt\n\n# Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n# what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n# is final. The same key answers the original request, so a retry never asks twice.\nfor attempt in 1 2 3 4 5; do\n  response=$(curl --silent --show-error --max-time 30 --request POST \\\n    --header @<(printf 'Authorization: Bearer %s\\n' \"$MART_API_KEY\") --header 'Content-Type: application/json' \\\n    --data \"$request\" --write-out '\\n%{http_code} %header{retry-after}' \"$MART_API_BASE/api/v1/withdrawals\") || response=$'\\n000'\n  read -r status retry_after <<<\"${response##*$'\\n'}\"\n  body=${response%$'\\n'*}\n  case $status in 000 | 429 | 500 | 502 | 503 | 504) ;; *) break ;; esac\n  [ \"$attempt\" = 5 ] && break\n  if [[ $retry_after =~ ^[0-9]+$ ]]; then\n    if [ \"$retry_after\" -gt 60 ]; then\n      echo \"error: $status, try again after $retry_after s with MART_IDEMPOTENCY_KEY=$idempotency_key\" >&2\n      exit 1\n    fi\n    wait_ms=$((retry_after * 1000))\n  else\n    wait_ms=$((1000 << (attempt - 1)))\n    [ \"$wait_ms\" -gt 30000 ] && wait_ms=30000\n    wait_ms=$((wait_ms / 2 + RANDOM % (wait_ms / 2 + 1)))\n  fi\n  printf 'retry: attempt %d %s, waiting %d.%d s\\n' \"$attempt\" \\\n    \"$([ \"$status\" = 000 ] && echo 'got no answer' || echo \"answered $status\")\" $((wait_ms / 1000)) $((wait_ms % 1000 / 100)) >&2\n  sleep \"$((wait_ms / 1000)).$(printf '%03d' $((wait_ms % 1000)))\"\ndone\n\nif [ \"$status\" = 000 ] || [ \"$status\" -ge 500 ] || [ \"$status\" = 429 ]; then\n  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\n  exit 1\nfi\nif [ \"$status\" -ge 300 ]; then\n  echo \"error: $status $(jq -r '.error.code' <<<\"$body\" 2>/dev/null || echo '(not JSON)')\" >&2\n  exit 1\nfi\njq -r '.data.withdrawal | \"withdrawal: \\(.withdrawal_id)\\nstatus: \\(.status)\"' <<<\"$body\"\nprintf 'amount: %.2f ILS\\n' \"$(jq -r '.data.withdrawal.amount' <<<\"$body\")\"\necho \"replay: $(jq -r '.meta.idempotency_replay' <<<\"$body\")\"\n"
          },
          {
            "lang": "typescript",
            "label": "TypeScript recipe",
            "source": "// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE, MART_API_KEY,\n// MART_WITHDRAW_AMOUNT (shekels, at most two decimals) and MART_IDEMPOTENCY_KEY: your own name for\n// this one request, kept until it is answered.\nconst base = process.env.MART_API_BASE;\nconst key = process.env.MART_API_KEY;\nconst idempotencyKey = process.env.MART_IDEMPOTENCY_KEY;\nif (!base || !key || !idempotencyKey) throw new Error('Set MART_API_BASE, MART_API_KEY and MART_IDEMPOTENCY_KEY');\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\nconst RETRYABLE = new Set([429, 500, 502, 503, 504]);\n\n// Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n// what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n// is final. Every attempt sends the same bytes.\nasync function send(path: string, payload: string, timeoutMs: number): Promise<Response | null> {\n  for (let attempt = 1; ; attempt++) {\n    let response: Response | null = null;\n    try {\n      response = await fetch(`${base}${path}`, {\n        method: 'POST',\n        headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },\n        body: payload,\n        signal: AbortSignal.timeout(timeoutMs),\n      });\n      if (!RETRYABLE.has(response.status) || attempt === 5) return response;\n    } catch {\n      if (attempt === 5) return null; // no answer at all\n    }\n    let wait: number;\n    const retryAfter = Number(response?.headers.get('retry-after'));\n    if (response && Number.isInteger(retryAfter) && retryAfter > 0) {\n      if (retryAfter > 60) return response; // too long to wait here: the caller says when to come back\n      wait = retryAfter;\n    } else {\n      const backoff = Math.min(30, 2 ** (attempt - 1));\n      wait = backoff / 2 + (Math.random() * backoff) / 2;\n    }\n    console.error(`retry: attempt ${attempt} ${response ? `answered ${response.status}` : 'got no answer'}, waiting ${wait.toFixed(1)} s`);\n    await sleep(wait * 1000);\n  }\n}\n\n// Decided once, before any attempt: the same key answers the original request. The amount is a\n// decimal string, such as \"125.50\": exact, never rounded on the way.\nconst request = JSON.stringify({ amount: String(process.env.MART_WITHDRAW_AMOUNT), idempotency_key: idempotencyKey });\nconsole.log(`idempotency key: ${idempotencyKey}`); // written down before the first attempt\n\nconst response = await send('/api/v1/withdrawals', request, 30_000);\nconst body = response ? await response.json().catch(() => null) : null;\nif (response === null || response.status === 429 || response.status >= 500) {\n  const when = response?.headers.get('retry-after');\n  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}`);\n  process.exit(1);\n}\nif (!response.ok || body === null) {\n  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}`);\n  process.exit(1);\n}\nconsole.log(`withdrawal: ${body.data.withdrawal.withdrawal_id}`);\nconsole.log(`status: ${body.data.withdrawal.status}`);\nconsole.log(`amount: ${body.data.withdrawal.amount.toFixed(2)} ILS`);\nconsole.log(`replay: ${body.meta.idempotency_replay}`);\n"
          },
          {
            "lang": "python",
            "label": "Python recipe",
            "source": "\"\"\"Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n\nPython 3.9 or later, with httpx. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels,\nat most two decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it\nis answered.\n\"\"\"\nimport os\nimport random\nimport sys\nimport time\n\nimport httpx\n\nTIMEOUT = 30\nclient = httpx.Client(\n    base_url=os.environ[\"MART_API_BASE\"],\n    headers={\"Authorization\": f\"Bearer {os.environ['MART_API_KEY']}\"},\n    timeout=TIMEOUT,\n)\nidempotency_key = os.environ[\"MART_IDEMPOTENCY_KEY\"]\n\n\ndef body_of(response: httpx.Response):\n    \"\"\"The JSON body, or None for an answer that is not JSON (an edge error page).\"\"\"\n    try:\n        return response.json()\n    except ValueError:\n        return None\n\nRETRYABLE = {429, 500, 502, 503, 504}\n\n\ndef send(path: str, payload: dict):\n    \"\"\"POST the same payload until it is answered for good.\n\n    Retries are your choice of numbers: at most 5 attempts; after no answer, a 429 or a 5xx, wait\n    what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter. Any other answer\n    is final. Returns None when no attempt got an answer.\n    \"\"\"\n    for attempt in range(1, 6):\n        response = None\n        try:\n            response = client.post(path, json=payload)\n            if response.status_code not in RETRYABLE or attempt == 5:\n                return response\n        except httpx.TransportError:\n            if attempt == 5:\n                return None\n        retry_after = response.headers.get(\"Retry-After\", \"\") if response is not None else \"\"\n        if retry_after.isdigit() and int(retry_after) > 0:\n            if int(retry_after) > 60:\n                return response  # too long to wait here: the caller says when to come back\n            wait = float(retry_after)\n        else:\n            backoff = min(30, 2 ** (attempt - 1))\n            wait = backoff / 2 + random.uniform(0, backoff / 2)\n        what = f\"answered {response.status_code}\" if response is not None else \"got no answer\"\n        print(f\"retry: attempt {attempt} {what}, waiting {wait:.1f} s\", file=sys.stderr)\n        time.sleep(wait)\n\n\ndef when(response) -> str:\n    \"\"\"\", try again after N s\" when the answer says how long to wait (Retry-After), else nothing.\"\"\"\n    retry_after = response.headers.get(\"Retry-After\") if response is not None else None\n    return f\", try again after {retry_after} s\" if retry_after else \"\"\n\n\n# Decided once, before any attempt: the same key answers the original request. The amount is a\n# decimal string, such as \"125.50\": exact, never rounded on the way.\nrequest = {\"amount\": os.environ[\"MART_WITHDRAW_AMOUNT\"], \"idempotency_key\": idempotency_key}\nprint(f\"idempotency key: {idempotency_key}\", flush=True)  # written down before the first attempt\n\nresponse = send(\"/api/v1/withdrawals\", request)\nif response is None or response.status_code == 429 or response.status_code >= 500:\n    status = response.status_code if response is not None else \"no answer\"\n    sys.exit(f\"error: {status}{when(response)}; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY={idempotency_key}\")\nbody = body_of(response)\nif response.is_error or body is None:\n    sys.exit(f\"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}{when(response)}\")\nwithdrawal = body[\"data\"][\"withdrawal\"]\nprint(f\"withdrawal: {withdrawal['withdrawal_id']}\")\nprint(f\"status: {withdrawal['status']}\")\nprint(f\"amount: {withdrawal['amount']:.2f} ILS\")\nprint(f\"replay: {str(body['meta']['idempotency_replay']).lower()}\")\n"
          },
          {
            "lang": "php",
            "label": "PHP recipe",
            "source": "<?php\n// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n// PHP 7.4 or later, with the curl extension. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT\n// (shekels, at most two decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept\n// until it is answered.\n$base = getenv('MART_API_BASE');\n$key = getenv('MART_API_KEY');\n$idempotencyKey = (string) getenv('MART_IDEMPOTENCY_KEY');\nif ($idempotencyKey === '') {\n    fwrite(STDERR, \"error: set MART_IDEMPOTENCY_KEY to your own name for this request\\n\");\n    exit(1);\n}\n\n/**\n * One request with the curl extension. Returns [status, headers (lower-case name => value), body];\n * status 0 when there was no answer at all.\n */\nfunction request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array\n{\n    $headers = [];\n    $curl = curl_init($url);\n    curl_setopt_array($curl, [\n        CURLOPT_CUSTOMREQUEST => $method,\n        CURLOPT_HTTPHEADER => [\"Authorization: Bearer $key\", 'Content-Type: application/json'],\n        CURLOPT_RETURNTRANSFER => true,\n        CURLOPT_CONNECTTIMEOUT => 10,\n        CURLOPT_TIMEOUT => $timeout,\n        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {\n            $parts = explode(':', $line, 2);\n            if (count($parts) === 2) {\n                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);\n            }\n            return strlen($line);\n        },\n    ]);\n    if ($payload !== null) {\n        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);\n    }\n    $body = curl_exec($curl);\n    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);\n    curl_close($curl);\n\n    return [$status, $headers, (string) $body];\n}\n\n/** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\nfunction when(array $headers): string\n{\n    return isset($headers['retry-after']) ? \", try again after {$headers['retry-after']} s\" : '';\n}\n\n/**\n * POST the same payload until it is answered for good. Retries are your choice of numbers: at most\n * 5 attempts; after no answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8\n * seconds (capped at 30) with jitter. Any other answer is final.\n */\nfunction send(string $url, string $key, string $payload, int $timeout): array\n{\n    for ($attempt = 1; ; $attempt++) {\n        [$status, $headers, $raw] = request('POST', $url, $key, $payload, $timeout);\n        if (!in_array($status, [0, 429, 500, 502, 503, 504], true) || $attempt === 5) {\n            return [$status, $headers, $raw];\n        }\n        $retryAfter = $headers['retry-after'] ?? '';\n        if (ctype_digit($retryAfter) && (int) $retryAfter > 0) {\n            if ((int) $retryAfter > 60) {\n                return [$status, $headers, $raw]; // too long to wait here: the caller says when to come back\n            }\n            $wait = (float) $retryAfter;\n        } else {\n            $backoff = min(30, 2 ** ($attempt - 1));\n            $wait = $backoff / 2 + mt_rand() / mt_getrandmax() * $backoff / 2;\n        }\n        fwrite(STDERR, sprintf(\"retry: attempt %d %s, waiting %.1f s\\n\", $attempt, $status === 0 ? 'got no answer' : \"answered $status\", $wait));\n        usleep((int) ($wait * 1000000));\n    }\n}\n\n// Decided once, before any attempt: the same key answers the original request. The amount is a\n// decimal string, such as \"125.50\": exact, never rounded on the way.\n$request = json_encode(['amount' => (string) getenv('MART_WITHDRAW_AMOUNT'), 'idempotency_key' => $idempotencyKey]);\necho \"idempotency key: $idempotencyKey\\n\"; // written down before the first attempt\n\n[$status, $headers, $raw] = send(\"$base/api/v1/withdrawals\", $key, $request, 30);\nif ($status === 0 || $status === 429 || $status >= 500) {\n    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status) . when($headers) . \"; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=$idempotencyKey\\n\");\n    exit(1);\n}\n$body = json_decode($raw, true);\nif ($status >= 300 || !is_array($body)) {\n    fwrite(STDERR, \"error: $status \" . ($body['error']['code'] ?? '(not JSON)') . when($headers) . \"\\n\");\n    exit(1);\n}\n$withdrawal = $body['data']['withdrawal'];\necho \"withdrawal: {$withdrawal['withdrawal_id']}\\n\";\necho \"status: {$withdrawal['status']}\\n\";\nprintf(\"amount: %.2f ILS\\n\", $withdrawal['amount']);\necho 'replay: ' . ($body['meta']['idempotency_replay'] ? 'true' : 'false') . \"\\n\";\n"
          },
          {
            "lang": "go",
            "label": "Go recipe",
            "source": "//go:build ignore\n\n// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n// Go 1.22 or later. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at most two\n// decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is answered.\n// Run it with: go run request-a-withdrawal.go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar client = &http.Client{Timeout: 30 * time.Second}\n\nfunc main() {\n\tidempotencyKey := os.Getenv(\"MART_IDEMPOTENCY_KEY\")\n\tif idempotencyKey == \"\" {\n\t\tfail(fmt.Errorf(\"set MART_IDEMPOTENCY_KEY to your own name for this request\"))\n\t}\n\n\t// Decided once, before any attempt: the same key answers the original request. The amount is a\n\t// decimal string, such as \"125.50\": exact, never rounded on the way.\n\trequest, err := json.Marshal(map[string]string{\n\t\t\"amount\":          os.Getenv(\"MART_WITHDRAW_AMOUNT\"),\n\t\t\"idempotency_key\": idempotencyKey,\n\t})\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tfmt.Println(\"idempotency key:\", idempotencyKey) // written down before the first attempt\n\n\tresp := send(\"/api/v1/withdrawals\", request)\n\tif resp == nil || resp.StatusCode == 429 || resp.StatusCode >= 500 {\n\t\tstatus := \"no answer\"\n\t\tif resp != nil {\n\t\t\tstatus = strconv.Itoa(resp.StatusCode)\n\t\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\t\tstatus += \", try again after \" + after + \" s\"\n\t\t\t}\n\t\t}\n\t\tfail(fmt.Errorf(\"%s; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=%s\", status, idempotencyKey))\n\t}\n\tvar answer struct {\n\t\tData struct {\n\t\t\tWithdrawal struct {\n\t\t\t\tID     string  `json:\"withdrawal_id\"`\n\t\t\t\tStatus string  `json:\"status\"`\n\t\t\t\tAmount float64 `json:\"amount\"`\n\t\t\t} `json:\"withdrawal\"`\n\t\t} `json:\"data\"`\n\t\tMeta struct {\n\t\t\tIdempotencyReplay bool `json:\"idempotency_replay\"`\n\t\t} `json:\"meta\"`\n\t}\n\tdecode(resp, &answer)\n\tfmt.Println(\"withdrawal:\", answer.Data.Withdrawal.ID)\n\tfmt.Println(\"status:\", answer.Data.Withdrawal.Status)\n\tfmt.Printf(\"amount: %.2f ILS\\n\", answer.Data.Withdrawal.Amount)\n\tfmt.Println(\"replay:\", answer.Meta.IdempotencyReplay)\n}\n\nvar retryable = map[int]bool{429: true, 500: true, 502: true, 503: true, 504: true}\n\n// send POSTs the same bytes until they are answered for good, and returns the last answer, or\n// nil when no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no\n// answer, a 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30)\n// with jitter. Any other answer is final.\nfunc send(path string, payload []byte) *http.Response {\n\tfor attempt := 1; ; attempt++ {\n\t\treq, err := http.NewRequest(http.MethodPost, os.Getenv(\"MART_API_BASE\")+path, bytes.NewReader(payload))\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+os.Getenv(\"MART_API_KEY\"))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tresp, err := client.Do(req)\n\t\tif err != nil && attempt == 5 {\n\t\t\treturn nil\n\t\t}\n\t\tif err == nil && (!retryable[resp.StatusCode] || attempt == 5) {\n\t\t\treturn resp\n\t\t}\n\t\twhat := \"got no answer\"\n\t\tbackoff := math.Min(30, math.Pow(2, float64(attempt-1)))\n\t\twait := backoff/2 + rand.Float64()*backoff/2\n\t\tif err == nil {\n\t\t\twhat = fmt.Sprintf(\"answered %d\", resp.StatusCode)\n\t\t\tif seconds, convErr := strconv.Atoi(resp.Header.Get(\"Retry-After\")); convErr == nil && seconds > 0 {\n\t\t\t\tif seconds > 60 {\n\t\t\t\t\treturn resp // too long to wait here: the caller says when to come back\n\t\t\t\t}\n\t\t\t\twait = float64(seconds)\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"retry: attempt %d %s, waiting %.1f s\\n\", attempt, what, wait)\n\t\ttime.Sleep(time.Duration(wait * float64(time.Second)))\n\t}\n}\n\n// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),\n// stops with its status and error code.\nfunc decode(resp *http.Response, out any) {\n\tdefer resp.Body.Close()\n\traw, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tvar envelope struct {\n\t\tError *struct {\n\t\t\tCode string `json:\"code\"`\n\t\t} `json:\"error\"`\n\t}\n\tif resp.StatusCode >= 300 {\n\t\tcode := \"(not JSON)\"\n\t\tif json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {\n\t\t\tcode = envelope.Error.Code\n\t\t}\n\t\twait := \"\"\n\t\tif after := resp.Header.Get(\"Retry-After\"); after != \"\" {\n\t\t\twait = \", try again after \" + after + \" s\"\n\t\t}\n\t\tfail(fmt.Errorf(\"%d %s%s\", resp.StatusCode, code, wait))\n\t}\n\tif err := json.Unmarshal(raw, out); err != nil {\n\t\tfail(fmt.Errorf(\"%d (not JSON)\", resp.StatusCode))\n\t}\n}\n\nfunc fail(err error) {\n\tfmt.Fprintln(os.Stderr, \"error:\", err)\n\tos.Exit(1)\n}\n"
          },
          {
            "lang": "java",
            "label": "Java recipe",
            "source": "// Ask Mart to pay out part of what is available, safely retried with the same idempotency key.\n// Java 17 or later, with Jackson. Needs MART_API_BASE, MART_API_KEY, MART_WITHDRAW_AMOUNT (shekels, at\n// most two decimals) and MART_IDEMPOTENCY_KEY: your own name for this one request, kept until it is\n// answered. Run it as a single file: java -cp <the Jackson jars> request-a-withdrawal.java\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ThreadLocalRandom;\n\nclass RequestAWithdrawal {\n    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n    static final ObjectMapper JSON = new ObjectMapper();\n\n    public static void main(String[] args) throws Exception {\n        String idempotencyKey = System.getenv(\"MART_IDEMPOTENCY_KEY\");\n        if (idempotencyKey == null || idempotencyKey.isEmpty()) {\n            fail(\"set MART_IDEMPOTENCY_KEY to your own name for this request\");\n        }\n\n        // Decided once, before any attempt: the same key answers the original request. The amount is a\n        // decimal string, such as \"125.50\": exact, never rounded on the way.\n        String payload = JSON.writeValueAsString(Map.of(\n                \"amount\", System.getenv(\"MART_WITHDRAW_AMOUNT\"),\n                \"idempotency_key\", idempotencyKey));\n        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv(\"MART_API_BASE\") + \"/api/v1/withdrawals\"))\n                .header(\"Authorization\", \"Bearer \" + System.getenv(\"MART_API_KEY\"))\n                .header(\"Content-Type\", \"application/json\")\n                .timeout(Duration.ofSeconds(30))\n                .POST(HttpRequest.BodyPublishers.ofString(payload))\n                .build();\n        System.out.println(\"idempotency key: \" + idempotencyKey); // written down before the first attempt\n\n        HttpResponse<String> response = send(request);\n        if (response == null || response.statusCode() == 429 || response.statusCode() >= 500) {\n            String status = response == null ? \"no answer\" : response.statusCode() + when(response);\n            fail(status + \"; it may have been recorded: run again later with MART_IDEMPOTENCY_KEY=\" + idempotencyKey);\n        }\n        JsonNode body = parse(response.body());\n        if (response.statusCode() >= 300 || body == null) {\n            fail(response.statusCode() + \" \" + code(body) + when(response));\n        }\n        JsonNode withdrawal = body.path(\"data\").path(\"withdrawal\");\n        System.out.println(\"withdrawal: \" + withdrawal.path(\"withdrawal_id\").asText());\n        System.out.println(\"status: \" + withdrawal.path(\"status\").asText());\n        System.out.printf(Locale.ROOT, \"amount: %.2f ILS%n\", withdrawal.path(\"amount\").asDouble());\n        System.out.println(\"replay: \" + body.path(\"meta\").path(\"idempotency_replay\").asBoolean());\n    }\n\n    static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503, 504);\n\n    /**\n     * Sends the same request until it is answered for good, and returns the last answer, or null when\n     * no attempt got one. Retries are your choice of numbers: at most 5 attempts; after no answer, a\n     * 429 or a 5xx, wait what Retry-After says, or else 1, 2, 4, 8 seconds (capped at 30) with jitter.\n     * Any other answer is final.\n     */\n    static HttpResponse<String> send(HttpRequest request) throws InterruptedException {\n        for (int attempt = 1; ; attempt++) {\n            HttpResponse<String> response = null;\n            try {\n                response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());\n                if (!RETRYABLE.contains(response.statusCode()) || attempt == 5) {\n                    return response;\n                }\n            } catch (IOException e) {\n                if (attempt == 5) {\n                    return null;\n                }\n            }\n            double backoff = Math.min(30, Math.pow(2, attempt - 1));\n            double wait = backoff / 2 + ThreadLocalRandom.current().nextDouble() * backoff / 2;\n            String what = \"got no answer\";\n            if (response != null) {\n                what = \"answered \" + response.statusCode();\n                String after = response.headers().firstValue(\"Retry-After\").orElse(\"\");\n                if (after.matches(\"[0-9]+\") && Long.parseLong(after) > 0) {\n                    if (Long.parseLong(after) > 60) {\n                        return response; // too long to wait here: the caller says when to come back\n                    }\n                    wait = Long.parseLong(after);\n                }\n            }\n            System.err.printf(Locale.ROOT, \"retry: attempt %d %s, waiting %.1f s%n\", attempt, what, wait);\n            Thread.sleep((long) (wait * 1000));\n        }\n    }\n\n    /** The JSON body, or null for an answer that is not JSON (an edge error page). */\n    static JsonNode parse(String text) {\n        try {\n            return JSON.readTree(text);\n        } catch (IOException e) {\n            return null;\n        }\n    }\n\n    static void fail(String message) {\n        System.err.println(\"error: \" + message);\n        System.exit(1);\n    }\n\n    static String code(JsonNode body) {\n        return body == null ? \"(not JSON)\" : body.path(\"error\").path(\"code\").asText();\n    }\n\n    /** \", try again after N s\" when the answer says how long to wait (Retry-After), else nothing. */\n    static String when(HttpResponse<String> response) {\n        return response.headers().firstValue(\"Retry-After\").map(s -> \", try again after \" + s + \" s\").orElse(\"\");\n    }\n}\n"
          }
        ]
      }
    },
    "/api/v1/withdrawals/{withdrawal_id}": {
      "get": {
        "summary": "Get a withdrawal",
        "description": "One of your withdrawal requests, in the shape of a list item. An id that belongs to another account answers exactly as an id that does not exist: `404` `withdrawal_not_found`. Full behaviour: https://mart.ps/api/docs#money/withdrawal.",
        "tags": [
          "Money"
        ],
        "operationId": "getWithdrawal",
        "x-required-scope": "money:read",
        "parameters": [
          {
            "name": "withdrawal_id",
            "in": "path",
            "required": true,
            "description": "The `withdrawal_id` a request or the list returned, exactly as returned. Anything else answers 404 `withdrawal_not_found`, the same answer as another account's id.",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9_-]{1,16}$",
              "example": "NDE"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Your withdrawal request.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "withdrawal": {
                              "$ref": "#/components/schemas/Withdrawal"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "withdrawal": {
                      "withdrawal_id": "NDE",
                      "amount": 125.0,
                      "status": "approved",
                      "iban": "PS92PALS000000000400123456702",
                      "reject_reason": null,
                      "requested_at": "2026-11-01T08:30:00+00:00",
                      "approved_at": "2026-11-02T09:00:00+00:00",
                      "paid_at": null,
                      "method": "bank",
                      "requested_amount": 125.0
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/WithdrawalsDisabled"
          },
          "404": {
            "$ref": "#/components/responses/WithdrawalNotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/WithdrawalUnavailable"
          }
        }
      }
    },
    "/api/v1/withdrawals/{withdrawal_id}/cancel": {
      "post": {
        "summary": "Cancel a withdrawal",
        "description": "Takes a request back while it is still `requested`: its amount is released at once. Cancelling one that is already `cancelled` answers `200` again and changes nothing. An `approved`, `paid` or `rejected` request answers `409` `withdrawal_not_cancellable`. An id that belongs to another account answers `404` `withdrawal_not_found`, as one that does not exist. No body is read. Full behaviour: https://mart.ps/api/docs#money/withdrawal-cancel.",
        "tags": [
          "Money"
        ],
        "operationId": "cancelWithdrawal",
        "x-required-scope": "withdrawals:write",
        "parameters": [
          {
            "name": "withdrawal_id",
            "in": "path",
            "required": true,
            "description": "The `withdrawal_id` a request or the list returned, exactly as returned. Anything else answers 404 `withdrawal_not_found`, the same answer as another account's id.",
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9_-]{1,16}$",
              "example": "NDE"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "The request, now `cancelled`.",
            "headers": {
              "X-Mart-Environment": {
                "$ref": "#/components/headers/X-Mart-Environment"
              },
              "X-RateLimit-Limit": {
                "$ref": "#/components/headers/X-RateLimit-Limit"
              },
              "X-RateLimit-Remaining": {
                "$ref": "#/components/headers/X-RateLimit-Remaining"
              },
              "X-RateLimit-Reset": {
                "$ref": "#/components/headers/X-RateLimit-Reset"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/SuccessEnvelope"
                    },
                    {
                      "type": "object",
                      "properties": {
                        "data": {
                          "type": "object",
                          "properties": {
                            "withdrawal": {
                              "$ref": "#/components/schemas/Withdrawal"
                            }
                          }
                        }
                      }
                    }
                  ]
                },
                "example": {
                  "status": "success",
                  "status_code": 200,
                  "message": "OK",
                  "data": {
                    "withdrawal": {
                      "withdrawal_id": "NDE",
                      "amount": 125.0,
                      "status": "cancelled",
                      "iban": null,
                      "reject_reason": null,
                      "requested_at": "2026-11-01T08:30:00+00:00",
                      "approved_at": null,
                      "paid_at": null,
                      "method": "bank",
                      "requested_amount": 125.0
                    }
                  },
                  "meta": null,
                  "error": null
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/WithdrawalsDisabled"
          },
          "404": {
            "$ref": "#/components/responses/WithdrawalNotFound"
          },
          "405": {
            "$ref": "#/components/responses/MethodNotAllowed"
          },
          "409": {
            "$ref": "#/components/responses/WithdrawalRefused"
          },
          "422": {
            "$ref": "#/components/responses/UnprocessableEntity"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "$ref": "#/components/responses/WithdrawalUnavailable"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Authorization: Bearer <key>"
      },
      "apiKeyHeader": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Api-Key"
      }
    },
    "headers": {
      "X-Mart-Environment": {
        "description": "Which installation answered: `production` or `sandbox`. Present on every response; assert it once at startup.",
        "schema": {
          "type": "string",
          "enum": [
            "production",
            "sandbox"
          ]
        }
      },
      "X-RateLimit-Limit": {
        "description": "Limit of the tightest active window.",
        "schema": {
          "type": "integer"
        }
      },
      "X-RateLimit-Remaining": {
        "description": "Requests remaining in the tightest active window.",
        "schema": {
          "type": "integer"
        }
      },
      "X-RateLimit-Reset": {
        "description": "Epoch seconds when the tightest window resets.",
        "schema": {
          "type": "integer"
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Missing or unusable API key (`missing_api_key`, `invalid_api_key`). Revoked and paused keys answer identically to unknown keys. A key issued for the other environment answers `key_environment_mismatch` before any lookup: `details.environment` names the environment you called (`production` or `sandbox`) — switch base URL or key. See the Environments note in the introduction.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "Forbidden": {
        "description": "The key does not have the scope this endpoint needs (`insufficient_scope`, `details.required_scope` names it; checked before the group and the rate limit, so it uses no quota), or the key customer is missing/inactive (`api_customer_not_configured`) or outside the allowed groups (`customer_group_not_allowed`). Group membership is re-checked on every request; access resumes when the customer rejoins an allowed group.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "ForbiddenGroup": {
        "description": "The key customer is missing or inactive (`api_customer_not_configured`) or outside the allowed groups (`customer_group_not_allowed`). Group membership is re-checked on every request; access resumes when the customer rejoins an allowed group. This endpoint needs no scope that can be missing: a key without the order-writing permission is answered `422` `orders_not_enabled` by the endpoint itself.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "NotFound": {
        "description": "The route does not exist (`route_not_found`) or the addressed resource does not (`product_not_found`). On the product detail route the two are distinct: a malformed id never matches the route; a well-formed unknown id answers `product_not_found`.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "MethodNotAllowed": {
        "description": "The method is not accepted on this endpoint (`method_not_allowed`). Read the `Allow` response header rather than assuming; `OPTIONS` is accepted everywhere and answered as a bodyless 204.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "UnprocessableEntity": {
        "description": "Invalid parameter value (`invalid_parameter`); `error.details` names the parameter.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "TooManyRequests": {
        "description": "Rate limit exceeded (`rate_limit_exceeded`). Carries `Retry-After` (seconds) plus the X-RateLimit-* trio of the exceeded window; day-window breaches advertise the day reset, not a 60-second retry.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "InternalError": {
        "description": "Opaque server failure (`internal_error`). Details are logged server-side and never exposed.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "BadRequest": {
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        },
        "description": "The request body is missing, is not valid JSON, or is not a JSON object (`bad_request`)."
      },
      "IdempotencyConflict": {
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        },
        "description": "This `partner_reference` was already used for a DIFFERENT order (`idempotency_conflict`; `details.original_order_id`) — the original is never modified. Card orders can also answer 409 `charge_amount_mismatch`: a captured charge no longer matches the current total. See https://mart.ps/api/docs#idempotency."
      },
      "OrderUnprocessable": {
        "description": "Order validation failed — no order was created and the same `partner_reference` may be reused for the corrected request. Product-level codes carry `details.index` (zero-based position in `products`). Codes: `orders_not_enabled`, `api_group_misconfigured`, `invalid_parameter`, `invalid_state`, `unknown_product`, `product_not_offered`, `product_not_orderable`, `combination_required`, `combination_not_allowed`, `unknown_combination`, `combination_mismatch`, `duplicate_product`, `price_override_not_allowed`, `price_below_minimum`, `insufficient_stock`, `free_shipping_not_covered`, `free_shipping_not_allowed`, `card_not_enabled`, `card_not_on_file`, `saved_card_invalid`, `card_price_not_allowed`, `card_free_shipping_not_allowed`. What each means and how to clear it: https://mart.ps/api/docs#errors.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "OrderNotFound": {
        "description": "No order with that `partner_reference` on YOUR account (`order_not_found`). Deliberately identical whether the reference never existed or belongs to another partner — the response never reveals other accounts' references.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "OrderNotCancellable": {
        "description": "The order is past the point partners may cancel from (`order_not_cancellable`); nothing was changed, and `details` carry only your reference. Treat as final for this order and read the order to see where it got to.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "OrderCancellationNotConfigured": {
        "description": "Cancellation is unavailable: `order_cancellation_not_configured` (partner cancellation is not enabled on this store — contact Mart) or `order_cancellation_in_progress` (transient — honour `Retry-After` and expect `already_cancelled: true`).",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "CardDeclined": {
        "description": "The gateway declined the charge (`card_declined`) — no order was created and nothing was captured. Retrying the same reference makes a fresh attempt, never a double charge; `details.attempts_exhausted: true` means the reference is terminally declined. See https://mart.ps/api/docs#payments.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "PaymentGatewayUnavailable": {
        "description": "Card charging is temporarily impossible: `payment_gateway_unavailable` (the gateway did not answer — retry the same `partner_reference` after `Retry-After`; never double-charges) or `order_creation_in_progress` (another request with this reference, or another order to the same recipient, is mid-flight — wait for `Retry-After` and retry; applies to cash-on-delivery orders too).",
        "headers": {
          "X-Mart-Environment": {
            "$ref": "#/components/headers/X-Mart-Environment"
          },
          "Retry-After": {
            "description": "Seconds to wait before retrying.",
            "schema": {
              "type": "integer"
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "EventFeedExpired": {
        "description": "`after` is older than what the feed still keeps (`cursor_expired`), with `error.details.resync: true`. First send `start=latest` and keep that `next_cursor`, then rebuild what you hold from the read endpoints, then read on from the cursor you kept: in another order, what happens during the rebuild is lost. Never answered to a read with no `after`.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            },
            "example": {
              "status": "fail",
              "status_code": 410,
              "message": "after is older than what this feed still keeps, so events you have not read may be gone. Send start=latest and keep that cursor, rebuild from your orders, ledger and withdrawals, then read on from the cursor you kept.",
              "data": null,
              "meta": null,
              "error": {
                "code": "cursor_expired",
                "details": {
                  "parameter": "after",
                  "resync": true
                }
              }
            }
          }
        }
      },
      "EventFeedInvalid": {
        "description": "`after` is not a cursor this feed issued (`invalid_cursor`), or `limit` or `start` is not valid (`invalid_parameter`). `error.details.parameter` names it.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            },
            "example": {
              "status": "fail",
              "status_code": 422,
              "message": "after is not a cursor this feed issued. Send a cursor or next_cursor exactly as it was returned.",
              "data": null,
              "meta": null,
              "error": {
                "code": "invalid_cursor",
                "details": {
                  "parameter": "after"
                }
              }
            }
          }
        }
      },
      "LedgerUnavailable": {
        "description": "The balance and ledger cannot be answered right now (`ledger_unavailable`). It is never answered with zeros or an empty list: retry later. There is no `Retry-After`.",
        "headers": {
          "X-Mart-Environment": {
            "$ref": "#/components/headers/X-Mart-Environment"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "StatementNotFound": {
        "description": "No such statement on your account (`statement_not_found`). A number that belongs to another account answers exactly as a number that does not exist.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "WithdrawalsDisabled": {
        "description": "Withdrawals are not enabled for your account (`withdrawals_disabled`), cash at the office is not offered to your account (`cash_not_allowed`), the key does not have the scope this endpoint needs (`insufficient_scope`), or the key's customer is missing, inactive or outside the allowed groups (`api_customer_not_configured`, `customer_group_not_allowed`).",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "PayoutMethodInvalid": {
        "description": "The method (`invalid_payout_method`: `bank` or `cash`), the IBAN (`invalid_iban`), the account holder name (`invalid_account_holder_name`) or the national ID (`invalid_national_id`) is not valid, or a bank transfer is not offered to your account (`bank_transfer_not_allowed`: nothing was saved). `error.details` says why and never repeats what you sent: for the IBAN `reason`, `country` and `expected_length` where they apply.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "PayoutMethodChangeBlocked": {
        "description": "The payout method cannot switch between bank and cash while a withdrawal is open (`payout_method_change_blocked`), so that every request is paid the way it was made. Cancel the open request, or wait until it is paid or rejected. Nothing was saved.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "WithdrawalNotFound": {
        "description": "No such withdrawal on your account (`withdrawal_not_found`). An id that belongs to another account, an id that never existed and a string this API never issued all answer exactly the same.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "WithdrawalRefused": {
        "description": "The request is understood and refused, and nothing was written. `payout_method_missing` (save a payout method first, cash included), `withdrawals_locked` (`details.locked_until`: the payout method changed and its lock has not passed), `too_many_open_withdrawals` (`details.maximum`), `insufficient_available` (`details.available`: the amount is above what `GET /balance` calls available), `idempotency_conflict` (this `idempotency_key` was already used for another amount), `withdrawal_not_cancellable` (cancel only). What each means and how to clear it: https://mart.ps/api/docs#errors.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "WithdrawalInvalid": {
        "description": "The request cannot be read as a withdrawal: `invalid_amount` (not a positive number with at most two decimals), `amount_below_minimum` (`details.minimum`), `amount_above_cash_maximum` (`details.maximum`, a cash request only), `bank_transfer_not_allowed` (your saved payout method is an IBAN, and a bank transfer is not offered to your account: save cash at the office to withdraw), or `invalid_parameter` (`details.parameter` is `idempotency_key`, or `status` or a page parameter on the list). Nothing was written.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      },
      "WithdrawalUnavailable": {
        "description": "The ledger cannot be answered right now (`ledger_unavailable`, no `Retry-After`), or, on a request, this account is being changed by another call (`withdrawal_busy`, with `Retry-After` in seconds: retry with the same `idempotency_key`). Nothing is created by a `503`, but a request that timed out may have been: retry with the same key and read the answer.",
        "headers": {
          "X-Mart-Environment": {
            "$ref": "#/components/headers/X-Mart-Environment"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorEnvelope"
            }
          }
        }
      }
    },
    "schemas": {
      "SuccessEnvelope": {
        "type": "object",
        "required": [
          "status",
          "status_code",
          "message",
          "data",
          "meta",
          "error"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "success"
            ]
          },
          "status_code": {
            "type": "integer",
            "example": 200
          },
          "message": {
            "type": "string",
            "example": "OK"
          },
          "data": {
            "type": "object",
            "description": "One key named after the resource (products / product / states / categories / attributes / order / validation)."
          },
          "meta": {
            "nullable": true,
            "type": "object"
          },
          "error": {
            "nullable": true,
            "type": "object",
            "enum": [
              null
            ]
          }
        }
      },
      "ErrorEnvelope": {
        "type": "object",
        "required": [
          "status",
          "status_code",
          "message",
          "data",
          "meta",
          "error"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "fail"
            ]
          },
          "status_code": {
            "type": "integer",
            "example": 422
          },
          "message": {
            "type": "string"
          },
          "data": {
            "nullable": true,
            "enum": [
              null
            ]
          },
          "meta": {
            "nullable": true,
            "enum": [
              null
            ]
          },
          "error": {
            "type": "object",
            "required": [
              "code",
              "details"
            ],
            "properties": {
              "code": {
                "type": "string",
                "enum": [
                  "missing_api_key",
                  "invalid_api_key",
                  "key_environment_mismatch",
                  "api_customer_not_configured",
                  "customer_group_not_allowed",
                  "insufficient_scope",
                  "product_not_found",
                  "order_not_found",
                  "route_not_found",
                  "method_not_allowed",
                  "invalid_parameter",
                  "invalid_state",
                  "rate_limit_exceeded",
                  "bad_request",
                  "orders_not_enabled",
                  "api_group_misconfigured",
                  "idempotency_conflict",
                  "unknown_product",
                  "product_not_offered",
                  "product_not_orderable",
                  "combination_required",
                  "combination_not_allowed",
                  "unknown_combination",
                  "combination_mismatch",
                  "duplicate_product",
                  "cart_minimum_not_met",
                  "price_below_minimum",
                  "price_override_not_allowed",
                  "insufficient_stock",
                  "free_shipping_not_covered",
                  "free_shipping_not_allowed",
                  "card_not_enabled",
                  "internal_error",
                  "order_not_cancellable",
                  "order_cancellation_not_configured",
                  "order_cancellation_in_progress",
                  "card_not_on_file",
                  "saved_card_invalid",
                  "card_price_not_allowed",
                  "card_free_shipping_not_allowed",
                  "card_declined",
                  "payment_gateway_unavailable",
                  "order_creation_in_progress",
                  "charge_amount_mismatch",
                  "invalid_cursor",
                  "cursor_expired",
                  "ledger_unavailable",
                  "statement_not_found",
                  "withdrawals_disabled",
                  "invalid_iban",
                  "invalid_account_holder_name",
                  "invalid_national_id",
                  "invalid_amount",
                  "amount_below_minimum",
                  "payout_method_missing",
                  "withdrawals_locked",
                  "too_many_open_withdrawals",
                  "insufficient_available",
                  "withdrawal_busy",
                  "withdrawal_not_found",
                  "withdrawal_not_cancellable",
                  "cash_not_allowed",
                  "payout_method_change_blocked",
                  "amount_above_cash_maximum",
                  "invalid_payout_method",
                  "bank_transfer_not_allowed"
                ]
              },
              "details": {
                "description": "Structured context (parameter name, supported values, retry hints). Empty array when none."
              }
            }
          }
        }
      },
      "ProductCategory": {
        "type": "object",
        "nullable": true,
        "description": "The product's category data (Meta product taxonomy). Null only when the product's category has no mapping row. The full category vocabulary — the valid `category_id` filter values — is `GET /api/v1/categories`.",
        "required": [
          "category_id",
          "category_name",
          "gender"
        ],
        "properties": {
          "category_id": {
            "type": "integer",
            "example": 429
          },
          "category_name": {
            "type": "string",
            "example": "clothing & accessories > shoes & footwear"
          },
          "gender": {
            "type": "string",
            "enum": [
              "men",
              "women",
              "unisex"
            ],
            "example": "women"
          }
        }
      },
      "ProductListItem": {
        "type": "object",
        "required": [
          "product_id",
          "reference",
          "name",
          "status",
          "brand",
          "category",
          "price",
          "currency",
          "total_quantity",
          "in_stock",
          "cover_image",
          "images",
          "combinations",
          "updated_at"
        ],
        "properties": {
          "product_id": {
            "type": "integer",
            "description": "Stable product identifier used in catalog synchronization and order creation.",
            "example": 68516
          },
          "reference": {
            "type": "string",
            "example": "1005118",
            "description": "Human-facing catalog reference. Descriptive data ONLY — editable in the back office and never resolved by the API. Key on `product_id` instead."
          },
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true,
            "description": "HTML as authored. ONLY present when the request carries include=description; omitted entirely otherwise."
          },
          "description_short": {
            "type": "string",
            "nullable": true,
            "description": "ONLY present when the request carries include=description; omitted entirely otherwise."
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "inactive"
            ]
          },
          "brand": {
            "$ref": "#/components/schemas/Brand"
          },
          "category": {
            "$ref": "#/components/schemas/ProductCategory"
          },
          "price": {
            "$ref": "#/components/schemas/Price"
          },
          "currency": {
            "type": "string",
            "example": "ILS"
          },
          "total_quantity": {
            "type": "integer",
            "description": "Aggregate quantity across combinations."
          },
          "in_stock": {
            "type": "boolean"
          },
          "cover_image": {
            "type": "string",
            "format": "uri",
            "nullable": true,
            "description": "Single thumbnail URL — the cover image, or the first image when no cover is flagged. Always equals `images[0]`; null only when the product has no images.",
            "example": "https://cdn.mart.ps/28359-thickbox_default/product.jpg"
          },
          "images": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uri"
            },
            "description": "All product image URLs ordered cover-first, then position."
          },
          "combinations": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CombinationSummary"
            },
            "description": "Empty for simple products."
          },
          "updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "CombinationAttribute": {
        "type": "object",
        "required": [
          "id",
          "name",
          "group"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "description": "Stable attribute-value identifier.",
            "example": 16
          },
          "name": {
            "type": "string",
            "description": "Localized value label.",
            "example": "بني"
          },
          "group": {
            "type": "string",
            "description": "Localized attribute-group label.",
            "example": "اللون"
          }
        }
      },
      "Combination": {
        "allOf": [
          {
            "$ref": "#/components/schemas/CombinationSummary"
          },
          {
            "type": "object",
            "description": "Detail-only extras on top of the listing shape. No price: pricing is product-level, never combination-level, so the document's single `price` is the product's.",
            "required": [
              "default",
              "images"
            ],
            "properties": {
              "default": {
                "type": "boolean"
              },
              "images": {
                "type": "array",
                "items": {
                  "type": "string",
                  "format": "uri"
                },
                "description": "Combination-specific image URLs; empty when none."
              }
            }
          }
        ]
      },
      "ProductDetail": {
        "type": "object",
        "required": [
          "product_id",
          "reference",
          "name",
          "description",
          "description_short",
          "status",
          "brand",
          "category",
          "price",
          "currency",
          "total_quantity",
          "in_stock",
          "cover_image",
          "images",
          "combinations",
          "updated_at"
        ],
        "properties": {
          "product_id": {
            "type": "integer",
            "description": "Stable product identifier used in catalog synchronization and order creation.",
            "example": 68516
          },
          "reference": {
            "type": "string",
            "description": "Human-facing catalog reference. Descriptive data ONLY — editable in the back office and never resolved by the API. Key on `product_id` instead."
          },
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true,
            "description": "HTML as authored."
          },
          "description_short": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "inactive"
            ]
          },
          "brand": {
            "$ref": "#/components/schemas/Brand"
          },
          "category": {
            "$ref": "#/components/schemas/ProductCategory"
          },
          "price": {
            "$ref": "#/components/schemas/Price"
          },
          "currency": {
            "type": "string",
            "example": "ILS"
          },
          "total_quantity": {
            "type": "integer"
          },
          "in_stock": {
            "type": "boolean"
          },
          "cover_image": {
            "type": "string",
            "format": "uri",
            "nullable": true,
            "description": "Single thumbnail URL — the cover image, or the first image when no cover is flagged. Always equals `images[0]`; null only when the product has no images.",
            "example": "https://cdn.mart.ps/28359-thickbox_default/product.jpg"
          },
          "images": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uri"
            },
            "description": "All product image URLs ordered cover-first, then position."
          },
          "combinations": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/Combination"
            }
          },
          "updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "ListPaginationMeta": {
        "type": "object",
        "required": [
          "page",
          "limit",
          "total",
          "total_pages",
          "has_next"
        ],
        "properties": {
          "page": {
            "type": "integer"
          },
          "limit": {
            "type": "integer"
          },
          "total": {
            "type": "integer"
          },
          "total_pages": {
            "type": "integer"
          },
          "has_next": {
            "type": "boolean"
          }
        }
      },
      "OrderMeta": {
        "type": "object",
        "required": [
          "idempotency_replay"
        ],
        "description": "Order-creation meta. Present on both the 201 and the 200 replay.",
        "properties": {
          "idempotency_replay": {
            "type": "boolean",
            "description": "false when this call created the order, true when it returned an order an identical earlier request had already created.",
            "example": false
          }
        }
      },
      "Price": {
        "type": "object",
        "description": "Three tax-included prices in the response `currency`, 2 decimals, all always present and never null. `base_price` is the highest (or equal); `group_price` is NOT guaranteed to be below `public_price`. Semantics: https://mart.ps/api/docs#catalog.",
        "required": [
          "group_price",
          "public_price",
          "base_price"
        ],
        "properties": {
          "group_price": {
            "type": "number",
            "description": "Your account's current price: after your customer group's discounts and any specific price in effect. This is the ONLY figure the order price floor compares against, and the baseline for reward.",
            "example": 55.99
          },
          "public_price": {
            "type": "number",
            "description": "What an unidentified visitor is charged on the storefront right now. Useful as a recommended retail price; it has no bearing on what you may sell at, and it is NOT always above group_price.",
            "example": 59.99
          },
          "base_price": {
            "type": "number",
            "description": "The catalogue price before any specific price or group reduction — the crossed-out price. Equal to the other two when nothing is discounted.",
            "example": 99.99
          }
        }
      },
      "Brand": {
        "type": "object",
        "nullable": true,
        "description": "Null when the product has no manufacturer.",
        "required": [
          "id",
          "name"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "example": 27
          },
          "name": {
            "type": "string",
            "example": "Rock"
          }
        }
      },
      "CombinationSummary": {
        "type": "object",
        "description": "Combination row as embedded in the listing. `id` is the stable variant token — the `combination_id` order creation accepts.",
        "required": [
          "id",
          "available_quantity",
          "attributes"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "example": 41206
          },
          "available_quantity": {
            "type": "integer",
            "example": 7
          },
          "attributes": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CombinationAttribute"
            },
            "description": "Ordered by attribute-group position."
          }
        }
      },
      "AttributeGroupItem": {
        "type": "object",
        "required": [
          "attribute_group_id",
          "attribute_group_name",
          "values"
        ],
        "properties": {
          "attribute_group_id": {
            "type": "integer",
            "example": 1,
            "description": "Groups this payload only — it appears NOWHERE in products responses. Not a `state_id`-style token; nothing accepts it as input."
          },
          "attribute_group_name": {
            "type": "string",
            "example": "اللون",
            "description": "Display string (ps public name) — identical to the `group` string on products' combination attributes, but names are not keys; join by `values[].attribute_id`."
          },
          "values": {
            "type": "array",
            "minItems": 1,
            "description": "The group's used values, ordered by position. Never empty.",
            "items": {
              "$ref": "#/components/schemas/AttributeValueItem"
            }
          }
        }
      },
      "AttributeValueItem": {
        "type": "object",
        "required": [
          "attribute_id",
          "attribute_name"
        ],
        "properties": {
          "attribute_id": {
            "type": "integer",
            "example": 16,
            "description": "Stable attribute-value identifier — equals the `id` in products' `combinations[].attributes[]`. The ONLY cross-endpoint join key."
          },
          "attribute_name": {
            "type": "string",
            "example": "بني",
            "description": "Display string; not unique across groups, not a key."
          }
        }
      },
      "CategoryItem": {
        "type": "object",
        "required": [
          "category_id",
          "category_name",
          "gender"
        ],
        "properties": {
          "category_id": {
            "type": "integer",
            "example": 455,
            "description": "The value accepted by the products `category_id` filter and returned in each product's `category.category_id`."
          },
          "category_name": {
            "type": "string",
            "example": "clothing & accessories > clothing > women's clothing",
            "description": "Full ' > ' taxonomy path — byte-identical to the products endpoints' `category.category_name` for the same id."
          },
          "gender": {
            "type": "string",
            "nullable": true,
            "enum": [
              "men",
              "women",
              "unisex"
            ],
            "example": "women",
            "description": "Null when the category spans more than one gender."
          }
        }
      },
      "CityItem": {
        "type": "object",
        "required": [
          "id",
          "name",
          "states"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "example": 255,
            "description": "City identifier, used only to group states. It is NOT a `state_id` — sending it as `shipping_address.state_id` returns 422 `invalid_state`."
          },
          "name": {
            "type": "string",
            "example": "الخليل",
            "description": "City name (store default language)."
          },
          "states": {
            "type": "array",
            "minItems": 1,
            "description": "The city's deliverable states/towns, ordered by name. Never empty.",
            "items": {
              "$ref": "#/components/schemas/StateItem"
            }
          }
        }
      },
      "StateItem": {
        "type": "object",
        "required": [
          "id",
          "name",
          "delivery"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "example": 774,
            "description": "Stable destination identifier — the ONLY valid value for `shipping_address.state_id` when creating an order. A city `id` is never accepted."
          },
          "name": {
            "type": "string",
            "example": "أبو الغزلان",
            "description": "Town/state name (single-language column). Names are NOT guaranteed unique, even within a single city; `id` is the only truth."
          },
          "delivery": {
            "$ref": "#/components/schemas/StateDelivery"
          }
        }
      },
      "StateDelivery": {
        "type": "object",
        "required": [
          "available",
          "fees"
        ],
        "description": "What delivery to this state costs your customer, by products total. These are the brackets an order of yours to this state is priced with: the `shipping_fee` of an order you create, and of the quote from POST /api/v1/orders/validate, is the fee of the bracket its products total falls in. They follow Mart's delivery set-up and can change between your read and your order, so the create answer is the binding one.",
        "properties": {
          "available": {
            "type": "boolean",
            "description": "false when delivery to this state cannot be priced right now: `fees` is then empty, and an order to it fails until Mart fixes its set-up. Do not offer the state while it is false."
          },
          "fees": {
            "type": "array",
            "description": "The brackets in order: the first starts at 0.00, each ends where the next starts, and the last has a null `to_total`. Empty when `available` is false.",
            "items": {
              "$ref": "#/components/schemas/DeliveryFee"
            }
          }
        }
      },
      "DeliveryFee": {
        "type": "object",
        "required": [
          "from_total",
          "to_total",
          "fee"
        ],
        "description": "One delivery bracket: a products total t pays `fee` when `from_total` <= t < `to_total`.",
        "properties": {
          "from_total": {
            "type": "number",
            "format": "double",
            "description": "The lowest products total (tax included, delivery excluded) of this bracket. Inclusive."
          },
          "to_total": {
            "type": "number",
            "format": "double",
            "nullable": true,
            "description": "Where the next bracket starts. Exclusive: a total equal to it pays the next bracket's fee. null on the last bracket, which has no upper end."
          },
          "fee": {
            "type": "number",
            "format": "double",
            "description": "The delivery fee for a products total in this bracket."
          }
        }
      },
      "OrderCreateRequest": {
        "type": "object",
        "required": [
          "partner_reference",
          "payment_type",
          "shipping_address",
          "products"
        ],
        "properties": {
          "payment_type": {
            "type": "string",
            "enum": [
              "cod",
              "card"
            ],
            "description": "REQUIRED: exact lowercase `cod` or `card` — never normalized, never defaulted. `card` charges your saved card synchronously for the server-computed total and needs per-key enablement (`card_not_enabled`) plus a reusable saved card on file (`card_not_on_file`). See https://mart.ps/api/docs#payments.",
            "example": "cod"
          },
          "partner_reference": {
            "type": "string",
            "maxLength": 64,
            "description": "Your own order id and the idempotency key, stored and matched byte-for-byte. Letters, digits, dot, underscore, hyphen; max 64 characters; surrounding whitespace is rejected, never trimmed; unique per key. Identity is judged on a canonical form — https://mart.ps/api/docs#idempotency.",
            "example": "100245"
          },
          "shipping_address": {
            "type": "object",
            "required": [
              "customer_name",
              "phone",
              "state_id",
              "address"
            ],
            "properties": {
              "customer_name": {
                "type": "string",
                "example": "محمد علي"
              },
              "phone": {
                "type": "string",
                "description": "The recipient's primary (mobile) number — the one the courier calls.",
                "example": "0599123456"
              },
              "extra_phone": {
                "type": "string",
                "nullable": true,
                "description": "Optional second number for the recipient. Omitted and null are equivalent.",
                "example": "022345678"
              },
              "state_id": {
                "type": "integer",
                "description": "A leaf `states[].id` from GET /api/v1/states — a city `id` is not a `state_id`. Unknown or inactive returns 422 invalid_state.",
                "example": 812
              },
              "address": {
                "type": "string",
                "example": "شارع الإرسال، عمارة 12"
              },
              "notes": {
                "type": "string",
                "nullable": true,
                "description": "Optional. Omitted and null are equivalent."
              }
            }
          },
          "products": {
            "type": "array",
            "minItems": 1,
            "maxItems": 200,
            "description": "Order is significant: error details reference the line index.",
            "items": {
              "type": "object",
              "required": [
                "product_id",
                "quantity"
              ],
              "properties": {
                "product_id": {
                  "type": "integer",
                  "description": "Stable product identifier used in catalog synchronization and order creation.",
                  "example": 68516
                },
                "combination_id": {
                  "type": "integer",
                  "nullable": true,
                  "description": "REQUIRED for a product that has combinations; MUST be null (or omitted) for one that does not. Mismatches return 422 combination_required / combination_not_allowed / unknown_combination / combination_mismatch."
                },
                "quantity": {
                  "type": "integer",
                  "minimum": 1,
                  "example": 2
                },
                "price": {
                  "type": "number",
                  "format": "double",
                  "exclusiveMinimum": true,
                  "minimum": 0,
                  "description": "Optional tax-included selling price per unit. Omitted or `null` = sell at your group's catalog price, resolved at creation. Must be at least `price.group_price` when your group allows overrides (`price_below_minimum`), and must equal it exactly when not (`price_override_not_allowed`). An explicit 0 is always invalid. Rejected with `card_price_not_allowed` on card orders. See https://mart.ps/api/docs#orders.",
                  "example": 120.0
                }
              }
            }
          },
          "free_shipping": {
            "type": "boolean",
            "default": false,
            "description": "`true` = you absorb the delivery fee (needs your group's permission — `free_shipping_not_allowed` otherwise; `free_shipping_not_covered` when your margin cannot cover the fee, exact coverage passing). Rejected with `card_free_shipping_not_allowed` on card orders. See https://mart.ps/api/docs#orders."
          }
        }
      },
      "Validation": {
        "type": "object",
        "description": "The dry-run verdict of POST /api/v1/orders/validate. Only ever present on a 200 — an invalid order answers the error envelope instead, so `valid` carries no information beyond the status. `quote` is what the order would cost and earn if you created it now.",
        "required": [
          "valid",
          "quote"
        ],
        "properties": {
          "valid": {
            "type": "boolean",
            "enum": [
              true
            ],
            "description": "Always true. An order that would be rejected answers the same error envelope POST /api/v1/orders would, not a `valid: false` body."
          },
          "quote": {
            "$ref": "#/components/schemas/OrderQuote"
          }
        }
      },
      "OrderQuote": {
        "type": "object",
        "nullable": true,
        "description": "What the order would cost and earn if you created it now, from the very figures a create with the same body freezes: the delivery fee is the `GET /api/v1/states` bracket its products total falls in, and `reward` is the created order's `money` figures. Stock, prices and delivery fees can move before you create, so the create answer is the binding one. `null` when your `partner_reference` already names an order: a create would return that order unchanged, so its figures are on `GET /api/v1/orders/{partner_reference}`.",
        "required": [
          "products_total",
          "shipping_fee",
          "free_shipping",
          "order_total",
          "cod_total",
          "reward"
        ],
        "properties": {
          "products_total": {
            "type": "number",
            "format": "double",
            "description": "The products at your prices (the group price where you sent none), tax included, delivery excluded: the total the delivery brackets are read with."
          },
          "shipping_fee": {
            "type": "number",
            "format": "double",
            "description": "The delivery fee for this destination and products total."
          },
          "free_shipping": {
            "type": "boolean",
            "description": "As you sent it. When true your customer pays no delivery and the fee is taken from your reward."
          },
          "order_total": {
            "type": "number",
            "format": "double",
            "description": "products_total plus shipping_fee, or products_total alone with free_shipping. A card order is charged this."
          },
          "cod_total": {
            "type": "number",
            "format": "double",
            "description": "What the courier collects: order_total for cod, 0.00 for card."
          },
          "reward": {
            "type": "object",
            "required": [
              "gross",
              "shipping_deduction",
              "net"
            ],
            "description": "What the order would earn your account: the `gross`, `shipping_deduction` and `net` its `money` block would show once created.",
            "properties": {
              "gross": {
                "type": "number",
                "format": "double",
                "description": "SUM((your price - group price) x quantity)."
              },
              "shipping_deduction": {
                "type": "number",
                "format": "double",
                "description": "The delivery fee taken out of it; 0.00 unless free_shipping is true."
              },
              "net": {
                "type": "number",
                "format": "double",
                "description": "gross - shipping_deduction."
              }
            }
          }
        }
      },
      "Order": {
        "type": "object",
        "required": [
          "id",
          "partner_reference",
          "status",
          "payment_type",
          "created_at",
          "order_total",
          "cod_total",
          "shipping_fee",
          "free_shipping",
          "payment_reference",
          "reward",
          "money",
          "products",
          "shipping_address"
        ],
        "properties": {
          "id": {
            "type": "integer",
            "description": "Mart's internal order id."
          },
          "partner_reference": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "processing"
            ],
            "description": "API-owned order status vocabulary, not the raw store state. Orders are created as `processing`. The vocabulary may extend over time — treat it as an enum, never as free text."
          },
          "payment_type": {
            "type": "string",
            "enum": [
              "cod",
              "card"
            ],
            "description": "Echoed from the request, frozen at creation. ONE documented exception: a 200 replay of an order created before this field existed returns its frozen body verbatim, which omits `payment_type` — the order read always carries it instead."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "order_total": {
            "type": "number",
            "format": "double",
            "description": "The payment-neutral total the order carries: SUM(price x quantity) plus the delivery fee unless you absorbed it. For card orders this is exactly the amount charged to your saved card."
          },
          "cod_total": {
            "type": "number",
            "format": "double",
            "description": "What the courier collects: SUM(price x quantity) plus the delivery fee unless you absorbed it. Always 0.00 for card orders — the courier collects nothing."
          },
          "shipping_fee": {
            "type": "number",
            "format": "double",
            "description": "The delivery fee for this destination, frozen at creation."
          },
          "free_shipping": {
            "type": "boolean"
          },
          "payment_reference": {
            "type": "string",
            "nullable": true,
            "description": "The gateway (Lahza) transaction reference actually charged for a card order — quote it when reconciling against your Lahza dashboard. Always null for cod."
          },
          "reward": {
            "type": "object",
            "required": [
              "gross_product_reward",
              "shipping_deduction",
              "net_reward"
            ],
            "description": "How you are paid, frozen at creation and never recomputed — the sole settlement record for this order. Your reward is the margin above the catalog price; with `free_shipping: true` the delivery fee is deducted from it.",
            "properties": {
              "gross_product_reward": {
                "type": "number",
                "format": "double",
                "description": "SUM((your price - catalog price) x quantity)."
              },
              "shipping_deduction": {
                "type": "number",
                "format": "double",
                "description": "The fee taken out of your margin; 0.00 unless free_shipping is true."
              },
              "net_reward": {
                "type": "number",
                "format": "double",
                "description": "gross_product_reward - shipping_deduction. What you are owed."
              }
            }
          },
          "money": {
            "type": "object",
            "required": [
              "gross",
              "shipping_deduction",
              "net",
              "earning_state",
              "available_at"
            ],
            "description": "What this order earns your account and when it can be counted. `gross`, `shipping_deduction` and `net` are the order's current settlement figures (`net` = `gross` - `shipping_deduction`), kept in step with Mart's staff edits. `available` means this order's money has matured, not that it can be withdrawn: a debt on the account can offset it. When `earning_state` is `reversed` every figure is `0.00`. In the creation response (201 and every replay) this block is a record of what was created, so it is always `pending` with a null `available_at`; read the order for the live state.",
            "properties": {
              "gross": {
                "type": "number",
                "format": "double",
                "description": "The order's gross product reward."
              },
              "shipping_deduction": {
                "type": "number",
                "format": "double",
                "description": "The delivery fee taken out of it; 0.00 unless free_shipping is true."
              },
              "net": {
                "type": "number",
                "format": "double",
                "description": "gross - shipping_deduction. What this order earns your account."
              },
              "earning_state": {
                "type": "string",
                "enum": [
                  "pending",
                  "held",
                  "available",
                  "reversed"
                ],
                "description": "`pending`: not earned yet, or not known. `held`: earned, inside its hold. `available`: this order's money matured. `reversed`: the order was cancelled or returned and earns nothing."
              },
              "available_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true,
                "description": "When the held money matures; null unless the order is `held` or `available` and has a maturity date."
              }
            }
          },
          "products": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "product_id",
                "combination_id",
                "quantity",
                "price",
                "group_price"
              ],
              "properties": {
                "product_id": {
                  "type": "integer"
                },
                "combination_id": {
                  "type": "integer",
                  "nullable": true
                },
                "quantity": {
                  "type": "integer"
                },
                "price": {
                  "type": "number",
                  "format": "double",
                  "description": "Your selling price, as submitted."
                },
                "group_price": {
                  "type": "number",
                  "format": "double",
                  "description": "The catalog price we used as the baseline for this line. Returned so you can verify your own margin and predict free-shipping coverage."
                }
              }
            }
          },
          "shipping_address": {
            "type": "object",
            "required": [
              "customer_name",
              "phone",
              "extra_phone",
              "state_id",
              "address",
              "notes"
            ],
            "description": "Echo of what you sent; notes and extra_phone are null when not supplied.",
            "properties": {
              "customer_name": {
                "type": "string"
              },
              "phone": {
                "type": "string"
              },
              "extra_phone": {
                "type": "string",
                "nullable": true
              },
              "state_id": {
                "type": "integer"
              },
              "address": {
                "type": "string"
              },
              "notes": {
                "type": "string",
                "nullable": true
              }
            }
          }
        }
      },
      "PartnerOrder": {
        "type": "object",
        "description": "The order-read shape: live status/quantities/totals with creation-frozen prices, fee and delivery address. Every key is always present (structural stability). Mart's internal order id and the settlement reward block are deliberately absent — the creation response remains the settlement record. The `money` block is the live view of what the order earns.",
        "required": [
          "partner_reference",
          "status",
          "payment_type",
          "created_at",
          "updated_at",
          "order_total",
          "cod_total",
          "shipping_fee",
          "free_shipping",
          "payment_reference",
          "products",
          "shipping_address",
          "cancellation",
          "money"
        ],
        "properties": {
          "partner_reference": {
            "type": "string",
            "example": "100245"
          },
          "status": {
            "type": "object",
            "description": "The latest customer-visible order state — the same status the customer sees on the storefront, in the order's language. `id` is an opaque status identifier (NOT Mart's order id); `name` is display text.",
            "required": [
              "id",
              "name"
            ],
            "properties": {
              "id": {
                "type": "integer",
                "example": 5
              },
              "name": {
                "type": "string",
                "example": "تم التوصيل"
              }
            }
          },
          "payment_type": {
            "type": "string",
            "enum": [
              "cod",
              "card"
            ],
            "description": "Frozen at creation. Present on EVERY read — orders created before the field existed read back as `cod` (which is what they were)."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time",
            "description": "Last modification of the order (status changes, BO edits)."
          },
          "order_total": {
            "type": "number",
            "format": "double",
            "description": "The live order total (products plus any delivery fee the customer carries) — the payment-neutral figure; for card orders, the amount that was charged."
          },
          "cod_total": {
            "type": "number",
            "format": "double",
            "description": "What the courier collects: the live order total for cod, 0.00 for card."
          },
          "shipping_fee": {
            "type": "number",
            "format": "double",
            "description": "The delivery fee frozen at creation."
          },
          "free_shipping": {
            "type": "boolean",
            "description": "Current value — BO edits can change it."
          },
          "payment_reference": {
            "type": "string",
            "nullable": true,
            "description": "The gateway (Lahza) transaction reference charged for a card order; null for cod."
          },
          "products": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "product_id",
                "combination_id",
                "quantity",
                "price",
                "line_total"
              ],
              "properties": {
                "product_id": {
                  "type": "integer",
                  "description": "Stable product identifier used in catalog synchronization and order creation."
                },
                "combination_id": {
                  "type": "integer",
                  "nullable": true,
                  "description": "Null for simple products."
                },
                "quantity": {
                  "type": "integer",
                  "description": "Current effective quantity: ordered minus refunded/returned, floored at 0."
                },
                "price": {
                  "type": "number",
                  "format": "double",
                  "description": "Your selling price per unit, frozen at creation — never the current catalog price."
                },
                "line_total": {
                  "type": "number",
                  "format": "double",
                  "description": "price × quantity."
                }
              }
            }
          },
          "shipping_address": {
            "type": "object",
            "description": "The delivery snapshot stored at creation — not the customer's current profile address. `state_name` is resolved from `state_id` for display.",
            "required": [
              "customer_name",
              "phone",
              "extra_phone",
              "state_id",
              "state_name",
              "address",
              "notes"
            ],
            "properties": {
              "customer_name": {
                "type": "string"
              },
              "phone": {
                "type": "string"
              },
              "extra_phone": {
                "type": "string",
                "nullable": true
              },
              "state_id": {
                "type": "integer"
              },
              "state_name": {
                "type": "string"
              },
              "address": {
                "type": "string"
              },
              "notes": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "cancellation": {
            "$ref": "#/components/schemas/OrderCancellation"
          },
          "money": {
            "type": "object",
            "required": [
              "gross",
              "shipping_deduction",
              "net",
              "earning_state",
              "available_at"
            ],
            "description": "What this order earns your account and when it can be counted. `gross`, `shipping_deduction` and `net` are the order's current settlement figures (`net` = `gross` - `shipping_deduction`), kept in step with Mart's staff edits. `available` means this order's money has matured, not that it can be withdrawn: a debt on the account can offset it. When `earning_state` is `reversed` every figure is `0.00`. In the creation response (201 and every replay) this block is a record of what was created, so it is always `pending` with a null `available_at`; read the order for the live state.",
            "properties": {
              "gross": {
                "type": "number",
                "format": "double",
                "description": "The order's gross product reward."
              },
              "shipping_deduction": {
                "type": "number",
                "format": "double",
                "description": "The delivery fee taken out of it; 0.00 unless free_shipping is true."
              },
              "net": {
                "type": "number",
                "format": "double",
                "description": "gross - shipping_deduction. What this order earns your account."
              },
              "earning_state": {
                "type": "string",
                "enum": [
                  "pending",
                  "held",
                  "available",
                  "reversed"
                ],
                "description": "`pending`: not earned yet, or not known. `held`: earned, inside its hold. `available`: this order's money matured. `reversed`: the order was cancelled or returned and earns nothing."
              },
              "available_at": {
                "type": "string",
                "format": "date-time",
                "nullable": true,
                "description": "When the held money matures; null unless the order is `held` or `available` and has a maturity date."
              }
            }
          }
        }
      },
      "OrderListItem": {
        "type": "object",
        "description": "A summary row of the order list: the first nine keys of the order read, with the same values. `products`, `shipping_address`, `payment_reference`, `cancellation` and `money` are not part of a summary and stay on the single read. Mart's internal order id is never present.",
        "required": [
          "partner_reference",
          "status",
          "payment_type",
          "created_at",
          "updated_at",
          "order_total",
          "cod_total",
          "shipping_fee",
          "free_shipping"
        ],
        "properties": {
          "partner_reference": {
            "type": "string",
            "example": "100245"
          },
          "status": {
            "type": "object",
            "description": "The latest customer-visible order state — the same status the customer sees on the storefront, in the order's language. `id` is an opaque status identifier (NOT Mart's order id); `name` is display text. Null only for an order that has no customer-visible state, which the single read reports as a server error.",
            "required": [
              "id",
              "name"
            ],
            "properties": {
              "id": {
                "type": "integer",
                "example": 5
              },
              "name": {
                "type": "string",
                "example": "تم التوصيل"
              }
            },
            "nullable": true
          },
          "payment_type": {
            "type": "string",
            "enum": [
              "cod",
              "card"
            ],
            "description": "Frozen at creation. Present on EVERY read — orders created before the field existed read back as `cod` (which is what they were)."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time",
            "description": "Last modification of the order (status changes, BO edits)."
          },
          "order_total": {
            "type": "number",
            "format": "double",
            "description": "The live order total (products plus any delivery fee the customer carries) — the payment-neutral figure; for card orders, the amount that was charged."
          },
          "cod_total": {
            "type": "number",
            "format": "double",
            "description": "What the courier collects: the live order total for cod, 0.00 for card."
          },
          "shipping_fee": {
            "type": "number",
            "format": "double",
            "description": "The delivery fee frozen at creation."
          },
          "free_shipping": {
            "type": "boolean",
            "description": "Current value — BO edits can change it."
          }
        }
      },
      "OrderCancelRequest": {
        "type": "object",
        "description": "Optional. Send no body at all if you have nothing to add — an empty request is valid. If you do send one it must be a JSON object.",
        "properties": {
          "reason": {
            "type": "string",
            "nullable": true,
            "maxLength": 500,
            "description": "Free text recorded against the cancellation; trimmed, whitespace-only stored as null. Max 500 characters (characters, not bytes).",
            "example": "Customer requested cancellation"
          }
        }
      },
      "CancelledOrder": {
        "type": "object",
        "description": "The outcome of a cancellation request. Deliberately narrow — it answers what the order's status IS now and when it became that. For money, lines or the delivery address, re-read the order with GET /api/v1/orders/{partner_reference}.",
        "required": [
          "partner_reference",
          "status",
          "cancelled_at",
          "already_cancelled"
        ],
        "properties": {
          "partner_reference": {
            "type": "string",
            "example": "PARTNER-ORDER-100245"
          },
          "status": {
            "type": "object",
            "description": "The order's status after cancellation — the same customer-visible PrestaShop state the order read returns. Branch on `id`; `name` is display text in the order's language and may be reworded.",
            "required": [
              "id",
              "name"
            ],
            "properties": {
              "id": {
                "type": "integer",
                "example": 6
              },
              "name": {
                "type": "string",
                "example": "Cancelled"
              }
            }
          },
          "cancelled_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "When the order actually reached the cancelled state, ISO 8601 with offset. **Null** in one case only: the order was already in that state because Mart cancelled it in the back office, so there is no API cancellation to timestamp.",
            "example": "2026-08-04T08:15:00+00:00"
          },
          "already_cancelled": {
            "type": "boolean",
            "description": "`false` when THIS call cancelled the order; `true` when it was already cancelled. Both are HTTP 200 — a repeat of a request that already succeeded is not an error, which is what makes retrying after a lost response safe.",
            "example": false
          }
        }
      },
      "OrderCancellation": {
        "type": "object",
        "nullable": true,
        "description": "Present on every order read, `null` unless the order was cancelled **through this API**. A back-office cancellation leaves it null: the order's `status` still shows it cancelled, but this block records only what you did.",
        "required": [
          "requested_via_api",
          "reason",
          "cancelled_at"
        ],
        "properties": {
          "requested_via_api": {
            "type": "boolean",
            "description": "Always `true` when this block is present.",
            "example": true
          },
          "reason": {
            "type": "string",
            "nullable": true,
            "description": "The reason you supplied, or null if you sent none.",
            "example": "Customer requested cancellation"
          },
          "cancelled_at": {
            "type": "string",
            "format": "date-time",
            "description": "When the order reached the cancelled state, ISO 8601 with offset.",
            "example": "2026-08-04T08:15:00+00:00"
          }
        }
      },
      "Event": {
        "type": "object",
        "required": [
          "cursor",
          "type",
          "reference",
          "occurred_at",
          "payload"
        ],
        "properties": {
          "cursor": {
            "type": "string",
            "description": "Opaque. Where this event stands in the feed: send it as `after`, and de-duplicate on it.",
            "example": "djE6NDI"
          },
          "type": {
            "type": "string",
            "description": "What happened. A type not listed here may appear later: treat it as informational.",
            "enum": [
              "order.created",
              "order.status_changed",
              "ledger.entry_posted",
              "withdrawal.requested",
              "withdrawal.approved",
              "withdrawal.rejected",
              "withdrawal.cancelled",
              "withdrawal.paid",
              "payout_method.changed"
            ]
          },
          "reference": {
            "type": "string",
            "nullable": true,
            "description": "What it is about: your `partner_reference` for an order or a ledger movement of one, the `withdrawal_id` for a withdrawal, null otherwise.",
            "example": "100245"
          },
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "description": "When it happened, in UTC. Use this for cause and effect, because feed order is visibility order.",
            "example": "2026-08-03T09:40:12+00:00"
          },
          "payload": {
            "type": "object",
            "description": "The matching read's row at that moment. `order.*`: a `GET /orders` item. `ledger.entry_posted`: a `GET /ledger` item. `withdrawal.*`: a `GET /withdrawals` item without `iban`. `payout_method.changed`: `{version, updated_at}`.",
            "additionalProperties": true
          }
        }
      },
      "EventFeedMeta": {
        "type": "object",
        "required": [
          "next_cursor",
          "has_more"
        ],
        "properties": {
          "next_cursor": {
            "type": "string",
            "description": "Store this and send it as `after` next time. Present even on an empty page.",
            "example": "djE6NDI"
          },
          "has_more": {
            "type": "boolean",
            "description": "More events may be ready now: ask again at once, and that page can be empty. False means nothing more right now, not the end: keep polling."
          }
        }
      },
      "ReportsSummary": {
        "type": "object",
        "description": "Your own order totals over the range. Money is the order total (`order_total` of each order) and nothing else. Mart's internal order id is never present.",
        "required": [
          "order_count",
          "order_value",
          "average_order_value",
          "by_month",
          "top_products"
        ],
        "properties": {
          "order_count": {
            "type": "integer",
            "description": "Orders in the range, cancelled ones included.",
            "example": 3
          },
          "order_value": {
            "type": "number",
            "format": "float",
            "description": "Sum of the order totals, rounded to 2 decimals.",
            "example": 350.55
          },
          "average_order_value": {
            "type": "number",
            "format": "float",
            "description": "`order_value` divided by `order_count`, rounded to 2 decimals. 0 when there are no orders.",
            "example": 116.85
          },
          "by_month": {
            "type": "array",
            "description": "One row per shop-local calendar month that has orders, newest first.",
            "items": {
              "$ref": "#/components/schemas/ReportsMonth"
            }
          },
          "top_products": {
            "type": "array",
            "description": "Up to 10 products, most units first.",
            "items": {
              "$ref": "#/components/schemas/ReportsProduct"
            }
          }
        }
      },
      "ReportsMonth": {
        "type": "object",
        "required": [
          "month",
          "orders",
          "value",
          "cod_orders",
          "card_orders",
          "cancelled"
        ],
        "properties": {
          "month": {
            "type": "string",
            "description": "Shop-local calendar month, `YYYY-MM`.",
            "example": "2026-08"
          },
          "orders": {
            "type": "integer",
            "example": 2
          },
          "value": {
            "type": "number",
            "format": "float",
            "description": "Sum of the order totals in the month, rounded to 2 decimals.",
            "example": 300.0
          },
          "cod_orders": {
            "type": "integer",
            "description": "Orders paid cash on delivery.",
            "example": 1
          },
          "card_orders": {
            "type": "integer",
            "description": "Orders paid by card.",
            "example": 1
          },
          "cancelled": {
            "type": "integer",
            "description": "Of `orders`, how many are cancelled.",
            "example": 1
          }
        }
      },
      "ReportsProduct": {
        "type": "object",
        "required": [
          "product_id",
          "combination_id",
          "name",
          "quantity",
          "orders"
        ],
        "properties": {
          "product_id": {
            "type": "integer",
            "example": 9597
          },
          "combination_id": {
            "type": "integer",
            "nullable": true,
            "description": "The combination ordered, or `null` for a product without combinations.",
            "example": 41206
          },
          "name": {
            "type": "string",
            "description": "The product name in the store language.",
            "example": "Example product"
          },
          "quantity": {
            "type": "integer",
            "description": "Units ordered in the range.",
            "example": 4
          },
          "orders": {
            "type": "integer",
            "description": "Distinct orders containing the product.",
            "example": 1
          }
        }
      },
      "Balance": {
        "type": "object",
        "required": [
          "currency",
          "balance",
          "available",
          "held",
          "next_maturity",
          "owed"
        ],
        "properties": {
          "currency": {
            "type": "string",
            "enum": [
              "ILS"
            ]
          },
          "balance": {
            "type": "number",
            "format": "float",
            "description": "Everything earned less everything paid out or deducted, held earnings included. Negative when the account owes.",
            "example": 210.0
          },
          "available": {
            "type": "number",
            "format": "float",
            "description": "What may be taken out now: what has matured, less your open withdrawal requests (`requested` or `approved`). Never negative.",
            "example": 160.0
          },
          "held": {
            "type": "number",
            "format": "float",
            "description": "Earned and not yet matured.",
            "example": 50.0
          },
          "next_maturity": {
            "nullable": true,
            "type": "object",
            "description": "The next part of `held` to become available, or null when nothing is held.",
            "required": [
              "at",
              "amount"
            ],
            "properties": {
              "at": {
                "type": "string",
                "format": "date-time",
                "example": "2026-08-10T09:40:12+00:00"
              },
              "amount": {
                "type": "number",
                "format": "float",
                "description": "The amount that matures then.",
                "example": 50.0
              }
            }
          },
          "owed": {
            "type": "number",
            "format": "float",
            "description": "A debt the account carries, 0 when there is none.",
            "example": 0.0
          },
          "pending": {
            "nullable": true,
            "type": "number",
            "format": "float",
            "description": "What your orders not delivered yet will earn once they are delivered. Not money yet: never in `balance`, `available` or a withdrawal. Exact, so it can be negative (an order whose remaining products earn less than the delivery it funds). Null when no exact figure can be given right now; `pending_state` says why. Never a partial total.",
            "example": 75.0
          },
          "pending_state": {
            "type": "string",
            "enum": [
              "ok",
              "incomplete",
              "unavailable"
            ],
            "description": "`ok`: `pending` is exact. `incomplete`: Mart is checking at least one of those orders, so there is no total until it has. `unavailable`: the figure cannot be given right now.",
            "example": "ok"
          },
          "under_review": {
            "type": "number",
            "format": "float",
            "description": "Earned money held back because its order is not in a delivered state right now (for example during a ticket or an exchange). It is never in `available` and becomes available again once the order is back to delivered. 0 when nothing is held this way. Read it on its own: it is not a part to add to or take from the other figures.",
            "example": 0.0
          }
        }
      },
      "LedgerEntry": {
        "type": "object",
        "required": [
          "entry_id",
          "type",
          "amount",
          "partner_reference",
          "payment_method",
          "occurred_at",
          "recorded_at",
          "available_at",
          "state"
        ],
        "properties": {
          "entry_id": {
            "type": "string",
            "description": "Opaque. Stable for the entry; de-duplicate pages on it.",
            "example": "MTIz"
          },
          "type": {
            "type": "string",
            "description": "`earning`, `reversal`, `payment`, `adjustment` or `charge`. A `charge` is a cost billed to your account for an order, such as a parcel refused at the door, and a positive one is such a charge undone. A value not listed here is informational.",
            "enum": [
              "earning",
              "reversal",
              "payment",
              "adjustment",
              "charge",
              "other"
            ]
          },
          "amount": {
            "type": "number",
            "format": "float",
            "description": "Signed. A credit to you is positive.",
            "example": 18.0
          },
          "partner_reference": {
            "type": "string",
            "nullable": true,
            "description": "Your own reference for the order, for an earning, a reversal or a charge of one of your API orders. Null otherwise, including for an order placed with another API key of the same account: the ledger is the account's, a reference is read per key.",
            "example": "100245"
          },
          "payment_method": {
            "type": "string",
            "nullable": true,
            "description": "How a payment was made, when it says.",
            "example": "bank"
          },
          "occurred_at": {
            "type": "string",
            "format": "date-time",
            "description": "When it happened.",
            "example": "2026-08-03T09:40:12+00:00"
          },
          "recorded_at": {
            "type": "string",
            "format": "date-time",
            "description": "When it was entered. This decides which statement it belongs to.",
            "example": "2026-08-03T09:40:13+00:00"
          },
          "available_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "When an earning matures and becomes available. Null when there is nothing to wait for.",
            "example": "2026-08-10T09:40:12+00:00"
          },
          "state": {
            "type": "string",
            "nullable": true,
            "enum": [
              "held",
              "available",
              null
            ],
            "description": "For an earning or a reversal: `held` until `available_at`, then `available`. Null for the other types."
          }
        }
      },
      "Statement": {
        "type": "object",
        "required": [
          "number",
          "period_start",
          "period_end",
          "opening",
          "closing",
          "finalized_at"
        ],
        "properties": {
          "number": {
            "type": "integer",
            "example": 12
          },
          "period_start": {
            "type": "string",
            "format": "date-time",
            "description": "Inclusive.",
            "example": "2026-07-01T00:00:00+00:00"
          },
          "period_end": {
            "type": "string",
            "format": "date-time",
            "description": "Exclusive.",
            "example": "2026-08-01T00:00:00+00:00"
          },
          "opening": {
            "type": "number",
            "format": "float",
            "description": "The balance at the start of the period, held earnings included.",
            "example": 120.5
          },
          "closing": {
            "type": "number",
            "format": "float",
            "description": "The balance at the end of the period, held earnings included. A snapshot, not a payout entitlement.",
            "example": 210.0
          },
          "finalized_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-08-01T02:00:00+00:00"
          }
        }
      },
      "StatementDetail": {
        "type": "object",
        "required": [
          "number",
          "period_start",
          "period_end",
          "opening",
          "closing",
          "finalized_at",
          "movements"
        ],
        "properties": {
          "number": {
            "type": "integer",
            "example": 12
          },
          "period_start": {
            "type": "string",
            "format": "date-time",
            "description": "Inclusive.",
            "example": "2026-07-01T00:00:00+00:00"
          },
          "period_end": {
            "type": "string",
            "format": "date-time",
            "description": "Exclusive.",
            "example": "2026-08-01T00:00:00+00:00"
          },
          "opening": {
            "type": "number",
            "format": "float",
            "description": "The balance at the start of the period, held earnings included.",
            "example": 120.5
          },
          "closing": {
            "type": "number",
            "format": "float",
            "description": "The balance at the end of the period, held earnings included. A snapshot, not a payout entitlement.",
            "example": 210.0
          },
          "finalized_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-08-01T02:00:00+00:00"
          },
          "movements": {
            "type": "array",
            "description": "The page of entries recorded in the period, oldest first.",
            "items": {
              "$ref": "#/components/schemas/LedgerEntry"
            }
          }
        }
      },
      "Account": {
        "type": "object",
        "required": [
          "shop_display_name",
          "status",
          "orders_enabled",
          "card_enabled",
          "price_override_allowed",
          "free_shipping_allowed",
          "rate_limits",
          "payout_method_saved",
          "withdrawals",
          "money"
        ],
        "properties": {
          "shop_display_name": {
            "type": "string",
            "description": "The name of your shop on Mart's records. When none was set, your first and last name.",
            "example": "Al Noor Shop"
          },
          "status": {
            "type": "string",
            "enum": [
              "active",
              "paused",
              "closed"
            ],
            "description": "`paused` stops new orders only: `POST /orders` and `POST /orders/validate` answer `422` `orders_not_enabled`. Everything you read, and cancelling an order, keeps working. `closed` is final: no new orders, and your key keeps at most reading your money and asking for withdrawals.",
            "example": "active"
          },
          "orders_enabled": {
            "type": "boolean",
            "description": "Whether `POST /orders` will take an order now: your key is enabled for orders and the account is active.",
            "example": true
          },
          "card_enabled": {
            "type": "boolean",
            "description": "Whether your key may send card orders.",
            "example": false
          },
          "price_override_allowed": {
            "type": "boolean",
            "description": "Whether you may send your own selling price on an order line.",
            "example": true
          },
          "free_shipping_allowed": {
            "type": "boolean",
            "description": "Whether you may send `free_shipping` on a cash order.",
            "example": false
          },
          "rate_limits": {
            "type": "object",
            "required": [
              "per_minute",
              "per_day"
            ],
            "description": "Your key's request limits across the API. Some endpoints have a tighter limit of their own.",
            "properties": {
              "per_minute": {
                "type": "integer",
                "example": 120
              },
              "per_day": {
                "type": "integer",
                "example": 20000
              }
            }
          },
          "payout_method_saved": {
            "type": "boolean",
            "description": "Whether a payout method is saved on the account.",
            "example": false
          },
          "withdrawals": {
            "type": "object",
            "required": [
              "enabled",
              "minimum",
              "max_open_requests"
            ],
            "properties": {
              "enabled": {
                "type": "boolean",
                "example": false
              },
              "minimum": {
                "type": "number",
                "format": "float",
                "nullable": true,
                "description": "The smallest request, in ILS. `null` when withdrawals are off or no minimum is set.",
                "example": null
              },
              "max_open_requests": {
                "type": "integer",
                "nullable": true,
                "description": "How many requests may be open at once. `null` when withdrawals are off or no limit is set.",
                "example": null
              }
            }
          },
          "money": {
            "type": "object",
            "required": [
              "available"
            ],
            "properties": {
              "available": {
                "type": "boolean",
                "description": "Whether `/balance`, `/ledger` and `/statements` can be read right now. `false` is not an error here: those endpoints answer `503` `ledger_unavailable`.",
                "example": true
              }
            }
          }
        }
      },
      "PayoutMethod": {
        "type": "object",
        "required": [
          "status",
          "iban",
          "iban_country",
          "account_holder_name",
          "national_id",
          "updated_at",
          "withdrawals_locked_until",
          "method",
          "pickup_instructions"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "not_set",
              "active",
              "locked"
            ],
            "description": "`not_set`: nothing saved yet. `active`: saved, withdrawals not locked by it. `locked`: withdrawals are locked until `withdrawals_locked_until`.",
            "example": "locked"
          },
          "iban": {
            "type": "string",
            "nullable": true,
            "description": "The whole IBAN, upper case, without spaces. `null` when not set, and when you are paid in cash. Kept, and shown, while a bank transfer is not offered to your account, but not paid to.",
            "example": "PS92PALS000000000400123456702"
          },
          "iban_country": {
            "type": "string",
            "nullable": true,
            "description": "The IBAN's two-letter country. `null` for cash.",
            "example": "PS"
          },
          "account_holder_name": {
            "type": "string",
            "nullable": true,
            "example": "Al Noor Shop",
            "description": "The account holder. For cash, the full name of the person who collects the money at the office."
          },
          "national_id": {
            "type": "string",
            "nullable": true,
            "description": "The national ID you saved, or `null`. For cash, the collector's ID number, checked against their ID card at the office."
          },
          "updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "The last change to the payout method.",
            "example": "2026-11-06T09:30:00+00:00"
          },
          "withdrawals_locked_until": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "Set only while `status` is `locked`.",
            "example": "2026-11-08T09:30:00+00:00"
          },
          "method": {
            "type": "string",
            "nullable": true,
            "enum": [
              "bank",
              "cash",
              null
            ],
            "description": "How you are paid: `bank` (a transfer to `iban`) or `cash` (collected at Mart's office). `null` when not set.",
            "example": "bank"
          },
          "pickup_instructions": {
            "type": "string",
            "nullable": true,
            "description": "For cash: where and when to collect (Mart's office address and hours), as Mart wrote it. `null` for a bank transfer, and when Mart has none published right now.",
            "example": null
          }
        }
      },
      "PayoutMethodRequest": {
        "type": "object",
        "required": [
          "account_holder_name"
        ],
        "properties": {
          "method": {
            "type": "string",
            "enum": [
              "bank",
              "cash"
            ],
            "description": "Optional. `bank` (the default when left out) or `cash`. `cash` is accepted only when Mart offers it to your account (`403` `cash_not_allowed`), and `bank` only when Mart offers a bank transfer to your account (`422` `bank_transfer_not_allowed`). You cannot switch between the two while a withdrawal is open (`409` `payout_method_change_blocked`).",
            "example": "bank"
          },
          "iban": {
            "type": "string",
            "description": "Required for a bank transfer, ignored for cash. Spaces and case are ignored. Up to 34 characters once cleaned.",
            "example": "PS92PALS000000000400123456702"
          },
          "account_holder_name": {
            "type": "string",
            "description": "2 to 70 characters, letters first. Names in any script, including Arabic. For cash, the full name of the person who will collect the money, as on their ID card.",
            "example": "Al Noor Shop"
          },
          "national_id": {
            "type": "string",
            "nullable": true,
            "description": "Optional. 5 to 32 letters, digits or hyphens. Arabic digits are accepted and stored as 0 to 9. Omitted keeps the saved one, except on a switch between bank and cash, which clears it; `null` or an empty string clears it. For cash, the collector's ID number: send it on the switch.",
            "example": "123456789"
          }
        }
      },
      "Withdrawal": {
        "type": "object",
        "required": [
          "withdrawal_id",
          "amount",
          "status",
          "iban",
          "reject_reason",
          "requested_at",
          "approved_at",
          "paid_at",
          "method",
          "requested_amount"
        ],
        "properties": {
          "withdrawal_id": {
            "type": "string",
            "description": "Opaque. Use it in `GET /withdrawals/{withdrawal_id}` and in the cancel path.",
            "example": "NDE"
          },
          "amount": {
            "type": "number",
            "format": "float",
            "description": "What is paid: what you asked for, unless Mart paid a cash request at another amount at the office counter (then `requested_amount` keeps what you asked for).",
            "example": 125.0
          },
          "status": {
            "type": "string",
            "enum": [
              "requested",
              "approved",
              "paid",
              "rejected",
              "cancelled"
            ],
            "description": "`requested` and `approved` are open: they hold their amount back from `available`. `paid` is final and shows in the ledger as a `payment`. `rejected` and `cancelled` release the amount."
          },
          "iban": {
            "type": "string",
            "nullable": true,
            "description": "The IBAN this request will be paid to, fixed when it was approved, so a later change of your payout method cannot redirect it. Null before approval, on a request that was never approved, and always for cash.",
            "example": "PS92PALS000000000400123456702"
          },
          "reject_reason": {
            "type": "string",
            "nullable": true,
            "description": "Why Mart rejected it, in one line. Null for any other status.",
            "example": null
          },
          "requested_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-11-01T08:30:00+00:00"
          },
          "approved_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "example": "2026-11-02T09:00:00+00:00"
          },
          "paid_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "example": null
          },
          "method": {
            "type": "string",
            "enum": [
              "bank",
              "cash"
            ],
            "description": "How this request is paid, fixed when you made it: `bank` (approved, then transferred) or `cash` (collected at the office: it goes from `requested` straight to `paid`, and `approved_at` stays null).",
            "example": "bank"
          },
          "requested_amount": {
            "type": "number",
            "format": "float",
            "description": "What you asked for. The same as `amount`, unless the office paid a cash request at another amount.",
            "example": 125.0
          }
        }
      },
      "WithdrawalRequest": {
        "type": "object",
        "required": [
          "amount",
          "idempotency_key"
        ],
        "properties": {
          "amount": {
            "description": "A positive amount in shekels: a JSON number or a decimal string, with at most two decimals. Anything else, including three decimals, answers `422` `invalid_amount`.",
            "oneOf": [
              {
                "type": "number"
              },
              {
                "type": "string",
                "pattern": "^[0-9]+(\\.[0-9]{1,2})?$"
              }
            ],
            "example": 125.0
          },
          "idempotency_key": {
            "type": "string",
            "pattern": "^[A-Za-z0-9._-]{1,64}$",
            "maxLength": 64,
            "description": "Your key for this request, unique per request you mean to make. Sending the same key and amount again answers the original request with `200`; the same key with another amount answers `409` `idempotency_conflict`. **Keys are compared without regard to case**: `AB` and `ab` are the same key.",
            "example": "wd-2026-11-01-001"
          }
        }
      }
    }
  },
  "tags": [
    {
      "name": "Products",
      "description": "Catalog: listing and product detail, with prices and stock."
    },
    {
      "name": "Categories",
      "description": "Catalog category vocabulary for the products category_id filter."
    },
    {
      "name": "Attributes",
      "description": "Attribute-group vocabulary behind the products combination attributes."
    },
    {
      "name": "Delivery",
      "description": "Delivery destinations for order shipping addresses."
    },
    {
      "name": "Orders",
      "description": "Cash-on-delivery order creation, order list, dry-run validation, order read and cancellation."
    },
    {
      "name": "Money",
      "description": "Your balance, the ledger of movements, your statements, your payout method, your withdrawals and the feed of events on your account."
    },
    {
      "name": "Reports",
      "description": "Your own order totals by month, and your most ordered products."
    },
    {
      "name": "Account",
      "description": "Your own account: its state, limits and withdrawal rules."
    }
  ]
}
