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

# Recipe: follow your account's events, once each

> Catch up on the events feed of your account after each run, skipping events you already handled and pausing between pages, in six languages and four frameworks.

This recipe reads `GET /api/v1/events` page after page, pausing a second between pages and stopping after 100 pages per run, then prints the cursor to store. Run it on a schedule with the cursor the last run printed. Delivery is at least once, so skip any `cursor` you already handled.

The Next.js and FastAPI forms are a route your scheduler calls, refusing any call without the secret in `INTERNAL_ROUTE_SECRET` (sent as `X-Internal-Secret`). The Laravel form is a scheduled command and the Spring form a scheduled job. All four store the cursor between runs.

## Prerequisites

* **`MART_API_KEY`**: your API key, with the `events:read` scope.
* **`MART_API_BASE`**: `https://sandbox.mart.ps` while you build, `https://mart.ps` when you go live.
* **`MART_EVENTS_CURSOR`**: the cursor the last run printed. Leave it unset the first time.

**One runtime:** cURL 7.84 or later with `jq`; Node 22.18 or later, which runs the `.ts` file as it is; Python 3.9 or later with `httpx`; PHP 7.4 or later with its curl extension; Go 1.22 or later; or Java 17 or later with Jackson (`jackson-databind`). Each file reads its variables from the environment and sets a timeout on every call. Run it on your own server: a browser or an app never holds the key.

## Run the recipe

```bash cURL theme={null}
#!/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"
```

```typescript TypeScript theme={null}
// 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}`);
```

```python Python theme={null}
"""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}")
```

```php PHP theme={null}
<?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";
```

```go Go theme={null}
//go:build ignore

// 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). Go 1.22 or later. 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 with: go run follow-events.go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"time"
)

var client = &http.Client{Timeout: 30 * time.Second}

func main() {
	cursor := os.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 := url.Values{"limit": {"100"}}
		if cursor != "" {
			query.Set("after", cursor)
		}
		var body struct {
			Data struct {
				Events []struct {
					Cursor    string  `json:"cursor"`
					Type      string  `json:"type"`
					Reference *string `json:"reference"`
				} `json:"events"`
			} `json:"data"`
			Meta struct {
				NextCursor string `json:"next_cursor"`
				HasMore    bool   `json:"has_more"`
			} `json:"meta"`
		}
		get("/api/v1/events?"+query.Encode(), &body)
		for _, event := range body.Data.Events {
			// Delivery is at least once: skip an event whose cursor you already handled.
			line := "event " + event.Cursor + " " + event.Type
			if event.Reference != nil {
				line += " " + *event.Reference
			}
			fmt.Println(line)
			count++
		}
		cursor = body.Meta.NextCursor
		if !body.Meta.HasMore {
			break
		}
		time.Sleep(time.Second) // a pause between pages
	}
	fmt.Println("events:", count)
	fmt.Println("cursor:", cursor)
}

// get sends one GET and decodes its answer into out.
func get(path string, out any) {
	req, err := http.NewRequest(http.MethodGet, os.Getenv("MART_API_BASE")+path, nil)
	if err != nil {
		fail(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
	resp, err := client.Do(req)
	if err != nil {
		fail(fmt.Errorf("no answer: %v", err))
	}
	decode(resp, out)
}

// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
	defer resp.Body.Close()
	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		fail(err)
	}
	var envelope struct {
		Error *struct {
			Code string `json:"code"`
		} `json:"error"`
	}
	if resp.StatusCode >= 300 {
		code := "(not JSON)"
		if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
			code = envelope.Error.Code
		}
		wait := ""
		if after := resp.Header.Get("Retry-After"); after != "" {
			wait = ", try again after " + after + " s"
		}
		fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
	}
	if err := json.Unmarshal(raw, out); err != nil {
		fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
	}
}

func fail(err error) {
	fmt.Fprintln(os.Stderr, "error:", err)
	os.Exit(1)
}
```

```java Java theme={null}
// 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("");
    }
}
```

```typescript Next.js theme={null}
// app/api/mart-events/route.ts: your scheduler calls it (a cron job every minute). It catches up on
// your Mart events and stores the cursor for the next run. It refuses any call without the secret in
// INTERNAL_ROUTE_SECRET (sent as the X-Internal-Secret header), so only your scheduler can run it.
// Needs MART_API_BASE and MART_API_KEY.
import { NextResponse } from 'next/server';
import { createHash, timingSafeEqual } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';

export const dynamic = 'force-dynamic';

const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// A file keeps this example short: keep the cursor in your database.
const cursorFile = process.env.MART_CURSOR_FILE ?? '.mart-events-cursor';
const loadCursor = () => readFile(cursorFile, 'utf8').catch(() => '');
const saveCursor = (cursor: string) => writeFile(cursorFile, cursor);

/** The caller holds the secret, compared in constant time. No secret configured: nobody does. */
function authorised(request: Request): boolean {
  const secret = process.env.INTERNAL_ROUTE_SECRET;
  if (!secret) return false;
  const given = createHash('sha256').update(request.headers.get('x-internal-secret') ?? '').digest();
  return timingSafeEqual(given, createHash('sha256').update(secret).digest());
}

export async function POST(request: Request) {
  if (!authorised(request)) {
    return NextResponse.json({ error: 'unauthorised' }, { status: 401 });
  }
  let cursor = await loadCursor();
  let handled = 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 response = await fetch(`${base}/api/v1/events?limit=100${after}`, {
      headers: { Authorization: `Bearer ${key}` },
      signal: AbortSignal.timeout(30_000),
      cache: 'no-store',
    }).catch(() => null); // no answer: the next run starts again from the stored cursor
    const body = response ? await response.json().catch(() => null) : null;
    if (response === null || !response.ok || body === null) {
      // 410 cursor_expired: start again from start=latest, then rebuild from the reads.
      return NextResponse.json({ error: body?.error?.code ?? 'unavailable' }, { status: 502 });
    }
    for (const event of body.data.events) {
      // Handle the event here. Delivery is at least once: skip a cursor you already handled.
      handled++;
    }
    cursor = body.meta.next_cursor;
    await saveCursor(cursor);
    if (!body.meta.has_more) break;
    await sleep(1000); // a pause between pages
  }
  return NextResponse.json({ handled, cursor });
}
```

```python FastAPI theme={null}
"""Your scheduler calls it (a cron job every minute): it catches up on your Mart events and stores
the cursor for the next run. It refuses any call without the secret in INTERNAL_ROUTE_SECRET (sent as
the X-Internal-Secret header), so only your scheduler can run it.

POST /mart-events/sync. Run: uvicorn follow_events:app
Needs MART_API_BASE and MART_API_KEY in the server's environment.
"""
import asyncio
import hmac
import os
from pathlib import Path

import httpx
from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()
mart = httpx.AsyncClient(
    base_url=os.environ["MART_API_BASE"],
    headers={"Authorization": f"Bearer {os.environ['MART_API_KEY']}"},
    timeout=30,
)

# A file keeps this example short: keep the cursor in your database.
cursor_file = Path(os.environ.get("MART_CURSOR_FILE", ".mart-events-cursor"))


def json_of(response: httpx.Response) -> dict:
    """The JSON body, or a 502 for an answer that is not JSON (an edge error page)."""
    try:
        return response.json()
    except ValueError:
        raise HTTPException(502, "Mart answered with something that is not JSON")


def require_secret(x_internal_secret: str = Header(default="")) -> None:
    """The caller holds the secret, compared in constant time. No secret configured: nobody does."""
    secret = os.environ.get("INTERNAL_ROUTE_SECRET", "")
    if not secret or not hmac.compare_digest(x_internal_secret.encode(), secret.encode()):
        raise HTTPException(401, "unauthorised")


@app.post("/mart-events/sync", dependencies=[Depends(require_secret)])
async def sync_events() -> dict:
    cursor = cursor_file.read_text() if cursor_file.exists() else ""
    handled = 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
        response = await mart.get("/api/v1/events", params=params)
        if response.is_error:
            # 410 cursor_expired: start again from start=latest, then rebuild from the reads.
            raise HTTPException(502, f"events answered {response.status_code}")
        body = json_of(response)
        for event in body["data"]["events"]:
            # Handle the event here. Delivery is at least once: skip a cursor you already handled.
            handled += 1
        cursor = body["meta"]["next_cursor"]
        cursor_file.write_text(cursor)
        if not body["meta"]["has_more"]:
            break
        await asyncio.sleep(1)  # a pause between pages
    return {"handled": handled, "cursor": cursor}
```

```php Laravel theme={null}
<?php
// app/Console/Commands/FollowMartEvents.php: catch up on your Mart events and store the cursor.
//   routes/console.php:  Schedule::command('mart:follow-events')->everyMinute()->withoutOverlapping();
//   config/services.php: 'mart' => ['base' => env('MART_API_BASE'), 'key' => env('MART_API_KEY')],

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class FollowMartEvents extends Command
{
    protected $signature = 'mart:follow-events';

    protected $description = 'Catch up on your Mart events and store the cursor for the next run';

    public function handle(): int
    {
        // A file keeps this example short: keep the cursor in your database.
        $cursor = Storage::disk('local')->get('mart-events-cursor') ?? '';
        $mart = Http::withToken(config('services.mart.key'))->timeout(30)->baseUrl(config('services.mart.base'));
        $handled = 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++) {
            $response = $mart->get('/api/v1/events', array_filter(['limit' => 100, 'after' => $cursor]));
            if ($response->failed()) {
                // 410 cursor_expired: start again from start=latest, then rebuild from the reads.
                $this->error('error: '.$response->status().' '.$response->json('error.code'));

                return self::FAILURE;
            }
            foreach ($response->json('data.events') as $event) {
                // Handle the event here. Delivery is at least once: skip a cursor you already handled.
                $handled++;
            }
            $cursor = $response->json('meta.next_cursor');
            Storage::disk('local')->put('mart-events-cursor', $cursor);
            if (! $response->json('meta.has_more')) {
                break;
            }
            sleep(1); // a pause between pages
        }
        $this->info("events: $handled, cursor: $cursor");

        return self::SUCCESS;
    }
}
```

```java Spring theme={null}
package com.example.martrecipes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Optional;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

/**
 * Every minute: catch up on your Mart events and store the cursor for the next run.
 */
@Component
public class FollowEventsJob {
    // A file keeps this example short: keep the cursor in your database.
    private static final Path CURSOR_FILE = Path.of(".mart-events-cursor");

    private final RestClient mart;

    // MART_API_BASE and MART_API_KEY come from the environment; every call has a timeout.
    public FollowEventsJob(@Value("${MART_API_BASE}") String base, @Value("${MART_API_KEY}") String key) {
        SimpleClientHttpRequestFactory timeouts = new SimpleClientHttpRequestFactory();
        timeouts.setConnectTimeout(Duration.ofSeconds(10));
        timeouts.setReadTimeout(Duration.ofSeconds(30));
        this.mart = RestClient.builder()
                .baseUrl(base)
                .defaultHeader("Authorization", "Bearer " + key)
                .requestFactory(timeouts)
                .build();
    }

    @Scheduled(fixedDelay = 60_000)
    public void catchUp() throws IOException, InterruptedException {
        String cursor = Files.exists(CURSOR_FILE) ? Files.readString(CURSOR_FILE) : "";
        // 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;
            // A 4xx or 5xx throws here; the next run starts again from the stored cursor.
            // 410 cursor_expired: start again from start=latest, then rebuild from the reads.
            JsonNode body = mart.get()
                    .uri(builder -> builder.path("/api/v1/events").queryParam("limit", 100)
                            .queryParamIfPresent("after", after.isEmpty() ? Optional.empty() : Optional.of(after))
                            .build())
                    .retrieve()
                    .body(JsonNode.class);
            for (JsonNode event : body.path("data").path("events")) {
                // Handle the event here. Delivery is at least once: skip a cursor you already handled.
            }
            cursor = body.path("meta").path("next_cursor").asText();
            Files.writeString(CURSOR_FILE, cursor);
            if (!body.path("meta").path("has_more").asBoolean()) {
                break;
            }
            Thread.sleep(1000); // a pause between pages
        }
    }
}
```

## Verify the result

```text theme={null}
event djE6MQ ledger.entry_posted
event djE6Mg order.created 100245
event djE6Mw order.status_changed 100245
events: 3
cursor: djE6Mw
```

Run it again with that cursor: with nothing new it prints `events: 0` and the same cursor. Store the printed cursor, not the last event's. See [Follow events](https://docs.mart.ps/developers/money/events.md).

## Troubleshooting

| What you see | What to do |
| - | - |
| `422` `invalid_cursor` | Send a cursor exactly as the feed returned it, or leave `MART_EVENTS_CURSOR` unset to start over. |
| `410` `cursor_expired` | Send `start=latest` and keep its `next_cursor`, rebuild from `GET /orders`, `GET /ledger` and `GET /withdrawals`, then read on from that cursor. |

| Any recipe | What to do |
| - | - |
| `401` `missing_api_key` or `invalid_api_key` | Check that `MART_API_KEY` holds the whole key. A key still refused needs a replacement from Mart. |
| `401` `key_environment_mismatch` | Point `MART_API_BASE` at the environment that issued the key. |
| `403` `insufficient_scope` | Ask Mart to add the scope in `details.required_scope`. |
| `429` `rate_limit_exceeded` | Wait the `Retry-After` the error line shows, then run it again. |
| `error: no answer`, or a timeout | Check `MART_API_BASE` and your network. |
| `error:` with `(not JSON)` | A proxy or firewall answered, not the API. Check `MART_API_BASE` and your network. |

Every other code is in the [error catalog](https://docs.mart.ps/developers/operate/error-catalog.md).


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