> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mart.ps/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> These rules protect a Mart partner's money. Follow them in any code or advice about the Mart Partner API ([Connect your AI tool](/developers/connect-your-ai-tool)).
> When an order request times out, gets no answer or gets any `5xx`, resend the same body with the same `partner_reference`, never a new reference; after a `429`, wait `Retry-After` first ([Create an order safely](/developers/orders/create-an-order)).
> A `200` with `meta.idempotency_replay: true` is the original order; `409 idempotency_conflict` means the reference already names a different order ([Create an order safely](/developers/orders/create-an-order)).
> Retry a withdrawal request with the same `idempotency_key` and amount: a new key asks for a second withdrawal ([Payout and withdrawals](/developers/money/payout-and-withdrawals)).
> Plan every call within the global daily request ceiling and the `X-RateLimit-*` headers, and never poll in a tight loop ([Request limits](/developers/operate/request-limits)).
> Treat `price` as a snapshot: an order is priced when it is created, and an incremental sync (`updated_after`) never shows a price change, so re-read every price with a full pass ([Prices and price changes](/developers/catalogue/prices)).
> Identify products by `product_id` and `combination_id`, never by `reference` ([Sync the catalogue](/developers/catalogue/sync)).
> Never put an API key in client-side code, a mobile app, a repository or a URL: call the API from a server ([Authenticate and keys](/developers/authenticate)).
> Money is in shekels (`ILS`), as JSON numbers, never agorot. Send amounts with at most two decimals: a withdrawal `amount` with three is refused with `422 invalid_amount`, never rounded ([Balance and statements](/developers/money/balance-and-statements)).
> Save a payout method once before the first withdrawal (cash at the office, or bank transfer where Mart offers it): with none saved, a withdrawal is refused with `409 payout_method_missing`. Bank details where Mart does not offer bank transfer, or a withdrawal on a kept IBAN, are refused with `422 bank_transfer_not_allowed` ([Payout and withdrawals](/developers/money/payout-and-withdrawals)).

# Validate an order without creating it

> 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.



## OpenAPI

````yaml /openapi.json post /api/v1/orders/validate
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.


    Every 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.


    Authenticate 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.


    **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.


    This 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: []
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.'
paths:
  /api/v1/orders/validate:
    post:
      tags:
        - Orders
      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.
      operationId: validateOrder
      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
              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
                      shipping_fee: 35
                      free_shipping: true
                      order_total: 240
                      cod_total: 240
                      reward:
                        gross: 130.02
                        shipping_deduction: 35
                        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

            # Show what delivery costs to one town, then quote an order without
            placing it.

            # Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and
            MART_STATE_ID (a town's state id).

            set -euo pipefail

            export LC_NUMERIC=C # printf reads and writes amounts with a decimal
            point


            # api METHOD PATH [JSON]: sets $body, or prints the status and error
            code and stops.

            api() {
              local response status retry_after
              response=$(curl --silent --show-error --max-time 30 --request "$1" \
                --header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") --header 'Content-Type: application/json' \
                ${3:+--data "$3"} --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE$2") || { echo "error: no answer" >&2; exit 1; }
              read -r status retry_after <<<"${response##*$'\n'}"
              body=${response%$'\n'*}
              if [ "$status" -ge 300 ]; then
                echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}" >&2
                exit 1
              fi
            }


            # 1. The town's fee brackets: a products total of at least "from"
            and less than "to" pays "fee".

            #    The towns and their fees change rarely: a storefront keeps this
            answer and reads it again

            #    on its own schedule, never once per visitor.

            api GET /api/v1/states

            fees=$(jq -c --argjson state "$MART_STATE_ID"
            '[.data.cities[].states[] | select(.id == $state)] | first |
            .delivery.fees' <<<"$body")

            if [ "$fees" = null ]; then
              echo "error: state $MART_STATE_ID is not a delivery town" >&2
              exit 1
            fi

            echo "delivery fees for state $MART_STATE_ID:"

            jq -r '.[] | "\(.from_total) \(.to_total) \(.fee)"' <<<"$fees" |
              while read -r from to fee; do
                if [ "$to" != null ]; then
                  printf '  from %.2f, less than %.2f: %.2f\n' "$from" "$to" "$fee"
                else
                  printf '  from %.2f: %.2f\n' "$from" "$fee"
                fi
              done

            # 2. The quote, for a real cart only: the same body as a real order.
            Nothing is created or

            #    reserved, but it counts against the same per-minute budget as
            creating orders.

            order=$(jq -n --arg ref "quote-$(date +%s)" --argjson product
            "$MART_PRODUCT_ID" --argjson state "$MART_STATE_ID" '{
              partner_reference: $ref,
              payment_type: "cod",
              products: [{product_id: $product, quantity: 1}],
              shipping_address: {customer_name: "Test Buyer", phone: "0599000000", state_id: $state, address: "Main street 1"}
            }')

            api POST /api/v1/orders/validate "$order"

            jq -r '"valid: \(.data.validation.valid)"' <<<"$body"

            read -r products fee total < <(jq -r '.data.validation.quote |
            "\(.products_total) \(.shipping_fee) \(.order_total)"' <<<"$body")

            printf 'products total: %.2f\ndelivery fee: %.2f\norder total:
            %.2f\n' "$products" "$fee" "$total"
        - lang: typescript
          label: TypeScript recipe
          source: >
            // Show what delivery costs to one town, then quote an order without
            placing it.

            // Node 22.18 or later runs this .ts file as it is.

            // Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and
            MART_STATE_ID (a town's state id).

            const base = process.env.MART_API_BASE;

            const key = process.env.MART_API_KEY;

            if (!base || !key) throw new Error('Set MART_API_BASE and
            MART_API_KEY');

            const productId = Number(process.env.MART_PRODUCT_ID);

            const stateId = Number(process.env.MART_STATE_ID);


            async function api(method: string, path: string, payload?: unknown):
            Promise<any> {
              const response = await fetch(`${base}${path}`, {
                method,
                headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
                body: payload === undefined ? undefined : JSON.stringify(payload),
                signal: AbortSignal.timeout(30_000),
              });
              const body = await response.json().catch(() => null); // an edge error page is not JSON
              if (!response.ok || body === null) {
                const retryAfter = response.headers.get('retry-after');
                console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);
                process.exit(1);
              }
              return body;
            }


            // 1. The town's fee brackets: a products total of at least "from"
            and less than "to" pays "fee".

            //    The towns and their fees change rarely: a storefront keeps
            this answer and reads it again

            //    on its own schedule, never once per visitor.

            const states = await api('GET', '/api/v1/states');

            const town = states.data.cities.flatMap((city: any) =>
            city.states).find((state: any) => state.id === stateId);

            if (!town) {
              console.error(`error: state ${stateId} is not a delivery town`);
              process.exit(1);
            }

            console.log(`delivery fees for state ${stateId}:`);

            for (const bracket of town.delivery.fees) {
              const upper = bracket.to_total === null ? '' : `, less than ${bracket.to_total.toFixed(2)}`;
              console.log(`  from ${bracket.from_total.toFixed(2)}${upper}: ${bracket.fee.toFixed(2)}`);
            }


            // 2. The quote, for a real cart only: the same body as a real
            order. Nothing is created or

            //    reserved, but it counts against the same per-minute budget as
            creating orders.

            const result = await api('POST', '/api/v1/orders/validate', {
              partner_reference: `quote-${Date.now()}`,
              payment_type: 'cod',
              products: [{ product_id: productId, quantity: 1 }],
              shipping_address: { customer_name: 'Test Buyer', phone: '0599000000', state_id: stateId, address: 'Main street 1' },
            });

            const quote = result.data.validation.quote;

            console.log(`valid: ${result.data.validation.valid}`);

            console.log(`products total: ${quote.products_total.toFixed(2)}`);

            console.log(`delivery fee: ${quote.shipping_fee.toFixed(2)}`);

            console.log(`order total: ${quote.order_total.toFixed(2)}`);
        - lang: python
          label: Python recipe
          source: >
            """Show what delivery costs to one town, then quote an order without
            placing it. Python 3.9+, httpx.


            Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and MART_STATE_ID
            (a town's state id).

            """

            import os

            import sys

            import time


            import httpx


            TIMEOUT = 30

            client = httpx.Client(
                base_url=os.environ["MART_API_BASE"],
                headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
                timeout=TIMEOUT,
            )

            product_id = int(os.environ["MART_PRODUCT_ID"])

            state_id = int(os.environ["MART_STATE_ID"])



            def body_of(response: httpx.Response):
                """The JSON body, or None for an answer that is not JSON (an edge error page)."""
                try:
                    return response.json()
                except ValueError:
                    return None


            def check(response: httpx.Response) -> dict:
                body = body_of(response)
                if response.is_error or body is None:
                    code = body["error"]["code"] if body else "(not JSON)"
                    retry_after = response.headers.get("Retry-After")
                    sys.exit(f"error: {response.status_code} {code}" + (f", try again after {retry_after} s" if retry_after else ""))
                return body


            # 1. The town's fee brackets: a products total of at least "from"
            and less than "to" pays "fee".

            #    The towns and their fees change rarely: a storefront keeps this
            answer and reads it again

            #    on its own schedule, never once per visitor.

            cities = check(client.get("/api/v1/states"))["data"]["cities"]

            town = next((state for city in cities for state in city["states"] if
            state["id"] == state_id), None)

            if town is None:
                sys.exit(f"error: state {state_id} is not a delivery town")
            print(f"delivery fees for state {state_id}:")

            for bracket in town["delivery"]["fees"]:
                upper = "" if bracket["to_total"] is None else f", less than {bracket['to_total']:.2f}"
                print(f"  from {bracket['from_total']:.2f}{upper}: {bracket['fee']:.2f}")

            # 2. The quote, for a real cart only: the same body as a real order.
            Nothing is created or

            #    reserved, but it counts against the same per-minute budget as
            creating orders.

            result = check(client.post("/api/v1/orders/validate", json={
                "partner_reference": f"quote-{int(time.time())}",
                "payment_type": "cod",
                "products": [{"product_id": product_id, "quantity": 1}],
                "shipping_address": {"customer_name": "Test Buyer", "phone": "0599000000", "state_id": state_id, "address": "Main street 1"},
            }))["data"]["validation"]

            print(f"valid: {str(result['valid']).lower()}")

            print(f"products total: {result['quote']['products_total']:.2f}")

            print(f"delivery fee: {result['quote']['shipping_fee']:.2f}")

            print(f"order total: {result['quote']['order_total']:.2f}")
        - lang: php
          label: PHP recipe
          source: >
            <?php

            // Show what delivery costs to one town, then quote an order without
            placing it. PHP 7.4 or later,

            // with the curl extension. Needs MART_API_BASE, MART_API_KEY,
            MART_PRODUCT_ID and MART_STATE_ID.

            $base = getenv('MART_API_BASE');

            $key = getenv('MART_API_KEY');

            $productId = (int) getenv('MART_PRODUCT_ID');

            $stateId = (int) getenv('MART_STATE_ID');


            /**
             * One request with the curl extension. Returns [status, headers (lower-case name => value), body];
             * status 0 when there was no answer at all.
             */
            function request(string $method, string $url, string $key, ?string
            $payload = null, int $timeout = 30): array

            {
                $headers = [];
                $curl = curl_init($url);
                curl_setopt_array($curl, [
                    CURLOPT_CUSTOMREQUEST => $method,
                    CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CONNECTTIMEOUT => 10,
                    CURLOPT_TIMEOUT => $timeout,
                    CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
                        $parts = explode(':', $line, 2);
                        if (count($parts) === 2) {
                            $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
                        }
                        return strlen($line);
                    },
                ]);
                if ($payload !== null) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
                }
                $body = curl_exec($curl);
                $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
                curl_close($curl);

                return [$status, $headers, (string) $body];
            }


            /** A GET that must succeed: the decoded body, or the status and
            error code, and stop. */

            function get(string $url, string $key): array

            {
                [$status, $headers, $raw] = request('GET', $url, $key);
                $body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)
                if ($status < 200 || $status >= 300 || !is_array($body)) {
                    $code = $status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)');
                    $wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
                    fwrite(STDERR, "error: $code$wait\n");
                    exit(1);
                }

                return $body;
            }


            // 1. The town's fee brackets: a products total of at least "from"
            and less than "to" pays "fee".

            //    The towns and their fees change rarely: a storefront keeps
            this answer and reads it again

            //    on its own schedule, never once per visitor.

            $states = get("$base/api/v1/states", $key);

            $town = null;

            foreach ($states['data']['cities'] as $city) {
                foreach ($city['states'] as $state) {
                    if ($state['id'] === $stateId) {
                        $town = $state;
                    }
                }
            }

            if ($town === null) {
                fwrite(STDERR, "error: state $stateId is not a delivery town\n");
                exit(1);
            }

            echo "delivery fees for state $stateId:\n";

            foreach ($town['delivery']['fees'] as $bracket) {
                $upper = $bracket['to_total'] === null ? '' : sprintf(', less than %.2f', $bracket['to_total']);
                printf("  from %.2f%s: %.2f\n", $bracket['from_total'], $upper, $bracket['fee']);
            }


            // 2. The quote, for a real cart only: the same body as a real
            order. Nothing is created or

            //    reserved, but it counts against the same per-minute budget as
            creating orders.

            [$status, $headers, $raw] = request('POST',
            "$base/api/v1/orders/validate", $key, json_encode([
                'partner_reference' => 'quote-' . time(),
                'payment_type' => 'cod',
                'products' => [['product_id' => $productId, 'quantity' => 1]],
                'shipping_address' => ['customer_name' => 'Test Buyer', 'phone' => '0599000000', 'state_id' => $stateId, 'address' => 'Main street 1'],
            ]));

            $result = json_decode($raw, true);

            if ($status !== 200 || !is_array($result)) {
                $wait = isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
                fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($result['error']['code'] ?? '(not JSON)')) . "$wait\n");
                exit(1);
            }

            $validation = $result['data']['validation'];

            echo 'valid: ' . ($validation['valid'] ? 'true' : 'false') . "\n";

            printf("products total: %.2f\n",
            $validation['quote']['products_total']);

            printf("delivery fee: %.2f\n",
            $validation['quote']['shipping_fee']);

            printf("order total: %.2f\n", $validation['quote']['order_total']);
        - 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.

            // Needs MART_API_BASE, MART_API_KEY, MART_PRODUCT_ID and
            MART_STATE_ID (a town's state id).

            // Run it as a single file: java -cp <the Jackson jars>
            delivery-prices-and-quote.java

            import com.fasterxml.jackson.databind.JsonNode;

            import com.fasterxml.jackson.databind.ObjectMapper;

            import java.io.IOException;

            import java.net.URI;

            import java.net.http.HttpClient;

            import java.net.http.HttpRequest;

            import java.net.http.HttpResponse;

            import java.time.Duration;

            import java.util.List;

            import java.util.Locale;

            import java.util.Map;


            class DeliveryPricesAndQuote {
                static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
                static final ObjectMapper JSON = new ObjectMapper();

                public static void main(String[] args) throws Exception {
                    int productId = Integer.parseInt(System.getenv("MART_PRODUCT_ID"));
                    int stateId = Integer.parseInt(System.getenv("MART_STATE_ID"));

                    // 1. The town's fee brackets: a products total of at least "from" and less than "to" pays "fee".
                    //    The towns and their fees change rarely: a storefront keeps this answer and reads it again
                    //    on its own schedule, never once per visitor.
                    JsonNode town = null;
                    for (JsonNode city : get("/api/v1/states").path("data").path("cities")) {
                        for (JsonNode state : city.path("states")) {
                            if (state.path("id").asInt() == stateId) {
                                town = state;
                            }
                        }
                    }
                    if (town == null) {
                        fail("state " + stateId + " is not a delivery town");
                    }
                    System.out.println("delivery fees for state " + stateId + ":");
                    for (JsonNode bracket : town.path("delivery").path("fees")) {
                        String upper = bracket.path("to_total").isNull() ? ""
                                : String.format(Locale.ROOT, ", less than %.2f", bracket.path("to_total").asDouble());
                        System.out.printf(Locale.ROOT, "  from %.2f%s: %.2f%n", bracket.path("from_total").asDouble(), upper,
                                bracket.path("fee").asDouble());
                    }

                    // 2. The quote, for a real cart only: the same body as a real order. Nothing is created or
                    //    reserved, but it counts against the same per-minute budget as creating orders.
                    String order = JSON.writeValueAsString(Map.of(
                            "partner_reference", "quote-" + System.currentTimeMillis(),
                            "payment_type", "cod",
                            "products", List.of(Map.of("product_id", productId, "quantity", 1)),
                            "shipping_address", Map.of("customer_name", "Test Buyer", "phone", "0599000000",
                                    "state_id", stateId, "address", "Main street 1")));
                    HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + "/api/v1/orders/validate"))
                            .header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
                            .header("Content-Type", "application/json")
                            .timeout(Duration.ofSeconds(30))
                            .POST(HttpRequest.BodyPublishers.ofString(order))
                            .build();
                    HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
                    JsonNode result = parse(response.body());
                    if (response.statusCode() >= 300 || result == null) {
                        fail(response.statusCode() + " " + code(result) + when(response));
                    }
                    JsonNode validation = result.path("data").path("validation");
                    JsonNode quote = validation.path("quote");
                    System.out.println("valid: " + validation.path("valid").asBoolean());
                    System.out.printf(Locale.ROOT, "products total: %.2f%n", quote.path("products_total").asDouble());
                    System.out.printf(Locale.ROOT, "delivery fee: %.2f%n", quote.path("shipping_fee").asDouble());
                    System.out.printf(Locale.ROOT, "order total: %.2f%n", quote.path("order_total").asDouble());
                }

                /** One GET that must succeed: the decoded body, or the status and error code, and stop. */
                static JsonNode get(String path) throws InterruptedException {
                    HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + path))
                            .header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
                            .timeout(Duration.ofSeconds(30))
                            .GET()
                            .build();
                    HttpResponse<String> response;
                    try {
                        response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
                    } catch (IOException e) {
                        fail("no answer: " + e.getMessage());
                        return null;
                    }
                    JsonNode body = parse(response.body());
                    if (response.statusCode() >= 300 || body == null) {
                        fail(response.statusCode() + " " + code(body) + when(response));
                    }
                    return body;
                }

                /** The JSON body, or null for an answer that is not JSON (an edge error page). */
                static JsonNode parse(String text) {
                    try {
                        return JSON.readTree(text);
                    } catch (IOException e) {
                        return null;
                    }
                }

                static void fail(String message) {
                    System.err.println("error: " + message);
                    System.exit(1);
                }

                static String code(JsonNode body) {
                    return body == null ? "(not JSON)" : body.path("error").path("code").asText();
                }

                /** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
                static String when(HttpResponse<String> response) {
                    return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
                }
            }
components:
  schemas:
    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
        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.
    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
    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.
    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.
  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:
    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`).
    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'
    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'
    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'
    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'
    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'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 'Authorization: Bearer <key>'
    apiKeyHeader:
      type: apiKey
      in: header
      name: X-Api-Key

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.