APIbase Integrator (merchant) guide

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.

StepREST (/api/v1/shop)MCP tool
1GET /auth/nonce?wallet=0x…&purpose=register—
2POST /merchantsshop.merchant.register
3GET /auth/nonce?wallet=0x…&purpose=accept_terms—
4POST /merchants/me/acceptancesshop.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)—
  1. Nonce. GET /auth/nonce returns {nonce, issued_at, expires_in, message}; message is the exact text to sign for that purpose. A nonce is single-use and lives 300 s.
  2. Register. Sign the register message:
    text
    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 message and signature. The reply is {merchant_id, slug, status: "pending", docs_to_accept: [{doc_id, version, sha256, url}]}. contact_email is required and private: it is never shown to buyers. support_email is optional (absent or "" = none, otherwise an e-mail, else 422 validation_failed with field: "support_email") and is the address buyers see as merchant_contact.email on their open orders; set or clear it, or change contact_email, later with PATCH /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 gets 403 grant_key_not_allowed), which answers {support_email}, plus contact_email_updated: true when the contact address changed (compared case-insensitively), and never the address. contact_email cannot be removed: null, "" or a non-address is 422 validation_failed with field: "contact_email". A change sends one notice to the previous address; at most 3 changes in 24 hours, then 429 rate_limited. Without a signature the call is 401. The sign-up IP country is checked as described under country_not_supported; form/IP mismatch never blocks.

  3. Accept the four documents (merchant-agreement, aup, dpa, refund-framework) by signing, with a fresh accept_terms nonce, exactly this text (one line; hashes are the sha256 values from docs_to_accept):
    text
    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 is active and 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.

  4. 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 with 428 terms_not_accepted.
  5. Deactivate. deactivate stops new quotes and shows the storefront as 410. Open orders stay serviceable: existing keys keep orders:read/orders:write; catalog:write calls get 410.

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.

merchant_unavailable (410) — the merchant is not available (deactivated or otherwise). The reason is not disclosed. Policy: /legal/refund-framework.

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

  1. 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 mode register or did not ask for the grant (422 validation_failed, field: "handoff"), a wallet other than the handoff's expected_wallet (401), wallet_registered and slug_taken (409). The message, single-use, 300 s:
    text
    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".

  2. POST /merchants/handoff with the merchant fields of step 2 (the slug of the message), wallet, handoff_id, message and signature, no Authorization header (the limits of POST /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 than expected_wallet is 401 and 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's sig_by_wallet is this signature with the text in signed_message (see Buyer PII, step 2). The answer is 201 {merchant_id, slug, status: "active", handoff: {handoff_id, state: "granted"}, grant: {grant_id, partner, mode, scopes, created_at}}, plus api_key (mk_live_…, shown once) unless the partner's registry entry has seller_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).

  1. POST /api/v1/shop/partners/handoffs/<handoff_id>/signature-text with exactly {wallet} answers 200 {handoff_id, message, issued_at, expires_in: 300}. The text is single use and lives 300 s; a second call replaces the first. Pass message to personal_sign byte for byte and do not parse it:
    text
    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 text apibase.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 with POST /merchants/me/keys/rotate (see Buyer PII).

  2. POST /api/v1/shop/partners/handoffs/<handoff_id>/registration with {wallet, signature, seller_ip, seller_user_agent?} answers 201 {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 (store active, encryption key with sig_by_wallet and signed_message, one acceptance per document, the grant, the handoff granted). seller_ip is 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_agent is optional, at most 512 characters. Take the webhook secret once from GET /partners/handoffs/<handoff_id>, as for any grant.

Errors on either route:

StatusCodeWhen
403partner_page_signature_offyour registry entry does not have partner_page_signature: true
404not_foundthe handoff is not yours or does not exist
422validation_failedfield names it: wallet, handoff, expected_wallet, prefill.<key>, signature, seller_ip, seller_user_agent, or an unknown body key
401unauthorizedthe wallet is not expected_wallet
409wallet_registered, slug_takenchecked before anything is signed, and again at registration
503service_unavailableretry 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:

  1. GET /api/v1/shop/auth/nonce?wallet=0x…&purpose=reissue returns a message to sign.
  2. Sign it with the merchant (identity) wallet (EIP-191) and call POST /api/v1/shop/merchants/me/keys/reissue with {wallet, message, signature} and no Authorization header.
  3. The response is {api_key}: a fresh mk_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 is 401.
  4. 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/catalog with { "items": [ … ] } (≤500 items, body ≤1 MB) · MCP shop.merchant.catalog_upsert. Idempotent by sku; the merchant is always the key's owner (a merchant field in the body is ignored). A price change applies to new quotes at once.
  • MCP shop.merchant.catalog_delete {skus[]} — refused with 409 and quote_ids while an open quote holds a sku.

Item (zod schema CatalogItemSchema, src/shop/catalog.service.ts):

fieldrule
sku[A-Za-z0-9._:-], ≤64
title≤120 after HTML/control/zero-width stripping
description≤2 000 after stripping
price_usddecimal, ≤2 fractional digits, $1.00 … limits.max_order_usd
is_testonly for the test SKU (below)
stockinteger ≥0; null/absent = not tracked
fulfillment_modeinstant · merchant · physical · stream
fulfillment.instant.payloadrequired 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
categoryone 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 with sku,title,price_usd plus optional description,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.json of the shop (url may be the shop root): each product becomes an item, each variants[] 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_email is 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-Key supported: a replay returns the same quote_id and holds stock once) · GET /api/v1/shop/quotes/:id.
  • The same X-Idempotency-Key header works on plain POST /api/v1/tools/:toolId/call: 10 minutes, scoped to the paying wallet, and a duplicate while the first call runs is a 409 conflict with retry_after. /mcp callers 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 is QUOTED; the quote is voided and the held stock released. reason is optional while the order is QUOTED (the quote's cancel_url). After payment: 409 not_cancellable (refund flow).
  • Physical items (T-INT-22). A quote with a physical product needs shipping_option (an id from the product's shipping_options[], else 422 listing the offered options); its price_usd is added once as shipping_usd and is part of total_usd. When the product lists delivery_slots[], delivery_slot is required too: the slot is held until the quote expires (one live hold per product and slot); a taken slot answers 409 slot_unavailable with alternatives (the free slots). A paid order keeps its slot. requires_pii always includes shipping_address (end-to-end encrypted, see the PII section); paying without it is 422 pii_required. shipping_option/delivery_slot on a quote without physical items → 422.
  • Physical order flow. PAID → CONFIRMED (merchant only, order_confirm; sets ship_due_at = now + policy.ship_sla_h, default 72 h) → SHIPPED (order_ship {order_id, tracking: {carrier, number, url?}, delivery_eta}; the buyer sees tracking and delivery_eta in order.get) → DELIVERED (the merchant calls order_ship {order_id, delivered_at}, or automatically delivery_eta + 7 days) → CLOSED when close_after (DELIVERED + refund_window_days) passes. There is no buyer-side confirm-delivery tool (not in §6): the buyer's way out is shop.order.cancel within the refund window or the automatic DELIVERED.

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 exactly total_usd to 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?} and order_url (the absolute https://apibase.pro/api/v1/shop/orders/<order_id>); without order.fulfillment the body also carries next, one sentence telling you to GET order_url with the buyer Bearer until FULFILLED. Instant products go PAID → CONFIRMED → FULFILLED; waive_withdrawal: true closes the order at once (CLOSED), otherwise it closes after refund_window_days (default 14). The test SKU delivers test ok. merchant fulfillment stays PAID until the merchant confirms.
  • GET /orders/:id and shop.order.get carry viewer: payer sees fulfillment, documents and merchant_contact {site_url, email?} (email is the shop's support e-mail when it set one; the registration contact e-mail is never shown); public sees state and events only and a hint naming the credential (on REST the quote's buyer_token as Authorization: Bearer, or, on REST, a request signed by the paying wallet: headers X-Payer-Address and X-Payer-Signature = personal_sign of apibase-order:<order_id>:<unix minute> (current or previous minute); read-only; a bad signature is 401 order_signature_invalid).
  • 202 payment_pending {order_id, order_url, next} — the receipt was not seen in time; the order stays PAYING. Poll shop.order.get / GET /api/v1/shop/orders/:id. The shop-payment-reconcile job (every 60 seconds, 24 h window) reads authorizationState(payer, nonce) and the USDC Transfer on-chain: confirmed → PAID and delivery; not confirmed after 24 h → PAYMENT_FAILED for good, the quote expires and the stock reservation is released. Only pending/failed payments are reconciled, never wallets. PAYING may 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 goes PAYMENT_FAILED → PAYING. A quote that is already paid, or has a payment in progress, also answers 402. The body states the x402 terms once, in accepts[]; pay in a 402 carries only mpp (and mpp_subscription), never x402, and is absent when the quote offers no other rail. The PAYMENT-REQUIRED header carries the x402 object only (x402Version, error, resource, accepts, extensions). A 402 also carries pay_before and, while the order is QUOTED, cancel_url.
  • payment-identifier (optional x402 extension). The order 402 lists it in extensions. Add extensions["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, never fulfillment — read it with order.get) with no second verify or settle for 24 hours; the same id with another quote, amount, recipient or payer is 409 payment_identifier_conflict; the same id while the first request is still running is 409 payment_in_flight. The 409 carries retry_after (and the Retry-After header on REST), order_id when known and poll: "shop.order.get"; wait, then re-send the same id; a conflict carries reason: "payer" | "request". A repeated answer carries replayed: 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 of shop.order.pay without a payment on a quote the same identity already paid returns the same order (with fulfillment) and order_url; any other identity gets 402.
  • 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) also fulfillment? (same on every call), documents[] (merchant links) and, while the order is open (PAID … DELIVERED, REFUND_PENDING, DISPUTED; not CLOSED), merchant_contact {site_url, email?}: email is the shop's support_email when it set one; the registration contact e-mail is never shown.
  • shop.order.cancel after payment: before the merchant confirms (PAID) it is always a refund → REFUND_PENDING and a shop_refunds row due in 7 days (shop.refund.requested); after CONFIRMED only if the SKUs accept returns and refund_window_days is still open, otherwise 409 not_cancellable with the policy. Digital content delivered under waive_withdrawal (FULFILLED/CLOSED) is 409.
  • Merchant order tools. orders_list {state?, since?, cursor?, limit?} (own orders only, next_cursor for the next page), order_confirm {order_id} (PAID → CONFIRMED, stops the confirm SLA; another merchant's order is 404), order_ship {order_id, tracking?, delivery_eta?, delivered_at?} (physical orders: CONFIRMED → SHIPPED, then delivered_at → DELIVERED; 409 not_shippable otherwise), order_document {order_id, url} (https:// only, else 422; shown in the buyer's order.get.documents).
  • Refunds (shop.merchant.refund {order_id, amount, tx_hash} / POST /merchants/me/refunds, scope refunds: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 USDC Transfer with to = the payer and value >= amount. Verified → shop_refunds.verified, the order goes REFUND_PENDING → REFUNDED (the refunds add up to total_usd) or PARTIALLY_REFUNDED (a further refund moves it through REFUND_PENDING again). A transaction that does not prove it → 422 refund_rejected with reject_reason, the record is rejected and the order is unchanged; more than the order total is 400 refund_exceeds_total; a transaction settles one refund only (409 tx_already_used). The platform fee is not returned; for reason = duplicate the fee leg is already written_off.
  • Disputes (shop.order.dispute {order_id, reason_code, note?} / POST /orders/:id/disputes, the payer only, another identity gets 404). reason_code: not_received | not_as_described | duplicate | canceled_recurring | agent_error | other; note up 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. After due_at the dispute is expired, the order returns to its prior state and one shop.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 in catalog.search/catalog.get/discover (merchant.reputation) and on /m/<slug>. The test SKU and reason = duplicate are not counted. At 10 or more closed orders dispute_rate >= 1% queues a warning (mail + shop.merchant.dispute_rate_warning, at most weekly); >= 2% with at least 3 disputed orders sets status_reason = disputes and quotes answer 410 until the operator clears it (scripts/shop/merchant-status.ts --clear-reason, event shop.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, QUOTED orders → EXPIRED); PAID past confirm_due_at (PAID + policy.confirm_sla_h, default 48 h, merchant-fulfilled orders only) → one shop.order.confirm_overdue, repeated every 24 h; CONFIRMED physical past ship_due_at → one shop.order.ship_overdue (pull-only); SHIPPED with delivery_eta + 7 days passed → DELIVERED; three late orders in a row → the merchant gets status_reason = unresponsive and quotes answer 410 until the operator clears it (scripts/shop/merchant-status.ts --clear-reason, event shop.merchant.reason_cleared); after a lift only orders settled after the lift count towards the flag again; close_after passed → CLOSED; refund due_at passed → overdue + one shop.refund.overdue; dispute due_at passed → expired + one shop.dispute.unanswered; merchant reputation recomputed hourly (disputes ≥ 1% warn; ≥ 2% and at least 3 disputed orders suspend); payout_pending.effective_at passed → the new payout wallet is applied; shop_connect_events older than 30 days are deleted.
  • Paid orders emit the shop.order.paid event; the PAID order event records request_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:

sh
# 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-keygen

The 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):

text
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:

json
{
  "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 reaching DELIVERED, CANCELLED, REFUNDED or PAYMENT_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.

  1. Call the check (step 6), then PATCH /api/v1/shop/merchants/me/stream-settings with {"settler": "merchant"} (scope catalog:write). The shop must be active.
  2. 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 scopes orders:read and orders:write.
  3. Every pass reads GET /api/v1/shop/merchants/me/streams/settle-queue (scope orders: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} with action = settle or close. The CLI sends the transaction from your wallet, then calls POST /api/v1/shop/merchants/me/streams/:channel_id/settled with {tx_hash} (scope orders: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's settled amount must have advanced (for a close, the channel must be finalized).
  4. 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 after CLOSE_GRACE_PERIOD.
  5. A close_pending channel, or one the buyer asked to close on-chain, that you have not settled for an hour raises the stream.settle_due event (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:

  1. shop.order.quote {merchant, items: [{sku, qty: 1}], subscribe: true} (one item) answers the quote of period 1 with subscription_terms {period, amount, max_periods, renewal_window_h: 72, cancel_anytime: true} and pay as usual. subscribe: true on an item without a subscription is 422; an item with a subscription cannot be quoted without it.
  2. Paying it moves the order to PAID and, in the same transaction, creates the subscription (active, next_charge_at = end of period 1) and its period 1. The PAID event of the order and the shop.order.paid outbox event carry subscription_id and period_no; shop.order.get shows subscription {id, period_no}.
  3. shop.subscription.get {subscription_id} (GET /api/v1/shop/subscriptions/:id, the payer only, another identity gets 404) returns {status, period_no, current_period_end, next_charge_at, renew?}. From 72 h before to 72 h after the end of the paid period renew {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), with pay.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 with 409 subscription_period_paid) and moves next_charge_at forward by one period.
  4. The paid period over without payment: status becomes past_due and get answers 402 subscription_renewal_due with the same renew. Paying it in time makes the subscription active again. At the end of the period + 24 h the merchant gets one subscription.past_due; at + 72 h the subscription is canceled with status_reason: unpaid (subscription.canceled). When max_periods is reached and the last period is over, it is expired.
  5. shop.subscription.cancel {subscription_id, reason?} (POST /api/v1/shop/subscriptions/:id/cancel) sets canceled; the period already paid runs to access_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.

  1. The shop runs apibase-merchant-renewer init (source in packages/merchant-renewer): it creates the key on the shop's machine and prints only its address. Register the address with PUT /api/v1/shop/merchants/me/renewer-key {key_id, expires_at} (scope catalog:write). Only a 20-byte address and a future expiry are accepted: a private key in the body is refused with 422, as is any other field. DELETE /api/v1/shop/merchants/me/renewer-key removes it.
  2. For a Tempo subscription of a shop with a key, shop.subscription.get carries pull_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 calls accessKey.authorize({accessKey: key_id, expiry, limits: [{token, amount: limit}]}) (viem/tempo) from the paying account, then shop.subscription.confirm_pull {subscription_id, tx_hash} (or POST /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). Then pull_mode is tempo_keychain.
  3. The shop's CLI reads GET /api/v1/shop/merchants/me/subscriptions/renew-queue (scope orders:read): the shop's own tempo_keychain subscriptions whose next period has started, as {subscription_id, period_no, payer, amount, memo, recipient, token, splits?} where memo = 0x + sha256(subscription_id:period_no), recipient is the shop's Tempo payout wallet and splits names 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, one transferWithMemo of amount - fee to recipient and one of fee to the fee wallet, then calls POST /api/v1/shop/merchants/me/subscriptions/:id/renewed {period_no, tx_hashes[]} (scope orders:write).
  4. APIbase reads every transaction: it must have succeeded and show, for the memo of that period, transfers from the payer, one to the shop payout wallet and (fee on) one to the fee wallet, with the exact amounts. Anything else is 400 renewal_not_proven with a reject_reason. The period is then paid through its order (rail tempo, 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 collected in_tx.
  5. If the key is revoked or expired, or its limit no longer covers a period, the item is not queued, pull_mode returns to none, the shop gets one subscription.pull_failed webhook (reason: key_revoked, key_expired or limit_exceeded) and the period stays due: the agent renews it explicitly and the usual past_due rules apply. shop.subscription.cancel (or the end of the term) empties the queue; the payer can also revoke the key at any time with accessKey.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:

FieldMust be
period_noa future period (later than the last paid one) and not above max_periods
fromthe wallet that paid the subscription
tothe shop payout wallet (the fee leg: the platform fee wallet)
valuethe 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
validAfterthe unix start of the period (the end of the previous one)
validBeforebetween 1 h and 72 h after validAfter (the same on both legs)
noncea fresh random 32 bytes, unique across all stored authorizations
signaturea 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 is settled and shows its tx_hash;
  • no receipt yet: submitted; the payment reconciler decides and the authorization follows it;
  • refused (for example not enough USDC): the authorization stays pending and is tried again on every tick until validBefore - 10 min;
  • time ran out: failed, the period is past_due (the agent can still renew it with the normal renewal quote), and the shop gets one subscription.pull_failed webhook {subscription_id, merchant_id, sku, period_no, reason}; the platform also opens a SUBSCRIPTION_PULL_FAILED incident.

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_modeRailPlansWho renewsWho pays the gas
none (default)anyanythe buyer's agent pays each periodthe payer
base_preauthBaseanyAPIbase, with signatures stored aheadAPIbase
tempo_keychainTempoanythe shop, with its own keythe shop
mpp_subscriptionTempoday and week onlyAPIbase, with the key the payer grantedAPIbase

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.

  1. When the mode applies, the quote of period 1 (shop.order.quote {..., subscribe: true}) carries pay.mpp_subscription {url, period {unit, count}, renewal: "platform"} next to pay.mpp. The mode is offered only for a day or week plan, 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 and pay.mpp is the way to pay.
  2. GET /api/v1/shop/quotes/:id/pay?intent=subscription answers 402 with one WWW-Authenticate: Payment challenge of method tempo, intent subscription: the amount (the plan price), the period (periodUnit day or week, periodCount), the recipient (the shop payout wallet), exactly one currency (USDC.e on mainnet), the key to authorize in methodDetails.accessKey and subscriptionExpires (the end of the plan term, or 365 days for a plan without max_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 with POST /api/v1/shop/quotes/:id/pay?intent=subscription. Any other value of intent is ignored and pay.mpp applies.
  3. 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 active with pull_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.
  4. shop.subscription.get shows pull_mode: mpp_subscription and renewal_key, the address of the key the payer authorized (APIbase's key, never the payer's).
  5. The worker job shop-subscription-sweep (every 5 minutes) renews every due period of an active or past_due subscription exactly once, before it applies the past_due rules: it signs with the renewal key through mppx renew, pays the gas, and records the transaction through the period order exactly as the other modes do (rail tempo, subscription.renewed). A period is attempted once: a second worker or a repeated tick does nothing.
  6. 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_failed with reason: payout_wallet_changed and the agent pays the renewal quote.
  7. 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_mode returns to none, the shop gets one subscription.pull_failed webhook (reason: key_revoked, key_expired, limit_exceeded, payout_wallet_changed or renew_failed) and the usual past_due rules apply: the agent can still pay the normal renewal quote.
  8. 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.
  9. 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.revoke from viem/tempo, for the address in renewal_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.

  1. Create. POST /api/v1/shop/partners/handoffs with {seller_ref?, prefill?: {name?, site_url?, contact_email?, category?, country?, slug?}, expected_wallet?, mode?, grant_requested?, scopes?}. seller_ref is your own reference (up to 128 characters, opaque to APIbase). Prefill fields follow the registration rules (non-empty name, https site 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, as slug_taken). expected_wallet is the EVM address you have on file for the seller. mode is register (default) or grant for a store already on APIbase, where the page asks only for the grant signature: send mode: "grant" when you already hold the seller's apibase_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 when grant_requested is true, before anything is signed. With mode: "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, or scopes in mode register, is 422 with field: "scopes". grant_requested: true (mode register) 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 is 422 validation_failed with field naming it. The answer is 201 {handoff_id, url, expires_at}, where url is https://apibase.pro/integrator/connect?from=<partner>&handoff=<handoff_id> and the handoff lives 24 hours.
  2. Connect page. Send the seller to url. A live handoff prefills the form. In mode register with grant_requested: true it 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_email in 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 to support_email or 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 with expected_wallet (case-insensitive): a different wallet shows a "Different wallet" notice with how to switch and, when the handoff carries expected_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. With expected_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). Without expected_wallet every 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 with from=<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 opens back_url (or site) in the same tab; every other link of the page opens in a new tab.
  3. Registration. The page sends handoff_id in the register body. An agent registering for a seller passes the same optional handoff_id (uuid) to POST /api/v1/shop/merchants or shop.merchant.register. A live handoff is bound to the new merchant; an unknown, expired or already used one never fails the registration.
  4. 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 when grant_requested is true), the seller returns to <return_url>?apibase_slug=<slug>&handoff=<handoff_id>, built from the registry return_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 with seller_keys: hidden whose 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 expect state: "granted" (step 5). Nothing else is in the URL.
  5. Read. GET /api/v1/shop/partners/handoffs/:id returns {handoff_id, state, seller_ref, slug?, merchant_id?, wallet_match?, created_at, expires_at, opened_at?, registered_at?, grant}. state moves created → opened (the page was opened) → registered, and to granted when the seller signs a partner grant through it; a handoff neither registered nor granted within 24 hours reads expired. wallet_match is false when the seller registered a wallet other than expected_wallet; it is also set when a grant binds the handoff (false when the granting wallet differs from expected_wallet), and registered_at is absent for a handoff bound by a grant alone. Another partner's id or an unknown id is 404. 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).

  1. Sign. GET /api/v1/shop/auth/nonce?wallet=0x…&purpose=grant&partner=<partner id> returns this message (a partner that is not in the registry is 422 validation_failed). Sign it exactly as returned; a changed line is 401.
    text
    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>
  2. Grant. POST /api/v1/shop/merchants/me/grants with {wallet, partner, message, signature, handoff_id?} and no Authorization header (10 requests/min per address). The wallet must be the identity wallet of an active store: none is 404 merchant_not_found; a pending, suspended or deactivated store is 410 merchant_unavailable. One active grant per store and partner: a second is 409 grant_exists, except that a live grant signed before quotes:read existed (its scopes lack 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, answered 200 with the usual body; no new key, endpoint or secret, and a live handoff named by handoff_id (as in step 3) is bound and turns granted without a secret. Through a handoff created with scopes: a store whose live grant already holds every scope asked answers 200 with the usual body, the handoff turns granted and nothing else changes; a store without a live grant of yours is 404 not_found and nothing is written. A new grant answers 201 {grant_id, partner, mode, scopes, created_at, slug} (mode is key or partner); neither answer carries a key or a secret.
  3. Delivery. When handoff_id names an unexpired handoff of that partner that is unbound or bound to this store, the handoff is bound to the store, turns granted, and holds the partner's secret encrypted: the key in mode key, the whsec_ secret of the endpoint created for the partner in mode partner. The partner's next GET /api/v1/shop/partners/handoffs/:id carries it once, as grant: {state: "granted", mode, scopes, key} (mode key) or grant: {state: "granted", mode, scopes, webhook_secret} (mode partner); every later read shows grant: {state: "granted", mode, scopes, delivered: true} and APIbase no longer holds it. A handoff bound by an added scope (step 2) reads grant: {state: "granted", mode, scopes}, with no secret and no delivered. grant.state is none when no grant came through the handoff and revoked after a revoke. In mode key a grant made without a live handoff has no way to reach the partner: revoke it and sign again through a new partner link; in mode partner the partner gets a new secret with rotate-secret (see Partner mode).
  4. What a grant key may do (mode key). Catalog: PUT /merchants/me/catalog (shop.merchant.catalog_upsert; idempotent by sku, the store's single __apibase_test item included), POST /merchants/me/catalog/import and GET /merchants/me/catalog/import/:id. Webhooks: PUT, GET and DELETE /merchants/me/webhooks (shop.merchant.webhook_set, shop.merchant.webhook_list, shop.merchant.webhook_delete) on its own endpoints. And GET /merchants/me/check (shop.merchant.check). Everything else is 403 grant_key_not_allowed with 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 /mcp every shop.merchant.* tool except the five named here. A grant key cannot rotate, get a new key or change a payout.
  5. 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 is 404. Its whsec_ 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.
  6. 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 is 404. A revoke at once revokes the partner's key (401 from then on; in mode partner the partner routes answer 403 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 shows grant: {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 is 422 validation_failed) returns this message, built by APIbase:
    text
    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>/revoke with {wallet, message, signature} and no Authorization header (10 requests/min per address). A changed line, another partner or address, or a used or expired nonce is 401. The wallet must be the identity wallet of a store in any status (a suspended or deactivated store can stop a partner): none is 404 merchant_not_found. The answer and the effects are those of DELETE: {partner, revoked: true}, or 404 not_found without 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 mode key (its key, its endpoints); a grant of mode partner holds 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/catalog with {items: [...]} (a live grant of either mode): the same body, per-item report, moderation, price ceiling, sku idempotency and single __apibase_test item as PUT /merchants/me/catalog; a suspended or deactivated store is 410 merchant_inactive.
  • GET /api/v1/shop/partners/merchants/:slug/grants returns {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. state is active or revoked, revoked_at is null or a time, and webhook: {endpoint_id, url, events, status} (mode partner only) reads status: "deleted" when the merchant removed the endpoint. A store without your grants answers 200 with grants: []. It never returns a key, a secret, a wallet or an e-mail.
  • POST /api/v1/shop/partners/merchants/:slug/webhook/rotate-secret (mode partner, live grant) answers {endpoint_id, url, events, secret} with a new whsec_ secret, once; the old secret stops signing at once, and the current registry URL and events are applied to the endpoint. In mode key it is 404 not_found; an endpoint the merchant deleted is 404.
  • GET /api/v1/shop/partners/merchants/:slug/quotes?updated_after=<ISO 8601>&limit=<1-200> (a live grant whose scopes include quotes:read; default limit 100; a bad query value is 422 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}. state is open, paid, cancelled or expired (also when the quote is past expires_at and not yet marked); challenges counts the 402 answers given to a call with no payment, pay_attempts the calls that carried a payment, and last_error_code is the code the buyer was answered when such a call failed (every x402 verification or settle refusal reads payment_required; an MPP credential refused before the pay route is not counted); paid_at is the settlement time, rail is base, tempo or null before payment, order_state is the order state; read_at is the first read of the paid order by its buyer (null does not mean undelivered: the pay answer already carries the order); client is a product token such as python-httpx, browser or the MCP client name (at most 40 characters of A-Za-z0-9._-). updated_at is 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 by updated_at then quote_id; a page never ends between two rows with the same updated_at (it runs past limit); next_updated_after is the last row's updated_at at microsecond precision, null when the page is not full. A quote made before outcomes were recorded has null for challenges, pay_attempts, last_error_code, last_error_at, read_at and client (not measured, not zero). A grant signed before quotes:read was part of the permission is 403 grant_scope_missing (with scope: "quotes:read") until the seller signs the new message once (send a scopes link, step 1). Read with an overlap and upsert by quote_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 and limit) returns {refusals: [{at, error_code, skus}], next_after} for the last 90 days, ordered by at then id with the same tie rule: the quote requests the store refused with a 4xx after 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 beyond client, 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):

js
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.json serves a provek_declaration: "1.1.0" document: the claims addressee (claims_url, else your site_url), the emergency stop (shop.merchant.deactivate makes the storefront answer 410), your insurance statement, a dispute path on your shop page, and the order, offering and pricing URLs. Your contact_email is never part of it. With opt_in false the path answers 404, for a deactivated shop 410. Your shop page links to it with <link rel="alternate" type="application/json">.
  • provek {declared, listed, registry_url} appears in shop.catalog.get (merchant), in apibase.discover results of kind merchant, in agent.json, and on /m/<slug>.
  • listed becomes true only when a daily job finds the host of your site_url in 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.

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 holds version: X; effective_from: YYYY-MM-DD; status: …. The fee appears only as the token 0% (pilot) (substituted when the HTML page is rendered; .md keeps the token). The country list in aup.md is generated from config/integrator/countries-restricted.json by scripts/shop/gen-aup-countries.ts, never by hand.
  • Hash. sha256 is computed over the exact bytes of the .md file. scripts/shop/sync-legal-docs.ts (run at app start, and as --check in npm run build) upserts shop_legal_docs(doc_id, version, sha256, url, effective_from, body_md). Changing text without changing version fails startup; a new version adds a row and old rows stay.
  • Routes. GET /legal/index.json → [{doc_id, version, sha256, url, effective_from}]; each entry also carries hash_of and source_url. GET /legal/<doc_id> → HTML, or the .md with Accept: 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 version 404 unknown_version; GET /legal/terms.body.txt and /legal/privacy.body.txt → the exact text hashed for /terms and /privacy. The sha256 is reproducible from the bytes at source_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, then 429.
  • DRAFT banner. HTML pages carry <div class="draft-banner"> and <meta name="robots" content="noindex"> until config/integrator/legal-published.json ({published_at, by}) exists. Publication is the committed config/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 via Current versions and hashes: /legal/index.json (latest effective 2026-12-10).. The .md never 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).
  • /terms and /privacy have a new Integrator section (marked integrator-legal in 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.

PathSourceWhat it is
/integratorindex.html / index.md12 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.txtllms.txtlinks to every page below.
/integrator/agent-guideagent-guide.mdnonce → 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/walletbuyers.md, wallet.mdlimits 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-tempowhy-base-tempo.mdthe F-5 text, without evaluative words.
/integrator/platforms/{shopify,woocommerce,tilda,wix,custom}platforms/*.mdpaste link A–C; no script (UC-20).
/integrator/connectconnect.htmlhuman 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/permissionspermissions.html / permissions.mdone 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).