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

# Events

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



## OpenAPI

````yaml /openapi.json get /api/v1/events
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/events:
    get:
      tags:
        - Money
      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.
      operationId: listEvents
      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
                        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

            # Catch up on your account's events, then print the cursor to store
            for the next run.

            # Run it on a schedule (every minute, say). Needs MART_API_BASE and
            MART_API_KEY.

            # MART_EVENTS_CURSOR is the cursor the previous run printed; without
            it, reading starts at the oldest event.

            set -euo pipefail


            # api PATH: 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 \
                --header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") \
                --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE$1") || { 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
            }


            cursor=${MART_EVENTS_CURSOR:-}

            count=0

            # At most 100 pages a run (your choice): a feed that keeps saying
            has_more is read on the next run.

            for page in $(seq 1 100); do
              api "/api/v1/events?limit=100${cursor:+&after=$cursor}"
              # Delivery is at least once: skip an event whose cursor you already handled.
              jq -r '.data.events[] | "event \(.cursor) \(.type)\(if .reference then " " + .reference else "" end)"' <<<"$body"
              count=$((count + $(jq '.data.events | length' <<<"$body")))
              cursor=$(jq -r '.meta.next_cursor' <<<"$body")
              [ "$(jq -r '.meta.has_more' <<<"$body")" = true ] || break
              sleep 1 # a pause between pages
            done

            echo "events: $count"

            echo "cursor: $cursor"
        - lang: typescript
          label: TypeScript recipe
          source: >
            // Catch up on your account's events, then print the cursor to store
            for the next run.

            // Run it on a schedule (every minute, say). Node 22.18 or later
            runs this .ts file as it is.

            // Needs MART_API_BASE and MART_API_KEY. MART_EVENTS_CURSOR is the
            cursor the previous run printed;

            // without it, reading starts at the oldest event.

            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 sleep = (ms: number) => new Promise((resolve) =>
            setTimeout(resolve, ms));


            async function get(path: string): Promise<any> {
              const response = await fetch(`${base}${path}`, {
                headers: { Authorization: `Bearer ${key}` },
                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;
            }


            let cursor = process.env.MART_EVENTS_CURSOR ?? '';

            let count = 0;

            // At most 100 pages a run (your choice): a feed that keeps saying
            has_more is read on the next run.

            for (let page = 1; page <= 100; page++) {
              const after = cursor ? `&after=${encodeURIComponent(cursor)}` : '';
              const body = await get(`/api/v1/events?limit=100${after}`);
              for (const event of body.data.events) {
                // Delivery is at least once: skip an event whose cursor you already handled.
                console.log(`event ${event.cursor} ${event.type}${event.reference ? ` ${event.reference}` : ''}`);
                count++;
              }
              cursor = body.meta.next_cursor;
              if (!body.meta.has_more) break;
              await sleep(1000); // a pause between pages
            }

            console.log(`events: ${count}`);

            console.log(`cursor: ${cursor}`);
        - lang: python
          label: Python recipe
          source: >
            """Catch up on your account's events, then print the cursor to store
            for the next run.


            Run it on a schedule (every minute, say). Python 3.9 or later, with
            httpx.

            Needs MART_API_BASE and MART_API_KEY. MART_EVENTS_CURSOR is the
            cursor the previous run printed;

            without it, reading starts at the oldest event.

            """

            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,
            )



            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


            cursor = os.environ.get("MART_EVENTS_CURSOR", "")

            count = 0

            # At most 100 pages a run (your choice): a feed that keeps saying
            has_more is read on the next run.

            for page in range(100):
                params = {"limit": 100}
                if cursor:
                    params["after"] = cursor
                body = check(client.get("/api/v1/events", params=params))
                for event in body["data"]["events"]:
                    # Delivery is at least once: skip an event whose cursor you already handled.
                    reference = f" {event['reference']}" if event["reference"] else ""
                    print(f"event {event['cursor']} {event['type']}{reference}")
                    count += 1
                cursor = body["meta"]["next_cursor"]
                if not body["meta"]["has_more"]:
                    break
                time.sleep(1)  # a pause between pages
            print(f"events: {count}")

            print(f"cursor: {cursor}")
        - lang: php
          label: PHP recipe
          source: >
            <?php

            // Catch up on your account's events, then print the cursor to store
            for the next run.

            // Run it on a schedule (every minute, say). PHP 7.4 or later, with
            the curl extension.

            // Needs MART_API_BASE and MART_API_KEY. MART_EVENTS_CURSOR is the
            cursor the previous run printed;

            // without it, reading starts at the oldest event.

            $base = getenv('MART_API_BASE');

            $key = getenv('MART_API_KEY');


            /**
             * 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;
            }


            $cursor = (string) getenv('MART_EVENTS_CURSOR');

            $count = 0;

            // At most 100 pages a run (your choice): a feed that keeps saying
            has_more is read on the next run.

            for ($page = 1; $page <= 100; $page++) {
                $query = http_build_query(array_filter(['limit' => 100, 'after' => $cursor]));
                $body = get("$base/api/v1/events?$query", $key);
                foreach ($body['data']['events'] as $event) {
                    // Delivery is at least once: skip an event whose cursor you already handled.
                    echo "event {$event['cursor']} {$event['type']}" . ($event['reference'] ? " {$event['reference']}" : '') . "\n";
                    $count++;
                }
                $cursor = $body['meta']['next_cursor'];
                if (!$body['meta']['has_more']) {
                    break;
                }
                sleep(1); // a pause between pages
            }

            echo "events: $count\n";

            echo "cursor: $cursor\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.

            // Run it on a schedule (every minute, say). Java 17 or later, with
            Jackson. Needs MART_API_BASE and

            // MART_API_KEY. MART_EVENTS_CURSOR is the cursor the previous run
            printed; without it, reading starts

            // at the oldest event. Run it as a single file: java -cp <the
            Jackson jars> follow-events.java

            import com.fasterxml.jackson.databind.JsonNode;

            import com.fasterxml.jackson.databind.ObjectMapper;

            import java.io.IOException;

            import java.net.URI;

            import java.net.URLEncoder;

            import java.net.http.HttpClient;

            import java.net.http.HttpRequest;

            import java.net.http.HttpResponse;

            import java.nio.charset.StandardCharsets;

            import java.time.Duration;

            import java.util.Locale;

            import java.util.Objects;


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

                public static void main(String[] args) throws Exception {
                    String cursor = Objects.requireNonNullElse(System.getenv("MART_EVENTS_CURSOR"), "");
                    int count = 0;
                    // At most 100 pages a run (your choice): a feed that keeps saying has_more is read on the next run.
                    for (int page = 1; page <= 100; page++) {
                        String after = cursor.isEmpty() ? "" : "&after=" + URLEncoder.encode(cursor, StandardCharsets.UTF_8);
                        JsonNode body = get("/api/v1/events?limit=100" + after);
                        for (JsonNode event : body.path("data").path("events")) {
                            // Delivery is at least once: skip an event whose cursor you already handled.
                            String reference = event.path("reference").isNull() ? "" : " " + event.path("reference").asText();
                            System.out.println("event " + event.path("cursor").asText() + " " + event.path("type").asText() + reference);
                            count++;
                        }
                        cursor = body.path("meta").path("next_cursor").asText();
                        if (!body.path("meta").path("has_more").asBoolean()) {
                            break;
                        }
                        Thread.sleep(1000); // a pause between pages
                    }
                    System.out.println("events: " + count);
                    System.out.println("cursor: " + cursor);
                }

                /** 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:
  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
  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
    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.
    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.
  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'
    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'
    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
    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.