Mart Partner API
Sell the Mart catalog from your own storefront: sync products, variants, stock and the prices for your account, then place cash-on-delivery or card orders — all through one stable JSON envelope.
Base URL:
https://mart.ps/api/v1All paths in this documentation are relative to it. The formal machine
contract is openapi.json;
where this documentation and that document disagree, the OpenAPI document wins —
and tell us, because it means one of them has a bug.
One envelope, always
Every response — success or failure — uses the same six-key shape:
- Branch on
error.code, never onmessage. Messages are written for humans and may be reworded; codes are the contract. - Keys are structurally stable. A documented key is never
conditionally omitted: absent objects are
null, absent collections are[]. The only caller-controlled structural variance is the products listing'sinclude=parameter. error.detailsis an empty array when there is no detail and an object when there is — handle both shapes.
Endpoints
| Endpoint | What it does |
|---|---|
| GET /api/v1/products | List products |
| GET /api/v1/products/{product_id} | Get product details |
| GET /api/v1/products/ids | List offered product ids |
| GET /api/v1/categories | List product categories |
| GET /api/v1/attributes | List attribute groups and values |
| GET /api/v1/states | List delivery destinations |
| POST /api/v1/orders | Create order |
| GET /api/v1/orders | List orders |
| POST /api/v1/orders/validate | Validate an order without creating it |
| GET /api/v1/orders/{partner_reference} | Get order by partner reference |
| POST /api/v1/orders/cancel/{partner_reference} | Cancel an order by partner reference |
| GET /api/v1/reports/summary | Reports summary |
| GET /api/v1/account | Your account |
| GET /api/v1/balance | Balance |
| GET /api/v1/ledger | Ledger |
| GET /api/v1/statements | List statements |
| GET /api/v1/statements/{statement_number} | Get statement |
| GET /api/v1/payout-method | Your payout method |
| PUT /api/v1/payout-method | Save your payout method |
| GET /api/v1/withdrawals | List your withdrawals |
| POST /api/v1/withdrawals | Ask to withdraw |
| GET /api/v1/withdrawals/{withdrawal_id} | Get a withdrawal |
| POST /api/v1/withdrawals/{withdrawal_id}/cancel | Cancel a withdrawal |
| GET /api/v1/events | Events |
New here? Start with Getting started and Authentication.
What's new in 1.1.0
Version 1.1.0 adds reads and one new filter. Nothing you call today
changes unless you call something new. Existing request fields, error codes, status codes, rate limits and key formats are as they were, and a field the
API does not know is still ignored. No existing response field changes. Three things are added to existing
responses: a money block (gross, shipping_deduction,
net, earning_state, available_at) on the order you create and on
the order you read, delivery prices on every town of GET /states, and a
quote on a valid POST /orders/validate answer.
New things you can call
| What | Where |
|---|---|
A money block on every order read (what the order earns your
account, and when it can be counted) |
Get order; the creation response carries it too |
| Delivery prices before an order exists: each town's fee brackets, by products total | Delivery destinations |
| A quote for an order: its delivery fee, totals and reward as a create would freeze them | Validate order |
| Your orders as a list | List orders |
| Your order totals over 3, 6 or 12 months | Reports summary |
| Your account | Your account |
| Balance, ledger and statements | Balance, Ledger, Statements |
| Your payout method | Read, save |
| Withdrawals | List, ask, read, cancel |
| An event feed | Events |
| The products you are offered | Offered product ids, the
product_ids filter on List products, and the
product_not_offered refusal when an order names a product you are not
offered |
What is not money yet, on the balance
Balance also says what your orders that are not delivered yet
will earn once they are (pending, with pending_state), and how much
earned money is held back while its order is under review (under_review).
Earnings can be withdrawn only while their order is delivered: if a delivered
order moves to a ticket or an exchange, its earnings wait under review until it is delivered
again.
Your account area on mart.ps
The partner pages on mart.ps can show the same money: balance, ledger, statements, reports, your payout method and withdrawals. They appear only when Mart switches them on for your account. Until then nothing in the area changes.
Keys and scopes
Every endpoint now names the scope a key needs, and a key without it is refused with
403 insufficient_scope. Keys you already have keep exactly the access they
have today. See Keys and scopes.
The one change to an existing call
GET /products?product_ids= with a list that is not 1 to 100 positive ids
separated by commas, including an empty value, used to be ignored. It now answers
422 invalid_parameter. If you never sent that parameter, nothing changes
for you.
Things that were not available and now are
GET /ordersused to answer405. It now lists your orders.POST /ordersis unchanged.- The money reads answer
503 ledger_unavailablewhen your balance cannot be read. They never answer zeros in its place. - The ledger, the statements and the event feed answer
503 ledger_unavailablewhen an order'spartner_referencecannot be read. They used to return the row with anullreference. - On the money endpoints that take a body, a malformed body is answered
400 bad_requesteven while the balance cannot be read; the503comes after. GET /reports/summarycounts your orders from the programme's sales records: an order placed after the update is applied can be missing from it until it is recorded.- Before the update is applied, the money and account endpoints answer
404 route_not_found(they answered503before). - When your account is closed, its key can read your money and ask to withdraw (the
rules of a closed account apply; it used to get
403), but cannot change the payout method or place orders. A key that does not hold those scopes keeps nothing more. - A new rate limit bucket exists for some of the new reads. The numbers of the existing limits are unchanged; see Errors & rate limits.
Getting started
Onboarding, in order. Each step links to the page with the full detail.
- Build against the sandbox first —
https://sandbox.mart.pstakesmk_test_…keys and nothing placed there is fulfilled or charged; yourmk_live_…key is forhttps://mart.psonce you are done (Environments). - Store your key securely — it is a bearer credential; anyone holding it can read your pricing and create orders in your name (Authentication).
- Make your first authenticated call —
GET /api/v1/products?limit=1. A200means the key works and your account is permitted. - Fetch the delivery destinations —
GET /api/v1/states. Only a leafstates[].idis a validshipping_address.state_id. - Run the initial full catalog sync — page through
GET /api/v1/productsuntilmeta.pagination.has_nextisfalse. - Confirm order creation is enabled for your key — until
Mart enables it,
POST /api/v1/ordersanswers422 orders_not_enabled; catalog access is unaffected. - Place one safe test order, then replay it — send the exact
same request twice and confirm the second answer is a
200withmeta.idempotency_replay: trueand the same order id. That single exercise proves the mechanism that protects you from duplicate orders (Idempotency & retries). Tell us the reference and we will remove the test order.
Timestamps
Timestamps in responses are ISO 8601 with an explicit UTC offset
(e.g. 2026-07-01T00:00:00+03:00). When you send
updated_after, always include an offset — a bare
timestamp is interpreted in our server's local zone, not UTC.
updated_at you actually received as your
next cursor, verbatim, rather than generating one from your own clock —
clock skew is the classic cause of silently missed rows.
Getting help
When something is wrong, send us the partner_reference (and
data.order.id if you got one), the error.code with the
full error.details, the approximate timestamp with offset, and — for
order problems — the exact request body. That set is almost always enough to
answer without a round trip.
Authentication
Send your key on every request, using either header.
Authorization: Bearer <your key> # preferred
X-Api-Key: <your key>Keys are issued per partner. A key prices the catalog as your own account:
two partners calling the same endpoint at the same moment can legitimately
receive different group_price values for the same product
(public_price and base_price are the same for
everyone). Access is re-checked on every request.
What the auth statuses mean
401— the key is missing, malformed, revoked or paused. Revoked and paused keys answer exactly like unknown ones, so treat any401as stop and alert a human, never as something to retry around.403— the key is valid, but the account behind it is not currently permitted. Group membership is re-checked live, so access resumes on its own once the account is put back. Contact us. A403insufficient_scopemeans the key lacks the scope the endpoint needs; see Keys and scopes.
Your first call, end to end:
curl -s https://mart.ps/api/v1/products?limit=1 \
-H 'Authorization: Bearer $MART_API_KEY'A 200 here means the key works, the account is active, and it is
in a group permitted to use the API.
Keys and scopes
A scope is one thing a key may do. Each endpoint names the scope it needs, and a
key without it is refused with 403 insufficient_scope.
orders:write and payments:card permissions already switched off. The
money scopes still meet your account's withdrawal settings (403 withdrawals_disabled
where withdrawals are off).
Nothing you call today changes.
The scopes
| Scope | What it allows | Endpoints |
|---|---|---|
catalog:read | Read the catalog and delivery destinations | Products, product details, offered ids, categories, attributes, states |
orders:read | Read your orders | List orders, get an order |
orders:write | Create, validate and cancel orders | Create, validate, cancel |
payments:card | Pay an order by card | The payment_type field of create |
money:read | Read your balance and what moved it | Balance, ledger, statements, one statement, payout method, withdrawals, one withdrawal |
iban:write | Save your payout method | Save payout method |
withdrawals:write | Ask to withdraw, and cancel a request | Ask to withdraw, cancel |
events:read | Read the event feed | Events |
reports:read | Read your order totals | Reports summary |
Your account needs no scope: every key can read its own profile,
which also shows what the key may do. Every operation in the
OpenAPI contract names its scope in
x-required-scope.
When a scope is missing
{
"status": "fail",
"status_code": 403,
"message": "This API key does not have the scope this endpoint needs.",
"data": null,
"meta": null,
"error": {
"code": "insufficient_scope",
"message": "This API key does not have the scope this endpoint needs.",
"details": { "required_scope": "money:read" }
}
}- The check runs right after the key is recognised, before the rate limit, so a refused call uses none of your quota and carries no rate-limit headers.
- Retrying unchanged will not help. Ask Mart to give the key the scope.
- Order writes are the one exception: a key that cannot create orders is answered
422 orders_not_enabled, as it always was, and a request that sets a card payment on a key withoutpayments:cardis answered422 card_not_enabled. Neither is a403.
Environments
Two separate installations, each with its own keys. Build and test against the sandbox; when you go live, change the base URL and the key, nothing else.
| Production | Sandbox | |
|---|---|---|
| Base URL | https://mart.ps/api/v1 | https://sandbox.mart.ps/api/v1 |
| Keys | mk_live_…; keys issued before environments
(mk_…) keep working here | mk_test_… |
| Data | The live catalog, stock and your real orders | A periodically refreshed copy of the catalog; synthetic customers and orders, reset on a published schedule |
| Payments | Cash on delivery, and card through Lahza | Lahza's test gateway: nothing placed there is fulfilled or charged |
X-Mart-Environment | production | sandbox |
A key works in one environment
The prefix says where. A key sent to the other environment answers
401 key_environment_mismatch before
anything else is checked, and error.details.environment names the
environment you called. Nothing is wrong with the key: fix the base URL, or use the
key issued for that environment.
Assert the header
Every response carries X-Mart-Environment: production or
X-Mart-Environment: sandbox. Check it in your client, so a misconfigured
base URL fails loudly instead of sending a test order to production.
https://mart.ps.
List products
Requires API keyOne page of the catalog, priced for your account, with stock and combinations
on every row. Page with page and limit until
meta.pagination.has_next is false. Returns
both active and inactive products by default — inactive rows
are returned precisely so you learn they were deactivated — and zero-stock
products stay visible with in_stock: false. Absence from a page is
never a deletion or out-of-stock signal.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| page | integer | optional | |
| limit | integer | optional | Default 500, maximum 1000 (both back-office configurable). |
| include | string | optional | Comma-separated opt-in heavy fields. Supported: `description` (adds description and description_short to every item — same content as the detail endpoint). Unknown values return 422. |
| status | string | optional | |
| updated_after | string | optional | ISO 8601 datetime; filters on the product's last edit time (`date_upd`). |
| in_stock | string | optional | |
| category_id | integer | optional | Product category id (Meta product taxonomy) — see `category.category_id`. Products without a category mapping do not match; an unknown id matches nothing (200, empty page). |
| brand_id | integer | optional | Brand (manufacturer) id — see `brand.id` on any product row. Must be a positive integer; `0`, a non-numeric value or a repeated `brand_id[]=` answer 422 `invalid_parameter`. Products with no brand never match, and an unknown id matches nothing (200, empty page). |
| product_ids | string | optional | Comma-separated product ids, 1 to 100, to fetch exactly those products (for example ones that entered your offer, see `GET /products/ids`). Combines with the other filters. Products you are not offered never appear. Anything else, including an empty value, answers 422 `invalid_parameter`. |
Identifiers: product_id and combination_id, never reference
product_id identifies a product and combination_id a
variant; both are stable, and they are exactly what
order creation accepts —
combinations[].id on a product response is the same token the order
endpoint's combination_id field expects. reference is
descriptive data only: editable on our side, never resolved by the API, and not
guaranteed unique. Do not key your local records on it, build URLs from it, or
match on it when reconciling.
product_id (plus combination_id where present)
the primary key of your local product table from day one, and treat every row
you receive as an upsert — update in place, never
insert-a-duplicate or delete-then-insert. And never treat disappearance from a
filtered view (status=active) as a deletion signal; read
status explicitly.Stock
There is no separate stock endpoint — every product row carries its
availability, so the catalog sync is also the stock sync. Simple products have
one figure (total_quantity); products with variants carry
available_quantity per combination, and the product-level figure is
the aggregate. A product can be in_stock: true overall while the
variant your customer wants is at zero — always check at the variant
level. A sync reserves nothing: stock is checked live
at order creation, and any short line rejects the whole order.
What price means
"price": {
"group_price": 55.99, // YOUR unit price — cost basis, and the only floor
"public_price": 59.99, // what the public pays on mart.ps right now
"base_price": 99.99 // the pre-discount catalogue price — the "was"
},
"currency": "ILS"All three are tax-included, 2 decimals, always present and never
null, each a snapshot of this instant.
base_price is always the highest (or equal); when nothing is
discounted all three are equal — the normal shape, not missing data. Pricing is
product-level: the one price object applies to
every variant, and combinations never carry a price of their own.
group_price is not guaranteed to be below
public_price — on part of the catalog your account's tier is the
shallower discount and you pay more than the public does. Compare the two per
product and take the lower as your merchandising cost basis. For a public
"was X, now Y", use base_price →
public_price — the shop's own claim; never present
group_price as a public discount.
Price changes are invisible to incremental sync
updated_after filters on the product's last edit time.
A scheduled or time-limited price beginning or ending edits nothing — no
timestamp moves — so an incremental sync will never see a promotion
start or end. You can poll every minute for a year and still sell at
last year's price. Pure stock movements do not touch it either.
price for every product, independently of any
updated_after cursor. Keep it a separate job from the incremental
sync. A stale price is not silently accepted anyway: an order priced from it
is rejected at creation (the price floor).
A workable sync schedule
| Job | Endpoint | Suggested interval |
|---|---|---|
| Stock poll | /api/v1/products (all pages) | every 5–15 minutes |
| Structural sync | /api/v1/products?updated_after=… | hourly |
| Full price refresh | /api/v1/products (all pages) | daily |
| Destinations and delivery prices | /api/v1/states | at least daily |
| Full catalog reconcile | /api/v1/products (all pages) | weekly |
Starting points — tune to your catalog size within your
rate budget, but do not drop the full price refresh. Use
include=description only on bulk imports, never on routine
polling: combined with a large limit it moves a lot of HTML you
already have.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s 'https://mart.ps/api/v1/products?page=1&limit=500' \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"products": [
{
"product_id": 9597,
"reference": "1005118",
"name": "Hebron Rock and Star Men's Bustar",
"status": "active",
"brand": {
"id": 100,
"name": "Rock"
},
"category": {
"category_id": 429,
"category_name": "clothing & accessories > shoes & footwear",
"gender": "men"
},
"price": {
"group_price": 54.99,
"public_price": 59.99,
"base_price": 129.99
},
"currency": "ILS",
"total_quantity": 3,
"in_stock": true,
"cover_image": "https://cdn.mart.ps/28359-thickbox_default/product.jpg",
"images": [
"https://cdn.mart.ps/28359-thickbox_default/product.jpg"
],
"combinations": [
{
"id": 41206,
"available_quantity": 3,
"attributes": [
{
"id": 16,
"name": "بني",
"group": "اللون"
}
]
}
],
"updated_at": "2026-07-20T14:03:00+03:00"
}
]
},
"meta": {
"pagination": {
"page": 1,
"limit": 500,
"total": 15297,
"total_pages": 31,
"has_next": true
}
},
"error": null
}Get product details
Requires API keyThe full product record: text fields and every combination with its stock
and images. Pricing is product-level — the single price object
applies to every combination (see
List products for the price semantics and the
price-refresh requirement).
Path parameters
| Name | Type | Description | |
|---|---|---|---|
| product_id | integer | required | Stable product identifier used in catalog synchronization and order creation. Positive integer; leading zeros are rejected so each product has exactly one URL. |
Two different 404s
A malformed id (/products/ABC, /products/0, leading
zeros) never matches the route and answers route_not_found — the
URL is wrong. A well-formed id with no such product answers
product_not_found with the id in error.details — the
URL is right and your local catalog is stale: re-sync it.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s https://mart.ps/api/v1/products/9597 \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"product": {
"product_id": 9597,
"reference": "1005118",
"name": "Hebron Rock and Star Men's Bustar",
"description": "<p>Leather upper, rubber sole.</p>",
"description_short": "Men's shoe.",
"status": "active",
"brand": {
"id": 100,
"name": "Rock"
},
"category": {
"category_id": 429,
"category_name": "clothing & accessories > shoes & footwear",
"gender": "men"
},
"price": {
"group_price": 54.99,
"public_price": 59.99,
"base_price": 129.99
},
"currency": "ILS",
"total_quantity": 3,
"in_stock": true,
"cover_image": "https://cdn.mart.ps/28359-thickbox_default/product.jpg",
"images": [
"https://cdn.mart.ps/28359-thickbox_default/product.jpg"
],
"combinations": [
{
"id": 41206,
"available_quantity": 3,
"attributes": [
{
"id": 16,
"name": "بني",
"group": "اللون"
}
],
"default": true,
"images": []
}
],
"updated_at": "2026-07-20T14:03:00+03:00"
}
},
"meta": null,
"error": null
}List offered product ids
Requires API keyThe ids of the products your account is offered, in ascending order, and
nothing else. It is the cheap way to notice what entered or left
your offer, which updated_after cannot show: a product that leaves
the offer does not change, it just stops appearing.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| page | integer | optional | |
| limit | integer | optional | Default and maximum are the same number, set by Mart (20000 unless changed). |
| status | string | optional |
How to use it
- Pull the ids now and then, or whenever
meta.offer_changed_athas moved. - Compare them with the ids you hold. Ids you hold that are not in the answer have left the offer: stop selling them.
- Ids in the answer that you do not hold are new: fetch them with
GET /products?product_ids=1,2,3(at most 100 ids per call).
Keep using updated_after for changes to products you already hold.
What it returns
data.product_ids: integers, ascending. It is the same setGET /productslists for your key.status(active,inactive,all; defaultall) works as it does there.meta.pagination:pageandlimitas usual. The default and the largestlimitare the same number, set by Mart, so a catalog normally fits one page. If it does not, read every page before comparing.meta.snapshot_at: when the read started (UTC). A product can enter or leave while you page, so compare against the snapshot as a whole and expect the next pull to settle the rest.meta.offer_changed_at: present only when your account has an offer of its own, and it moves when Mart edits that offer. Segment-based offers can also change when a segment is refreshed, which does not move this time, so pull on a schedule as well.
Products you are not offered cannot be read with
GET /products/{product_id} (the answer is the same
404 product_not_found as for an id that does not exist), and an order
line for one is refused with 422 product_not_offered.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/products/ids" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"product_ids": [
9597,
12402,
12410
]
},
"meta": {
"pagination": {
"page": 1,
"limit": 20000,
"total": 3,
"total_pages": 1,
"has_next": false
},
"snapshot_at": "2026-11-06T09:00:00+00:00"
},
"error": null
}List product categories
Requires API keyThe category vocabulary behind the products endpoints, as a flat list
ordered by name — no pagination (meta is null).
Mart's category ids follow Meta's product taxonomy.
category_id is the exact value the products
category_id filter accepts and matches the category
object each product row carries. The list changes rarely; caching it and
refreshing weekly is enough.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s https://mart.ps/api/v1/categories \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"categories": [
{
"category_id": 528,
"category_name": "clothing & accessories > clothing",
"gender": null
},
{
"category_id": 455,
"category_name": "clothing & accessories > clothing > women's clothing",
"gender": "women"
}
]
},
"meta": null,
"error": null
}List attribute groups and values
Requires API keyThe attribute vocabulary behind combination attributes, grouped
by attribute group; only values actually in use are served — no pagination
(meta is null).
Joining
values[].attribute_id equals the id the products
endpoints emit in combinations[].attributes[] — join by that id.
attribute_group_id structures this payload only and appears
nowhere in product responses; group and value names are display strings, not
keys. The list changes rarely; caching it and refreshing weekly is enough.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s https://mart.ps/api/v1/attributes \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"attributes": [
{
"attribute_group_id": 1,
"attribute_group_name": "اللون",
"values": [
{
"attribute_id": 1,
"attribute_name": "أحمر"
},
{
"attribute_id": 16,
"attribute_name": "بني"
}
]
}
]
},
"meta": null,
"error": null
}List delivery destinations
Requires API keyAll delivery destinations as a two-level tree: cities, each holding its
deliverable states/towns — no pagination (meta is
null). Every town carries delivery: what delivery to it
costs your customer, by products total, so you can show delivery prices before an
order exists.
states[].id is a valid
shipping_address.state_id. A city id is a different
id space and is never accepted — sending one fails
order creation with invalid_state.
Names are not guaranteed unique, even within one city —
store and match on id, never on name. Present the
list to your customer as a picker rather than free text, because an unknown or
inactive state_id fails the whole order at creation. The towns
change rarely; their prices can change, so re-read the list at least daily.
Delivery prices
delivery.fees lists the brackets an order of yours to the town is
priced with. The fee depends on the products total: your line prices
times quantities (the group price where you send none), tax included, delivery
excluded. A total t pays the fee of the bracket where
from_total ≤ t < to_total: a total equal to
to_total already pays the next bracket, and the last bracket
(to_total: null) has no upper end.
available: false (and empty fees) cannot be
priced right now and an order to it fails; do not offer it until it is
true again.
At checkout, send the final basket to Validate order:
its quote carries the fee and totals a create would freeze. Prices can
move before you create, so the create answer is the binding one.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s https://mart.ps/api/v1/states \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"cities": [
{
"id": 255,
"name": "الخليل",
"states": [
{
"id": 774,
"name": "أبو الغزلان",
"delivery": {
"available": true,
"fees": [
{
"from_total": 0,
"to_total": 300,
"fee": 35
},
{
"from_total": 300,
"to_total": null,
"fee": 20
}
]
}
},
{
"id": 726,
"name": "إذنا",
"delivery": {
"available": true,
"fees": [
{
"from_total": 0,
"to_total": 300,
"fee": 35
},
{
"from_total": 300,
"to_total": null,
"fee": 20
}
]
}
}
]
}
]
},
"meta": null,
"error": null
}Create order
Requires API keyCreates an order priced at your selling prices. You send
exactly five things — partner_reference, payment_type,
shipping_address, products, and optionally
free_shipping. We derive the rest, and you cannot
influence it: the amount the courier collects, the currency, the
delivery provider, and the delivery fee. Unknown fields are ignored, not
rejected, and they do not take part in the idempotency comparison.
In shipping_address, phone is the recipient's
primary (mobile) number — the one the courier calls. An optional
extra_phone carries a second number; omitted and
null are the same thing.
Request body (OrderCreateRequest)
| Field | Type | Description | |
|---|---|---|---|
| payment_type | string | required | REQUIRED: exact lowercase `cod` or `card` — never normalized, never defaulted. `card` charges your saved card synchronously for the server-computed total and needs per-key enablement (`card_not_enabled`) plus a reusable saved card on file (`card_not_on_file`). See https://mart.ps/api/docs#payments. |
| partner_reference | string | required | Your own order id and the idempotency key, stored and matched byte-for-byte. Letters, digits, dot, underscore, hyphen; max 64 characters; surrounding whitespace is rejected, never trimmed; unique per key. Identity is judged on a canonical form — https://mart.ps/api/docs#idempotency. |
| shipping_address | object | required | |
| products | array | required | Order is significant: error details reference the line index. |
| free_shipping | boolean | optional | `true` = you absorb the delivery fee (needs your group's permission — `free_shipping_not_allowed` otherwise; `free_shipping_not_covered` when your margin cannot cover the fee, exact coverage passing). Rejected with `card_free_shipping_not_allowed` on card orders. See https://mart.ps/api/docs#orders. |
Product entries
- Each entry needs
product_idandquantity;combination_idis required for a product with variants and must benullor omitted for one without. Between 1 and 200 entries; the same(product_id, combination_id)may not appear twice (duplicate_product). - Product order is significant: error details refer to lines
by
details.index, the zero-based position in your array.
The price floor: group_price and nothing else
products[].price is optional. Omitting it (or sending
null) means "sell at the catalog price for my account's group",
resolved at the moment of creation and frozen into the order. An explicit
0 is always invalid; only omission delegates. Whether you may set
a custom price is governed by your account's group:
- Overrides allowed (the default): a supplied price must be
≥
price.group_priceat the moment the order is created — not at the moment you synced. Below it:422 price_below_minimumwithdetails.minimum. Exact equality passes (you simply earn nothing on that line). - Overrides not enabled: a supplied price is accepted only
when it equals the group price exactly
(
price_override_not_allowed,details.expected) — we never silently replace a price you sent. In this mode, just omitprice.
public_price and base_price never constrain what
you may sell at — selling below public_price is the ordinary case.
Carry a margin above group_price rather than selling at exactly
the floor, so a price that moves between sync and submission costs you margin
instead of failing the order.
422 creates nothing, the
correct response is always: fix what the error names, then resubmit under
the same partner_reference.
Free shipping — funded from your margin
free_shipping: true means you absorb the
delivery fee and your customer pays for products only:
gross_product_reward = SUM((your price − group_price) × quantity)
shipping_deduction = the delivery fee (0.00 when free_shipping is false)
net_reward = gross_product_reward − shipping_deduction
accepted only when net_reward >= 0 (exactly 0.00 passes)The fee is not a flat per-destination rate — it depends on
the destination and the order total, so changing your prices can
change the fee you need to cover. The fee that applied is returned as
shipping_fee, and a free_shipping_not_covered
rejection reports it in details.shipping_fee alongside
details.shortfall. On rejection you have two ways forward, both
retryable under the same reference: raise your prices, or resubmit with
free_shipping: false. Requesting it at all needs your group's
permission (free_shipping_not_allowed otherwise), and it cannot
be combined with card payment.
The response
data.order carries id,
partner_reference, status (an API-owned vocabulary
that may extend — switch on it with a default branch), created_at,
the totals (cod_total is what the courier collects),
shipping_fee, free_shipping, a settlement
reward object, a money object (frozen with the order:
always pending here, with a null available_at; read the order
for the live state), products (each with the frozen
group_price floor so you can verify your margin), and
shipping_address.
data.order.id against your own reference — it is the fastest way
for us to help with a query.
If Mart adjusts the order afterwards
Staff can adjust an order after creation (a quantity reduced, a line refunded) and your reward follows the goods: per-unit margins never move (frozen at creation), the reward tracks remaining quantity, and a free-shipping grant the remaining margin can no longer cover can be withdrawn — the frozen fee goes back on the customer's order. Never applied silently; Mart staff confirm it explicitly.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s -X POST https://mart.ps/api/v1/orders \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
--max-time 60 \
-d '{
"partner_reference": "ACME-100245",
"payment_type": "cod",
"shipping_address": {
"customer_name": "محمد نور", "phone": "0599000000",
"extra_phone": "022345678",
"state_id": 431, "address": "شارع المدارس 12"
},
"products": [
{ "product_id": 9597, "combination_id": 41206,
"quantity": 2, "price": 120.00 }
]
}'
# timeout? re-run THIS EXACT COMMAND — same reference, same body.{
"status": "success",
"status_code": 201,
"message": "Created",
"data": {
"order": {
"id": 100311,
"partner_reference": "100245",
"status": "processing",
"payment_type": "cod",
"created_at": "2026-08-01T10:15:00+00:00",
"cod_total": 240,
"shipping_fee": 35,
"free_shipping": true,
"reward": {
"gross_product_reward": 130.02,
"shipping_deduction": 35,
"net_reward": 95.02
},
"money": {
"gross": 130.02,
"shipping_deduction": 35,
"net": 95.02,
"earning_state": "pending",
"available_at": null
},
"products": [
{
"product_id": 9597,
"combination_id": 41206,
"quantity": 2,
"price": 120,
"group_price": 54.99
}
],
"shipping_address": {
"customer_name": "محمد علي",
"phone": "0599123456",
"extra_phone": "022345678",
"state_id": 386,
"address": "شارع الإرسال، عمارة 12",
"notes": null
}
}
},
"meta": {
"idempotency_replay": false
},
"error": null
}List orders
Requires API keyOne page of your orders, newest first, as summaries. Page with
page and limit until meta.pagination.has_next
is false. Key-scoped: you can never see or probe another partner's
orders. A search that matches nothing is a normal 200 with
orders: [], never a 404.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| status | string | optional | Comma-separated status ids, as `status.id` is returned on an order, for example `5,7`. Matches the status shown on each row, which is the status the single order read shows. At most 50 ids. A non-numeric value answers 422 `invalid_parameter`. |
| payment_type | string | optional | Only orders paid this way. |
| created_from | string | optional | ISO 8601 datetime; orders created at or after this instant. |
| created_to | string | optional | ISO 8601 datetime; orders created strictly before this instant, so consecutive windows never overlap. |
| updated_since | string | optional | ISO 8601 datetime; orders last modified at or after this instant (`updated_at`). With `order=asc` this is the way to follow changes. |
| order | string | optional | Sort by creation time, with the order's creation sequence breaking a tie, so a page boundary never repeats or skips a row. |
| page | integer | optional | |
| limit | integer | optional | Default 50, maximum 100. |
What a row carries
Each row holds the same values Get order returns for
that order: partner_reference, status,
payment_type, created_at, updated_at,
order_total, cod_total, shipping_fee and
free_shipping. The lines, delivery address, payment reference,
cancellation and money are not repeated here: read one order by its
partner_reference when you need them. A row's status is
what the customer sees on mart.ps, exactly as on the single read; treat
status.id as opaque and status.name as display text.
Filters
status: one or morestatus.idvalues, comma-separated (at most 50). It matches the status each row shows.payment_type:codorcard.created_from(inclusive) andcreated_to(exclusive, so consecutive windows never overlap): ISO 8601 datetimes on the order's creation time.updated_since(inclusive): an ISO 8601 datetime onupdated_at.order:desc(default) orasc, by creation time. Two orders created at the same instant keep a fixed order.limit: default 50, maximum 100.
A malformed value answers 422 invalid_parameter naming the
parameter; it is never silently ignored.
partner_reference. To follow changes, ask
for updated_since (your last high-water mark) with
order=asc, and re-read any order you care about by its reference.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/orders?payment_type=cod&limit=20" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"orders": [
{
"partner_reference": "100245",
"status": {
"id": 5,
"name": "تم التوصيل"
},
"payment_type": "cod",
"created_at": "2026-08-01T10:15:00+00:00",
"updated_at": "2026-08-03T09:40:12+03:00",
"order_total": 275,
"cod_total": 275,
"shipping_fee": 35,
"free_shipping": true
}
]
},
"meta": {
"pagination": {
"page": 1,
"limit": 50,
"total": 1,
"total_pages": 1,
"has_next": false
}
},
"error": null
}Validate an order without creating it
Requires API keyThe dry-run twin of Create order: same body,
same validation pipeline, nothing written. An invalid request answers the
byte-identical error envelope create would return — same HTTP status, same
error.code, same error.details including
index. A valid order answers a quote: what the order would
cost and earn if you created it now.
Request body (OrderCreateRequest)
| Field | Type | Description | |
|---|---|---|---|
| payment_type | string | required | REQUIRED: exact lowercase `cod` or `card` — never normalized, never defaulted. `card` charges your saved card synchronously for the server-computed total and needs per-key enablement (`card_not_enabled`) plus a reusable saved card on file (`card_not_on_file`). See https://mart.ps/api/docs#payments. |
| partner_reference | string | required | Your own order id and the idempotency key, stored and matched byte-for-byte. Letters, digits, dot, underscore, hyphen; max 64 characters; surrounding whitespace is rejected, never trimmed; unique per key. Identity is judged on a canonical form — https://mart.ps/api/docs#idempotency. |
| shipping_address | object | required | |
| products | array | required | Order is significant: error details reference the line index. |
| free_shipping | boolean | optional | `true` = you absorb the delivery fee (needs your group's permission — `free_shipping_not_allowed` otherwise; `free_shipping_not_covered` when your margin cannot cover the fee, exact coverage passing). Rejected with `card_free_shipping_not_allowed` on card orders. See https://mart.ps/api/docs#orders. |
- The quote is what create would freeze —
products_total,shipping_fee(the delivery bracket of that total for the destination),free_shipping,order_total,cod_totalandreward(thegross,shipping_deductionandnetof the created order'smoneyblock) are the very figures a create with the same body freezes at this moment. Show them at checkout, then create with the same body; the create answer is the binding one. - Creates nothing, reserves nothing, consumes nothing — no
order, no stock movement, and the
partner_referenceis NOT consumed: a reference that validated here still answers201withmeta.idempotency_replay: falseon the real create. - Idempotency is predicted, not processed — a reference
already used with different content answers the same
409 idempotency_conflictcreate would; one already used with identical content answers200without re-validating, mirroring create's replay; itsquoteisnull, because the order exists (read it with Get order). - Point-in-time — a
200means the order would be accepted right now. Stock, prices and delivery fees can move before your real create, so create can still reject a body that validated a moment earlier, or freeze other figures than the quote. - Card bodies — validation confirms card payment is enabled for your key, a reusable saved card is on file, and the body is card-legal; it does not contact the payment gateway, so a valid verdict does not guarantee the charge will be approved (Card payment).
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s -X POST https://mart.ps/api/v1/orders/validate \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
-d @order-body.json # the exact body you would send to create{
"status": "success",
"status_code": 200,
"message": "Order is valid",
"data": {
"validation": {
"valid": true,
"quote": {
"products_total": 240,
"shipping_fee": 35,
"free_shipping": true,
"order_total": 240,
"cod_total": 240,
"reward": {
"gross": 130.02,
"shipping_deduction": 35,
"net": 95.02
}
}
}
},
"meta": null,
"error": null
}Get order by partner reference
Requires API keyReturns your order, addressed by the same
partner_reference you submitted at creation. Key-scoped: a
reference that does not exist on your account — including another partner's —
answers the identical 404 order_not_found; you can never see or
probe other partners' orders.
Path parameters
| Name | Type | Description | |
|---|---|---|---|
| partner_reference | string | required | The reference you submitted to POST /api/v1/orders, exactly as you sent it (references are stored byte-for-byte). Letters, digits, dot, underscore, hyphen; max 64 characters. |
Live view, frozen prices
- Live:
status(exactly what the customer sees on mart.ps — treatstatus.idas opaque andstatus.nameas display text in the order's language), quantities (net of refunds/returns),cod_total,free_shipping,updated_at. - Frozen: each item's
pricestays your selling price frozen at creation, andshipping_feestays the creation-time fee.shipping_addressis the creation snapshot (extra_phoneisnullwhen none was sent) plus a resolvedstate_name.
The read does not repeat the settlement reward block — keep the
creation response for settlement reconciliation. Its last key, money,
is the live view of what the order earns your account:
gross, shipping_deduction, net,
earning_state (pending, held,
available or reversed, where every figure reads
0.00) and available_at. available means this
order's money matured, not that it can be withdrawn: a debt on your account can
offset it. Poll this endpoint for
operational status; never poll the create replay, which is
frozen forever. The order carries a
cancellation object — null unless the order was
cancelled through this API: an order Mart cancelled in the back office
shows the cancelled status but a null
cancellation.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s https://mart.ps/api/v1/orders/ACME-100245 \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"order": {
"partner_reference": "100245",
"status": {
"id": 5,
"name": "تم التوصيل"
},
"payment_type": "cod",
"created_at": "2026-08-01T10:15:00+00:00",
"updated_at": "2026-08-03T09:40:12+03:00",
"cod_total": 240,
"shipping_fee": 35,
"free_shipping": true,
"products": [
{
"product_id": 9597,
"combination_id": 41206,
"quantity": 2,
"price": 120,
"line_total": 240
}
],
"shipping_address": {
"customer_name": "محمد علي",
"phone": "0599123456",
"extra_phone": null,
"state_id": 386,
"state_name": "الخليل",
"address": "شارع الإرسال، عمارة 12",
"notes": null
},
"cancellation": null
}
},
"meta": null,
"error": null
}Cancel an order by partner reference
Requires API keyWithdraws an order you created, addressed by your
reference. The body is optional — { "reason": "…" }, free text up
to 500 characters (not bytes; a 500-character Arabic reason is fine).
No new permission: if your key can create orders, it can
cancel them.
Path parameters
| Name | Type | Description | |
|---|---|---|---|
| partner_reference | string | required | The reference you submitted to POST /api/v1/orders, exactly as you sent it. Letters, digits, dot, underscore, hyphen; max 64 characters. A reference outside that shape does not match this route at all and answers 404 `route_not_found`. |
Request body (OrderCancelRequest)
| Field | Type | Description | |
|---|---|---|---|
| reason | string | optional | Free text recorded against the cancellation; trimmed, whitespace-only stored as null. Max 500 characters (characters, not bytes). |
- Mart decides when — which states are cancellable, and the
state the order lands in, are our configuration; the request cannot
influence either. Past the threshold:
409 order_not_cancellable, order untouched. Treat it as final and read the order to see where it got to. - Repeating is safe and IS the retry procedure — cancelling
an already-cancelled order answers
200withalready_cancelled: true, records nothing twice, and completes a cancellation that was interrupted mid-flight. - Concurrency is handled — requests against one order are
serialised; a second request waits, then reports
already_cancelled: true. Only if that wait is exhausted do you get503 order_cancellation_in_progresswithRetry-After. - Not a refund — it moves the order through our normal workflow (which releases stock) but does not itself move money. For anything already paid or dispatched, talk to us.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s -X POST https://mart.ps/api/v1/orders/cancel/ACME-100245 \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "reason": "Customer requested cancellation" }'
# lost the response? run it again — 200 with already_cancelled: true.{
"status": "success",
"status_code": 200,
"message": "Order cancelled",
"data": {
"order": {
"partner_reference": "PARTNER-ORDER-100245",
"status": {
"id": 6,
"name": "Cancelled"
},
"cancelled_at": "2026-08-04T08:15:00+00:00",
"already_cancelled": false
}
},
"meta": null,
"error": null
}Cash on delivery
payment_type is required on every order:
"cod" or "card", exact lowercase. Values are never
normalized — "COD" is rejected — and omission or null
answers 422 invalid_parameter; there is no default.
COD is the default flow. The courier collects cod_total — your
product prices plus the delivery fee (unless you absorbed it with
free_shipping). Everything on
Create order applies as written: custom prices per
your group's permission, free-shipping coverage from your margin, settlement
through the reward block.
cod_total
is live (it follows refunds and edits made by Mart's staff), while each
item's price and the shipping_fee stay frozen at
creation.
Card payment
With payment_type: "card", your own saved card is
charged synchronously inside the create request for the exact
server-computed total (group prices plus the delivery fee). The order is
created only when the charge succeeds; a failed charge creates nothing.
Preconditions (both per-key)
- Card payment enabled for your key — otherwise
422 card_not_enabled; send"cod"until Mart enables it. - A reusable saved card on file for your account — otherwise
422 card_not_on_file; complete the card-setup step with Mart first.
Two constraints follow from "the server computes the charge"
- No
products[].price— a present price is rejected withcard_price_not_allowedeven when it equals the group price, because a partner-supplied price can never influence a server-computed charge. The group price is what is charged. - No
free_shipping—trueis rejected withcard_free_shipping_not_allowed: a card order has no margin to absorb the fee from. Omit it or sendfalse.
Charge outcomes
| Outcome | What it means |
|---|---|
| 201 | Charged and created. The response carries
payment_reference for dashboard reconciliation. |
| 402 card_declined | The gateway declined; no order, nothing captured. Retrying the same
partner_reference makes a fresh attempt, never a double
charge. details.gateway_response carries the reason; after
several declines details.attempts_exhausted is
true and the reference is terminally declined — fix the card
with Mart and use a new reference. |
| 422 saved_card_invalid | The gateway confirmed the saved card can no longer be charged. Nothing was charged; re-add or update the card with Mart before retrying. |
| 503 payment_gateway_unavailable | The gateway did not answer and the charge outcome is unknown. Retry
the same reference after Retry-After: the retry reconciles
any charge that did land and never double-charges. |
| 409 charge_amount_mismatch | A previous attempt already captured a charge at an amount that no longer matches the current total (prices moved between attempts). No order, no second charge; contact Mart to resolve the captured payment. |
partner_reference: a retry after a timeout or crash reconciles
the earlier charge instead of repeating it. The whole
idempotency contract holds for card orders too.
The dry run confirms card enablement, the card on file, and that the body is card-legal — but it does not contact the gateway: a valid verdict does not guarantee the charge will be approved.
Reports summary
Requires API keyYour own order totals over a recent range: how many orders, their value, the
average order, a breakdown by calendar month and the products you order most.
Key-scoped: you can never see or probe another partner's orders. An account with
no orders in the range gets a normal 200 with zeros and empty lists,
never a 404.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| months | integer | optional | How many calendar months to cover, counting the current one. Exactly 3, 6 or 12; anything else, including 03 or 12.0, answers 422 `invalid_parameter`. |
The range
months is exactly 3, 6 or 12
(default 12), counting the current month: months=3 covers
this month and the two before it, from the first day of the earliest one. Any other
value, including 03, 12.0 or an empty value, answers
422 invalid_parameter naming months. It is never
silently changed to a range you did not ask for.
What it returns
order_count,order_valueandaverage_order_value: the orders in the range (cancelled ones included) and the sum and mean of their totals, rounded to 2 decimals.by_month: one row per calendar month that has orders, newest first. A month is a month in the shop's local time. Each row hasmonth(YYYY-MM),orders,value,cod_orders,card_ordersandcancelled(how many of that month's orders are cancelled).top_products: up to 10 products, most units first. Each hasproduct_id,combination_id(nullfor a product without combinations),name,quantity(units ordered) andorders(distinct orders containing it).
Values are order totals and nothing else.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/reports/summary?months=6" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"summary": {
"order_count": 3,
"order_value": 350.55,
"average_order_value": 116.85,
"by_month": [
{
"month": "2026-08",
"orders": 2,
"value": 300,
"cod_orders": 1,
"card_orders": 1,
"cancelled": 1
},
{
"month": "2026-07",
"orders": 1,
"value": 50.55,
"cod_orders": 1,
"card_orders": 0,
"cancelled": 0
}
],
"top_products": [
{
"product_id": 9597,
"combination_id": 41206,
"name": "Example product",
"quantity": 4,
"orders": 1
},
{
"product_id": 12402,
"combination_id": null,
"name": "Another product",
"quantity": 3,
"orders": 2
}
]
}
},
"meta": null,
"error": null
}Your account
Requires API keyYour own account in one read: its name, whether it is active, paused or closed, what your
key may do, your request limits, whether a payout method is saved and the
withdrawal rules. Key-scoped, and the same shape for every partner. Once you are
authenticated it always answers 200.
What it returns
shop_display_name: the name on Mart's records for your shop, or your first and last name when none was set.status:active,pausedorclosed. A paused account takes no new orders:POST /ordersandPOST /orders/validateanswer422 orders_not_enabled. Reads and cancelling an order keep working. A closed account is closed for good: it takes no orders, and its key keeps at most reading its money and asking for withdrawals.orders_enabled: whetherPOST /orderswill take an order now. It istrueonly when your key is enabled for orders and the account is active.card_enabled: whether your key may send card orders.price_override_allowed,free_shipping_allowed: whether you may send your own selling price on a line, andfree_shippingon a cash order.rate_limits:{per_minute, per_day}, your key's request limits across the API. Some endpoints also have a tighter limit of their own.payout_method_saved:truewhen a payout method is saved on the account.withdrawals:{enabled, minimum, max_open_requests}.minimum(ILS) andmax_open_requestsarenullwhen withdrawals are off, or when no number has been set.money:{available}, whether the money endpoints can be read right now.
When the money cannot be read
This is not an error here. money.available is false
and everything else is answered as usual; the money endpoints themselves answer
503 ledger_unavailable.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/account" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"account": {
"shop_display_name": "Al Noor Shop",
"status": "active",
"orders_enabled": true,
"card_enabled": false,
"price_override_allowed": true,
"free_shipping_allowed": false,
"rate_limits": {
"per_minute": 120,
"per_day": 20000
},
"payout_method_saved": false,
"withdrawals": {
"enabled": false,
"minimum": null,
"max_open_requests": null
},
"money": {
"available": true
}
}
},
"meta": null,
"error": null
}Balance
Requires API keyYour account's money in one read. Key-scoped: it is your own balance and nobody
else's. An account with no movements yet is a normal 200 of zeros.
What it returns
currency: alwaysILS. Every amount is a number with 2 decimals.balance: everything earned less everything paid out or deducted, including earnings that are still held. It is negative when the account owes.available: what may be taken out now. Never negative.held: earned and not yet matured. It becomes available at its maturity date.next_maturity:{at, amount}, the next part ofheldto become available, ornullwhen nothing is held.owed: a debt the account carries,0when there is none.under_review: earned money held back because its order is not delivered right now, for example during a ticket or an exchange. It is never inavailable, and becomes available again once the order is delivered.0when nothing is held this way.pending: what your orders that are not delivered yet will earn once they are. Not money yet: never inbalance,available, a statement or a withdrawal. Exact, so it can be negative (an order whose remaining products earn less than the delivery it funds).nullwhen there is no exact figure.pending_state:ok(pendingis exact),incomplete(Mart is checking at least one of those orders; the total comes back once it has, and a partial total is never given) orunavailable(it cannot be given right now).
balance but move from
available to under_review until the order is delivered again.
If the order is cancelled or returned they are reversed as usual. A charge always counts.
balance: payments and charges count in it too.
When it cannot be answered
If the balance cannot be read, the answer is 503 ledger_unavailable,
never zeros: a partner who sees 0.00 reads it as "nothing owed". There is
no Retry-After; retry later with backoff. This does not affect any other
endpoint.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/balance" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"balance": {
"currency": "ILS",
"balance": 210,
"available": 160,
"held": 50,
"next_maturity": {
"at": "2026-08-10T09:40:12+00:00",
"amount": 50
},
"owed": 0,
"pending": 75,
"pending_state": "ok",
"under_review": 0
}
},
"meta": null,
"error": null
}Ledger
Requires API keyYour account's movements, newest first. Page with page and
limit until meta.pagination.has_next is false.
Key-scoped. An account with no movements gets entries: [].
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| page | integer | optional | Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`. |
| limit | integer | optional | Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`. |
What a movement carries
entry_id: opaque, stable for the entry. De-duplicate pages on it.type:earning,reversal,paymentoradjustment. A value not listed here may appear later (for exampleother): treat it as informational.amount: signed. A credit to you is positive; a payment to you or a deduction is negative.partner_reference: your own reference for the order, on the earning and the reversal of one of your API orders.nullfor everything else, and also for an order placed with another API key of your account: the ledger belongs to the account, but a reference is only resolved for the key you call with.payment_method: how a payment was made, when it says.occurred_at,recorded_at: when it happened and when it was entered. The entry belongs to the statement whose period containsrecorded_at.available_atandstate: for an earning or a reversal,helduntilavailable_atandavailableafter it.nullfor the other types.
meta.pagination.total is the number of entries on the
account when the first part was read.
If the ledger cannot be read, the answer is 503 ledger_unavailable,
never an empty list.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/ledger?limit=20" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"entries": [
{
"entry_id": "MTIz",
"type": "earning",
"amount": 18,
"partner_reference": "100245",
"payment_method": null,
"occurred_at": "2026-08-03T09:40:12+00:00",
"recorded_at": "2026-08-03T09:40:13+00:00",
"available_at": "2026-08-10T09:40:12+00:00",
"state": "held"
}
]
},
"meta": {
"pagination": {
"page": 1,
"limit": 50,
"total": 1,
"total_pages": 1,
"has_next": false
}
},
"error": null
}List statements
Requires API keyYour finalized statements, newest first. Key-scoped. An account with none gets
statements: []; a statement that is still being prepared is not listed.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| page | integer | optional | Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`. |
| limit | integer | optional | Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`. |
opening and closing are the balance at the start and at
the end of the period, and they include earnings that were still held. They are not
an amount that could be paid out: read available on
Balance for that.
Each row carries number, period_start (inclusive),
period_end (exclusive), opening, closing and
finalized_at. Use number to
read one statement with its movements.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/statements" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"statements": [
{
"number": 12,
"period_start": "2026-07-01T00:00:00+00:00",
"period_end": "2026-08-01T00:00:00+00:00",
"opening": 120.5,
"closing": 210,
"finalized_at": "2026-08-01T02:00:00+00:00"
}
]
},
"meta": {
"pagination": {
"page": 1,
"limit": 50,
"total": 1,
"total_pages": 1,
"has_next": false
}
},
"error": null
}Get statement
Requires API keyOne finalized statement and the movements that belong to it. Key-scoped.
Path parameters
| Name | Type | Description | |
|---|---|---|---|
| statement_number | integer | required | The statement's `number`: digits only, no leading zero. |
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| page | integer | optional | Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`. |
| limit | integer | optional | Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`. |
Its movements
movements are the entries recorded in the statement's period,
from period_start up to but not including period_end, oldest
first, in the same shape as the ledger. A movement belongs
to the period in which it was recorded, which can differ from
occurred_at. The movements are paged with page and
limit; meta.pagination.total counts the period.
The statement is a balance snapshot: opening and closing
include held earnings and are not a payout entitlement.
A number that is not yours
A number your account does not have answers 404 statement_not_found,
exactly as a number that does not exist does. The number is digits only, with no
leading zero.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/statements/12" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"statement": {
"number": 12,
"period_start": "2026-07-01T00:00:00+00:00",
"period_end": "2026-08-01T00:00:00+00:00",
"opening": 120.5,
"closing": 210,
"finalized_at": "2026-08-01T02:00:00+00:00",
"movements": [
{
"entry_id": "MTIz",
"type": "earning",
"amount": 18,
"partner_reference": "100245",
"payment_method": null,
"occurred_at": "2026-08-03T09:40:12+00:00",
"recorded_at": "2026-08-03T09:40:13+00:00",
"available_at": "2026-08-10T09:40:12+00:00",
"state": "held"
}
]
}
},
"meta": {
"pagination": {
"page": 1,
"limit": 50,
"total": 1,
"total_pages": 1,
"has_next": false
}
},
"error": null
}Your payout method
Requires API keyHow your money is paid, in full: cash at Mart's office, or a bank transfer to your IBAN where Mart offers that to your account. It is yours: only your key reads it. Key-scoped, and the same for every partner.
What it returns
status:not_set(nothing saved, every other field isnull),active, orlocked.method:bankorcash;nullwhile nothing is saved. A withdrawal is paid by it, and only once one is saved. While a bank transfer is not offered to your account, an IBAN you saved before is kept and shown, but a withdrawal on it is refused until you save cash.iban,iban_country,account_holder_name,national_id: what you saved. The IBAN is upper case without spaces.national_idisnullwhen you saved none. For cash,ibanandiban_countryarenull, andaccount_holder_nameandnational_idare the name and ID number of the person who collects the money.pickup_instructions: for cash, where and when to collect (Mart's office address and hours, as Mart wrote them).nullfor a bank transfer, and when Mart has none published right now.updated_at: the last change.withdrawals_locked_until: whilestatusislocked, when withdrawals can start. Saving the IBAN for the first time, changing it, switching between bank and cash, and for cash changing the collector, locks withdrawals for a number of hours Mart sets for your account. A paused account can read this.
If the ledger cannot be read, the answer is 503 ledger_unavailable,
never not_set.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/payout-method" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"payout_method": {
"status": "locked",
"iban": "PS92PALS000000000400123456702",
"iban_country": "PS",
"account_holder_name": "Al Noor Shop",
"national_id": null,
"updated_at": "2026-11-06T09:30:00+00:00",
"withdrawals_locked_until": "2026-11-08T09:30:00+00:00",
"method": "bank",
"pickup_instructions": null
}
},
"meta": null,
"error": null
}Save your payout method
Requires API keySaves how your money is paid. For a bank transfer send iban,
account_holder_name and, if you want one, national_id;
method may be left out, exactly as before cash existed. For cash at Mart's
office, where Mart offers it to your account, send "method": "cash", the full
name of the person who will collect the money as account_holder_name and, if you
want, their ID number as national_id; no IBAN. Leaving national_id
out keeps the one already saved; sending null or an empty string clears it.
A switch between bank and cash never carries the ID number over: leaving
national_id out on a switch clears it, so send it whenever the collector (or,
back to bank, the account holder) has one.
Request body (PayoutMethodRequest)
| Field | Type | Description | |
|---|---|---|---|
| method | string | optional | Optional. `bank` (the default when left out) or `cash`. `cash` is accepted only when Mart offers it to your account (`403` `cash_not_allowed`), and `bank` only when Mart offers a bank transfer to your account (`422` `bank_transfer_not_allowed`). You cannot switch between the two while a withdrawal is open (`409` `payout_method_change_blocked`). |
| iban | string | optional | Required for a bank transfer, ignored for cash. Spaces and case are ignored. Up to 34 characters once cleaned. |
| account_holder_name | string | required | 2 to 70 characters, letters first. Names in any script, including Arabic. For cash, the full name of the person who will collect the money, as on their ID card. |
| national_id | string | optional | Optional. 5 to 32 letters, digits or hyphens. Arabic digits are accepted and stored as 0 to 9. Omitted keeps the saved one, except on a switch between bank and cash, which clears it; `null` or an empty string clears it. For cash, the collector's ID number: send it on the switch. |
What is checked
methodisbankorcash, in lower case (422 invalid_payout_method). A request without it meansbank, so on a cash account it switches back to a bank transfer and needs an IBAN.- Cash only where Mart offers it to your account:
403 cash_not_allowedotherwise. Cash too is saved once before your first cash withdrawal, naming who collects: yourself, or someone else with their ID number. - A bank transfer only where Mart offers it to your account:
422 bank_transfer_not_allowedotherwise, before the IBAN is checked, and nothing is saved. - No switch between bank and cash while a withdrawal is requested or approved:
409 payout_method_change_blocked. Cancel it first, or wait until it is paid or rejected; every request is paid the way it was made. - The IBAN may be typed with spaces or in lower case. Its check digits, its length for the country and its country are checked, and only the countries Mart has enabled for your account are accepted.
- The account holder name is 2 to 70 characters and starts with a letter, in any script.
- The national ID, if sent, is 5 to 32 letters, digits or hyphens. Arabic digits are accepted and stored as 0 to 9.
The lock
Saving an IBAN for the first time, and every later change of the IBAN, locks
withdrawals for a number of hours Mart sets for your account (a change never shortens a lock still running); the response shows when
in withdrawals_locked_until. A switch between bank and cash locks the same way,
and so does, for cash, a change of the collector's name or ID number: the collector is who
receives the money. For a bank transfer, changing only the name or the national ID does
not lock. Saving what is already saved changes nothing and starts no lock. Every change
is recorded with who made it.
Refusals
403 withdrawals_disabled when withdrawals are not enabled for your
account. 422 invalid_iban says why in error.details.reason
(format, country_not_allowed, length,
checksum or bban), with country and
expected_length where they apply. No error repeats what you sent. A paused
account can save. If the ledger cannot be read the answer is
503 ledger_unavailable and nothing is saved.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s -X PUT https://mart.ps/api/v1/payout-method \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "iban": "PS92 PALS 0000 0000 0400 1234 5670 2", "account_holder_name": "Al Noor Shop" }'{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"payout_method": {
"status": "locked",
"iban": "PS92PALS000000000400123456702",
"iban_country": "PS",
"account_holder_name": "Al Noor Shop",
"national_id": null,
"updated_at": "2026-11-06T09:30:00+00:00",
"withdrawals_locked_until": "2026-11-08T09:30:00+00:00",
"method": "bank",
"pickup_instructions": null
}
},
"meta": null,
"error": null
}List your withdrawals
Requires API keyYour withdrawal requests, newest first. Page with page and
limit until meta.pagination.has_next is false,
and narrow with status. Key-scoped: you only ever see your own.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| status | string | optional | Only requests in this status: `requested`, `approved`, `paid`, `rejected` or `cancelled`. Anything else answers 422 `invalid_parameter`. |
| page | integer | optional | Page number, from 1. Anything that is not a positive integer answers 422 `invalid_parameter`. |
| limit | integer | optional | Rows per page, 1 to 100 (default 50). Anything else answers 422 `invalid_parameter`. |
What a request carries
withdrawal_id: opaque. Use it to read or cancel the request.amountandstatus:requestedandapprovedare open and hold their amount back from theavailablefigure of Balance.paidis final and shows in your Ledger as apayment.rejectedandcancelledrelease the amount.iban: the IBAN the request will be paid to, fixed when Mart approved it, so a later change of your payout method cannot redirect it.nullbefore that, and always for cash.method:bankorcash, fixed when you made the request. A cash request goes fromrequestedstraight topaid, so itsapproved_atstaysnull.requested_amount: what you asked for.amountis what is (or was) paid; the two differ only when a cash request was paid at another amount at the office counter.reject_reason: why Mart rejected it, in one line, otherwisenull.requested_at,approved_at,paid_at.
The list works whether or not withdrawals are enabled for your account right now, and
while the account is paused. A status that does not exist answers
422 invalid_parameter. If the ledger cannot be read, the answer is
503 ledger_unavailable, never an empty list.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/withdrawals?status=approved" \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"withdrawals": [
{
"withdrawal_id": "NDE",
"amount": 125,
"status": "approved",
"iban": "PS92PALS000000000400123456702",
"reject_reason": null,
"requested_at": "2026-11-01T08:30:00+00:00",
"approved_at": "2026-11-02T09:00:00+00:00",
"paid_at": null,
"method": "bank",
"requested_amount": 125
}
]
},
"meta": {
"pagination": {
"page": 1,
"limit": 50,
"total": 1,
"total_pages": 1,
"has_next": false
}
},
"error": null
}Ask to withdraw
Requires API keyAsks Mart to pay out part of what is available. Send amount and your own
idempotency_key. Mart reviews each request by hand: nothing is paid at this
call, and the request holds its amount back from available until it is paid,
rejected or cancelled. A request is paid the way your payout method says when you make it
(method).
Request body (WithdrawalRequest)
| Field | Type | Description | |
|---|---|---|---|
| amount | object | required | A positive amount in shekels: a JSON number or a decimal string, with at most two decimals. Anything else, including three decimals, answers `422` `invalid_amount`. |
| idempotency_key | string | required | Your key for this request, unique per request you mean to make. Sending the same key and amount again answers the original request with `200`; the same key with another amount answers `409` `idempotency_conflict`. **Keys are compared without regard to case**: `AB` and `ab` are the same key. |
The amount
Shekels, as a JSON number or a decimal string, with at most two decimals
(125, 125.5, "125.50"). A third decimal is refused
with 422 invalid_amount, never rounded.
Retrying safely
idempotency_key is 1 to 64 letters, digits, dots, underscores or hyphens.
Send the same key and amount again and you get the original request back with
200 and meta.idempotency_replay: true, whatever has changed since;
never a second request. The same key with another amount is
409 idempotency_conflict. Keys are compared without regard to
case: AB and ab are one key. If the answer is
503 withdrawal_busy, wait Retry-After seconds and retry with the
same key.
What is checked, in this order
- A repeat of an earlier request is answered first.
- Withdrawals must be enabled for your account:
403 withdrawals_disabled. - A payout method must be saved and not locked:
409 payout_method_missing(cash too is saved once),409 withdrawals_locked(details.locked_until). - A saved IBAN is paid to only where a bank transfer is offered to your account:
422 bank_transfer_not_allowedotherwise. Save cash instead. - When it is cash: cash must still be offered to your account,
403 cash_not_allowed(switch to a bank transfer), and the amount must not exceed the most Mart pays in cash at once when Mart has set one,422 amount_above_cash_maximum(details.maximum). - The amount must reach the minimum your account has, if any:
422 amount_below_minimum(details.minimum). - You must be under the limit of open requests:
409 too_many_open_withdrawals(details.maximum). - The amount must not exceed
available:409 insufficient_available(details.available).
Cash at the office
A cash request goes from requested straight to paid: the
collector brings an ID card to the office, and the cash is handed over once Mart has
recorded the payment. At the counter the amount may change, within what is available:
amount is then what was paid, and requested_amount keeps what you
asked for. Retrying the original request with the same key and amount still answers
200 with that request.
A paused account can ask. If the ledger cannot be read the answer is
503 ledger_unavailable and nothing is recorded.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s -X POST https://mart.ps/api/v1/withdrawals \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "amount": 125.50, "idempotency_key": "wd-2026-11-01-001" }'{
"status": "success",
"status_code": 201,
"message": "Created",
"data": {
"withdrawal": {
"withdrawal_id": "NDE",
"amount": 125,
"status": "requested",
"iban": null,
"reject_reason": null,
"requested_at": "2026-11-01T08:30:00+00:00",
"approved_at": null,
"paid_at": null,
"method": "bank",
"requested_amount": 125
}
},
"meta": {
"idempotency_replay": false
},
"error": null
}Get a withdrawal
Requires API keyOne of your withdrawal requests, in the shape of a list item. Use the
withdrawal_id a request or the list returned, exactly as returned.
Path parameters
| Name | Type | Description | |
|---|---|---|---|
| withdrawal_id | string | required | The `withdrawal_id` a request or the list returned, exactly as returned. Anything else answers 404 `withdrawal_not_found`, the same answer as another account's id. |
An id that belongs to another account answers exactly as an id that does not exist, or
that this API never issued: 404 withdrawal_not_found. If the ledger cannot be
read the answer is 503 ledger_unavailable.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s https://mart.ps/api/v1/withdrawals/NDE \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"withdrawal": {
"withdrawal_id": "NDE",
"amount": 125,
"status": "approved",
"iban": "PS92PALS000000000400123456702",
"reject_reason": null,
"requested_at": "2026-11-01T08:30:00+00:00",
"approved_at": "2026-11-02T09:00:00+00:00",
"paid_at": null,
"method": "bank",
"requested_amount": 125
}
},
"meta": null,
"error": null
}Cancel a withdrawal
Requires API keyTakes a request back while it is still requested: its amount is released
at once. No body is read.
Path parameters
| Name | Type | Description | |
|---|---|---|---|
| withdrawal_id | string | required | The `withdrawal_id` a request or the list returned, exactly as returned. Anything else answers 404 `withdrawal_not_found`, the same answer as another account's id. |
Cancelling a request that is already cancelled answers 200
again and changes nothing. An approved, paid or
rejected request answers 409 withdrawal_not_cancellable. An id that
belongs to another account answers 404 withdrawal_not_found, as one that does
not exist. Cancelling still works when withdrawals are no longer enabled for your account.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s -X POST https://mart.ps/api/v1/withdrawals/NDE/cancel \
-H "Authorization: Bearer $MART_API_KEY"{
"status": "success",
"status_code": 200,
"message": "OK",
"data": {
"withdrawal": {
"withdrawal_id": "NDE",
"amount": 125,
"status": "cancelled",
"iban": null,
"reject_reason": null,
"requested_at": "2026-11-01T08:30:00+00:00",
"approved_at": null,
"paid_at": null,
"method": "bank",
"requested_amount": 125
}
},
"meta": null,
"error": null
}Events
Requires API keyWhat happened to your account, oldest first, as one feed with a cursor: orders, ledger
movements, withdrawals and your payout method. Store meta.next_cursor and ask
again with after. Key-scoped.
Query parameters
| Name | Type | Description | |
|---|---|---|---|
| after | string | optional | 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`. |
| limit | integer | optional | Events per page, 1 to 500 (default 100). Anything else answers 422 `invalid_parameter`. |
| start | string | optional | `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`. |
What an event carries
cursor: opaque, where this event stands in the feed. De-duplicate on it.type:order.created,order.status_changed,ledger.entry_posted,withdrawal.requested,withdrawal.approved,withdrawal.rejected,withdrawal.cancelled,withdrawal.paidorpayout_method.changed. A type not listed here may appear later: treat it as informational.reference: yourpartner_referencefor an order or a ledger movement of one, thewithdrawal_idfor a withdrawal, otherwisenull.occurred_at: when it happened, in UTC.payload: the matching read's row at that moment.order.*is aGET /ordersitem,ledger.entry_postedaGET /ledgeritem,withdrawal.*aGET /withdrawalsitem withoutiban(so with itsmethodandrequested_amount), andpayout_method.changedis{version, updated_at}and nothing of what it holds.
Reading it
meta.next_cursor is there even on an empty page. 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 and not your
last event's cursor. meta.has_more is true when more may be ready now, so
ask again at once, and that page can be empty; false means nothing more right now, not the end, so poll again
later. With no after you read from the oldest event kept.
start=latest answers an empty page whose next_cursor is the head of
the feed, to start from now.
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. Use occurred_at for cause and effect.
An after this feed did not issue answers 422 invalid_cursor. That
includes a blank one, so a cursor your system lost never silently replays everything, and one
above anything the feed has given out, which means the store was restored or reseeded under a
cursor you kept: leave after out to start over, or send
start=latest.
An after older than what the feed still keeps answers
410 cursor_expired with details.resync: true, never a page with a gap
in it. Events are kept for good unless a retention period is set for your account, and a consumer
that reads to the end of the feed at least once within that period stays ahead of it. If you do get
it, first send start=latest and keep that next_cursor. Then rebuild what
you hold from GET /orders, GET /ledger and GET /withdrawals,
and read on from the cursor you kept. Do it in that order, or what happens during the rebuild is
lost, and apply events so that one already in your rebuild does not count twice. Your orders and
your money are untouched. A read with no after is never refused.
An event can arrive late. If it could not be written when the change happened,
Mart writes it afterwards, once. It carries the original occurred_at and a new place
in the feed, so it can follow newer events. A late order.created shows the order as
it is when written, so its status can be newer than its occurred_at. Nothing from
before your account's feed began is ever written late.
Responses
Every error code is explained, with what to do about it, in Errors & rate limits.
curl -s "https://mart.ps/api/v1/events?after=djE6NDI&limit=100" \
-H "Authorization: Bearer $MART_API_KEY"{
"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
}Idempotency & retries
partner_reference is your own order id
and the idempotency key. Send it exactly as it appears in your
system — it is stored, matched and returned byte-for-byte.
Letters, digits, dot, underscore and hyphen; 64 characters maximum; surrounding whitespace is rejected, never trimmed. Unique per key: the same value under another partner's key is an unrelated order.
The timeout procedure — the part that goes wrong
If your request times out or the response is lost, you do not know whether the order was created. The procedure:
partner_reference. If the original
succeeded you get 200 with
meta.idempotency_replay: true and the original order; if it did
not, the order is created now and you get 201. Either way:
exactly one order. The idempotency check runs before any
catalog check, so a retry is never rejected over stock, price or product
status — including the stock your own original order consumed.
partner_reference to "try again" after a
timeout. That is how duplicate orders are created — the reference is the only
thing tying your retry to the original.
"Identical" is judged on a canonical form
These do not count as differences:
| Ignored | Example |
|---|---|
| JSON key order | {"products":…,"partner_reference":…} ≡ the other order |
| Surrounding / repeated whitespace | " محمد نور " ≡ "محمد نور" |
| Number formatting | 120 ≡ "120.00" ≡ 120.0 |
| Boolean spelling | true ≡ "true" ≡ "1" ≡ "yes" |
| Unicode composition | the same Arabic text composed either way |
| Unknown extra fields | ignored entirely |
| Omitted vs explicit null | notes absent ≡ "notes": null; the same for extra_phone |
What does count: any change to
partner_reference, shipping_address,
free_shipping, or products — including
reordering the products array, which is significant.
partner_reference, and replay that stored body verbatim rather
than rebuilding it. Rebuilding risks picking up a refreshed price or a
reordered basket, which turns a safe replay into a 409.
The replay is a frozen record, not a live view
A replay returns the original response, byte for byte —
frozen at creation, unaffected by later catalog movement, and
status is frozen with it. Do not poll the replay to track order
progress; poll Get order instead.
Conflicts
Reusing a reference for a genuinely different order answers
409 idempotency_conflict with
details.original_order_id and
details.original_created_at; the original is never modified. If
you see this, your reference generation has a bug. Two requests with the same
reference racing each other answer
503 order_creation_in_progress on the loser — wait and retry to
get the replay. The same answer is given, briefly, to a second order for a
recipient (same name and phone) whose first order is still being created:
retry after Retry-After and it is created normally.
Cancellation is idempotent the same way:
repeating the cancel request is always safe, answers 200 with
already_cancelled: true, and is also what completes a
cancellation whose response you never received.
Errors & rate limits
A failure keeps the envelope: data and
meta are null and error carries
{code, details}. Branch on error.code, never on
message.
{
"status": "fail",
"status_code": 422,
"message": "...",
"data": null,
"meta": null,
"error": {
"code": "insufficient_stock",
"details": { "index": 3, "requested": 5, "available": 2 }
}
}On product-line errors details always carries
index, the zero-based position in your products array
— log it; it is what makes a 40-line order debuggable. Two rules cover most of
it: every 422 means nothing was created — fix
what the code names and resubmit under the same
partner_reference; and on a timeout, retry the identical
request with the same reference
(the procedure). Retry 429 and
500 with backoff; never retry a 422 unchanged; alert
a human on 401, 403 and repeated 500.
Every error code
| Code | HTTP | What it means | What to do |
|---|---|---|---|
| Access & transport | |||
| missing_api_key | 401 | No API key was sent, or the Authorization / X-Api-Key header is malformed. | Fix the header. Do not retry unchanged. |
| invalid_api_key | 401 | The key is unknown, revoked, or paused. Revoked and paused keys answer exactly like unknown ones. | Alert a human. Retrying does not help; contact Mart for a replacement key. |
| key_environment_mismatch | 401 | The key was issued for the other environment: a sandbox key (mk_test_…) sent to production, or a production key (mk_live_…) sent to the sandbox. details.environment names the environment you called; whether the key exists is never checked. | Fix the base URL, or use the key issued for this environment. Do not retry unchanged. |
| api_customer_not_configured | 403 | The account behind your key is missing or inactive. Not something your request can fix. | Contact Mart. |
| customer_group_not_allowed | 403 | Your account is not currently in a group permitted to use the API. Membership is re-checked on every request, so access resumes on its own once corrected. | Contact Mart; no client-side change helps. |
| insufficient_scope | 403 | Your key does not have the scope this endpoint needs. details.required_scope names it. Checked right after the key, before the rate limit, so the refusal uses none of your quota. Keys made before scopes existed keep exactly the access they had. Order writes are answered orders_not_enabled (422) instead, as they always were. | Ask Mart to give your key that scope (see Keys and scopes). Do not retry unchanged. |
| route_not_found | 404 | The URL does not match any endpoint. A malformed product id (/products/ABC, /products/0, leading zeros) or a malformed partner reference lands here rather than reaching a controller. | Fix the URL. If it happens on a path you know exists, that is a routing fault on our side — tell us. |
| method_not_allowed | 405 | Wrong HTTP verb for this endpoint. Read endpoints are GET-only; order validation and cancellation are POST-only; the orders collection takes GET (list) and POST (create). | Read the Allow response header rather than assuming, and use the verb it lists. |
| rate_limit_exceeded | 429 | A per-minute or per-day budget is exhausted. Retry-After gives seconds; a daily breach advertises the daily reset, not 60 seconds. Denied requests still consume budget. | Wait out Retry-After, then resume. Back off when X-RateLimit-Remaining gets low instead of hammering. |
| internal_error | 500 | A server-side failure. Details are logged on our side and never exposed in the response. | Retry with exponential backoff. If it persists, contact Mart with the timestamp. |
| Request shape | |||
| bad_request | 400 | The body is empty, is not valid JSON, or is not a JSON object. | Fix the body. The same partner_reference may be reused. |
| invalid_parameter | 422 | A field is missing, the wrong type, or out of range; details.parameter names it and item-level ones carry details.index. Includes a partner_reference with disallowed characters or surrounding whitespace (references are rejected, never trimmed) and a missing, null, wrongly-cased or unknown payment_type (cod/card, exact lowercase, required — never defaulted). | Fix the named field and resend under the same partner_reference. |
| product_not_found | 404 | Product detail only: the id is well formed but no such product exists. Distinct from route_not_found, which means the URL itself was malformed. | Your local catalog is stale — re-sync it. |
| order_not_found | 404 | Order read/cancel only: no order with that partner_reference on YOUR account. Identical whether it never existed or belongs to another partner — the response never reveals which. | Check your own order records; you can never see or probe another partner's orders. |
| Order creation — configuration | |||
| orders_not_enabled | 422 | Order creation is not enabled for your key. Catalog and stock access are unaffected. | Ask Mart to enable it, then resend under the same partner_reference. |
| api_group_misconfigured | 422 | Your account is not set up for API settlement. Nothing in the request can change this. | Contact Mart; resend under the same reference once fixed. |
| Order creation — basket | |||
| invalid_state | 422 | shipping_address.state_id is unknown or not currently deliverable. Only a leaf states[].id from GET /api/v1/states is valid — a city id is a different id space and is never accepted. | Refresh the destinations list and correct the id. |
| unknown_product | 422 | No product has that product_id. Usually a stale local catalog. | Refresh that product, then your catalog; remove the line if it is gone. |
| product_not_offered | 422 | This product is not available to your account. details.product_id names it and details.index the line. | Remove the line. GET /api/v1/products/ids lists what your account can order. |
| product_not_orderable | 422 | The product exists but cannot be sold right now. details.reason is inactive or not_available_for_order. | Remove the line; do not retry until the product returns. |
| combination_required | 422 | The product has variants and you sent no combination_id. | Send the variant's combination id from the product detail. |
| combination_not_allowed | 422 | The product has no variants but you sent a combination_id. | Send null or omit the key for that product. |
| unknown_combination | 422 | No variant has that id. | Re-sync the product detail and reselect the variant. |
| combination_mismatch | 422 | That variant belongs to a different product; details.belongs_to_product_id says which. Usually a wiring bug on the sending side. | Fix the pairing and resend. |
| duplicate_product | 422 | The same (product_id, combination_id) appears twice; details.first_index points at the earlier line. | Merge the lines into one entry with a higher quantity. |
| insufficient_stock | 422 | Not enough stock for one line, checked live against the exact product or combination row. details.requested and details.available give the gap; details.index names the line. The whole order was rejected and nothing was created. | Reduce the quantity or remove the line, then resend under the same reference. |
| price_below_minimum | 422 | Your price is under price.group_price for your account at the moment of creation — never public_price or base_price. details.minimum is the floor that applied; selling exactly at it passes. | Refresh that product's price, re-price the line (confirm with your customer if it rose), and resend. |
| price_override_not_allowed | 422 | Your group may not set custom prices: a supplied price is accepted only when it equals the catalog price exactly, and details.expected is that price. Nothing you send is ever silently replaced. | Omit price entirely (sells at the group price), or send exactly details.expected. |
| free_shipping_not_covered | 422 | With free_shipping: true, your margin does not cover the delivery fee. details gives gross_reward, shipping_fee and shortfall. The fee depends on the destination AND the order total, so changing prices can change the fee to cover. | Raise your prices by the shortfall, or resend with free_shipping: false and let the customer pay delivery. |
| free_shipping_not_allowed | 422 | Your group may not absorb delivery fees. true is rejected, never silently changed. | Send free_shipping: false or omit it; the customer pays the fee. |
| cart_minimum_not_met | 422 | A product in this order carries a minimum-order threshold the total does not reach. Not expected for API orders under the current configuration; the code stays documented as defence in depth. | Add more products or remove the item, then resend. |
| Card payment | |||
| card_not_enabled | 422 | payment_type: "card" is a valid value but card payment is not enabled for your key. | Send payment_type: "cod", or ask Mart about card enablement. |
| card_not_on_file | 422 | No reusable saved card is on file for your account. | Complete the card-setup step with Mart before sending card orders. |
| saved_card_invalid | 422 | The gateway confirmed your saved card can no longer be charged. Nothing was charged and no order was created. | Re-add or update the card with Mart, then retry under the same reference — retrying before that changes nothing. |
| card_price_not_allowed | 422 | products[].price is not accepted with card payment (carries details.index), even when it equals the group price: a partner-supplied price can never influence a server-computed charge. The group price is what is charged. | Omit price on every product in a card order. |
| card_free_shipping_not_allowed | 422 | free_shipping cannot be combined with card payment — a card order has no margin to absorb the fee from. | Omit the field or send false. |
| card_declined | 402 | The gateway declined the charge. No order was created and nothing was captured. details.gateway_response carries the decline reason; after several declines details.attempts_exhausted is true and the reference is terminally declined. | Retry the same partner_reference for a fresh attempt (never a double charge). Once attempts are exhausted, fix the card with Mart and submit a NEW reference. |
| payment_gateway_unavailable | 503 | The payment gateway did not answer and the charge outcome is unknown. No order was created. | Retry the same partner_reference after Retry-After seconds; the retry reconciles any charge that did land and never double-charges. |
| Money | |||
| ledger_unavailable | 503 | Your balance, ledger, statements, payout method, withdrawals or events cannot be answered right now, including when the order reference of an entry cannot be read (it is never returned as null in its place). This is never answered with zeros or an empty list, because a figure that looks like "nothing owed" would be wrong. There is no Retry-After. | Retry later with backoff, and show your partner that the balance is unavailable rather than a figure. If it persists, contact Mart. |
| withdrawals_disabled | 403 | Withdrawals are not enabled for your account, so a payout method cannot be saved and no withdrawal can be requested. Reading them, and cancelling a request, still work. | Ask Mart to enable withdrawals for your account. Do not retry unchanged. |
| cash_not_allowed | 403 | Cash at the office is not offered to your account right now: Mart has not allowed it for your account, or has no pickup instructions published. On a payout method save nothing was saved. On a withdrawal request your saved payout method is cash, so no new request can be made; a cash request already open can still be collected. | Where a bank transfer is offered to your account, save a payout method with an IBAN (cancel any open request first), then ask again. Ask Mart if you expected cash to be offered. |
| bank_transfer_not_allowed | 422 | A bank transfer is not offered to your account. On a payout method save nothing was saved. On a withdrawal request your saved payout method is an IBAN: it is kept, never deleted, but not paid to while a bank transfer is not offered, so no request can be made on it. | Save cash at the office with PUT /api/v1/payout-method (method cash) where Mart offers it to your account, then ask again; or ask Mart if you expected a bank transfer to be offered. |
| invalid_iban | 422 | The IBAN was refused. details.reason says why: format (not an IBAN), country_not_allowed (the country is not enabled for your account), length (details.expected_length is the length for details.country), checksum (a typing mistake) or bban (the account part has the wrong shape for the country). The error never repeats what you sent. | Check the IBAN against your bank statement and send it again. |
| invalid_account_holder_name | 422 | The account holder name was refused: it must be 2 to 70 characters, start with a letter, and contain only letters, digits, spaces and . ' & -. | Send the name exactly as the bank holds it. |
| invalid_national_id | 422 | The national ID was refused: it must be 5 to 32 letters, digits or hyphens, starting with a letter or digit. Leave it out, or send null, when you have none. | Correct the ID, or omit the field. |
| invalid_payout_method | 422 | The payout method must be bank or cash, in lower case. Leaving method out means bank. | Send method as bank or cash, or leave it out for a bank transfer. |
| statement_not_found | 404 | Statements only: your account has no statement with that number. Identical whether it never existed or belongs to another account. | List your statements and use a number from that list. |
| invalid_amount | 422 | The withdrawal amount was refused: it must be a positive number, or a decimal string, with at most two decimals, and not beyond what the system can hold. | Send the amount in shekels with at most two decimals, for example 125.50. |
| amount_below_minimum | 422 | The amount is below the minimum withdrawal set for your account. details.minimum is that minimum. | Ask for at least details.minimum. |
| amount_above_cash_maximum | 422 | Cash requests only: the amount is above the most Mart pays in cash at once. details.maximum is that limit. | Ask for at most details.maximum, or switch to a bank transfer for a larger amount. |
| payout_method_missing | 409 | No payout method is saved for your account, so there is nowhere to pay a withdrawal. Cash at the office too is saved once, naming who collects. | Save one with PUT /api/v1/payout-method, then ask again. |
| withdrawals_locked | 409 | Withdrawals are locked because your payout method was saved, or its IBAN changed, recently. details.locked_until is when the lock ends. | Wait until details.locked_until, then ask again. |
| too_many_open_withdrawals | 409 | Your account already has as many open withdrawal requests as it may have (details.maximum). A request stays open until it is paid, rejected or cancelled. | Wait for one to be paid or rejected, or cancel one that is still requested. |
| payout_method_change_blocked | 409 | The payout method cannot switch between a bank transfer and cash while a withdrawal is requested or approved, so every request is paid the way it was made. Nothing was saved. A change that keeps the same kind is still accepted. | Cancel the open request, or wait until it is paid or rejected, then save again. |
| insufficient_available | 409 | The amount is above what you can withdraw now. details.available is that figure: what has matured, less your open withdrawal requests. | Ask for at most details.available. GET /api/v1/balance shows the same figure as available. |
| withdrawal_busy | 503 | Another call on your account is being processed right now, usually your own retry. This call recorded nothing. | Wait for Retry-After seconds and send the same request again with the same idempotency_key. |
| withdrawal_not_found | 404 | Withdrawals only: your account has no withdrawal with that withdrawal_id. Identical whether it never existed or belongs to another account. | List your withdrawals and use an id from that list. |
| withdrawal_not_cancellable | 409 | The withdrawal can no longer be cancelled: only a request that is still requested can be. Nothing was changed. | Read the withdrawal to see where it got to; contact Mart if it must still be stopped. |
| invalid_cursor | 422 | Events only: after is not a cursor this feed issued. It is malformed, blank, or above anything the feed has given out, which means the store was restored or reseeded under a cursor you kept. | Send a cursor or next_cursor exactly as it was returned. To start over, leave after out, or send start=latest to start from now. |
| cursor_expired | 410 | Events only: after is older than what the feed still keeps. Events past the retention period were removed, so some you had not read may be gone from the feed. Your orders and your money are untouched. details.resync is true. | First send start=latest and keep the next_cursor it returns. Then rebuild what you hold from GET /orders, GET /ledger and GET /withdrawals, and read on from that cursor, applying events so that one already in your rebuild does not count twice. Reading with no after is never refused. |
| Card payment | |||
| charge_amount_mismatch | 409 | A previous attempt already captured a charge for this partner_reference at an amount that no longer matches the current server-computed total (catalog prices moved between attempts). No order was created and no second charge was made. details carries charged, current_total and payment_reference. | Contact Mart to resolve the captured payment; do not resend as-is. |
| Idempotency & concurrency | |||
| idempotency_conflict | 409 | This partner_reference was already used for a DIFFERENT order. details.original_order_id and details.original_created_at identify the original, which is never modified. On a withdrawal it means this idempotency_key was already used for another amount. | This reference is taken — fix your reference generation. Never reuse a reference for a different basket. For a withdrawal, use a new idempotency_key for a new request. |
| order_creation_in_progress | 503 | Another request with this partner_reference — or another order of yours to the same recipient (same name and phone) — is mid-flight right now. Usually your own retry racing the original. | Wait for Retry-After and send the same request again. A retried reference returns the replay of its result; a second order to the same recipient is then created normally. |
| Cancellation | |||
| order_not_cancellable | 409 | The order has moved past the point where partners may cancel it. Which states are cancellable is Mart's configuration; nothing was changed, and details deliberately carry only your reference, never the order's internal state. | Treat as final for this order. Read the order to see where it got to; contact Mart if it must still be stopped. |
| order_cancellation_not_configured | 503 | Partner cancellation is not enabled on this store. Not caused by your request. | Contact Mart; retrying will not help. |
| order_cancellation_in_progress | 503 | Another request is cancelling this same order right now — usually your own retry. Requests against one order are serialised. | Retry after Retry-After seconds and expect already_cancelled: true. |
Rate limits
Limits are enforced per key, on two fixed windows (per minute and per day), at two scopes: a global budget across all endpoints and a per-endpoint budget. Both apply; whichever is tighter is what you hit first. Current defaults — operator-configurable, and your key may carry different values, so the headers are authoritative:
| Scope | Per minute | Per day |
|---|---|---|
| Global (all endpoints combined) | 120 | 20,000 |
| Products | 60 | 10,000 |
| Product detail | 120 | 20,000 |
| Destinations | 60 | 5,000 |
| Order creation | 30 | 2,000 |
limit=1000 every
15 minutes is ~1,920 calls/day: comfortable. Every 30 seconds would be
57,600 and would fail partway through the day.
X-RateLimit-Limit,X-RateLimit-RemainingandX-RateLimit-Reset(epoch seconds) describe the currently tightest window. They appear on all2xxresponses and on errors raised by an endpoint itself; they are absent on401,403,405, aroute_not_found404, and the204preflight.- Exceeding a limit answers
429 rate_limit_exceededwithRetry-Afterin seconds — a daily breach advertises the daily reset, not 60 seconds. Honour the header. - Denied requests still consume budget: hammering during a
429keeps your own counter pinned. Back off whenX-RateLimit-Remaininggets low. - Windows are fixed, not sliding, and the daily window rolls at 00:00 UTC — schedule heavy nightly jobs relative to UTC or they may straddle two daily budgets.
OPTIONS is accepted on every endpoint and answered as a
bodyless 204. Wrong verbs answer 405 with an
Allow header — read it rather than assuming. And watch for a
404 on a path you know exists: that means a routing problem on
our side — tell us.
Code examples
All examples read the key from the MART_API_KEY
environment variable — never hard-code it. Calls must come from your server,
never a browser.
Paged full catalog sync
Pages until meta.pagination.has_next is false,
upserting by product_id. This same loop, run daily without an
updated_after cursor, is your
full price refresh.
# one page; loop over page= until meta.pagination.has_next is false
curl -s 'https://mart.ps/api/v1/products?page=1&limit=500' \
-H "Authorization: Bearer $MART_API_KEY"$page = 1;
do {
$ch = curl_init('https://mart.ps/api/v1/products?page=' . $page . '&limit=500');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MART_API_KEY')],
CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if ($body['status'] !== 'success') {
throw new RuntimeException('sync failed: ' . $body['error']['code']);
}
foreach ($body['data']['products'] as $product) {
upsertProduct($product); // keyed by product_id — update in place
}
$page++;
} while ($body['meta']['pagination']['has_next']);const headers = { Authorization: `Bearer ${process.env.MART_API_KEY}` };
let page = 1, hasNext = true;
while (hasNext) {
const res = await fetch(
`https://mart.ps/api/v1/products?page=${page}&limit=500`, { headers });
const body = await res.json();
if (body.status !== 'success') {
throw new Error(`sync failed: ${body.error.code}`);
}
for (const product of body.data.products) {
await upsertProduct(product); // keyed by product_id — update in place
}
hasNext = body.meta.pagination.has_next;
page++;
}import os, requests
headers = {'Authorization': f"Bearer {os.environ['MART_API_KEY']}"}
page, has_next = 1, True
while has_next:
body = requests.get(
'https://mart.ps/api/v1/products',
params={'page': page, 'limit': 500},
headers=headers, timeout=30,
).json()
if body['status'] != 'success':
raise RuntimeError(f"sync failed: {body['error']['code']}")
for product in body['data']['products']:
upsert_product(product) # keyed by product_id — update in place
has_next = body['meta']['pagination']['has_next']
page += 1Create an order — with the timeout-safe retry
The retry sends the byte-identical stored body under the
same partner_reference. A 201 is a
fresh creation, a 200 with
meta.idempotency_replay: true is your original order — either way,
exactly one order exists (the procedure).
curl -s -X POST https://mart.ps/api/v1/orders \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
--max-time 60 \
-d '{
"partner_reference": "ACME-100245",
"payment_type": "cod",
"shipping_address": {
"customer_name": "محمد نور", "phone": "0599000000",
"extra_phone": "022345678",
"state_id": 431, "address": "شارع المدارس 12"
},
"products": [
{ "product_id": 9597, "combination_id": 41206, "quantity": 2, "price": 120.00 }
]
}'
# timeout? re-run THIS EXACT COMMAND — same reference, same body.$orderBody = json_encode([
'partner_reference' => 'ACME-100245', // your order id — generate ONCE, store it
'payment_type' => 'cod',
'shipping_address' => [
'customer_name' => 'محمد نور', 'phone' => '0599000000',
'extra_phone' => '022345678',
'state_id' => 431, 'address' => 'شارع المدارس 12',
],
'products' => [
['product_id' => 9597, 'combination_id' => 41206, 'quantity' => 2, 'price' => 120.00],
],
]);
storeRequestBody('ACME-100245', $orderBody); // replay THIS on retry, never rebuild
$attempt = function () use ($orderBody) {
$ch = curl_init('https://mart.ps/api/v1/orders');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $orderBody,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MART_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_TIMEOUT => 60, // creation does real work — be generous
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [$status, $raw === false ? null : json_decode($raw, true)];
};
list($status, $body) = $attempt();
if ($body === null) { // timeout / lost response: outcome unknown
sleep(5);
list($status, $body) = $attempt(); // same reference, same body — always safe
}
if ($status === 201) {
$orderId = $body['data']['order']['id']; // created now
} elseif ($status === 200 && $body['meta']['idempotency_replay']) {
$orderId = $body['data']['order']['id']; // the original order
} else {
log_error($body['error']['code'], $body['error']['details']);
}// Generate the reference ONCE and store the exact body you send.
const orderBody = JSON.stringify({
partner_reference: 'ACME-100245',
payment_type: 'cod',
shipping_address: {
customer_name: 'محمد نور', phone: '0599000000',
extra_phone: '022345678',
state_id: 431, address: 'شارع المدارس 12',
},
products: [
{ product_id: 9597, combination_id: 41206, quantity: 2, price: 120.0 },
],
});
async function attempt() {
const res = await fetch('https://mart.ps/api/v1/orders', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MART_API_KEY}`,
'Content-Type': 'application/json',
},
body: orderBody,
signal: AbortSignal.timeout(60000), // creation does real work
});
return { status: res.status, body: await res.json() };
}
let result;
try {
result = await attempt();
} catch (e) { // timeout / lost response: outcome unknown
await new Promise(r => setTimeout(r, 5000));
result = await attempt(); // same reference, same body — always safe
}
if (result.status === 201) {
saveOrderId(result.body.data.order.id); // created now
} else if (result.status === 200 && result.body.meta.idempotency_replay) {
saveOrderId(result.body.data.order.id); // the original order
} else {
logError(result.body.error.code, result.body.error.details);
}import os, time, requests
# Generate the reference ONCE and store the exact body you send.
order_body = {
'partner_reference': 'ACME-100245',
'payment_type': 'cod',
'shipping_address': {
'customer_name': 'محمد نور', 'phone': '0599000000',
'extra_phone': '022345678',
'state_id': 431, 'address': 'شارع المدارس 12',
},
'products': [
{'product_id': 9597, 'combination_id': 41206, 'quantity': 2, 'price': 120.00},
],
}
headers = {'Authorization': f"Bearer {os.environ['MART_API_KEY']}"}
def attempt():
res = requests.post('https://mart.ps/api/v1/orders',
json=order_body, headers=headers,
timeout=60) # creation does real work — be generous
return res.status_code, res.json()
try:
status, body = attempt()
except requests.Timeout: # outcome unknown
time.sleep(5)
status, body = attempt() # same reference, same body — always safe
if status == 201:
order_id = body['data']['order']['id'] # created now
elif status == 200 and body['meta']['idempotency_replay']:
order_id = body['data']['order']['id'] # the original order
else:
log_error(body['error']['code'], body['error']['details'])Cancel an order — repeat-safe
Repeating the same request is the retry procedure:
already_cancelled: true is success, not an error.
curl -s -X POST https://mart.ps/api/v1/orders/cancel/ACME-100245 \
-H "Authorization: Bearer $MART_API_KEY" \
-H 'Content-Type: application/json' \
-d '{ "reason": "Customer requested cancellation" }'
# lost the response? run it again — 200 with already_cancelled: true.$ch = curl_init('https://mart.ps/api/v1/orders/cancel/ACME-100245');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(['reason' => 'Customer requested cancellation']),
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MART_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if ($body['status'] === 'success') {
// already_cancelled: true on a repeat is still success
$cancelledAt = $body['data']['order']['cancelled_at'];
} elseif ($body['error']['code'] === 'order_not_cancellable') {
// past Mart's cancellation threshold — final for this order
}const res = await fetch(
'https://mart.ps/api/v1/orders/cancel/ACME-100245', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MART_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ reason: 'Customer requested cancellation' }),
});
const body = await res.json();
if (body.status === 'success') {
// already_cancelled: true on a repeat is still success
} else if (body.error.code === 'order_not_cancellable') {
// past Mart's cancellation threshold — final for this order
}import os, requests
body = requests.post(
'https://mart.ps/api/v1/orders/cancel/ACME-100245',
json={'reason': 'Customer requested cancellation'},
headers={'Authorization': f"Bearer {os.environ['MART_API_KEY']}"},
timeout=30,
).json()
if body['status'] == 'success':
pass # already_cancelled: true on a repeat is still success
elif body['error']['code'] == 'order_not_cancellable':
pass # past Mart's cancellation threshold — final for this order