#!/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"// 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}`);
"""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
// 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: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)
}
// 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("");
}
}
{
"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
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"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
}
}
}{
"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"
}
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}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.
#!/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"// 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}`);
"""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
// 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: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)
}
// 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("");
}
}
{
"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
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"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
}
}
}{
"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"
}
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}{
"status": "fail",
"status_code": 422,
"message": "<string>",
"data": null,
"meta": null,
"error": {
"code": "missing_api_key",
"details": "<unknown>"
}
}Query Parameters
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.
Response
One page, oldest first. An account with nothing new gets events: [], with next_cursor still there.
