On this page
Registration & terms
A merchant goes pending → active in three calls. Everything is authenticated by the merchant wallet's EIP-191 signature; the mk_live_ API key is issued once, at the end. A marketplace partner can send merchants to a prefilled connect page and learn their slug: see Partner handoff.
| Step | REST (/api/v1/shop) | MCP tool |
|---|---|---|
| 1 | GET /auth/nonce?wallet=0x…&purpose=register | — |
| 2 | POST /merchants | shop.merchant.register |
| 3 | GET /auth/nonce?wallet=0x…&purpose=accept_terms | — |
| 4 | POST /merchants/me/acceptances | shop.merchant.accept_terms |
| — | POST /merchants/handoff (no Bearer, one wallet signature) | — |
| — | POST /merchants/me/keys/rotate (Bearer) | shop.merchant.rotate_key |
| — | POST /merchants/me/keys/reissue (no Bearer, wallet-signed) | — |
| — | POST /merchants/me/deactivate (Bearer, orders:write) | shop.merchant.deactivate |
| — | GET /merchants/me/orders (Bearer, orders:read) | shop.merchant.orders_list |
| — | POST /merchants/me/orders/:id/confirm (orders:write) | shop.merchant.order_confirm |
| — | POST /merchants/me/orders/:id/ship (orders:write) | shop.merchant.order_ship |
| — | POST /merchants/me/orders/:id/document (orders:write) | shop.merchant.order_document |
| — | PUT /merchants/me/webhooks (webhooks:write) | shop.merchant.webhook_set |
| — | GET /merchants/me/webhooks (webhooks:write) | shop.merchant.webhook_list |
| — | DELETE /merchants/me/webhooks/:endpoint_id (webhooks:write) | shop.merchant.webhook_delete |
| — | GET /merchants/me/events?since=<cursor> (orders:read) | — |
| — | POST /partners/handoffs (partner key) | — |
| — | GET /partners/handoffs/:id (partner key) | — |
| — | POST /partners/handoffs/:id/signature-text (partner key) | — |
| — | POST /partners/handoffs/:id/registration (partner key) | — |
| — | POST /merchants/me/grants (no Bearer, wallet-signed) | — |
| — | GET /merchants/me/grants (Bearer, merchant key only) | shop.merchant.grants_list |
| — | DELETE /merchants/me/grants/:partner (merchant key only) | shop.merchant.grant_revoke |
| — | POST /merchants/me/grants/:partner/revoke (no Bearer, wallet-signed) | — |
| — | PATCH /merchants/me/contact (merchant key only) | — |
| — | PUT /partners/merchants/:slug/catalog (partner key) | — |
| — | GET /partners/merchants/:slug/grants (partner key) | — |
| — | POST /partners/merchants/:slug/webhook/rotate-secret | — |
| — | GET /partners/merchants/:slug/quotes (partner key) | — |
| — | GET /partners/merchants/:slug/quote-refusals (partner key) | — |
- Nonce.
GET /auth/noncereturns{nonce, issued_at, expires_in, message};messageis the exact text to sign for that purpose. A nonce is single-use and lives 300 s. - Register. Sign the
registermessage:apibase.pro wants you to sign in with your wallet. Address: <wallet> Purpose: register Nonce: <nonce> Issued At: <ISO-8601 time>
Send the merchant fields plus
messageandsignature. The reply is{merchant_id, slug, status: "pending", docs_to_accept: [{doc_id, version, sha256, url}]}.contact_emailis required and private: it is never shown to buyers.support_emailis optional (absent or""= none, otherwise an e-mail, else422 validation_failedwithfield: "support_email") and is the address buyers see asmerchant_contact.emailon their open orders; set or clear it, or changecontact_email, later withPATCH /merchants/me/contact {support_email?: "<e-mail>" | null, contact_email?: "<e-mail>"}(at least one of the two; merchant key only, a partner grant key gets403 grant_key_not_allowed), which answers{support_email}, pluscontact_email_updated: truewhen the contact address changed (compared case-insensitively), and never the address.contact_emailcannot be removed:null,""or a non-address is422 validation_failedwithfield: "contact_email". A change sends one notice to the previous address; at most 3 changes in 24 hours, then429 rate_limited. Without a signature the call is401. The sign-up IP country is checked as described undercountry_not_supported; form/IP mismatch never blocks. - Accept the four documents (
merchant-agreement,aup,dpa,refund-framework) by signing, with a freshaccept_termsnonce, exactly this text (one line; hashes are thesha256values fromdocs_to_accept):I accept APIbase documents: merchant-agreement v<version> sha256:<h1>; aup v<version> sha256:<h2>; dpa v<version> sha256:<h3>; refund-framework v<version> sha256:<h4>. Wallet: <wallet>. Nonce: <nonce>. Time: <ISO-8601 time>
Send
{wallet, doc_hashes: [{doc_id, version, sha256}], message, signature}. All four documents are required and the message must match the template byte for byte. On success the merchant isactiveand the response is{status: "active", api_key: "mk_live_…"}— the key is shown once. Repeating the call returns{status: "active"}without a new key. The message and signature are stored whole as the acceptance record. - New document versions. When a document is republished you have 30 days to accept it again: merchant-tool responses carry
terms_update_pending: {docs: [...]}during that window; afterwards new quotes are refused with428 terms_not_accepted. - Deactivate.
deactivatestops new quotes and shows the storefront as410. Open orders stay serviceable: existing keys keeporders:read/orders:write;catalog:writecalls get410.
Errors
Every error carries error_code, message, suggested_action, documentation_url.
country_not_supported (403) — the entity country or the sign-up IP's country (looked up at registration in a monthly country-level database) or the declared region is not served. When the lookup has no answer the IP rule is not applied. See /legal/aup.
category_prohibited (403) — the category is not supported; alternatives[] lists the nearest allowed categories. See /legal/aup#categories.
terms_not_accepted (428) — the merchant is pending, a document hash/version in the request is not the current one, fewer than four documents were sent, or a re-acceptance is overdue. docs[] holds the current {doc_id, version, sha256, url} of all four documents.
Other codes: unauthorized (401, bad/missing signature, nonce used or expired), rate_limited (429), validation_failed (422), slug_taken/wallet_registered (409), payout_wallet_sanctioned (403), payout_wallet_platform (400). The payout wallet must be the merchant's own; platform addresses are refused with payout_wallet_platform (400). Limits per IP: nonce 30/min, POST /merchants 5/hour, acceptances 10/min.
One signature for a partner handoff
For a live partner handoff of mode register with grant_requested: true, steps 1 to 4 and the grant are one signature (the connect page does this; the per-purpose routes above stay as they are).
GET /auth/nonce?purpose=handoff&wallet=0x…&handoff=<handoff_id>&slug=<slug>&kid=<kid>&pub=<base64 X25519 public key>returns{nonce, issued_at, expires_in, message}. APIbase builds the text; the browser only sends the public key. Before anything is signed it refuses what the write would refuse: a handoff that is not live, not moderegisteror did not ask for the grant (422 validation_failed,field: "handoff"), a wallet other than the handoff'sexpected_wallet(401),wallet_registeredandslug_taken(409). The message, single-use, 300 s:APIbase (apibase.pro): open my shop apibase.pro/m/<slug> and let <Partner name> sell for it. I accept the four APIbase documents: Merchant Agreement, Acceptable Use Policy, Data Processing Addendum, Refund Framework. <Partner name> may: <the permission text of the Allows line below>. It may not touch payouts, keys, orders or refunds. You can stop this any time at apibase.pro/integrator/permissions. This is a signature only: no transaction, no payment, no gas. Technical details 1. Encryption key of the shop kid: <kid> alg: x25519 pub: <pub> 2. Registration Address: <wallet> Purpose: register 3. I accept the APIbase documents merchant-agreement v<version> sha256:<h1> aup v<version> sha256:<h2> dpa v<version> sha256:<h3> refund-framework v<version> sha256:<h4> 4. Permission for <Partner name> Partner: <partner id> Allows: upload and import your catalog; register its own webhook endpoint and receive your order events; read the outcome of each quote for your products (paid, unpaid, expired, refused), never who the buyer is Does not allow: payouts, keys, orders, refunds Revoke any time: DELETE /api/v1/shop/merchants/me/grants/<partner id> Nonce: <nonce> Issued At: <ISO-8601 time>
The first five lines are for the person; a verifier relies on the lines after "Technical details".
POST /merchants/handoffwith the merchant fields of step 2 (theslugof the message),wallet,handoff_id,messageandsignature, noAuthorizationheader (the limits ofPOST /merchants). APIbase rebuilds the message from the nonce and compares it byte for byte; a changed byte, a used or expired nonce, another signer or a wallet other thanexpected_walletis401and writes nothing. Otherwise one transaction writes the store (active), its encryption key, one acceptance per document, the grant and the handoff (granted); each record keeps this message and signature as its proof, and the key'ssig_by_walletis this signature with the text insigned_message(see Buyer PII, step 2). The answer is201 {merchant_id, slug, status: "active", handoff: {handoff_id, state: "granted"}, grant: {grant_id, partner, mode, scopes, created_at}}, plusapi_key(mk_live_…, shown once) unless the partner's registry entry hasseller_keys: hidden: then no key is created (see A shop without keys).
Signature on the partner's page
A partner whose registry entry has partner_page_signature: true may collect this one signature on its own page instead of sending the seller to the handoff url. Both calls are server to server with the partner key (Authorization: Bearer pk_live_…; 401 partner_key_invalid otherwise) and share the 60 writes/min per key of the partner routes. No key of any kind is created or returned.
The handoff must be live (unexpired, not yet registered), mode register with grant_requested: true, have expected_wallet, and carry all six prefill keys (name, site_url, contact_email, category, country, slug). The store is registered from that prefill; the calls carry no shop fields, and payouts go to the signing wallet (no other payout wallet on this path).
POST /api/v1/shop/partners/handoffs/<handoff_id>/signature-textwith exactly{wallet}answers200 {handoff_id, message, issued_at, expires_in: 300}. The text is single use and lives 300 s; a second call replaces the first. Passmessagetopersonal_signbyte for byte and do not parse it:APIbase (apibase.pro), asked on <host of your registry site>: open my shop apibase.pro/m/<slug> and let <Partner name> sell for it. I accept the four APIbase documents: Merchant Agreement v<version>, Acceptable Use Policy v<version>, Data Processing Addendum v<version>, Refund Framework v<version>. Texts: https://apibase.pro/legal <Partner name> may: <the permission text of the Allows line below>. It may not touch payouts, keys, orders or refunds. You can stop this any time at apibase.pro/integrator/permissions. Payouts go to this wallet. The shop starts without a decryption key. This is a signature only: no transaction, no payment, no gas. Technical details 1. Registration Address: <wallet> Purpose: register Handoff: <handoff_id> 2. I accept the APIbase documents merchant-agreement v<version> sha256:<h1> aup v<version> sha256:<h2> dpa v<version> sha256:<h3> refund-framework v<version> sha256:<h4> 3. Permission for <Partner name> Partner: <partner id> Allows: upload and import your catalog; register its own webhook endpoint and receive your order events; read the outcome of each quote for your products (paid, unpaid, expired, refused), never who the buyer is Does not allow: payouts, keys, orders, refunds Revoke any time: DELETE /api/v1/shop/merchants/me/grants/<partner id> 4. Encryption key of the shop kid: none-<handoff_id> alg: x25519 pub: <placeholder> Nonce: <nonce> Issued At: <ISO-8601 time>
The encryption key is a placeholder that no one can open:
<placeholder>is the standard base64 of the sha256 of the UTF-8 textapibase.pro shop without a decryption key\n<handoff_id>(lower-case id). Nothing is generated on your page and no private half exists; the seller sets a real key later withPOST /merchants/me/keys/rotate(see Buyer PII).POST /api/v1/shop/partners/handoffs/<handoff_id>/registrationwith{wallet, signature, seller_ip, seller_user_agent?}answers201 {merchant_id, slug, status: "active", handoff: {handoff_id, state: "granted"}, grant: {grant_id, partner, mode, scopes, created_at}}. APIbase rebuilds the text from its record and checks the signature as in step 2 above, then writes the same records in one transaction (storeactive, encryption key withsig_by_walletandsigned_message, one acceptance per document, the grant, the handoffgranted).seller_ipis required: the public address your server saw on the browser request that carried the signature (a private, loopback, link-local or CGNAT address is refused). The sign-up country rule and the per-address registration limit apply to it. The address itself is not stored: the acceptances keep its hash, the store its country, a refused attempt its /24 prefix.seller_user_agentis optional, at most 512 characters. Take the webhook secret once fromGET /partners/handoffs/<handoff_id>, as for any grant.
Errors on either route:
| Status | Code | When |
|---|---|---|
| 403 | partner_page_signature_off | your registry entry does not have partner_page_signature: true |
| 404 | not_found | the handoff is not yours or does not exist |
| 422 | validation_failed | field names it: wallet, handoff, expected_wallet, prefill.<key>, signature, seller_ip, seller_user_agent, or an unknown body key |
| 401 | unauthorized | the wallet is not expected_wallet |
| 409 | wallet_registered, slug_taken | checked before anything is signed, and again at registration |
| 503 | service_unavailable | retry shortly |
Errors on registration only: 401 unauthorized (no text issued, text expired or used, another wallet than the text's, a bad signature), 428 terms_not_accepted (a document changed after the text was issued), 409 grant_exists, 403 country_not_supported, category_prohibited, payout_wallet_sanctioned or moderation_banned, 400 payout_wallet_platform, 429 rate_limited (too many registrations from one seller address). After any registration error the text is spent: ask for a new one. After a timeout, read the handoff: state: "granted" means it is done. Until one path completes it, the same handoff still works through its url.
Lost key
If you lost your mk_live_ key there is no Bearer to call keys/rotate with. Recover with the merchant wallet instead:
GET /api/v1/shop/auth/nonce?wallet=0x…&purpose=reissuereturns amessageto sign.- Sign it with the merchant (identity) wallet (EIP-191) and call
POST /api/v1/shop/merchants/me/keys/reissuewith{wallet, message, signature}and noAuthorizationheader. - The response is
{api_key}: a freshmk_live_key, shown once. All earlier keys are revoked immediately. The nonce is single-use and expires after 5 minutes; a bad or replayed signature is401. - What it does to partner grants: Partner grants, step 6.
The route is rate-limited to 5 requests per hour per address. A merchant.keys_reissued event is recorded (subscribable through webhooks, also in GET /merchants/me/events). This route is an addition to §6.3 of the spec.
Catalog
Inactive merchants (410 merchant_inactive). The key of a suspended or deactivated merchant can still read (GET) and close open orders (order confirm/ship/document, refunds, stream settle, subscription renewed/cancel, fee-invoice paid, deactivate); every other write (catalog, webhooks, provek, stream-settings, renewer-key, key rotation) is refused with 410 merchant_inactive, on REST and on the MCP tools alike.
Write path (merchant key mk_live_…, scope catalog:write, 60 writes/min per key; merchants must have accepted the current documents — pending → 428, deactivated/suspended → 410):
PUT /api/v1/shop/merchants/me/catalogwith{ "items": [ … ] }(≤500 items, body ≤1 MB) · MCPshop.merchant.catalog_upsert. Idempotent bysku; the merchant is always the key's owner (amerchantfield in the body is ignored). A price change applies to new quotes at once.- MCP
shop.merchant.catalog_delete {skus[]}— refused with409andquote_idswhile an open quote holds a sku.
Item (zod schema CatalogItemSchema, src/shop/catalog.service.ts):
| field | rule |
|---|---|
sku | [A-Za-z0-9._:-], ≤64 |
title | ≤120 after HTML/control/zero-width stripping |
description | ≤2 000 after stripping |
price_usd | decimal, ≤2 fractional digits, $1.00 … limits.max_order_usd |
is_test | only for the test SKU (below) |
stock | integer ≥0; null/absent = not tracked |
fulfillment_mode | instant · merchant · physical · stream |
fulfillment.instant.payload | required for instant; stored encrypted with the server key, never returned or logged |
tax_included, tax_note, shipping_options[], delivery_slots[], requires_pii[], refund_window_days, returns_accepted, currency_display, images[] (https URLs), variants[] | as in the spec; no discounts or coupons |
subscription | {period_unit: day|week|month, period_count >= 1, max_periods? <= 120, trial: none} for instant/merchant items; price_usd is the price of ONE period (>= $1.00). No stock count, variants, buyer data or test SKU. See Subscriptions |
category | one of config/integrator/prohibited-categories.json → allowed |
Response: { upserted, flagged[{sku,reason}], rejected[{sku,reason,category,status:422}], errors[{index,sku,status:422,message}] }. Items are judged one by one: a bad item never blocks the rest of the batch. More than 500 items → 422 for the whole call.
Feed import (F-2, UC-11). POST /api/v1/shop/merchants/me/catalog/import (scope catalog:write, answer 202) with { "source": "csv" | "gmc" | "shopify", "url"?: "https://…", "body"?: "<CSV text, ≤1 MB>", "category"?: "<slug for records without one>" } returns import_job_id; a worker job downloads and imports it in batches of ≤500 through the same upsert and layer-1 moderation as PUT …/catalog. Poll GET /api/v1/shop/merchants/me/catalog/import/:id → {status: queued|running|done|failed, total, upserted, rejected[{sku, reason}], rejected_count, error} (the list shows the first 1000). One import per merchant per 10 minutes (429). Downloads follow the webhook rules: https only, public addresses only (DNS pinned), redirects are not followed, ≤10 MB, 20 s; a refused URL is 400.
csv— our schema: header withsku,title,price_usdplus optionaldescription,category,stock,images(|-separated),currency_display,fulfillment_mode,tax_included,tax_note,returns_accepted,refund_window_days.gmc— Google Merchant Center RSS/XML:g:id→sku,g:title,g:description,g:price(12.50 USD; any other currency is rejected),g:availability(in stock→unlimited,out of stock/preorder/backorder→0),g:image_link→images,g:product_type→category. DOCTYPE/ENTITY declarations are refused.shopify— the public/products.jsonof the shop (urlmay be the shop root): each product becomes an item, eachvariants[]entry a variant; prices are taken as USD.
A feed category must be one of the allowed slugs, otherwise the record is rejected by moderation (the category request field only fills in records that have none).
Test SKU. Exactly one item per merchant may be sku: "__apibase_test", is_test: true, price_usd: 0.01 (any other price or a second test item → 422). It is not listed by shop.catalog.search, but shop.catalog.get returns it, so an agent can run an end-to-end purchase. No fee is taken on it.
Description rule. description must read as a plain description of the product: what it is and when it is useful. An item whose description instructs the agent (ignore all|any|previous, always call, you must call, do not call other, system prompt, as an ai, disregard, override, before any|every other tool, instead of any|all other, case-insensitive) is not saved; it appears in the call's errors[] with status: 422 and error_code: "description_reads_as_instruction", the rest of the batch is unaffected. The same applies to feed imports (…/catalog/import), which go through the same upsert.
Price rule. A price stated in a product's title or description must equal its price_usd. An amount written $5 or USD 5 counts as a stated price only when it follows price, priced, cost or costs (directly or through :, =, a dash, is, of, at, now, only, just), stands next to only or just (only $5, just $5, $5 only), or is directly followed by tier ($5 tier, $0.75 micro-tier). Other amounts (examples, fees, face values, the subject of a report or a dataset) are not checked. An item that states a different price is not saved; it appears in errors[] with status: 422 and error_code: "price_claim_mismatch", and the message quotes the phrase. Items with a stream rate are exempt. The same applies to feed imports.
Decryption key rule. While nobody can open a shop's encryption key, an item with a non-empty requires_pii or fulfillment_mode: "physical" is not saved; it appears in errors[] with status: 422 and error_code: "decryption_key_missing", and the rest of the batch is saved. Nobody can open the key when it is the placeholder (kid starts with none-, as for a shop registered on a partner's page), or when the shop was registered through a partner with seller_keys: hidden and its first encryption key was never rotated. The rule applies to the catalog push, the partner push and feed imports, and ends when POST /merchants/me/keys/rotate sets a new encryption key.
Moderation. The description rule above runs first (an item it refuses never reaches moderation). Order per item: category in allowed (else rejected, category_prohibited) → prohibited-category keywords and the platform content filter (rejected) → hidden characters and instruction-like text (you must, system:, non-https URL schemes → flagged). Every check writes a shop_moderation_reviews row (scope=product, layer=rules). A flagged product is saved but invisible to buyers (search omits it, get → 404) until a layer-3 or human review of that item returns ok; a flagged item is re-checked within 24 h of the change; re-uploading the item moderates it again. A call with rejected items also emits one shop.catalog.rejected event. The scanned fields are title, description, category, variants[].title and variants[].attributes (keys and values), shipping_options[].label, delivery_slots[].label, tax_note and stream.content_ref; hidden characters are checked on the same fields. The shop name and the site_url host at registration, and the Provek insurance.note and claims_url host, pass the same text rules. Repeated rejected writes temporarily block catalog writes for this merchant (403 moderation_banned with retry_after; one write call with any rejected item counts once). When the platform rules change, listed items are re-checked and may be hidden or rejected; the merchant receives the same category notice. Re-uploading a rejected item puts it back to review, not on the shelf: after a layer-3 or human reject, the item stays invisible (flagged) until the next layer-3 or human review returns ok.
Buyer path (/mcp, free, read-only, merchant = slug is required, only active merchants — otherwise 410 merchant_unavailable):
shop.catalog.search {merchant, query?, category?, max_price_usd?, limit≤50, cursor?}→products[{sku,title,price_usd,availability,requires_pii,fulfillment_mode}],merchant{name,reputation,policy_summary},next_cursor. Full-text over title+description, ordered by rank then product id.shop.catalog.get {merchant, sku}→ full card incl.shipping_options,delivery_slots,refund_policy,variants[],merchant_encryption_key.contact_emailis never returned.
Quotes
Buyer path. A quote is a price snapshot plus a stock hold; nothing is charged by it (payment is a separate step).
shop.order.quote {merchant, items[{sku, variant?, qty}], shipping_option?, delivery_slot?, buyer_ref?, subscribe?}on/mcp·POST /api/v1/shop/quotes(same body,X-Idempotency-Keysupported: a replay returns the samequote_idand holds stock once) ·GET /api/v1/shop/quotes/:id.- The same
X-Idempotency-Keyheader works on plainPOST /api/v1/tools/:toolId/call: 10 minutes, scoped to the paying wallet, and a duplicate while the first call runs is a 409conflictwithretry_after./mcpcallers use_meta["apibase/idempotency_key"](see "Payment transport on /mcp" in the agent guide). shop.order.cancel {order_id, reason}·POST /api/v1/shop/orders/:id/cancel {reason}: free while the order isQUOTED; the quote is voided and the held stock released.reasonis optional while the order isQUOTED(the quote'scancel_url). After payment:409 not_cancellable(refund flow).- Physical items (T-INT-22). A quote with a
physicalproduct needsshipping_option(anidfrom the product'sshipping_options[], else422listing the offered options); itsprice_usdis added once asshipping_usdand is part oftotal_usd. When the product listsdelivery_slots[],delivery_slotis required too: the slot is held until the quote expires (one live hold per product and slot); a taken slot answers409 slot_unavailablewithalternatives(the free slots). A paid order keeps its slot.requires_piialways includesshipping_address(end-to-end encrypted, see the PII section); paying without it is422 pii_required.shipping_option/delivery_sloton a quote without physical items →422. - Physical order flow.
PAID→CONFIRMED(merchant only,order_confirm; setsship_due_at = now + policy.ship_sla_h, default 72 h) →SHIPPED(order_ship {order_id, tracking: {carrier, number, url?}, delivery_eta}; the buyer seestrackinganddelivery_etainorder.get) →DELIVERED(the merchant callsorder_ship {order_id, delivered_at}, or automaticallydelivery_eta + 7 days) →CLOSEDwhenclose_after(DELIVERED+refund_window_days) passes. There is no buyer-side confirm-delivery tool (not in §6): the buyer's way out isshop.order.cancelwithin the refund window or the automaticDELIVERED.
Response (201): quote_id, order_id, items[{sku, variant?, title, qty, unit_price_usd, line_total_usd}], total_usd, fee_disclosed: false, expires_at, pay_before, cancel_url, requires_pii[], requires_human_confirmation, pay. Prices come from the server catalog, never from the request.
pay (in the quote; a 402 repeats only pay.mpp) contains only the rails the quote offers: x402: {payTo, amount, network, asset, extra: {quote_id}} — payTo is the merchant's payout_wallet_base (never the platform wallet), amount is micro-USDC (toMicroUsdc(total_usd)); mpp: {url} = POST /api/v1/shop/quotes/{id}/pay. On /mcp orders are paid by x402 only, so pay.mpp is omitted there. The quote stores the MPP challenge id; the receipt carries the transaction hash: use them to find the payment on-chain.
TTL. 15 minutes by default (limits.quote_ttl_s, merchant range 5–60 min). Act on pay_before (see /integrator/buyers#the-price-is-fixed-by-the-quote). Past expires_at the quote is expired: GET returns 410 quote_expired with a fresh quote in quote (same items, current prices); if the items have meanwhile sold out, 410 carries alternatives instead. Next to a fresh quote the 410 carries changes: {changed, total_usd: {old, new}, shipping_usd?: {old, new}, lines: [{sku, variant?, unit_price_usd: {old, new}}]}, copied from the expired quote and the fresh one; lines lists only the lines whose unit price moved, shipping_usd is present only when the quote has shipping, and changed is true when any of them moved: changed covers prices only. A fresh quote can differ in the unit price (product or variant price), the shipping option price and so the total; outside changes it always has a new quote_id, order_id and expires_at, and it can also differ in the line title, the pay rails and payTo, requires_pii, merchant_encryption_key, requires_human_confirmation, terms_update_pending, a new buyer_token (anonymous REST buyer) and, for a subscribe: true quote, subscription_terms (period, max_periods) and whether pay.mpp_subscription is offered; compare those fields yourself, changed: false does not cover them. A payment presented on an expired quote (POST /api/v1/shop/quotes/:id/pay, shop.order.pay) gets the same 410 with quote and changes.
Reservations. Items with tracked stock are held atomically when the quote is made (all lines or none) until expires_at; the loser of a race gets 409 out_of_stock with available and up to 3 alternatives of the same category. Expiry or cancel releases the hold.
Limits. Order total ≥ $1.00 (INTEGRATOR_MIN_ORDER_USD), ≤ limits.max_order_usd; merchants younger than 30 days with fewer than 10 closed orders are capped at limits.new_merchant_cap_usd ($200) → 422. requires_human_confirmation is true above limits.human_confirm_above_usd (default $100). Quotes per buyer identity (agent, wallet hash or IP): 30/min, 300/hour → 429 rate_limited; a banned identity → 429 banned. The merchant must have accepted the current terms (428) and be active (410).
Test SKU. __apibase_test is bought alone, qty 1, no minimum, fee_usd = 0. At most INTEGRATOR_TEST_SKU_DAILY_CAP (3) paid test orders per merchant per 24 hours; the next quote → 429 test_sku_daily_cap.
Fee (internal, not in the response): when INTEGRATOR_FEE_ENABLED=true, max(total × INTEGRATOR_FEE_BPS / 10000, INTEGRATOR_FEE_MIN_USD) rounded up to the cent (150 bps, min $0.05); 0 otherwise and for the test SKU. With the fee on it must also be ≥ X402_GAS_ESTIMATE_USD × 10, else 422.
Error codes: a request without merchant or items is 422 validation_failed with missing[]; an unknown merchant is 404 not_found with suggested_action: fix_request; quote_expired (410), out_of_stock (409), test_sku_daily_cap (429), below_minimum/above_max_order/new_merchant_cap (422), not_cancellable (409), quote_not_open (409).
Payment & fulfillment
Buyer path after a quote: pay with x402 (Base). Settle comes before delivery — the order is delivered only after the USDC transfer has a successful receipt.
shop.order.pay {quote_id}on/mcp(X-Payment header on that call) ·POST /api/v1/shop/quotes/:id/pay(X-Payment/PAYMENT-SIGNATURE). The authorization must be for exactlytotal_usdto the merchant payout wallet; the platform verifies it, claims its nonce (single use; Redis unavailable →503, nothing is settled), then settles through the platform facilitator and waits for the receipt (≤ 30 s). The PayAI facilitator is used only if the local one throws; a refused settle (success:false) is final — no retry, no second facilitator.200 paid—order {order_id, state, tx_hash, fulfillment?}andorder_url(the absolutehttps://apibase.pro/api/v1/shop/orders/<order_id>); withoutorder.fulfillmentthe body also carriesnext, one sentence telling you to GETorder_urlwith the buyer Bearer untilFULFILLED. Instant products goPAID → CONFIRMED → FULFILLED;waive_withdrawal: truecloses the order at once (CLOSED), otherwise it closes afterrefund_window_days(default 14). The test SKU deliverstest ok.merchantfulfillment staysPAIDuntil the merchant confirms.GET /orders/:idandshop.order.getcarryviewer:payerseesfulfillment,documentsandmerchant_contact {site_url, email?}(email is the shop's support e-mail when it set one; the registration contact e-mail is never shown);publicsees state and events only and ahintnaming the credential (on REST the quote'sbuyer_tokenasAuthorization: Bearer, or, on REST, a request signed by the paying wallet: headersX-Payer-AddressandX-Payer-Signature= personal_sign ofapibase-order:<order_id>:<unix minute>(current or previous minute); read-only; a bad signature is 401order_signature_invalid).202 payment_pending {order_id, order_url, next}— the receipt was not seen in time; the order staysPAYING. Pollshop.order.get/GET /api/v1/shop/orders/:id. Theshop-payment-reconcilejob (every 60 seconds, 24 h window) readsauthorizationState(payer, nonce)and the USDCTransferon-chain: confirmed →PAIDand delivery; not confirmed after 24 h →PAYMENT_FAILEDfor good, the quote expires and the stock reservation is released. Onlypending/failedpayments are reconciled, never wallets.PAYINGmay last until the reconcile job runs (it first reads the receipt of a broadcast transaction when there is one). A settle that was broadcast but not yet confirmed (settlement_pending) or whose facilitator call timed out is unknown, not failed: the order is never failed while the chain may still confirm it, and nobody settles twice.402 payment_required— the settle was refused (PAYMENT_FAILED, nothing delivered); the quote stays open until its TTL, sign a new authorization (new nonce) and pay again: the same order row goesPAYMENT_FAILED → PAYING. A quote that is already paid, or has a payment in progress, also answers402. The body states the x402 terms once, inaccepts[];payin a 402 carries onlympp(andmpp_subscription), neverx402, and is absent when the quote offers no other rail. ThePAYMENT-REQUIREDheader carries the x402 object only (x402Version,error,resource,accepts,extensions). A 402 also carriespay_beforeand, while the order isQUOTED,cancel_url.payment-identifier(optional x402 extension). The order 402 lists it inextensions. Addextensions["payment-identifier"].info.id(16-128 characters) to the payment payload to make a retry safe: the same id with the same payment returns the stored answer (order_id,state,tx_hash, neverfulfillment— read it withorder.get) with no second verify or settle for 24 hours; the same id with another quote, amount, recipient or payer is409 payment_identifier_conflict; the same id while the first request is still running is409 payment_in_flight. The 409 carriesretry_after(and theRetry-Afterheader on REST),order_idwhen known andpoll: "shop.order.get"; wait, then re-send the same id; a conflict carriesreason: "payer" | "request". A repeated answer carriesreplayed: true. A payment attempt that crashed is resolved from the order after 3 minutes: the same id then returns the order or lets you pay again. A supervising worker takes over by re-presenting the same identifier, not by re-signing. Without an id nothing changes.200 already_placed— a repeat ofshop.order.paywithout a payment on a quote the same identity already paid returns the same order (withfulfillment) andorder_url; any other identity gets402.shop.order.get {order_id}·GET /api/v1/shop/orders/:id→{order_id, state, tx_hash, events[], refund_policy {refund_window_days, returns_accepted}}; for the identity that paid (the quote's buyer, or the wallet identity of the payer) alsofulfillment?(same on every call),documents[](merchant links) and, while the order is open (PAID…DELIVERED,REFUND_PENDING,DISPUTED; notCLOSED),merchant_contact {site_url, email?}: email is the shop'ssupport_emailwhen it set one; the registration contact e-mail is never shown.shop.order.cancelafter payment: before the merchant confirms (PAID) it is always a refund →REFUND_PENDINGand ashop_refundsrow due in 7 days (shop.refund.requested); afterCONFIRMEDonly if the SKUs accept returns andrefund_window_daysis still open, otherwise409 not_cancellablewith the policy. Digital content delivered underwaive_withdrawal(FULFILLED/CLOSED) is409.- Merchant order tools.
orders_list {state?, since?, cursor?, limit?}(own orders only,next_cursorfor the next page),order_confirm {order_id}(PAID → CONFIRMED, stops the confirm SLA; another merchant's order is404),order_ship {order_id, tracking?, delivery_eta?, delivered_at?}(physical orders:CONFIRMED → SHIPPED, thendelivered_at→DELIVERED;409 not_shippableotherwise),order_document {order_id, url}(https://only, else422; shown in the buyer'sorder.get.documents). - Refunds (
shop.merchant.refund {order_id, amount, tx_hash}/POST /merchants/me/refunds, scoperefunds:write). A refund is the merchant's own transaction: send USDC back to the payer's wallet on the order's rail, then pass the hash. APIbase only reads the chain (viem, read-only; it never sends or signs anything): the transaction must be confirmed, carry a USDCTransferwithto= the payer andvalue >= amount. Verified →shop_refunds.verified, the order goesREFUND_PENDING → REFUNDED(the refunds add up tototal_usd) orPARTIALLY_REFUNDED(a further refund moves it throughREFUND_PENDINGagain). A transaction that does not prove it →422 refund_rejectedwithreject_reason, the record isrejectedand the order is unchanged; more than the order total is400 refund_exceeds_total; a transaction settles one refund only (409 tx_already_used). The platform fee is not returned; forreason = duplicatethe fee leg is alreadywritten_off. - Disputes (
shop.order.dispute {order_id, reason_code, note?}/POST /orders/:id/disputes, the payer only, another identity gets404).reason_code:not_received | not_as_described | duplicate | canceled_recurring | agent_error | other;noteup to 1000 characters.PAID…DELIVERED→DISPUTED,due_at= +7 days, one open dispute per order,shop.dispute.opened. Merchant dispute response channel: the refund tool (a verified refund resolves the dispute) or the mail intake of §12.2 MERCHANT_REPLY; §6.3 has no REST reply route. Afterdue_atthe dispute isexpired, the order returns to its prior state and oneshop.dispute.unanswered(DISPUTE_UNANSWERED, pull-only) is queued. Escalation is reputation and suspension only. - Reputation (
shop_merchants.reputation, recomputed by the sweeper once an hour):closed_on_time_pct,dispute_rate,refund_rate(fractions,0.02= 2%),orders_closed,as_of; published incatalog.search/catalog.get/discover(merchant.reputation) and on/m/<slug>. The test SKU andreason = duplicateare not counted. At 10 or more closed ordersdispute_rate >= 1%queues a warning (mail +shop.merchant.dispute_rate_warning, at most weekly);>= 2%with at least 3 disputed orders setsstatus_reason = disputesand quotes answer410until the operator clears it (scripts/shop/merchant-status.ts --clear-reason, eventshop.merchant.reason_cleared); after a lift only orders settled after the lift count towards the flag again. - SLA sweeper (
shop-sla-sweeper, worker, every 5 minutes): expired open quotes →expired(stock released,QUOTEDorders →EXPIRED);PAIDpastconfirm_due_at(PAID+policy.confirm_sla_h, default 48 h, merchant-fulfilled orders only) → oneshop.order.confirm_overdue, repeated every 24 h;CONFIRMEDphysical pastship_due_at→ oneshop.order.ship_overdue(pull-only);SHIPPEDwithdelivery_eta+ 7 days passed →DELIVERED; three late orders in a row → the merchant getsstatus_reason = unresponsiveand quotes answer410until the operator clears it (scripts/shop/merchant-status.ts --clear-reason, eventshop.merchant.reason_cleared); after a lift only orders settled after the lift count towards the flag again;close_afterpassed →CLOSED; refunddue_atpassed →overdue+ oneshop.refund.overdue; disputedue_atpassed →expired+ oneshop.dispute.unanswered; merchant reputation recomputed hourly (disputes ≥ 1% warn; ≥ 2% and at least 3 disputed orders suspend);payout_pending.effective_atpassed → the new payout wallet is applied;shop_connect_eventsolder than 30 days are deleted. - Paid orders emit the
shop.order.paidevent; thePAIDorder event recordsrequest_id, the buyer agent (client name/version or user agent) and the first 8 hex characters of the payer wallet's SHA-256 — never the wallet.
Buyer PII (end-to-end encrypted)
Some products need buyer data (requires_pii: shipping_address, passport, phone, company). APIbase is a processor on the merchant's behalf and cannot read this data: the buyer's agent encrypts it to the merchant's public key and the platform stores only the ciphertext. There is no server-side decryption anywhere, and no way to ask the platform for a plaintext copy.
1. Generate the key pair (merchant). An X25519 pair, the public key as base64 of the raw 32 bytes:
# Node
node -e "const c=require('crypto');const k=c.generateKeyPairSync('x25519');console.log('pub',k.publicKey.export({type:'spki',format:'der'}).subarray(-32).toString('base64'));console.log('priv',k.privateKey.export({type:'pkcs8',format:'der'}).subarray(-32).toString('base64'))"
# Python (cryptography)
python3 -c "import base64;from cryptography.hazmat.primitives import serialization as s;from cryptography.hazmat.primitives.asymmetric import x25519;k=x25519.X25519PrivateKey.generate();r=lambda b:base64.b64encode(b).decode();print('pub',r(k.public_key().public_bytes(s.Encoding.Raw,s.PublicFormat.Raw)));print('priv',r(k.private_bytes(s.Encoding.Raw,s.PrivateFormat.Raw,s.NoEncryption())))"
# CLI (age-keygen prints an X25519 recipient; convert its key to raw bytes yourself)
age-keygenThe private key never leaves you. Keep it out of APIbase, out of logs and out of the repository.
2. Publish it. encryption_key {kid, alg, pub, sig_by_wallet} at registration (kid up to 64 characters). sig_by_wallet is an EIP-191 signature by the merchant identity wallet over exactly this text (the same text at registration and at rotation; --prepare of the seed script prints it):
apibase.pro merchant encryption key kid: <kid> alg: <alg> pub: <pub>
The signature is stored and handed to the buyer's agent together with the key (merchant_encryption_key in shop.catalog.get and in every quote that has requires_pii), so the agent can check that the key belongs to the merchant wallet. A key registered with one signature for a partner handoff also carries signed_message: sig_by_wallet then signs that text, which holds the same kid, alg and pub lines.
3. Envelope (buyer's agent). Encrypt the JSON ({full_name, passport_number, nationality, dob, expiry} for a passport, the address object for shipping_address) to pub with HPKE (RFC 9180, X25519-HKDF-SHA256 + ChaCha20-Poly1305, alg: "hpke-x25519-sha256-chacha20") or libsodium crypto_box_seal (alg: "sealed-box-x25519"). AAD = the quote_id (HPKE; sealed boxes have no AAD, so the merchant checks the quote inside the decrypted JSON). Send one envelope per kind in shop.order.pay / POST /quotes/:id/pay:
{
"pii": {
"passport": {
"kid": "<merchant kid>",
"alg": "hpke-x25519-sha256-chacha20",
"ciphertext_b64": "<base64>"
}
}
}At most 16 KB decoded per envelope. The platform accepts nothing else: a string, a number, an object with readable fields (passport_number, address, …), any extra field, a bad base64 or an oversize envelope is 400 pii_plaintext_rejected ("encrypt with merchant key, see docs"); the value is never echoed, stored or logged. Other errors: 422 pii_required (a kind the quote needs is missing; extra.merchant_encryption_key and extra.required say what to send), 409 merchant_key_rotated (the kid is not the current one; extra.merchant_encryption_key is the new key; re-encrypt and pay, or request a new quote), 400 pii_unexpected_kind, 400 pii_alg_unsupported. The platform cannot check the AAD (it cannot decrypt): a wrong AAD only fails at the merchant.
4. Delivery to the merchant. The same bytes arrive in the order.paid webhook as data.pii[{kind, kid, alg, ciphertext_b64, sha256}] and on GET /api/v1/shop/merchants/me/orders/:id/pii (Bearer, scope orders:read, 60 per minute) as {order_id, envelopes[...]}; another merchant's order is 404. sha256 is the hash of the ciphertext bytes. The buyer's shop.order.get and the merchant's orders_list show only pii: {kinds, sha256}, never ciphertext.
5. Merchant duties. Fetch the envelopes (webhook or GET) before you rotate the key; decrypt with your private key; store what you need yourself — the platform keeps data only temporarily and cannot restore it. Retention (spec 10.3), enforced by the shop-sla-sweeper with a physical DELETE and a pii.purged order event:
- passport: the first of 7 days after
delivered_to_merchant_at(first successful webhook or first GET), the order reachingDELIVERED,CANCELLED,REFUNDEDorPAYMENT_FAILED, or 30 days after creation; - shipping address, phone, company: 30 days after the order is
CLOSED; - logs never contain an envelope or its hash; metrics are counters only.
The merchant gets a "stored temporarily, keep your own copy" e-mail on the first delivery (at most one such e-mail per merchant in 7 days; every order still carries its own pii route). There is no early-purge request route: data is purged by rule only. Terms: the data-processing agreement at /legal/dpa (APIbase acts as a processor on the merchant's behalf).
6. Rotation. POST /merchants/me/keys/rotate / shop.merchant.rotate_key with encryption_key {kid, alg, pub, sig_by_wallet} (a NEW kid, signature as in step 2; this call also rotates the API key as before) replaces the published key and emits merchant.key_rotated. Stored envelopes are not re-encrypted: those not yet delivered get a pii.undeliverable order event and one pii_undeliverable e-mail per merchant (at most one in 7 days; the pii.undeliverable order event lists every affected order) — fetch them and open them with the OLD private key. The private (decryption) key never leaves the merchant: it opens only the buyer-detail envelopes of this store, cannot move funds or change the store, and a leaked copy is useless without the envelopes (reachable with the API key or at the store's webhook); if either key was exposed, rotate both with this one call. Open quotes keep their requires_pii; paying one with the old kid is 409 merchant_key_rotated.
Buyer data: for buyer agents
The whole purchase, quote to delivery, is in Buy step by step (REST).
Passing a passport or an address to merchant X is a legal and privacy decision for your user: a human confirmation is recommended before you send it (UC-2). Always encrypt to the key in the quote, check sig_by_wallet if you can, send one envelope per required kind, and never log, echo or store the plaintext.
Streams (UC-7 / F-9)
A product with fulfillment_mode: "stream" is sold by the second over an MPP tempo.session payment channel. Catalog item: stream: {rate_per_s_usd (>= 0.0001), min_deposit_usd (>= 1), unit: "second", content_ref} plus the content in fulfillment.instant.payload; price_usd is the per-second rate (omit it, or set it equal to rate_per_s_usd) and the $1.00 order minimum applies to the deposit, not to the rate. The test SKU can never be a stream. shop.catalog.get returns stream.url = https://apibase.pro/api/v1/shop/m/<slug>/stream/<sku>; streams are not listed by shop.catalog.search, the storefront pages or quotes (shop.order.quote refuses a stream sku with 422).
GET|POST /api/v1/shop/m/:slug/stream/:sku?seconds=N (1 <= N <= 60, default 1; 120 requests/min per address) is the only route that issues the session challenge, MPP only: an X-Payment header answers 400 with pay.mpp.url. Without a credential: 402 with the challenge (unit amount = N x rate). open needs an on-chain deposit of at least min_deposit_usd (otherwise 402 deposit_below_minimum, no session is recorded); each accepted open/voucher request deducts N x rate and returns the next slice of the content (consumed_s, consumed_usd, highest_voucher); topUp raises the deposit; close settles the final amount. A channel of another shop or another product is 404 unknown_channel.
Who may settle: on-chain only the channel payee, which is always the merchant's payout_wallet_tempo. shop_merchants.stream_settler is apibase_pilot only for the APIbase demo shop (the pilot key INTEGRATOR_STREAM_PILOT_TEMPO_KEY must be the key of that payout wallet, else 500 stream_settler_misconfigured), merchant (settlement with the merchant's own key, INT-46) or empty (409 stream_unavailable). The worker job shop-stream-settle runs every minute: it settles at highest - settled >= $0.50, hourly while highest > settled, and at once when the payer requests a close on-chain (stream.close_requested). A settle that keeps failing for an hour raises STREAM_SETTLE_OVERDUE. The platform fee of a stream is a receivable (shop_fee_ledger, source = stream): the fee percentage of each settled increment, and at close the missing part of the minimum fee once per session; nothing while the fee switch is off.
Streaming for your shop: run the settler with your own key
A shop that sells streams (fulfillment_mode: "stream") is paid over an on-chain payment channel. Only the channel payee, your payout_wallet_tempo, can settle or close it on-chain. APIbase never holds your key: you run the settler yourself, and APIbase keeps the accounting and verifies the buyer's vouchers.
- Call the check (step 6), then
PATCH /api/v1/shop/merchants/me/stream-settingswith{"settler": "merchant"}(scopecatalog:write). The shop must be active. - Install the CLI (MIT, source in
packages/stream-settler):apibase-stream-settler --key-env MERCHANT_TEMPO_KEY --api https://apibase.pro --mk mk_live_... --interval 60. The key of your payout wallet is read from your own environment variable or file and signs on your machine only; it is never sent to APIbase. Your merchant key needs the scopesorders:readandorders:write. - Every pass reads
GET /api/v1/shop/merchants/me/streams/settle-queue(scopeorders:read): your channels with at least $0.50 unsettled, or an hour since the last settle, or a close requested. Each item is{channel_id, escrow_contract, chain_id, cumulative_amount, signature, action}withaction=settleorclose. The CLI sends the transaction from your wallet, then callsPOST /api/v1/shop/merchants/me/streams/:channel_id/settledwith{tx_hash}(scopeorders:write); the CLI reports a transaction only after its receipt, and retries the report until APIbase has seen it. APIbase reads the chain: the transaction must come from your payout wallet and the channel'ssettledamount must have advanced (for a close, the channel must be finalized). - When a buyer closes a channel, the reply is
202 {"status": "close_pending", "channel_id": ..., "note": ...}: you settle within the grace period; the buyer may request a close and withdraw on-chain afterCLOSE_GRACE_PERIOD. - A
close_pendingchannel, or one the buyer asked to close on-chain, that you have not settled for an hour raises thestream.settle_dueevent (webhook and events feed) and a notice by e-mail. Keep the CLI running.
A close is proven by the ChannelClosed event of the reported transaction; getChannel() is zeroed after close.
The platform fee of settled amounts is a receivable, as for any stream.
Subscriptions (UC-9 / F-8)
A subscription is renewed by the buyer's agent with an explicit payment; by default funds are never debited automatically: the agent renews by paying. A Base payer can opt in to pre-signed authorizations that the platform executes period by period, see Base pull subscriptions. Each period is an ordinary order: it is quoted, paid on either rail, carries the platform fee of an order of that amount (§7.1) and is delivered like any other. The renewal is yours to honor: grant access from the subscription.* webhooks or by reading the subscription.
Catalog: subscription: {period_unit: "day"|"week"|"month", period_count >= 1, max_periods? <= 120, trial: "none"} on an instant or merchant item; price_usd (>= $1.00) is the price of one period.
Buyer flow:
shop.order.quote {merchant, items: [{sku, qty: 1}], subscribe: true}(one item) answers the quote of period 1 withsubscription_terms {period, amount, max_periods, renewal_window_h: 72, cancel_anytime: true}andpayas usual.subscribe: trueon an item without a subscription is422; an item with a subscription cannot be quoted without it.- Paying it moves the order to
PAIDand, in the same transaction, creates the subscription (active,next_charge_at= end of period 1) and its period 1. ThePAIDevent of the order and theshop.order.paidoutbox event carrysubscription_idandperiod_no;shop.order.getshowssubscription {id, period_no}. shop.subscription.get {subscription_id}(GET /api/v1/shop/subscriptions/:id, the payer only, another identity gets404) returns{status, period_no, current_period_end, next_charge_at, renew?}. From 72 h before to 72 h after the end of the paid periodrenew {quote_id, expires_at, total_usd, period_no, pay}is included: the quote of the next period, created on request (15-minute TTL; the same quote while it lives, a new one after it expired), withpay.x402.extra.subscription = {id, period_no}. Paying it adds the period (a period can be paid once: a second quote of the same period is refused with409 subscription_period_paid) and movesnext_charge_atforward by one period.- The paid period over without payment:
statusbecomespast_dueandgetanswers402 subscription_renewal_duewith the samerenew. Paying it in time makes the subscriptionactiveagain. At the end of the period + 24 h the merchant gets onesubscription.past_due; at + 72 h the subscription iscanceledwithstatus_reason: unpaid(subscription.canceled). Whenmax_periodsis reached and the last period is over, it isexpired. shop.subscription.cancel {subscription_id, reason?}(POST /api/v1/shop/subscriptions/:id/cancel) setscanceled; the period already paid runs toaccess_until(=current_period_end) and no further quotes are issued.
Merchant: GET /api/v1/shop/merchants/me/subscriptions?status=&limit=&cursor= (scope orders:read, your own only) and POST /api/v1/shop/merchants/me/subscriptions/:id/cancel {reason} (scope orders:write; canceled, status_reason: merchant, subscription.canceled; another shop's id is 404). Webhook data: {subscription_id, merchant_id, sku, period_no, ...} (order_id and current_period_end on started/renewed; access_until on canceled). shop.merchant.stats reports subscriptions_active (no recurring-revenue figure). The worker job shop-subscription-sweep (every 5 minutes) applies the time-driven steps even when nobody calls get.
Tempo keychain subscriptions
A subscription paid on Tempo can renew without the agent being online, with an access key that the shop generates and keeps. APIbase holds the schedule, verifies on-chain and does the accounting; it never receives, stores or uses a private key and never sends a transaction. The shop pays the gas of each renewal.
- The shop runs
apibase-merchant-renewer init(source inpackages/merchant-renewer): it creates the key on the shop's machine and prints only its address. Register the address withPUT /api/v1/shop/merchants/me/renewer-key {key_id, expires_at}(scopecatalog:write). Only a 20-byte address and a future expiry are accepted: a private key in the body is refused with422, as is any other field.DELETE /api/v1/shop/merchants/me/renewer-keyremoves it. - For a Tempo subscription of a shop with a key,
shop.subscription.getcarriespull_setup {method: "tempo_keychain", key_id, token, limit, expiry, how}: the USDC token on Tempo,limit= plan price x remaining periods in micro-USDC,expiry= the earlier of the key expiry and the end of the subscription term. The payer's agent callsaccessKey.authorize({accessKey: key_id, expiry, limits: [{token, amount: limit}]})(viem/tempo) from the paying account, thenshop.subscription.confirm_pull {subscription_id, tx_hash}(orPOST /api/v1/shop/subscriptions/:id/confirm-pull {tx_hash}). APIbase reads the keychain: the key must be authorized by the paying wallet, not revoked, not expired, and its remaining USDC limit must cover one period (400 keychain_not_authorized | keychain_expired | keychain_limit_too_low). Thenpull_modeistempo_keychain. - The shop's CLI reads
GET /api/v1/shop/merchants/me/subscriptions/renew-queue(scopeorders:read): the shop's owntempo_keychainsubscriptions whose next period has started, as{subscription_id, period_no, payer, amount, memo, recipient, token, splits?}wherememo=0x+ sha256(subscription_id:period_no),recipientis the shop's Tempo payout wallet andsplitsnames the platform fee wallet and the fee when the platform fee is on. For each item the CLI sends, from the payer's account signed by the access key, onetransferWithMemoofamount - feetorecipientand one offeeto the fee wallet, then callsPOST /api/v1/shop/merchants/me/subscriptions/:id/renewed {period_no, tx_hashes[]}(scopeorders:write). - APIbase reads every transaction: it must have succeeded and show, for the memo of that period, transfers
fromthe payer, one to the shop payout wallet and (fee on) one to the fee wallet, with the exact amounts. Anything else is400 renewal_not_provenwith areject_reason. The period is then paid through its order (railtempo,subscription.renewed). With the fee on and no fee transfer the shop must have received the whole price: the period is paid and the fee is recorded as a receivable; with both transfers it is collectedin_tx. - If the key is revoked or expired, or its limit no longer covers a period, the item is not queued,
pull_modereturns tonone, the shop gets onesubscription.pull_failedwebhook (reason:key_revoked,key_expiredorlimit_exceeded) and the period stays due: the agent renews it explicitly and the usualpast_duerules apply.shop.subscription.cancel(or the end of the term) empties the queue; the payer can also revoke the key at any time withaccessKey.revoke.
Base pull subscriptions
A payer who paid period 1 on Base can sign the next periods ahead of time, so the subscription renews without the agent being online. No allowance and no key is handed over: each stored item is one EIP-3009 TransferWithAuthorization for one future period, to a fixed recipient (the shop payout wallet), for a fixed amount (the plan price), valid in a fixed window. It works with any wallet that can sign typed data (a plain EOA); Coinbase Spend Permissions are not needed.
Store them with shop.subscription.preauthorize {subscription_id, authorizations[1..12]} on /mcp or POST /api/v1/shop/subscriptions/:id/preauthorize {authorizations} (the payer only, another identity gets 404; status active or past_due, paid on Base). Each item is {period_no, authorization {from, to, value, validAfter, validBefore, nonce}, signature, fee_authorization? {authorization, signature}} and is checked against the server's data:
| Field | Must be |
|---|---|
period_no | a future period (later than the last paid one) and not above max_periods |
from | the wallet that paid the subscription |
to | the shop payout wallet (the fee leg: the platform fee wallet) |
value | the plan price in micro-USDC; with the platform fee on and a fee leg: price minus fee, and the fee leg is exactly the fee |
validAfter | the unix start of the period (the end of the previous one) |
validBefore | between 1 h and 72 h after validAfter (the same on both legs) |
nonce | a fresh random 32 bytes, unique across all stored authorizations |
signature | a valid signature of from over the USDC domain (USD Coin, version 2, Base) |
One bad item refuses the whole call with 422 and stores nothing; a period that already has a live authorization is 409 period_already_preauthorized. With the fee on, the fee leg is optional: with it the fee is settled in the same transaction (in_tx), without it the whole price goes to the shop and the fee is invoiced to the shop (receivable). Stored signatures are encrypted at rest and never returned or logged. shop.subscription.get shows pull_mode: base_preauth and preauthorized_periods[] {period_no, status, valid_after, valid_before, fee_leg, tx_hash?}.
The worker job shop-subscription-pull (hourly, at :00) takes every stored authorization whose window has opened (validAfter <= now < validBefore - 10 min) for the next unpaid period of an active or past_due subscription. It reads authorizationState(from, nonce) on the USDC contract first: an authorization that was already used or canceled on-chain is marked canceled and never settled. Otherwise it creates the period quote on the server and pays it through the same ESCROW and settle path as shop.order.pay (the quote fixes the payee and the amount; the stored authorizations are the X-Payment payload). Outcomes:
- paid: the period is credited (
subscription.renewed), the authorization issettledand shows itstx_hash; - no receipt yet:
submitted; the payment reconciler decides and the authorization follows it; - refused (for example not enough USDC): the authorization stays
pendingand is tried again on every tick untilvalidBefore - 10 min; - time ran out:
failed, the period ispast_due(the agent can still renew it with the normal renewal quote), and the shop gets onesubscription.pull_failedwebhook{subscription_id, merchant_id, sku, period_no, reason}; the platform also opens aSUBSCRIPTION_PULL_FAILEDincident.
shop.subscription.cancel (and a subscription that ends or expires) turns every pending authorization into canceled: it is never executed. To revoke an authorization yourself, call cancelAuthorization(authorizer, nonce, signature) on the USDC contract. A working client that signs a batch with viem signTypedData (with the fee leg) is scripts/shop/examples/preauthorize-base.ts.
MPP subscription intent
A third way to renew without the buyer's agent paying every period: the official MPP subscription intent on Tempo (pull_mode: mpp_subscription). The payer authorizes one periodic access key whose address belongs to APIbase; APIbase renews each period with it, signs with its own key and pays the gas. The buyer's agent never signs a renewal, and APIbase never receives or stores a payer's key.
Which mode applies:
pull_mode | Rail | Plans | Who renews | Who pays the gas |
|---|---|---|---|---|
none (default) | any | any | the buyer's agent pays each period | the payer |
base_preauth | Base | any | APIbase, with signatures stored ahead | APIbase |
tempo_keychain | Tempo | any | the shop, with its own key | the shop |
mpp_subscription | Tempo | day and week only | APIbase, with the key the payer granted | APIbase |
Monthly plans never get mpp_subscription (the MPP specification accepts day and week only) and keep their current modes. Nothing changes for an existing subscription.
- When the mode applies, the quote of period 1 (
shop.order.quote {..., subscribe: true}) carriespay.mpp_subscription {url, period {unit, count}, renewal: "platform"}next topay.mpp. The mode is offered only for adayorweekplan, only when the platform fee is on and covers ten times the renewal gas (PAY-5), and only for a quote payable on Tempo. With the fee off the mode is not offered andpay.mppis the way to pay. GET /api/v1/shop/quotes/:id/pay?intent=subscriptionanswers402with oneWWW-Authenticate: Paymentchallenge of methodtempo, intentsubscription: the amount (the plan price), the period (periodUnitdayorweek,periodCount), the recipient (the shop payout wallet), exactly one currency (USDC.e on mainnet), the key to authorize inmethodDetails.accessKeyandsubscriptionExpires(the end of the plan term, or 365 days for a plan withoutmax_periods). An mppx client (0.9.3 or newer, 0.13.5 recommended) signs a key authorization bound to that challenge and sends it as the credential withPOST /api/v1/shop/quotes/:id/pay?intent=subscription. Any other value ofintentis ignored andpay.mppapplies.- APIbase activates the key and charges period 1 in one transfer of the whole plan price to the shop payout wallet; the response is the usual paid order and the receipt names the transaction. The subscription starts
activewithpull_mode: mpp_subscription. This intent has no fee split: with the platform fee on, the fee of each period is invoiced to the shop (fee_settlement: receivable) like a fee on Base. shop.subscription.getshowspull_mode: mpp_subscriptionandrenewal_key, the address of the key the payer authorized (APIbase's key, never the payer's).- The worker job
shop-subscription-sweep(every 5 minutes) renews every due period of anactiveorpast_duesubscription exactly once, before it applies thepast_duerules: it signs with the renewal key through mppxrenew, pays the gas, and records the transaction through the period order exactly as the other modes do (railtempo,subscription.renewed). A period is attempted once: a second worker or a repeated tick does nothing. - The shop payout wallet is fixed when the key is granted. If the shop moves its payout wallet, the next renewal is not made (the money would go to the old wallet); the shop gets
subscription.pull_failedwithreason: payout_wallet_changedand the agent pays the renewal quote. - Failure: a revoked or expired key, a spending limit that no longer covers a period, or any error before the transaction is sent leaves the period unpaid,
pull_modereturns tonone, the shop gets onesubscription.pull_failedwebhook (reason:key_revoked,key_expired,limit_exceeded,payout_wallet_changedorrenew_failed) and the usualpast_duerules apply: the agent can still pay the normal renewal quote. - An unknown outcome (the transaction may have been mined, for example a confirmation timeout) is never sent again. The platform checks the chain: a transfer to the shop payout wallet for the plan price completes the period; a reverted transaction or one that never appears ends the attempt as a failure; an attempt with no transaction hash is given up after two hours and raised to the operator.
shop.subscription.cancel(or the end of the term) stops all renewals. It does not touch the chain: the payer revokes the key from the paying account (accessKey.revokefrom viem/tempo, for the address inrenewal_key). A revoked key never renews again.
The renewal key is generated and held by APIbase; the payer's authorization expires on its own at subscriptionExpires, after which the buyer subscribes again.
Partner handoff
A marketplace partner listed in config/integrator/partners.json sends merchants to APIbase and gets them back with their shop address. The partner authenticates with its own key, Authorization: Bearer pk_live_<32 hex>; APIbase keeps only its SHA-256. A missing, malformed or unknown key is 401 partner_key_invalid. A registry entry may carry back_url (optional, https; any other value stops the start): the address of the one link back to you on the connect page (step 2); without it that link goes to the entry's site. Creating is limited to 60 requests/min and reading to 600 requests/min per key.
- Create.
POST /api/v1/shop/partners/handoffswith{seller_ref?, prefill?: {name?, site_url?, contact_email?, category?, country?, slug?}, expected_wallet?, mode?, grant_requested?, scopes?}.seller_refis your own reference (up to 128 characters, opaque to APIbase). Prefill fields follow the registration rules (non-empty name,httpssite URL, e-mail, an allowed category, ISO 3166-1 alpha-2 country, slug[a-z0-9-]{3,40}; whether the slug is free is checked only at registration, asslug_taken).expected_walletis the EVM address you have on file for the seller.modeisregister(default) orgrantfor a store already on APIbase, where the page asks only for the grant signature: sendmode: "grant"when you already hold the seller'sapibase_slug(a prefill e-mail is ignored in this mode); a register link opened by a wallet that already owns a store falls back to the grant step only whengrant_requestedis true, before anything is signed. Withmode: "grant",scopes: ["quotes:read"]asks a store that already allowed you to add that scope: the page then names only what is added (outcomes in Partner grants step 2); any other value, orscopesin moderegister, is422withfield: "scopes".grant_requested: true(moderegister) asks for the partner grant in the registration itself: a seller who registers through a partner handoff with the grant signs once: one message states the shop's encryption key, the registration, the four documents with their versions and hashes, and the partner's permission (see One signature for a partner handoff). A bad field is422 validation_failedwithfieldnaming it. The answer is201 {handoff_id, url, expires_at}, whereurlishttps://apibase.pro/integrator/connect?from=<partner>&handoff=<handoff_id>and the handoff lives 24 hours. - Connect page. Send the seller to
url. A live handoff prefills the form. In moderegisterwithgrant_requested: trueit is one page with one button: a line naming you as the payment partner, two lines on the store page that is opened and where payouts go, the four documents in one line above the button, and everything else (what the message says, the store details read-only, Support email, another payout wallet, another wallet, document versions) under one closed "More options". There a prefill key you send (name,site_url,category,country,slug) is not shown as a field and its value is used even if the seller typed another one in this browser; a key you do not send stays a visible field. A sent value is asked again only when it fails: the slug is taken (slug_taken), or the value does not pass the page's checks when the seller presses the button. Every other live handoff keeps the three steps; values the seller already typed in this browser win, and the seller can change every value.contact_emailin the prefill is optional: when it is present the page shows the address in one line with a Change button and does not ask for it, and it is never copied tosupport_emailor shown to buyers (see the orders line above); after registration the seller changes it with the merchant key (see Registration, step 2); when it is absent or empty the page says the partner does not pass the email and asks the seller to type it. An expired, already registered or foreign handoff shows the plain connect page with one line saying the link is no longer valid. After the wallet connects, the page compares it withexpected_wallet(case-insensitive): a different wallet shows a "Different wallet" notice with how to switch and, when the handoff carriesexpected_wallet, the connect page does not start the signatures while another address is connected and shows both addresses, because the partner will not accept a shop registered with another wallet. Withexpected_wallet, a press first reads the accounts the wallet already permits for apibase.pro (eth_accounts, at most 2 s): when the expected one is among them the page goes straight to the signature; otherwise the press opens the wallet's account window and, while it is open, the page names the expected account (after a run that went straight to the signature and failed for any reason but a rejected signature, the next press opens that window). Withoutexpected_walletevery press opens the account window. The page continues by itself to the signature when that account arrives; another account shows both addresses and one "Choose <address> in wallet" button that opens the window again. The page finds wallet extensions by EIP-6963 and lets the seller choose which one signs. Any connect page opened withfrom=<your id>(live, dead or no handoff) has no site navigation, tabs or footers: one bar with the word APIbase and one link, "← Back to <your name>", which opensback_url(orsite) in the same tab; every other link of the page opens in a new tab. - Registration. The page sends
handoff_idin the register body. An agent registering for a seller passes the same optionalhandoff_id(uuid) toPOST /api/v1/shop/merchantsorshop.merchant.register. A live handoff is bound to the new merchant; an unknown, expired or already used one never fails the registration. - Return. After registration, and equally after a grant signed by a store that already exists (a
mode: "grant"link, or a register link opened by a wallet that already owns a store whengrant_requestedis true), the seller returns to<return_url>?apibase_slug=<slug>&handoff=<handoff_id>, built from the registryreturn_url. With keys on the page the return is the Continue button, enabled once the seller ticks "I saved both keys", and nothing returns by itself. When no keys are shown (a partner withseller_keys: hiddenwhose seller signed the grant, see A shop without keys, or a grant alone) there is no APIbase page and no countdown: the browser goes to the return address at once, so your return page carries the confirmation; read the handoff server to server and expectstate: "granted"(step 5). Nothing else is in the URL. - Read.
GET /api/v1/shop/partners/handoffs/:idreturns{handoff_id, state, seller_ref, slug?, merchant_id?, wallet_match?, created_at, expires_at, opened_at?, registered_at?, grant}.statemovescreated→opened(the page was opened) →registered, and tograntedwhen the seller signs a partner grant through it; a handoff neither registered nor granted within 24 hours readsexpired.wallet_matchisfalsewhen the seller registered a wallet other thanexpected_wallet; it is also set when a grant binds the handoff (falsewhen the granting wallet differs fromexpected_wallet), andregistered_atis absent for a handoff bound by a grant alone. Another partner's id or an unknown id is404. The read never returns the prefill, the merchant's own key, a wallet or an e-mail; the one secret it can carry, once, is your grant key (mode key) or the secret of the webhook endpoint created for you (mode partner) (see Partner grants).
Retention. The prefill is deleted when the handoff is registered or expires (at most 24 hours); handoff rows are deleted after 30 days. The handoff link carries the prefill: treat it like a password-reset link and send it only to the seller.
Partner grants
A merchant can allow a registered partner (see Partner handoff) to act for its store with one wallet signature. A grant names three scopes, catalog:write, webhooks:write and quotes:read (the read of quote outcomes). The partner's registry entry chooses what else the grant gives (grant_mode): in mode key the partner holds its own mk_live_ key for that store, limited to the first two scopes (the key never holds quotes:read); in mode partner no key is created: the partner pushes the catalog with its own partner key and receives the store's order events at the webhook endpoint APIbase creates for it at grant time (see Partner mode). The merchant's own key is never shared. The entry may also carry seller_keys: shown (the default) or hidden, allowed only with grant_mode: "partner" (any other value or combination stops the start). With hidden, a seller who registers through that partner's handoff and signs the grant is not shown an API key or a decryption key; the partner acts with its own key (see A shop without keys). An entry with seller_keys: "hidden" may also carry partner_page_signature: true (default false; with any other seller_keys the start stops): that partner may collect the registration signature on its own page (see Signature on the partner's page).
- Sign.
GET /api/v1/shop/auth/nonce?wallet=0x…&purpose=grant&partner=<partner id>returns thismessage(a partner that is not in the registry is422 validation_failed). Sign it exactly as returned; a changed line is401.apibase.pro: allow <Partner name> to act for your store Address: <wallet> Partner: <partner id> Allows: upload and import your catalog; register its own webhook endpoint and receive your order events; read the outcome of each quote for your products (paid, unpaid, expired, refused), never who the buyer is Does not allow: payouts, keys, orders, refunds Revoke any time: DELETE /api/v1/shop/merchants/me/grants/<partner id> Nonce: <nonce> Issued At: <ISO-8601 time>
- Grant.
POST /api/v1/shop/merchants/me/grantswith{wallet, partner, message, signature, handoff_id?}and noAuthorizationheader (10 requests/min per address). The wallet must be the identity wallet of an active store: none is404 merchant_not_found; a pending, suspended or deactivated store is410 merchant_unavailable. One active grant per store and partner: a second is409 grant_exists, except that a live grant signed beforequotes:readexisted (itsscopeslack it) gains the scope from a valid signature over the current message: the same grant row, with the new message and signature as its proof, answered200with the usual body; no new key, endpoint or secret, and a live handoff named byhandoff_id(as in step 3) is bound and turnsgrantedwithout a secret. Through a handoff created withscopes: a store whose live grant already holds every scope asked answers200with the usual body, the handoff turnsgrantedand nothing else changes; a store without a live grant of yours is404 not_foundand nothing is written. A new grant answers201 {grant_id, partner, mode, scopes, created_at, slug}(modeiskeyorpartner); neither answer carries a key or a secret. - Delivery. When
handoff_idnames an unexpired handoff of that partner that is unbound or bound to this store, the handoff is bound to the store, turnsgranted, and holds the partner's secret encrypted: the key in modekey, thewhsec_secret of the endpoint created for the partner in modepartner. The partner's nextGET /api/v1/shop/partners/handoffs/:idcarries it once, asgrant: {state: "granted", mode, scopes, key}(modekey) orgrant: {state: "granted", mode, scopes, webhook_secret}(modepartner); every later read showsgrant: {state: "granted", mode, scopes, delivered: true}and APIbase no longer holds it. A handoff bound by an added scope (step 2) readsgrant: {state: "granted", mode, scopes}, with no secret and nodelivered.grant.stateisnonewhen no grant came through the handoff andrevokedafter a revoke. In modekeya grant made without a live handoff has no way to reach the partner: revoke it and sign again through a new partner link; in modepartnerthe partner gets a new secret withrotate-secret(see Partner mode). - What a grant key may do (mode
key). Catalog:PUT /merchants/me/catalog(shop.merchant.catalog_upsert; idempotent bysku, the store's single__apibase_testitem included),POST /merchants/me/catalog/importandGET /merchants/me/catalog/import/:id. Webhooks:PUT,GETandDELETE /merchants/me/webhooks(shop.merchant.webhook_set,shop.merchant.webhook_list,shop.merchant.webhook_delete) on its own endpoints. AndGET /merchants/me/check(shop.merchant.check). Everything else is403 grant_key_not_allowedwith the message "this key was granted to <partner>; use the merchant key":keys/rotate,deactivate,acceptances, the grant routes, catalog delete, the Provek declaration, stream settings, the renewer key, orders, refunds, fee invoices, stats and events, and on/mcpeveryshop.merchant.*tool except the five named here. A grant key cannot rotate, get a new key or change a payout. - Endpoint ownership. An endpoint created with a grant key belongs to that grant: the grant key lists, updates (
endpoint_id) and deletes only its own endpoints, and any other id is404. Itswhsec_secret is returned once to the partner, as for any new endpoint. The merchant's key sees and manages every endpoint (see Webhooks). The limit of 5 endpoints per store counts all of them. - List and revoke.
GET /api/v1/shop/merchants/me/grants(shop.merchant.grants_list, merchant key) returns{grants: [{grant_id, partner, mode, scopes, created_at, endpoints}]}: the active grants, their mode and the ids of the endpoints each created.DELETE /api/v1/shop/merchants/me/grants/:partner(shop.merchant.grant_revoke {partner}) answers{partner, revoked: true}; an unknown or already revoked partner is404. A revoke at once revokes the partner's key (401from then on; in modepartnerthe partner routes answer403 grant_revoked), deletes its endpoints (no new deliveries; retries already scheduled stop after the current attempt), drops a key or secret the partner has not read yet and showsgrant: {state: "revoked", mode}on the handoff. The partner may be granted again afterwards. Without the merchant key the store's wallet stops a partner the same way:GET /api/v1/shop/auth/nonce?wallet=0x…&purpose=grant_revoke&partner=<partner id>(a partner that is not in the registry is422 validation_failed) returns thismessage, built by APIbase:apibase.pro: stop <Partner name> acting for your store Address: <wallet> Partner: <partner id> Effect: <Partner name> can no longer upload your catalog or receive your order events. Your store, payouts and orders stay. Nonce: <nonce> Issued At: <ISO-8601 time>
Sign it exactly as returned (EOA or ERC-1271) and send
POST /api/v1/shop/merchants/me/grants/<partner id>/revokewith{wallet, message, signature}and noAuthorizationheader (10 requests/min per address). A changed line, another partner or address, or a used or expired nonce is401. The wallet must be the identity wallet of a store in any status (a suspended or deactivated store can stop a partner): none is404 merchant_not_found. The answer and the effects are those ofDELETE:{partner, revoked: true}, or404 not_foundwithout an active grant. A person does this at /integrator/permissions: one button per partner, one signature. Rotating the merchant key leaves grants in place.keys/reissue(lost key) revokes the merchant's keys and every grant of modekey(its key, its endpoints); a grant of modepartnerholds no key and stays, with its endpoint. To end it, revoke it.
Partner mode
A partner with grant_mode: "partner" also names delivery_webhook_url (https) and delivery_events in its registry entry. At grant time APIbase creates one webhook endpoint for the store at that URL with those events, owned by the grant: it counts towards the 5 endpoints per store, and a URL that breaks the URL rules or a store already at 5 endpoints fails the grant with 422 validation_failed. Its whsec_ secret reaches the partner once through the handoff (step 3). The routes below take the partner's own key (Authorization: Bearer pk_live_…; 401 partner_key_invalid otherwise), 60 writes/min and 600 reads/min per key. A slug that is not a store is 404 merchant_not_found. A store that never granted this partner is 403 grant_missing ("<slug> has not allowed <partner>; send the seller a grant link"); a store whose latest grant of this partner is revoked is 403 grant_revoked with revoked_at. Another partner's grant never counts.
PUT /api/v1/shop/partners/merchants/:slug/catalogwith{items: [...]}(a live grant of either mode): the same body, per-item report, moderation, price ceiling,skuidempotency and single__apibase_testitem asPUT /merchants/me/catalog; a suspended or deactivated store is410 merchant_inactive.GET /api/v1/shop/partners/merchants/:slug/grantsreturns{slug, grants: [{grant_id, partner, mode, state, scopes, signed_at, revoked_at, webhook?}]}: your grants for that store only, active first, then newest, at most 20.stateisactiveorrevoked,revoked_atisnullor a time, andwebhook: {endpoint_id, url, events, status}(modepartneronly) readsstatus: "deleted"when the merchant removed the endpoint. A store without your grants answers200withgrants: []. It never returns a key, a secret, a wallet or an e-mail.POST /api/v1/shop/partners/merchants/:slug/webhook/rotate-secret(modepartner, live grant) answers{endpoint_id, url, events, secret}with a newwhsec_secret, once; the old secret stops signing at once, and the current registry URL and events are applied to the endpoint. In modekeyit is404 not_found; an endpoint the merchant deleted is404.GET /api/v1/shop/partners/merchants/:slug/quotes?updated_after=<ISO 8601>&limit=<1-200>(a live grant whosescopesincludequotes:read; defaultlimit100; a bad query value is422 validation_failed) returns{quotes: [...], next_updated_after}. A quote is{quote_id, order_id, created_at, updated_at, expires_at, is_test, items: [{sku, qty}], total_usd, state, challenges, pay_attempts, last_error_code, last_error_at, paid_at, rail, order_state, read_at, client}.stateisopen,paid,cancelledorexpired(also when the quote is pastexpires_atand not yet marked);challengescounts the402answers given to a call with no payment,pay_attemptsthe calls that carried a payment, andlast_error_codeis the code the buyer was answered when such a call failed (every x402 verification or settle refusal readspayment_required; an MPP credential refused before the pay route is not counted);paid_atis the settlement time,railisbase,tempoornullbefore payment,order_stateis the order state;read_atis the first read of the paid order by its buyer (nulldoes not mean undelivered: the pay answer already carries the order);clientis a product token such aspython-httpx,browseror the MCP client name (at most 40 characters ofA-Za-z0-9._-).updated_atis the latest of creation, the last change of the order, the last recorded event and, once passed while still open,expires_at. Rows come ordered byupdated_atthenquote_id; a page never ends between two rows with the sameupdated_at(it runs pastlimit);next_updated_afteris the last row'supdated_atat microsecond precision,nullwhen the page is not full. A quote made before outcomes were recorded hasnullforchallenges,pay_attempts,last_error_code,last_error_at,read_atandclient(not measured, not zero). A grant signed beforequotes:readwas part of the permission is403 grant_scope_missing(withscope: "quotes:read") until the seller signs the new message once (send ascopeslink, step 1). Read with an overlap and upsert byquote_id: a quote appears again whenever something happens to it.GET /api/v1/shop/partners/merchants/:slug/quote-refusals?after=<ISO 8601>&limit=<1-200>(same grant, limiters andlimit) returns{refusals: [{at, error_code, skus}], next_after}for the last 90 days, ordered byatthen id with the same tie rule: the quote requests the store refused with a4xxafter the shop was known, with the code and the requested SKUs (at most 20, each cut to 64 characters). A request naming an unknown shop, or missing its fields, is not stored. Neither route ever returns an IP address, a user-agent beyondclient, an e-mail, a buyer token or identity, a payer address or its hash, a payment header, signature or transaction hash, an item title or the fee.
A shop without keys
A seller who registers through a partner with seller_keys: hidden and signs the partner's permission is shown no API key and no decryption key. The partner adds the products with its own key, and payouts go straight to the payout wallets. The shop's wallet is enough for the rest.
- Orders and fees: the owner page
/m/<slug>/owner; sign in with the wallet. It is read-only. See Owner view. - To stop the partner: /integrator/permissions with the shop's wallet, one signature. See Partner grants, step 6.
- An API key, to record a refund or to manage the catalogue yourself: the reissue route with a wallet signature (purpose
reissue). It revokes earlier keys and returns a new one; the partner's permission stays. See Lost key. - Buyer personal data: the first encryption key of such a shop has no stored private half; a shop registered on the partner's page has a placeholder key that no one can open (see Signature on the partner's page). Until you rotate the encryption key the catalog refuses such items and physical items (
decryption_key_missing, see the Decryption key rule). See Rotation (step 6).
Webhooks
Register an endpoint with PUT /merchants/me/webhooks (shop.merchant.webhook_set) — body {url, events[], endpoint_id?, rotate_secret?}. events is a non-empty subset of order.paid, order.confirmed, order.shipped, order.delivered, order.cancelled, refund.requested, refund.verified, dispute.opened, catalog.rejected, merchant.key_rotated, merchant.keys_reissued, subscription.started, subscription.renewed, subscription.past_due, subscription.canceled, subscription.expired, subscription.pull_failed, stream.settle_due. A new endpoint returns its signing secret (whsec_ + 32 hex) once; APIbase keeps only its SHA-256 and an encrypted copy for signing. Pass endpoint_id to change an endpoint of yours (another merchant's id is 404; rotate_secret: true issues a new secret).
GET /merchants/me/webhooks lists your endpoints without secrets, each with partner: the partner whose grant created it, or null for your own (a partner's grant key sees and changes only the endpoints it created); DELETE /merchants/me/webhooks/:endpoint_id stops deliveries to it; a lost secret is replaced with rotate_secret: true or by deleting the endpoint and registering a new one. A deleted endpoint is 404 for endpoint_id updates and a second delete (another merchant's id is 404 too), does not count towards the endpoint limit, and receives no new deliveries; retries already scheduled stop after the current attempt. A suspended or deactivated shop may still list, but not delete.
URL rules. https:// only; every address the host resolves to must be public — RFC 1918, loopback, link-local (169.254.169.254 included), CGNAT and IPv6 equivalents are 422. The name is resolved again at every delivery and the connection is pinned to that address; redirects are never followed (a 3xx counts as a failed attempt).
Delivery. POST with a JSON body {id, event, created_at, data} and the headers X-APIbase-Event, X-APIbase-Delivery-Id (the event id, identical on every retry) and X-APIbase-Signature: t=<unix>,v1=<hex>, where v1 = HMAC-SHA256(secret, t + "." + body) over the raw body bytes. Verify it and reject old t (e.g. older than 5 minutes):
const [t, v1] = header.split(',').map((p) => p.split('=')[1]);
const ok = timingSafeEqual(
Buffer.from(createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex')),
Buffer.from(v1),
);Any 2xx within 10 s is delivery. Anything else (other status, timeout, connection error) is retried after 1 min, 5 min, 30 min, 2 h, 12 h, 24 h — seven attempts in all, then the delivery is failed. After 10 failures in a row an endpoint is only tried on that schedule (new events wait one minute before their first attempt) until one delivery succeeds. Status code and the first 1 KB of the answer are kept per attempt.
Instant fulfillment. Answer 200 to order.paid with a fulfillment body and the order goes PAID → CONFIRMED → FULFILLED at once; the exact bodies, limits and what happens to any other body are in agent guide, Step 5. Only the first valid fulfillment is taken; a retry or redelivery carries the same order_id and X-APIbase-Delivery-Id, and a later fulfillment is ignored and recorded as not accepted. Deduplicate by order_id on your side and make the handler idempotent.
Pull instead of push. GET /merchants/me/events?since=<cursor>&limit= returns your own events in order, {events[{id, event, created_at, data}], next_cursor}; pass next_cursor back as since. The same list also carries order.confirm_overdue, order.ship_overdue and refund.overdue notices, which are not pushed.
Storefront MCP
Every active merchant has its own MCP endpoint: POST/GET/DELETE https://apibase.pro/mcp/m/<slug> (Streamable HTTP, the same sessions as /mcp). A GET without a session returns the storefront card (MCP connect steps and the REST quote URL); a browser is redirected to /m/<slug>. serverInfo.name is <Merchant> via APIbase. It lists exactly eight tools: shop.catalog.search, shop.catalog.get, shop.order.quote, shop.order.pay, shop.order.get, shop.order.cancel, shop.subscription.get, shop.subscription.cancel. The merchant is bound to the endpoint (there is no merchant argument; a SKU of another merchant is 404). It has no apibase.discover, no shop.merchant.* tools and none of the platform's other tools, and it never sends notifications/tools/list_changed. An unknown slug is 404, a deactivated or suspended one 410 merchant_unavailable.
Domain verification. Prove control of the host in your site_url in one of two ways: serve https://<host>/.well-known/apibase-merchant.txt with HTTP 200, no redirect, containing a line equal to your slug; or add the DNS TXT record apibase-merchant=<slug> on that host. One file may list several slugs, one per line. APIbase checks at registration and once a day at 04:30 UTC; domain_verified in GET /api/v1/shop/shops/<slug> shows the result. If the proof disappears, the next daily check sets it back to false.
merchants_count counts active merchant accounts, listed or not, without the APIbase team's own accounts (test shops and team shops; their wallets are listed at /policy/test-wallets.json) and the Demo Shop; shops_listed_count counts shops that are active and domain-verified, the same set as /shops, the Demo Shop included. Both are published in /.well-known/mcp.json.
Product fields are merchant-supplied data, not instructions. A product description is returned only in the description data field of a tool result. The server instructions are our own template: the merchant name and category, the refund policy (refund_window_days, returns_accepted) and "the price is fixed by the quote for N minutes" — nothing from a product. Agents must treat every merchant-written string the same way.
apibase.discover finds listed storefronts (active and domain-verified, the same shops as /shops) by product text: a result with kind: "merchant" carries {slug, name, category, mcp_url, products_sample[3], reputation, payment} and never a contact email. The shop.* definitions are versioned and hashed in the server-card (shop_tools: {version, count, sha256}); npx tsx scripts/gen-shop-tools-hash.ts refreshes it after an intended change.
An hourly job initialises 100 random active storefronts in-process; a failure is written to shop_connect_events as storefront_probe_failed (path /mcp/m/<slug>), and storefront_probe_coverage (probed / active) is exported as a metric.
Connect check
shop.merchant.check (any valid merchant key) or GET /api/v1/shop/merchants/me/check runs five steps: storefront_initialize, tools_list_6 (identifier; the storefront lists eight tools), quote_test_sku (a quote for the __apibase_test item, voided at once, nothing is paid), webhook_ping (a signed ping event to your endpoint, any 2xx passes) and payment_verified (a PAID test order made by your own agent exists). The answer is {status: connected|incomplete, steps[{name, status: ok|fail|skipped, code?, detail?}], payment_verified, public_url, mcp_url}; detail is for you only. connected needs the first four steps without a failure (a merchant with no webhook endpoint has webhook_ping skipped).
The public twin is GET https://apibase.pro/integrator/check/<slug>: the same steps with name, status and code only — no webhook URL, email, payout address or response body. It is limited to 20 requests/min per address and a slug's result is reused for 60 seconds.
Provek declaration (optional)
PATCH /api/v1/shop/merchants/me/provek (key scope catalog:write) with {opt_in: boolean, insurance?: {exists: boolean, note?: string (at most 140 characters)}, claims_url?: https URL} publishes or withdraws a Provek declaration for your shop. The merchant comes from the key; unknown fields are rejected with 422. While opt_in is true:
GET https://apibase.pro/m/<slug>/provek.jsonserves aprovek_declaration: "1.1.0"document: the claims addressee (claims_url, else yoursite_url), the emergency stop (shop.merchant.deactivatemakes the storefront answer410), your insurance statement, a dispute path on your shop page, and the order, offering and pricing URLs. Yourcontact_emailis never part of it. Withopt_infalse the path answers404, for a deactivated shop410. Your shop page links to it with<link rel="alternate" type="application/json">.provek {declared, listed, registry_url}appears inshop.catalog.get(merchant), inapibase.discoverresults of kindmerchant, inagent.json, and on/m/<slug>.listedbecomes true only when a daily job finds the host of yoursite_urlin the public Provek registry (https://provek.dev/data/registry.json; public addresses only, no redirects, 20 s timeout, at most 10 MB; if the download fails the previous values stay). Only then does a page call the entry "verified"; a declaration alone says "declared by the merchant; not listed in the Provek registry".- Provek and APIbase belong to the same owner; the assessment is not independent. This line is shown next to every mention of Provek.
GET /api/v1/shop/shops/<slug>/evidence.json (public, cached for 60 s) returns aggregates only: {slug, as_of, reputation {closed_on_time_pct, dispute_rate, refund_rate, orders_closed}, domain_verified, connected, payment_verified, active_since, rails, provek}. No wallet, e-mail or order data. The __apibase_test item is never counted.
Merchant stats
shop.merchant.stats or GET /api/v1/shop/merchants/me/stats?from&to&group=day|week (key scope stats:read) returns your own aggregates for the range (default: the last 30 days, at most 366): the funnel quotes -> paid -> closed, gross_usd / fee_usd / net_usd, avg_order_usd, a series by day or week, refunds, disputes by status, the top 20 products, a cut by rail, a cut by agent (client_name, client_version, user-agent family, 8-character wallet hash prefix, never the full address), webhook success % and p95 delivery time, and the orders past their confirm/ship SLA. The __apibase_test item is never counted. The answer is cached for 60 s per merchant and parameters. format=csv returns one row per paid order with its tx_hash; the payer appears only as a hash prefix.
Fee invoices
Orders paid on Tempo carry the platform fee inside the payment, and so do Base orders paid with a fee-split client (two EIP-3009 signatures, one Multicall3 transaction; the ledger row is collected). Orders paid on Base with a single authorization owe it as a receivable from the first order: on the 1st of each month every owed Base fee created before that month becomes one USDC invoice for the closed period ({invoice_id, period, amount_usd, due_at}, due 30 days after it is issued) and you get a mail with the amount, our wallet and the invoice id as the payment reference. With the fee switched off the amount is 0 and no invoice exists.
GET /api/v1/shop/merchants/me/fee-invoices (key scope stats:read) lists your invoices with pay_to and memo. After sending USDC on Base to pay_to, call POST /api/v1/shop/merchants/me/fee-invoices/:id/paid {tx_hash} (key scope refunds:write). APIbase only reads the chain: the transaction must be confirmed and carry a USDC transfer to the fee wallet of at least the invoice amount; otherwise 422 fee_payment_rejected with the reason and the invoice is unchanged. A transaction pays one invoice only.
An invoice unpaid 30 days after due_at switches the Base rail off for your shop (new quotes offer Tempo only, status_reason: fee_overdue_base_off) and raises a FEE_INVOICE_OVERDUE notice for the operator; after 60 days the shop is suspended and quotes answer 410. Paying the invoice lifts both limits automatically. shop.merchant.stats (fee_receivable) and the owner view show the owed amount and the open invoices.
Owner view
GET /m/<slug>/owner is a read-only page for the merchant wallet: status, the last 50 orders, the platform fee (owed, invoiced, collected), your open fee invoices and webhook health. It has no forms and writes nothing. Get a nonce with GET /api/v1/shop/auth/nonce?wallet=<wallet>&purpose=owner, sign the returned message with the merchant wallet, and send it base64-encoded in X-Owner-Message with the signature in X-Owner-Signature. The reply sets a 15-minute HttpOnly cookie, so later loads need no new signature. No credential is 401; a valid signature of any other wallet is 404.
Legal documents
Texts accepted by the operator without legal review; the version and hash a merchant accepted are in shop_acceptances.
- Where.
static/legal/{merchant-agreement,aup,dpa,refund-framework}.md— English text first, Russian section below, both canonical in one file. The first line is an HTML comment that holdsversion: X; effective_from: YYYY-MM-DD; status: …. The fee appears only as the token0% (pilot)(substituted when the HTML page is rendered;.mdkeeps the token). The country list inaup.mdis generated fromconfig/integrator/countries-restricted.jsonbyscripts/shop/gen-aup-countries.ts, never by hand. - Hash.
sha256is computed over the exact bytes of the.mdfile.scripts/shop/sync-legal-docs.ts(run at app start, and as--checkinnpm run build) upsertsshop_legal_docs(doc_id, version, sha256, url, effective_from, body_md). Changing text without changingversionfails startup; a newversionadds a row and old rows stay. - Routes.
GET /legal/index.json→[{doc_id, version, sha256, url, effective_from}]; each entry also carrieshash_ofandsource_url.GET /legal/<doc_id>→ HTML, or the.mdwithAccept: text/markdown; both serve the current effective version.GET /legal/<doc_id>.md→ that version with the fee token rendered;GET /legal/<doc_id>.src.md[?version=<v>]→ the raw file. It is the exact registry bytes of the current effective (or the requested registered) version,ETag: "sha256-<hex>", unknown version404 unknown_version;GET /legal/terms.body.txtand/legal/privacy.body.txt→ the exact text hashed for/termsand/privacy. The sha256 is reproducible from the bytes atsource_url(the signed document, fee token unsubstituted). A scheduled version is shown on /legal and on the document page with its effective date, listed at /legal/index.next.json, and announced to every active merchant by e-mail; acceptance is possible from the effective date. 60 requests/min per address, then429. - DRAFT banner. HTML pages carry
<div class="draft-banner">and<meta name="robots" content="noindex">untilconfig/integrator/legal-published.json({published_at, by}) exists. Publication is the committedconfig/integrator/legal-published.json{published_at, by}(operator decision, committed by the dispatcher after the operator's word), not a host file:config/is baked into the image. The Integrator pages state the status from that file viaCurrent versions and hashes: /legal/index.json (latest effective 2026-12-10).. The.mdnever carries a banner. - Acceptance. A merchant accepts the four documents by signing the §11.2 message with its wallet — see Registration & terms (
shop.merchant.accept_terms,POST /merchants/me/acceptances). /termsand/privacyhave a new Integrator section (markedintegrator-legalin the HTML); the other sections are unchanged.
Integrator pages (INT-17)
Served by src/shop/routes/integrator.router.ts from static/integrator/ (copied into the image by docker/Dockerfile). Each page is HTML, or Markdown with Accept: text/markdown; Vary: Accept; 120 requests/min per address.
| Path | Source | What it is |
|---|---|---|
/integrator | index.html / index.md | 12 blocks in the §13.1 order: offer (RU/EN canon), flow diagram, shop illustration, variants A–D, connect in 10 minutes, sandbox + check, fee, security, FAQ, legal, AIpush.app, buyers. HTML ≤ 35 KB, no external resources, no script. |
/integrator/llms.txt | llms.txt | links to every page below. |
/integrator/agent-guide | agent-guide.md | nonce → register → accept_terms → catalog_upsert → webhook_set → check → pay test-SKU → payment_verified, wallet precondition first, and one anchor per §6.4 error code (#quote_expired … #test_sku_daily_cap) for documentation_url. |
/integrator/buyers, /integrator/wallet | buyers.md, wallet.md | limits live in the buyer's wallet, price fixed by the quote, keys are never requested, what stays outside the guarantees; wallet help (no wallet is issued). |
/integrator/why-base-tempo | why-base-tempo.md | the F-5 text, without evaluative words. |
/integrator/platforms/{shopify,woocommerce,tilda,wix,custom} | platforms/*.md | paste link A–C; no script (UC-20). |
/integrator/connect | connect.html | human form: fields, category list from prohibited-categories.json, links to the four documents (versions and hashes from /legal/index.json; the page names the versions in force today and, from /legal/index.next.json, any announced change with its date, in words; ids and hashes under "Technical details"), three personal_sign signatures (encryption key, register, accept_terms), POST /api/v1/shop/merchants then POST /api/v1/shop/merchants/me/acceptances with method: wallet_signature (the signature is the single act of acceptance; checkbox+wallet_signature remains in records made before this change and stays a valid input), or one signature and POST /api/v1/shop/merchants/handoff in a partner handoff with the grant (One signature for a partner handoff); one inline script ≤ 40 lines, no libraries. The browser generates an X25519 key; its private half is shown once next to the API key, except where A shop without keys applies. |
/integrator/permissions | permissions.html / permissions.md | one row per registry partner (?partner=<id> shows only that row) with one button, "Stop <Partner name>": the wallet chosen by EIP-6963, one personal_sign of the grant_revoke message and POST /api/v1/shop/merchants/me/grants/:partner/revoke (Partner grants, step 6); each outcome is one visible line; noindex. |
Tokens. Templates carry 0% (pilot), $1.00, 11, 1, Sandbox: https://sandbox.apibase.pro — the same image on Base Sepolia and Tempo testnet with its own database; register and run the connection check there first, then repeat on mainnet with the $0.01 test SKU.; they are filled at request time from INTEGRATOR_FEE_ENABLED/INTEGRATOR_FEE_BPS, INTEGRATOR_MIN_ORDER_USD, SANDBOX_STATUS; MERCHANTS_COUNT comes from static/.well-known/mcp.json (sync-counts baseline, in the image), not from env (INT-19 replaces the env defaults with sync-counts values). With the fee off the canon reads "0% fee during the pilot". The default sandbox line points at https://sandbox.apibase.pro (see DEFAULT_SANDBOX_STATUS).