# AIPAY — full text bundle > One fetch for every Markdown file AIPAY publishes: this bundle contains > llms.txt, agents.md and every file in /docs. The canonical, always-current > copies are the individual URLs; if they disagree, the individual file wins. Generated by `scripts/build-llms-full.mjs` — do not edit by hand. --- # AIPAY > AIPAY (https://aipay.im) is a non-custodial, multi-chain crypto wallet and merchant payment gateway, shipped as a Progressive Web App (PWA). One BIP-39 recovery phrase and one local wallet password control every chain. Keys are generated and encrypted in your browser and never sent to a server; payments settle directly on-chain. There is no account and no custody. The app is a static export, and balances and payments are read directly from public RPC endpoints. Merchants may **optionally** enable the hosted order-tracking API described below; until they do, nothing about their orders leaves the browser. This file exists so both humans and AI agents can understand what AIPAY is and, more importantly, **which features are actually enabled today** and **how to operate them correctly**. AIPAY is fail-closed: several features ship disabled and must not be described as available. ## Before you integrate: what AIPAY is not (read this) These are product boundaries, not missing features, and an integrator who assumes otherwise will build the wrong thing: - **No sandbox, no testnet.** `api.aipay.im` is mainnet only: a test order is a real order for a real (small) amount. To rehearse without money, run the Worker locally (`wrangler dev` + local D1, `RPC_OVERRIDES` for a fake node) and drive it with the copy-paste clients in the source repository (`examples/merchant-node/aipay.mjs`, `examples/merchant-python/aipay.py`; both ship a self-check and a demo). We intentionally do not host a test service. - **No refunds, reversals, chargebacks or dispute handling.** AIPAY never holds the money, so it cannot move or claw it back. The merchant refunds from their own wallet and records it in their own ledger. Do not promise a payer anything else. - **Confirmed is a receipt, not finality and not delivery.** We re-read the transaction and require the chain's confirmation depth at that moment. For EVM chains we then re-read each confirmed order **once**, 30 minutes to 6 hours later: if the transaction has vanished or its depth dropped, the order gets a `confirmation_regressed` event and a merchant-visible `last_error`, but the status **never** changes and no webhook is sent. Treat that event as a warning to reconcile, not as an automatic reversal. - **One recipient per merchant, no on-chain memo.** Two pending orders with the same amount and recipient are ambiguous; use distinct amounts. - **Native coins need a transaction hash** (`POST /v1/orders/:reference/confirm`); only token transfers are discovered by the sweep. - **An off-chain confirmation is the merchant's receipt**, never chain evidence; `channel` / `confirmed_source` say which one you are looking at. - **MSG / MSGChain is disabled**, paid plans are **not on sale**, and the fiat on-ramp is off. See "Feature status" below. - **Zero commission today.** A per-merchant rate can be recorded (max 500 bps) but it is never deducted from a payment: `GET /v1/merchants/me` reports it with `collectable: false`, because a direct transfer has no hook to split. For one order's full paper trail (state, timeline, notification attempts, what the verifier saw), read `GET /v1/orders/:reference/evidence` — read-only, owning key required, and it says out loud whether the proof is on-chain or a merchant receipt. Machine-readable companions: `/agents.md` (operating rules), `/openapi.json` (the merchant HTTP API), `/agent.json` (capability surface), `/.well-known/mcp.json` (there is **no hosted MCP endpoint** — the agent runtime is a local stdio process), and `/docs/provider-assessment-answers.md` (a point-by-point third-party review with the gaps listed). ## Five minutes to your first paid order The whole merchant side is four HTTP calls. No SDK, no key rotation dance, no dashboard: the key is returned once by the first call and only its hash is stored. ```bash # 1. open a merchant account (one call, returns the API key once) curl -sS -X POST https://api.aipay.im/v1/merchants \ -H 'content-type: application/json' \ -d '{"shopName":"My Shop","recipientAddress":"0xYourReceivingAddress","chainKey":"bsc"}' # 2. create an order (returns a reference and a hosted checkout link) curl -sS -X POST https://api.aipay.im/v1/orders \ -H "Authorization: Bearer $AIPAY_API_KEY" \ -H 'content-type: application/json' \ -d '{"amount":"12.50","asset":"USDT","chainKey":"bsc"}' # 3. the payer opens the checkoutUrl and pays from any wallet # 4. watch it (public, no key) — or receive a signed webhook curl -sS https://api.aipay.im/v1/orders/$REFERENCE/status ``` Then, in order of how often you will want them: | You want | Read | | --- | --- | | Every endpoint, limit and error code | | | A copy-paste integration guide | | | Find payments faster with your own RPC quota | | | What it costs today (nothing) | | | What we never touch, and how to check it | | | Every developer surface in one list | | ## One file, or many Everything in this file is also published as a single bundle: (this file + agents.md + every doc). Start with that if you can only make one request; the individual files stay canonical. ## If you are an AI agent, read this first AIPAY has **two different surfaces**, and confusing them is the most common integration mistake: | Surface | Who uses it | How you reach it | |---|---|---| | The **web app** (PWA) | humans, and anyone paying a link | `https://aipay.im/…` in a browser — no API, no cookies, no backend | | The **agent surface** (MCP server + CLI) | an agent with its **own** wallet and merchant profile | a local Node.js process from the AIPAY project checkout: `agent/mcp-server.mjs` / `agent/cli.mjs` | **Honest access boundary — do not invent your way around it:** - There is **no hosted HTTP API** for the *agent surface* and **no public npm package**: the tools run locally on the machine that owns the agent's key. - A separate, **opt-in merchant order API** exists for merchants who explicitly enable "Cloud orders" in the app (see *Merchant cloud orders* below). It never holds keys or funds, needs no account, and is not an agent surface. - **You can still install it.** The sanitized runtime is downloaded from — `agent-latest.json` names the current version, the tarball URL and the sha256, and `https://aipay.im/downloads/install.sh` verifies that sha256 before installing anything. The repository at is a **mirror of the same bytes** (same sha256), not the only place to get them. The step-by-step operating manual is . It needs Node.js >= 22.18. If you cannot install anything, say so and stop — do not guess endpoints, do not scrape the app, and do not fabricate tool results. - The agent surface acts on the **agent's own key** (`AIPAY_AGENT_HOME`). It can never touch a human's browser wallet, and the human wallet cannot sign for the agent. - The spending policy is **local** (`policy_engine.on_chain: false`). It is a real check by the local engine, not a chain rule. - Nothing here can approve its own escalation, grant itself a capability, or deliver goods. See "What you must never do" below. A capability is a **signed** object: the engine refuses one that carries no signature, or one signed by a key this machine does not trust, so a capability the agent wrote for itself buys it nothing. ## How to connect (MCP, about two minutes) Requirements: **Node.js ≥ 22.18** (native TypeScript type stripping) and one of: - the **published runtime**: `curl -fsSL -o install.sh https://aipay.im/downloads/install.sh && AIPAY_AGENT_VERSION= bash install.sh` (the script verifies the tarball sha256 against the published CHECKSUMS, then installs to `~/.aipay/agent-dist/package`; it prefers aipay.im and falls back to the GitHub mirror), or - a checkout of the AIPAY project (what the operator usually has). No build step is needed. The published runtime already contains its `package.json` with the exact dependency versions; the checkout runs the same code straight from source. 1. Give the agent its **own** identity — once per machine: ```bash export AIPAY_AGENT_HOME="$HOME/.aipay/agent" # state.json + keystore.json + approval.json export AIPAY_AGENT_PASSPHRASE='a strong passphrase' node agent/cli.mjs keystore init --generate # prints the mnemonic ONCE — never log or echo it node agent/cli.mjs address # this agent's EVM / Solana (/ MSG) address node agent/cli.mjs config # resolved paths, store kind, node version ``` 2. Register the stdio MCP server with your host (example for pi; any MCP client works): ```bash pi mcp add aipay -- node /path/to/repo/agent/mcp-server.mjs # or with credentials in the server process environment: pi mcp add aipay \ --env AIPAY_AGENT_HOME="$HOME/.aipay/agent" \ --env AIPAY_AGENT_PASSPHRASE='…' \ -- node /path/to/repo/agent/mcp-server.mjs ``` Generic client configuration: ```json { "mcpServers": { "aipay": { "command": "node", "args": ["/path/to/repo/agent/mcp-server.mjs"], "cwd": "/path/to/repo", "env": { "AIPAY_AGENT_HOME": "~/.aipay/agent" } } } } ``` 3. Talk JSON-RPC over **stdin/stdout**. The server speaks `initialize`, `notifications/initialized`, `tools/list`, `tools/call`, `ping`: ```json {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"your-agent","version":"1.0"}}} {"jsonrpc":"2.0","method":"notifications/initialized"} {"jsonrpc":"2.0","id":2,"method":"tools/list"} {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"aipay_chains_list","arguments":{}}} ``` - Successful calls return `result.content[0].text` (a JSON string) **and** `result.structuredContent` (the same object). Prefer `structuredContent`. - Tool failures are **results, not protocol errors**: `result.isError: true` with `structuredContent: {code, nextAction, retryable, retryAfterMs?}`. Branch on `code`/`nextAction`, never on prose. - stdout carries JSON-RPC only. Logs go to stderr — a stray `console.log` corrupts the stream. - `initialize` returns an `instructions` string with the same boundary rules as this file. CLI equivalent for every tool (useful for scripts and for humans): ```bash node agent/cli.mjs help # every command node agent/cli.mjs tool --list # the same 34 tools node agent/cli.mjs tool aipay_chains_list --json '{}' ``` Environment variables: | Variable | Meaning | |---|---| | `AIPAY_AGENT_HOME` | State + keystore directory (default `~/.aipay/agent`) | | `AIPAY_AGENT_PASSPHRASE` | Keystore passphrase (needed for signing calls only) | | `AIPAY_AGENT_KEYSTORE` | Keystore file (default `/keystore.json`) | | `AIPAY_AGENT_MNEMONIC` / `AIPAY_AGENT_MNEMONIC_FILE` | Plain phrase — CI/tests only, never production | | `AIPAY_AGENT_STORE` | `file` (default) or `memory` | | `AIPAY_AGENT_SUBJECT` | Capability namespace the agent belongs to (default `agent`) | | `AIPAY_AGENT_BASE_URL` | Origin used for payment links (default `https://aipay.im`) | | `AIPAY_AGENT_LOCALE` | Link locale (default `en`) | Credential resolution is **lazy**: read-only tools work before any wallet exists, and a signing call without credentials fails closed with `credentials_unavailable`. ## First call: the zero-side-effect self-check Start read-only. This creates nothing, signs nothing and spends nothing: 1. `aipay_chains_list` → which `chainKey` values exist (MSG appears only when configured). 2. `aipay_wallet_addresses` → the agent's own addresses. 3. `aipay_wallet_balances {chainKey}` → funds available. 4. `aipay_merchant_profile_get` → `null` means "not a merchant yet". 5. `aipay_payment_options` → per chain: registered assets, decimals, the smallest payable amount and the per-payment cap of an existing capability. **This is the only source of truth for what is acceptable.** 6. `aipay_policy_status` → kill switch, capabilities, remaining budget, pending approvals, and lifecycle `warnings[]` (expiring / expired / revoked / out of budget). Report what is missing instead of acting on assumptions. ## Two jobs you can do ### A. Merchant: create a request, then reconcile it ```text 1. aipay_merchant_profile_set { "recipientAddress": "0x…", "shopName": "My Shop" } → { "profile": { … } } // saving a valid address IS "becoming a merchant" 2. aipay_payment_options {} // pick a chain + asset that is "available" 3. aipay_payment_request_create { "amount": "12.5", "currency": "USDC", "chainKey": "base", "description": "Order 1042", "merchantOrderId": "order-1042" } → { "url": "https://aipay.im/en/pay?intent=…", "reference": "…", "order": { … }, "nextAction": "share_link", "deduplicated": false } ``` - The **URL is the payment link and the QR payload**. Hand it to the payer; creating a request is **not** authorising a payment and moves no funds. - `merchantOrderId` is *your* business order id, scoped to the merchant address. Repeating it with the same parameters returns the **original** request (`deduplicated: true`); the same id with different parameters fails with `merchant_order_conflict`; once the original has expired the answer is `nextAction: "stop"` — use a new id, never re-create it silently. - Reconcile later with `aipay_orders_get {reference}` (order + `nextAction`) and verify against the chain with `aipay_orders_confirm {reference}`. A confirmation sets `confirmedAt` and always keeps `delivery: "not_tracked"`: **a verified payment is not proof of delivery.** ### B. Payer: quote, then pay once ```text 1. aipay_quote { "intentUrl": "https://aipay.im/en/pay?intent=…" } → { symbol, decimals, amountBaseUnits, precheck: {ok:true}, policy: { enforced: true, decision: "allow" | "escalate" | "deny", reason } } 2. aipay_pay { "intentUrl": "…", "idempotencyKey": "order-1042" } → { txHash, chainKey, amountBaseUnits, fromAddress?, capabilityId?, escalationId?, nextAction } ``` - **Quote before you pay.** A `deny` is final (`stop`); an `escalate` means a human must sign a single-use approval token for exactly that payment. Re-sending the payment will not help. - `idempotencyKey` makes a retry safe: the same key with the same parameters returns the first result (`deduplicated: true`); the same key with different parameters fails with `idempotency_conflict`. - `aipay_pay` moves real funds and cannot be undone. Never retry it because it "looked slow" — check `aipay_orders_get` / the explorer first. - Cross-check the amount and asset before signing; never substitute a "close enough" chain, asset or amount. ## Spending capabilities (who may spend what) Nothing can be paid until a **human** grants the agent a capability: scope (chains / assets / recipients / merchants), budget (per payment, per window, lifetime), expiry, approval mode. An empty list in a scope means **none**, never "any". The human's side (CLI, or the web planner at `/en/agent`): ```bash node agent/cli.mjs approval keygen # the human's approval key (not a wallet key) node agent/cli.mjs capabilities grant \ --chain base --asset USDC --to 0x…merchant \ --per-payment 25 --per-window 100 --window-seconds 86400 --total 500 \ --expiry 2026-12-31T00:00:00Z --approval-mode escalate --escalate-above 25 # → creates the capability AND signs it with the approval key # (needs that key's passphrase; the issuer is that key's address) ``` `capabilities grant` is a **human** command: it signs what you asked for, so the agent can spend exactly what you signed and nothing else. The agent has no key and cannot run it. A capability made before signing existed can be signed once with `aipay-agent capabilities sign --id ` (look at it first — you are signing what is stored). - `approval` modes: `auto` (within scope, no per-payment human artifact), `escalate` (amount ≥ `escalateAbove` needs a human token), `human` (every payment does). - **What is signed, and what is not.** Three things carry a signature, all of them by a **human key**: the *capability* (`aipay-grant-v1`, signed by the approval key; the engine refuses a capability with no signature, one signed by another key, or one edited after signing), the *mandate* (`aipay-mandate-v1`, covers every field), and the *approval token* (`node agent/cli.mjs approval approve --id esc_…`, single-use, bound to that one payment). The trust anchor on a machine is the **address of the approval key** (`~/.aipay/agent/approval.json`): a capability issued by anybody else is not honoured there, and with no approval key on the machine nothing is honoured at all. Keep the approval key's passphrase **different** from the wallet's (`AIPAY_AGENT_APPROVAL_PASSPHRASE`): the agent process reads the wallet passphrase, and it must never be able to unlock the approval key. What is still *not* signed: the local spend ledger (who spent what) and the state file itself — a machine owner can still edit those, so treat the local store as untrusted and use a mandate when you need consent that is cryptographically checkable; there is deliberately no approve tool. - **The limit that no local design can lift:** the agent process runs as the same OS user as you, so somebody who can rewrite your home directory can move the trust anchor and edit the spend ledger. The signature stops *the agent's own tools* from granting it authority; it does not stop *the owner of the machine*. Keep the agent on a machine you control. - Portable grants: a capability can travel as a signed `aipay-grant-v1` envelope (token or CryptoKey carrier). Import it with `aipay_capability_import` (or `aipay-agent capabilities import --token`). Signing/exporting needs the human's approval key; an edited envelope fails verification, and delegated envelopes must fit inside their parent (scope subset, expiry ≤ parent, budget ≤ parent remaining, one level deep). - Lifecycle warnings: `aipay_policy_status` returns `warnings: [{ code, capabilityId?, at?, detail? }]` with the stable codes `kill_switch_on`, `capability_unsigned`, `capability_untrusted`, `capability_revoked`, `capability_expired`, `capability_expiring`, `delegation_expiring`, `budget_exhausted`. "Expiring soon" defaults to seven days; pass `expiringWithinSeconds` to change the horizon. Warnings are advisory (never a verdict) and `detail` is prose — branch on `code`. - Migration bundles: `aipay-agent capabilities export --all --out bundle.json` writes an `aipay-grant-bundle-v1` (same signed envelopes, parents first, revoked skipped); `capabilities import --bundle bundle.json` verifies every envelope and imports idempotently. A bundle carries no new authority. - Delegation (**signer ≠ approver**): a capability may name a `holder` address. That holder can delegate a narrower child inside it with `aipay_capability_delegate` — the child is signed by the holder's own key but keeps the parent's `issuer` (the human approval key) and subject, so the delegate still needs the human for escalated payments. A delegator can never widen scope/expiry/budget, change the issuer, or delegate a second time. "Narrower" means narrower in **every** dimension: the child's scope, expiry, budgets, **window length** (a shorter window refills sooner), **approval mode** (never weaker, and the escalation threshold is never raised), **timelock** (never shortened), **stream ceiling** (never raised, and no streams the parent does not have) and the height mirrors all stay inside the parent's. A delegation also **shares** the parent's allowance: what the children spent counts against the parent, and a revoked or expired parent withdraws the delegation. The bounds are checked on import *and* on every payment, because the local state file is writable. - `aipay_spending_kill` stops **every** agent payment immediately, regardless of capability; `aipay_spending_revive` clears it. Both directions are audited with `actor: "human" | "agent"`. - Revocation is immediate and one-way: `aipay_capability_revoke {id}`. ## Errors: what to do next Every failure carries a closed `nextAction` and `retryable` flag. Only these two are retryable, and only after the given delay: | `code` | `nextAction` | retryable | |---|---|---| | `state_unavailable` | `wait` | yes, ~2 s | | `payment_failed` | `wait` | yes, ~5 s (check the chain before retrying a broadcast) | | `policy_escalated` | `await_human_approval` | no — get a token from the human | | `credentials_unavailable` | `share_link` | no — this host cannot sign | | `invalid_input`, `unknown_chain`, `unknown_asset`, `not_found`, `conflict` | `stop` | no | | `idempotency_conflict`, `merchant_order_conflict` | `stop` | no — keep the original record | | `order_expired` | `stop` | no — the request is over | | `policy_denied`, `grant_invalid` | `stop` | no | Unknown codes default to `stop` / non-retryable. `nextAction` appears on created requests, payment results, order views and escalated errors, always from the same closed set: `pay_now`, `share_link`, `await_human_approval`, `wait`, `stop`. ## Tools (40) Read-only unless marked. Signing happens only inside `aipay_pay` (and `aipay_capability_grant` only **imports** a capability a human already signed — it never creates one, and it never touches funds). | Area | Tools | |---|---| | chains / wallet | `aipay_chains_list`, `aipay_wallet_addresses`, `aipay_wallet_balances`, `aipay_wallet_history` | | merchant | `aipay_merchant_profile_get`, `aipay_merchant_profile_set`, `aipay_merchant_products_list`, `aipay_merchant_products_create`, `aipay_merchant_products_delete` | | requests | `aipay_payment_request_create`, `aipay_payment_options`, `aipay_receive_uri` | | money | `aipay_quote`, **`aipay_pay` (signs and broadcasts)** | | policy | `aipay_policy_status`, `aipay_capability_list`, `aipay_capability_grant`, `aipay_capability_import`, `aipay_capability_delegate`, `aipay_capability_revoke`, `aipay_spending_kill`, `aipay_spending_revive`, `aipay_escalations_list`, `aipay_escalations_get`, `aipay_escalations_deny`, `aipay_spends_list` | | mandates | `aipay_mandate_list` — read-only: the user's own signed limits on automatic spending | | streams | `aipay_stream_open`, `aipay_stream_close`, `aipay_stream_list` — local authorization only: no signing, no broadcast, MSG disabled. The reserved session cap is credited back only when the close carries a settlement reference: the local ledger cannot read the chain, so an amount the agent states by itself must not widen the budget | | orders (local) | `aipay_orders_list`, `aipay_orders_get`, `aipay_orders_create`, `aipay_orders_confirm` | | cloud orders (hosted) | `aipay_cloud_profile_get`, `aipay_cloud_orders_create`, `aipay_cloud_orders_list`, `aipay_cloud_orders_get`, `aipay_cloud_orders_cancel` — the merchant-key order service: checkout links, signed webhooks, chain verification, 90-day history. The key comes from `AIPAY_API_KEY` or the 0600 merchant file, never from a tool argument | | audit | `aipay_audit_tail` | Machine-readable mirror with schemas and annotations: `https://aipay.im/agent.json` (`tool_count: 40`). ## Paying out (agent → merchant), and the user's limits on it **AIPAY can pay out.** The agent wallet signs and broadcasts a real payment (`aipay_pay`); the merchant or the payer can also pay a link by hand. Nothing about that needs our server: the agent holds its own key on the machine that runs it, and the money moves on-chain from that wallet to the recipient. Two independent controls decide whether a payment may go out, and **both** must allow it: 1. **The capability** (`aipay_capability_grant`): what the human granted — chains, assets, recipients/merchants, per-payment / per-window / lifetime budget, expiry, approval mode — signed by the human's approval key. Without one, nothing can be paid; without a valid signature, nothing is paid either. 2. **The mandate** (`node agent/cli.mjs mandate create`): the user's own signed limit on *automatic* spending — a signed object (`aipay-mandate-v1`) that lives on the user's machine, with its own per-payment / per-window / total / daily caps, its own expiry, and its own anti-replay nonce. A mandate can only **narrow** what the capability allows; it can never widen it. What happens when a payment is outside a limit: it is **not** paid. It goes back to a human as an escalation (`await_human_approval`), and the human signs a single-use approval for exactly that one payment. The verdict says "this needs a human" and never says how much is missing. | Command (local CLI) | What it does | |---|---| | `node agent/cli.mjs mandate create --chain ... --asset ... --per-payment --total [--per-window --window <1h>] [--daily ] [--expires-in ]` | The **human** signs a mandate with the approval key. The agent cannot create one. | | `node agent/cli.mjs mandate list` / `show --id ` | What the agent may spend automatically, and what is left. | | `node agent/cli.mjs mandate revoke --id ` | One-way. The unused allowance does not survive. | For an integrator: a mandate is a **document**, not a service. AIPAY hosts no "payout API" for someone else's agent on purpose — we hold no keys and sign nothing, so an attacker who reaches our servers still cannot move a user's money. If your platform wants automatic payouts, your agent runs the mandate check locally against the user's signed mandate (the format and a reference verifier are published), and the user keeps every limit on their own machine. ## What you must never do - Never print, echo, store or transmit the mnemonic, a private key, or the passphrase. `keystore init --generate` prints the phrase exactly once, to the operator. - Never claim an action succeeded without a tool result; never fabricate a `txHash` or reuse another payment's hash. - Never create a second payment link for an unpaid/expired order, and never pay twice "to be safe" — use `merchantOrderId` and `idempotencyKey`. - Never describe MSG, fiat on-ramp, NFTs or EVM swaps as available (see the status below). - Never treat `confirmed` as "delivered", and never promise a refund or a delivery time AIPAY cannot verify. - Never try to reach the human's wallet: the agent surface has its own key and no path to theirs. ## Feature status (read this first) Enabled today: - EVM mainnet wallet: receive, send, balances, transaction history, contacts. - Solana wallet: receive, send, balances, history. - Tron wallet: receive, send (TRX and TRC20 USDT), balances, history. Sending needs a little TRX in the address for the fee; confirmations use Tron's 19-block (~57s) rule. - Solana swaps (via Jupiter) on the `/swap` page. - Merchant tools: payment requests, POS QR checkout, payment links, order tracking, products, analytics. - **Pricing: free usage stage.** The merchant API costs nothing today; paid subscriptions (1 / 3 / 6 / 12 months) are planned but not on sale and have no start date. `/v1` and `/v1/health` return `billing: {status:"free", plans: []}`; never describe the API as paid, metered or trial-limited. - **API keys rotate with a grace window.** `POST /v1/merchants/me/keys/rotate` returns a new key once and keeps the previous one valid for 1–72 hours (default 24), so an integration can roll without downtime; `revokeOldImmediately: true` cuts it at once after a leak. - **Merchant cloud orders (opt-in beta):** on the 8 EVM mainnets, Solana and Tron the AIPAY server can track an order after the merchant closes the tab, notify a webhook / email / Telegram, and expose a public payer status endpoint. Zero commission, 90-day retention, non-custodial. The API key is shown once and stored only in the merchant's browser (localStorage, unencrypted); "delete cloud merchant" removes it server-side. - **Off-chain channels (Alipay / WeChat Pay / UnionPay / Stripe / other):** an order can carry the merchant's own payment link instead of a chain. AIPAY orchestrates and reconciles; it never calls the provider, never stores a provider credential and never receives the money. Confirmations come from the merchant — manually, by a signed webhook, by an adopted CSV statement row, or by a statement row the merchant's own automation policy confirmed — so the receipt always says `merchant_manual`, `merchant_webhook`, `statement` or `statement_auto`, never `chain`. - Encrypted backup and restore (local JSON file, or CryptoKey.im `.ckx` / PNG carrier). - External `/earn` directory linking to official staking/earning sites. - Agent surface: local MCP server + CLI, local spending policy, portable `aipay-grant-v1` capabilities, browser-side signing on `/agent`. Disabled today (fail-closed — do NOT tell users these work): - **MSG (MSGChain) — NOT enabled.** The adapter is implemented but `public/msg-config.json` ships with `enabled: false`. MSG addresses, MSG balances and MSG payments are hidden until MSGChain mainnet parameters are provided. - **Fiat on-ramp (buy crypto with a card) — NOT enabled.** `public/buy-config.json` ships with `enabled: false` and no provider. - **NFT gallery — NOT enabled.** `public/nfts-config.json` ships with `enabled: false` and no Alchemy key. - **EVM token swaps — NOT enabled.** `public/swap-config.json` ships with `enabled: false`. The Solana swap is unaffected. - **Merchant payouts on MSGChain — NOT open.** Routing merchant payments through an AIPAY on-chain contract on MSGChain is not available yet. - **Cloud order verification for MSGChain — NOT available.** The order API answers `unsupported_chain` until mainnet parameters exist; those sales stay on the local flow. Solana **is** verified server-side. ### Merchant cloud orders (opt-in, EVM mainnets + Solana + Tron) - Enable in **Merchant → Settings → Cloud orders**: create a merchant (shop name, EVM receiving address, default chain) or paste an existing API key. The key is displayed once; the server stores only its SHA-256. - Endpoints (no SDK): `GET /v1` (live discovery), `POST /v1/merchants`, `POST /v1/orders`, `GET /v1/orders/:reference/status` (public payer poll), `POST /v1/orders/:reference/confirm` (server-side verification; the payer's browser may call it without a key — see the caveats above). Base URL: `https://api.aipay.im`; it can be overridden at runtime by `public/api-config.json`. - Supported chains: `ethereum`, `bsc`, `polygon`, `arbitrum`, `optimism`, `avalanche`, `base`, `xlayer`, `solana`, `tron`. ERC-20/TRC20 payments are discovered by the server's sweep; native coins need a transaction hash. Solana payments are discovered from the merchant's recent signatures (`"sweep":"signature-scan"`) and can also be confirmed by signature (`POST /confirm`, base58); Tron payments come from TronGrid's indexed transfer list and confirm at **19 blocks** (~57s). - A cloud error never hides local orders, and a `202` from `/confirm` means "seen, not deep enough yet" — it is not a confirmation. - **`/confirm` works with or without a key, and both mean the same thing.** A merchant key (or a watcher SDK) reports a hash; without a header the payer's own browser attests one — the checkout page carries chain, token, recipient and amount, runs `eth_getLogs` itself (EVM) or looks up the order's own derived reference account (Solana) and reports a candidate **once**, dropping its `/status` poll to a heartbeat. Either way the server re-reads the receipt, recipient, amount and depth: an attestation is a hint, never a confirmation, and a lie is a `409`. That endpoint is the only write with a budget — **120/min per order** for an anonymous caller (so a shared egress address cannot spend another payer's budget), with a per-address ceiling of 360/min on top of it, and one bucket per credential when a key is sent; `429` + `Retry-After`, and `details.scope` says which budget tripped. - `GET /v1/health.usage` reports what this deployment used this month against the free-tier allowances (orders / events / deliveries / sweep scans, plus an `ok|watch|upgrade` verdict at 70%). Worker requests are **not** in it: a Worker cannot read the account's usage, so the field says "check the dashboard" instead of guessing. - **Nothing here is required.** The watcher SDK (`/docs/sdk-watch.md`) and `watcher: true` are opt-in: without them the server sweep and the payer's own browser still confirm. There is still no sandbox — a test order is a real (small) order. - The profile (shop, receiving address, chain, webhook, email, Telegram) can be edited from the same settings card; rotating the webhook secret invalidates the previous one immediately and shows the new one once. Order **Details** exposes the server's events and delivery states read-only. ### Off-chain channels (merchant-owned payment links) - Prerequisite: a **cloud merchant** (Settings → Cloud orders) and its API key — the Channels card is inert without it. - Enable in **Merchant → Settings → Channels**: register the link you already use (`https://…` containing `{reference}`; `{amount}`/`{currency}` optional; `settleCurrency` is a 3–5 letter code; **max 8 channels**), then run the reachability check and enable it. A static QR with no `{reference}` placeholder cannot work. Verification proves the link is **reachable** and nothing else — the payee name and one small test payment are the merchant's job. Changing the link sets the channel back to `pending` and disables it. - Order with a channel instead of a chain: `POST /v1/orders {"amount":"12.50","channelId":"ch_…"}`. The amount is then in the channel's `settleCurrency` (2 decimals), and the response carries the rendered `payUrl` next to the reference. The public payer status exposes `channel` and `payUrl` too. Off-chain orders are never swept for chain transfers. - Three ways to confirm, one receipt field (`confirmedSource`): 1. `POST /v1/orders/:reference/offchain-confirm {channelId, channelRef, amount?}` — merchant API key; `channelRef` (the receipt/serial) is required. 2. `POST /v1/offchain/confirmations` — signed by the merchant's own system with a per-channel secret (`POST /v1/channels/:channelId/secret`, shown once): `X-AIPAY-Channel-Signature: sha256=HMAC-SHA256(secret, ".")` plus a unix-seconds timestamp header accepted only within ±5 minutes. The signature is verified before any order lookup, so an unsigned call cannot discover references; a bad signature and an unknown channel answer identically. 3. `POST /v1/offchain/statements?channelId=…` (CSV, 2 MB / 10 000 rows) **proposes** matches only — `confirmed` is `0` unless the merchant's own automation policy covers the row (below). Each row is otherwise adopted explicitly (`POST /v1/offchain/statements/:id/adopt`), which runs the same confirmation path. Matching is by `reference`, otherwise by a single pending order with the same amount within ±10 minutes of `paid_at`; ambiguity is reported, never guessed. - **Automation policy (opt-in, off by default).** `GET|PATCH|DELETE /v1/merchants/me/automation` holds one policy per merchant: which channels may confirm an order by themselves, and up to what limit — `{"v":1,"statementAutoAdopt":{"enabled":true,"channels":["ch_…"],"maxPerOrder":"50","maxPerDay":"500","minOrderAgeSeconds":0}}`. Without a policy an import only proposes matches and the merchant adopts each row; that is still the default, and `enabled:false` stores nothing. The policy only *adds* a gate: an automatic confirmation runs the same matching and the same confirmation as a manual adopt, and both ceilings are required (`400 validation_failed` without them). The limits are amounts in the channel's settle currency, and the daily cap resets at 00:00 UTC. A statement row still cannot confirm an on-chain order. - **A statement confirmation is not chain evidence.** `statement_auto` means the merchant's own statement row confirmed the order under the merchant's own policy — not a chain verification, not a provider callback, and not something AIPAY checked. The merchant carries the risk of a wrong statement file: AIPAY never custodies money, never signs for the merchant and never verifies that the payment channel really paid. - Trust levels are not interchangeable: `channel: "onchain"` plus a transaction hash is chain evidence; anything else is the merchant's receipt. Do not describe an off-chain confirmation as "verified on-chain", and do not say AIPAY processed the payment. - Merchant controls: rotate the API key with a grace window (`POST /v1/merchants/me/keys/rotate`), rotate or revoke a channel's signing secret, and delete a channel (historical orders keep their `payUrl` snapshot). ## Onboarding a merchant with no human in the loop A third-party platform can be wired for on-chain collection by an agent alone: the published CLI creates the receiving wallet, the cloud merchant and the credentials, and the human only receives a file. Off-chain channels stay a human decision. ```bash # 1. create the merchant AND its receiving wallet in one step node agent/cli.mjs merchant onboard --chain bsc --shop "Blue Bottle" # -> merchantId, per-chain addresses, secretsFile (~/.aipay/agent/merchant.json, mode 0600) # -> the recovery phrase and the API key are written to that file and NEVER printed # 2. integrate with the key from that file (read it in-process; never echo it) curl -s -X POST https://api.aipay.im/v1/orders \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' \ -d '{"amount":"12.50","asset":"USDT","merchantOrderId":"INV-1"}' # 3. hand over: point the merchant at the human's own wallet, then delete the file node agent/cli.mjs merchant rotate-recipient --address 0xTheHumanWallet node agent/cli.mjs merchant show # redacted view: ids, addresses, key prefix ``` Rules that are not optional: - The file holds the **recovery phrase of the receiving wallet**. Never print it, paste it into a chat or a log, embed it in generated code, or commit it. Tell the human where the file is and that whoever holds it owns incoming funds. - You are not the custodian. `rotate-recipient` moves the merchant to the human's own address; after that the agent file can be destroyed. Existing orders keep the address they were created with. - Off-chain channels are **not** part of this flow: applying for Alipay / WeChat Pay / UnionPay / Stripe is a human business decision. `POST /v1/channels` only registers a link the merchant already has. - Everything else (orders, receipts, reconciliation export) is the merchant HTTP API: and . ## Documentation - [Gateway integration guide](https://aipay.im/docs/integration.md): use AIPAY as a payment gateway from a backend, a platform or an AI agent — the three integration shapes, the first call in curl, the go-live checklist, and what AIPAY refuses to do. - [Getting started](https://aipay.im/docs/getting-started.md): create or import a wallet, receive and send your first payment, and reconcile it. - [Wallets and keys](https://aipay.im/docs/wallets.md): the recovery phrase, the local wallet password, address derivation, and what AIPAY can and cannot do with your keys. - [Security model](https://aipay.im/docs/security.md): what protects the money, what a stolen merchant key can and cannot do, residual risks, and the duties that stay with the merchant. - [Provider assessment answers](https://aipay.im/docs/provider-assessment-answers.md): point-by-point answers to a third-party capability assessment — endpoints, state machine, confirmation depth, webhook contract, and the features we do not have (refunds, reorg re-checks, sandbox, SLA). - [Supported chains](https://aipay.im/docs/chains.md): every chain AIPAY supports today, plus the per-chain rules that prevent lost funds. - [Encrypted backup and restore](https://aipay.im/docs/backup.md): what a backup contains, the two different passwords, and how to restore on another device. - [Merchant guide](https://aipay.im/docs/merchant.md): set up a shop, charge a customer, share a payment link, confirm orders, and reconcile off-chain channels (Alipay/WeChat/UnionPay/Stripe) with a receipt, a signed webhook or an imported statement. - [Merchant API reference](https://aipay.im/docs/merchant-order-service.md): every `/v1` endpoint, the off-chain channel and confirmation contracts, platform access, error codes, and what the server does and does not verify. `GET https://api.aipay.im/v1` is the live, machine-readable version. - [Platform guide](https://aipay.im/docs/platforms.md): you operate many shops — the read-only grant model, `GET /v1/platform/merchants`, the `changes` feed with `epoch`+`nextAfter` (and `409 platform_sync_reset`), signed webhooks identical to merchant ones, self-service key rotation, budgets, and the honest limits (merchant onboarding is invite-and-claim: the platform mints a one-time invite token and never holds a merchant key; no refunds, no settlement). - [Watcher SDK](https://aipay.im/docs/sdk-watch.md): a Node library/CLI that watches the merchant's own address with the merchant's own RPC quota and reports only a transaction hash — install, flags, `200/202/409/429` meanings, EVM, Solana and Tron (TRC20 + native TRX) coverage, and what `watcher: true` makes the merchant responsible for. - [Guide for the human running an agent](https://aipay.im/docs/agent.md): what the agent surface is, install, the first run, capabilities and delegation, operating rules, and troubleshooting. - [Automatic payments and spending limits](https://aipay.im/docs/automation.md): the `aipay-mandate-v1` authorization object — format, signed bytes, a copy-paste verifier, the rules (caps, expiry against chain time, refunds at 20 %), who carries which risk, and how to run the check inside your own agent. ## App entry points - [Home / wallet](https://aipay.im/en/): balances, quick receive and send. - [Create wallet](https://aipay.im/en/create-wallet): generate a new recovery phrase. - [Restore wallet](https://aipay.im/en/import-wallet): key login — unlock the wallet you already have from a backup file (`.ckx` / PNG / `.json`) plus its password, or fall back to a 12-word recovery phrase. No account, no email. - [Receive](https://aipay.im/en/receive): pick a chain and show an address or QR code. - [Send](https://aipay.im/en/send): send native coins or tokens on a chosen chain. - [History](https://aipay.im/en/history): local and on-chain transaction history. - [Contacts](https://aipay.im/en/contacts): saved addresses with automatic chain detection, sealed at rest with a device key. - [Swap](https://aipay.im/en/swap): Solana token swaps. - [Earn](https://aipay.im/en/earn): directory of external staking / earning sites. - [Settings](https://aipay.im/en/settings): backup, restore, change password, biometric unlock, AI (BYOK) settings. - [Integrate as a gateway](https://aipay.im/en/integrate): the third-party view — payer vs merchant vs platform, a curl quickstart, and the non-custodial boundaries in both languages. - [AI agent payments](https://aipay.im/en/agent): plan a spending capability, sign it here with the approval key, wrap it with CryptoKey, or inspect a policy snapshot. The policy engine is local (not enforced on-chain) and MSG is not enabled. - [Merchant dashboard](https://aipay.im/en/merchant/dashboard): shop setup, payment links, POS, orders, products, analytics. - [Point of sale](https://aipay.im/en/merchant/pos): charge a customer amount and show a payment QR code. - [Checkout](https://aipay.im/en/pay): the page a customer opens from an AIPAY payment link. ## Agent skill and machine surfaces - `https://aipay.im/skills/aipay/SKILL.md` — the operating manual: capability boundary, a **zero-side-effect self-check**, the merchant and payer flows, granular consent ("creating a request is not authorising a payment"), interruption recovery, a report template, and an FAQ. It uses exactly the tools above; it is not a second payment system. - `https://aipay.im/agent.json` — machine-readable capability surface: tool count, `nextAction` vocabulary, error-guidance fields, policy modes, grant envelope (`aipay-grant-v1`) bounds and delegation (signer ≠ approver), transport (CKX / plaintext fallback), distribution, and every fail-closed feature with the config file that gates it. - `https://aipay.im/downloads/agent-latest.json` — the current runtime version, tarball URL, sha256, size and the exact file list (allowlist + hashes). - `https://aipay.im/agent/README.md` is not published; the operational source of truth for the MCP server and CLI is the project checkout (`agent/README.md`) plus SKILL.md. ## Key facts for AI agents - AIPAY is **non-custodial**: the recovery phrase and private keys never leave the user's browser (web app) or the agent's local keystore (agent surface). - One recovery phrase produces **the same `0x` address on every EVM chain**, a **separate Solana address** and a **separate Tron address** (`T…`). Funds do not move between chains automatically. - The **local wallet password (PIN)** decrypts the stored recovery phrase. It is never stored anywhere and cannot be recovered. It is different from the **backup password**. - **A backup does not contain the wallet password.** Restoring a backup gives you the encrypted wallet back, and you still need the original wallet password (or the recovery phrase) to unlock it. - There is no server, no email, no password reset, and no support channel that can recover a lost phrase or password. - AIPAY's UI is available in English and Simplified Chinese (`/en/...` and `/zh/...`). These documents are English-only. - **The agent policy is local, not a chain rule.** An escalated payment is approved with the human's approval key; the approval token is single-use and bound to one payment. The kill switch is the panic button and is audited from both sides. --- # AIPAY — operating notes for an AI agent You are reading the short version. The long ones are `llms.txt` (what this is and what is enabled) and `llms-full.txt` (every doc in one file). If you only have one request, read this file and then `https://api.aipay.im/v1`. ## What AIPAY is A non-custodial, multi-chain crypto wallet and merchant payment gateway. Payments move from a payer's wallet to a merchant's address; AIPAY never holds keys or funds. There is no account and no signup for a payer. Two surfaces, and mixing them up is the usual mistake: | Surface | Transport | Use it for | | --- | --- | --- | | Merchant order API | HTTPS at `https://api.aipay.im/v1`, `Authorization: Bearer aipay_sk_…` | creating orders, reading receipts and status, signed webhooks, CSV export | | Agent surface | local Node.js process (`agent/mcp-server.mjs`, `agent/cli.mjs`) | an agent paying with **its own** key under a local spending policy | There is **no hosted agent endpoint and no npm package**; the runtime is at . The merchant API is not exposed through the agent tools. ## How to do the common thing ```bash # 1. merchant (returns the API key once — store it in a secret manager) curl -s -X POST https://api.aipay.im/v1/merchants -H 'Content-Type: application/json' \ -d '{"shopName":"My Shop","recipientAddress":"0xYourAddress","chainKey":"bsc"}' # 2. order (checkoutUrl + reference; merchantOrderId makes it idempotent) curl -s -X POST https://api.aipay.im/v1/orders \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' \ -d '{"amount":"12.50","asset":"USDT","merchantOrderId":"INV-1042"}' # 3. poll (no key needed) curl -s https://api.aipay.im/v1/orders//status ``` Push beats polling: configure `webhookUrl` and verify `X-AIPAY-Signature: sha256=.")>`, rejecting timestamps older than five minutes. Events: `order.confirmed`, `order.expired`, `order.cancelled`. Retries 1 m / 5 m / 30 m / 2 h / 6 h. One recorded delivery can be re-sent on demand with `POST /v1/orders/:reference/notifications/:deliveryId/replay` (merchant key, same delivery id, fresh retry budget, written to the order timeline); there is still no event stream and no bulk replay, so bulk recovery is pulling `GET /v1/orders` or `GET /v1/orders/export.csv`. ## Rules that are not negotiable (and not our opinion) - **Mainnet only.** There is no sandbox and no testnet behind `api.aipay.im`; a test order is a real order for a small amount. To rehearse without money, run the Worker yourself (`wrangler dev` with `RPC_OVERRIDES`, see `/docs/merchant-order-service.md` §11) or use the repository at . - **We are not a PSP and never touch the money.** Consequently there are **no refunds, reversals, chargebacks or dispute handling** in the API: the merchant refunds from their own wallet. Do not promise a payer a refund through AIPAY. - **Confirmed means "we re-read the transaction and it is deep enough"** — not "the goods shipped" and not "the payment is final forever". EVM orders are re-read once (30 min – 6 h later) and a vanished or shallow transaction is recorded as `confirmation_regressed` (event + `last_error`); the status never changes and no webhook fires. Reconcile on it, do not reverse on it. - **One recipient per merchant, no on-chain memo.** Two pending orders with the same amount and recipient are ambiguous — use distinct amounts. - **Native coins (ETH/BNB/POL/…) need `POST /confirm` with the tx hash**; only token transfers are discovered by the sweep. - **An off-chain confirmation is the merchant's own receipt**, not chain evidence, and `channel` says which it is. - **MSG / MSGChain is disabled.** Do not offer it. - **Paid plans are not on sale.** `GET /v1` reports `billing.status: "free"` with no plans; there is no price list to quote. ## What you may not do Do not invent endpoints, statuses or webhook fields; do not claim an order is paid without a `confirmed` state from the API; do not treat a 202 (`insufficient_confirmations`) as success; do not mint spendable value from a webhook without verifying its signature and timestamp; do not describe AIPAY as custodial, as a licensed payment institution, or as covering fiat collection (the off-chain layer only orchestrates *the merchant's own* channels). ## Where the rest is - `llms.txt` — capabilities and fail-closed features - `llms-full.txt` — all docs concatenated - `agent.json` — machine-readable capability surface - `openapi.json` — merchant HTTP API description - `.well-known/mcp.json` — says out loud that our MCP runtime is local (stdio) and that there is **no hosted MCP endpoint** - `/docs/provider-assessment-answers.md` — point-by-point answers to a third-party capability assessment, including the gaps above --- # Getting started with AIPAY AIPAY is a non-custodial, multi-chain crypto wallet and merchant payment gateway that runs entirely in your browser. Nothing is stored on an AIPAY server: there is no account and no login, only a wallet that lives on your device. This guide covers the real, currently available path: create a wallet, receive funds, send funds, and check that a payment arrived. It takes about five minutes. **Before you start:** AIPAY handles real assets on public blockchains. A transaction sent on the wrong chain cannot be undone. Read [chains.md](chains.md) before moving funds for the first time. ## 1. Open the app - Visit **https://aipay.im**. You will land on the English UI at `/en/` (or `/zh/` for Simplified Chinese). - Optional but recommended: install it as a PWA (Progressive Web App) so it opens full-screen and works offline. - **Android (Chrome):** tap the install prompt, or menu → *Add to Home screen*. - **iOS (Safari):** Share → *Add to Home Screen*. - **Desktop (Chrome/Edge):** the install icon in the address bar. - AIPAY also shows an install banner on user pages when the app is not yet installed. ## 2. Create a wallet 1. Go to **https://aipay.im/en/create-wallet**. 2. Enter a wallet **name** (just a label for this device) and a **local wallet password** of at least 10 characters. Confirm it. 3. AIPAY generates a **12-word recovery phrase** and shows it on screen. 4. **Write the 12 words down in order, on paper, offline.** This phrase is the wallet. Anyone who has it owns the funds. Nobody — not AIPAY, not any support desk — can recover it if it is lost. 5. Confirm you have saved it, and you are done. The wallet is now unlocked on this device. You will need the local wallet password whenever you sign a transaction, unlock after a reload, or use biometric unlock. It is never stored, so a forgotten password can only be reset by re-importing the recovery phrase. > Already have a wallet? Go to **https://aipay.im/en/import-wallet**. If you saved a backup, that page restores it with the backup file plus its password ("key login" — no account, no email). If you only have the 12 words, the same page rebuilds the same wallet from them. See [wallets.md](wallets.md) for the full model, and [backup.md](backup.md) for what a backup carries. ## 3. Receive funds 1. Open **https://aipay.im/en/receive**. 2. Pick the chain you want to be paid on (for example *Ethereum*, *BNB Chain*, *Polygon*, *Base*, *X Layer*, *Solana* or *Tron*). The full list is in [chains.md](chains.md). 3. AIPAY shows the address for that chain and a QR code. 4. Share the address or QR code with the sender, or scan the QR code from your own device. **Critical:** the sender must send on the same chain you selected. Two EVM chains share the same `0x` address, but coins sent over the wrong network can be lost. Read [chains.md](chains.md). Your address is derived from the recovery phrase, so it is stable. You can receive many times to the same address. ## 4. Send funds 1. Open **https://aipay.im/en/send**. 2. Choose the chain, then the asset (native coin or a token). 3. Enter the recipient address and the amount. AIPAY detects the address type and suggests a matching chain. 4. Review the fee estimate, then confirm and enter your **local wallet password** to sign. 5. The transaction is signed locally and broadcast directly to the chain's public RPC endpoint. AIPAY does not submit anything through its own servers. AIPAY checks your balance before you sign, so an obviously unaffordable payment is stopped with an `insufficient balance` message rather than a failed transaction. ## 5. Check that a payment arrived - Open **https://aipay.im/en/history** to see local and on-chain activity. - On the **Receive** page you can also scan or paste a transaction hash to verify a specific payment. - For merchants: from a POS sale or payment link, the **Orders** page tracks each order and confirms it automatically once the payment is seen on-chain. See [merchant.md](merchant.md). ## 6. Protect the wallet | Risk | What to do | |---|---| | Phone lost, stolen or wiped | Restore the recovery phrase on another device — or [restore an encrypted backup](backup.md). | | Browser data cleared | Same as above. Clearing site data deletes the local wallet copy. | | Phrase photographed / in cloud notes | Rewrite it on paper; delete any digital copy. | | Weak local password | Use at least 10 characters; it protects the stored phrase on this device. | | Not sure what a feature does | Open **Settings → Local Backup** and take a backup *before* experimenting. | ## What is not available yet Be aware of these when reading marketing or third-party material about AIPAY: - **MSG / MSGChain**: implemented but disabled. No MSG addresses, balances or payments are shown. - **Buy crypto with a card (fiat on-ramp)**: disabled. - **NFT gallery**: disabled. - **EVM token swaps**: disabled (Solana swaps work). - **Merchant payouts on MSGChain**: not open. The authoritative list with config files is in [../llms.txt](../llms.txt). --- # Use AIPAY as a payment gateway This page is for a third party — a shop's backend, a platform, or an AI agent acting for a merchant — that wants AIPAY to take the payment and tell the caller when the money actually arrived. It is the task-oriented companion to the [API reference](merchant-order-service.md): read this one to decide *which* integration you need and to get to a working call; read the reference for every field, error code and verification rule. Everything below is live on `https://api.aipay.im` today. `GET https://api.aipay.im/v1` returns the same endpoint list in machine-readable form, and `GET /v1/health` reports which verifiers and notification channels are actually switched on. ## What AIPAY is, and what it is not | AIPAY does | AIPAY does not | | --- | --- | | Gives you a hosted checkout URL and a QR the payer can open | Hold, move or custody funds — money goes straight to *your* address | | Watches the chain and confirms an order when the payment is deep enough | Need your private key, seed phrase or exchange password | | Orchestrates off-chain channels (Alipay / WeChat Pay / UnionPay / Stripe / other) | Call the provider, store a provider credential, or receive that money | | Notifies your webhook / inbox / Telegram, with a signed payload | Act as a licensed payment institution, offer refunds, or reverse a payment | | Rotates API keys with a grace window, and keeps 90 days of order history | Guarantee that a confirmed payment means the merchant delivered anything | Two claims that matter, because they are unusual: **zero commission** (nothing in the service computes a percentage) and **free usage stage** (`/v1` returns `billing: {"status":"free","plans":[],"startsAt":null}`; paid subscriptions are planned but not on sale and have no start date). ### If you are an AI agent: onboard with two commands The published runtime can create the merchant **and** its receiving wallet, without a secret ever reaching your transcript: ```bash node agent/cli.mjs merchant onboard --chain bsc --shop "Blue Bottle" # -> { merchantId, recipientAddress, addresses, secretsFile, secretsFileMode: "0600", apiKey: "aipay_sk_…" } node agent/cli.mjs merchant show # ids + addresses + key prefix only node agent/cli.mjs merchant rotate-recipient --address 0xTheHumanWallet # hand over ``` The file (`~/.aipay/agent/merchant.json`, mode 0600) holds the recovery phrase and the API key. Hand it to the human, never print it, and finish the handover so the merchant pays the human's own wallet. Off-chain channels still need a human to sign up with the provider — `POST /v1/channels` only registers a link the merchant already has. ## Pick the shape you need 1. **Hosted checkout, on-chain** — the payer pays with a wallet on one of 8 EVM mainnets, Solana or Tron. You create an order, share `checkoutUrl`, and poll or receive a webhook. This is the default. 2. **Off-chain channel** — the customer pays through *your* Alipay / WeChat Pay / Stripe link. AIPAY renders the link with the order reference, and the confirmation comes from you (manual, signed webhook, or adopted CSV row). 3. **AI agent acting for a merchant** — the MCP server and CLI cover the *payer* side (quote, pay, order, policy). Merchant-side channel tools are **not** in the MCP surface; an agent integrates the same HTTP API in shapes 1 and 2. ## Shape 1 — hosted on-chain checkout (5 minutes) ```bash BASE=https://api.aipay.im # 1) Create the merchant. apiKey (and webhookSecret, when you pass a webhookUrl) # is returned exactly once; only its SHA-256 is stored. curl -s -X POST "$BASE/v1/merchants" -H 'Content-Type: application/json' -d '{ "shopName": "Blue Bottle Coffee", "recipientAddress": "0xYourReceivingAddress", "chainKey": "bsc", "webhookUrl": "https://shop.example.com/aipay/webhook" }' # 2) Create an order. The amount is in human units of the asset you name. curl -s -X POST "$BASE/v1/orders" \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' \ -d '{"amount":"12.50","asset":"USDT","merchantOrderId":"INV-1042"}' # => { "order": { "reference": "ap_…", "checkoutUrl": "https://aipay.im/en/pay?intent=…" } } # 3) Show checkoutUrl as a link or QR. The payer page needs no account. # Poll the payer-safe status endpoint (no API key, no merchant data): curl -s "$BASE/v1/orders/ap_…/status" # 4) Optional: confirm from a transaction hash (webhooks/cron do this for you). curl -s -X POST "$BASE/v1/orders/ap_…/confirm" \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' \ -d '{"txHash":"0x…"}' ``` The checkout URL encodes the same `StaticPaymentIntent` v1 the AIPAY app decodes on `/pay`, so the payer sees the amount, chain, asset and recipient pre-filled and signs locally. AIPAY never asks the payer for a key. ### Reading the answer honestly - `201` on create, then `status: "pending"` until the payment is seen on chain. - `202` from `/confirm` is **not** success: it means "seen, not deep enough yet" (`verification.confirmations` vs `requiredConfirmations`). Keep polling. - `confirmed` means the server re-read the receipt, the transfer event, the recipient, the amount and the confirmation depth. It never means "shipped". - `merchantOrderId` is idempotent per `(merchant, merchantOrderId)`: replaying the same id with the same parameters returns the original order; changing the parameters is `409 merchant_order_conflict`. - A receipt that arrives after the order expired still confirms (`late: true`); the sweep alone never resurrects a closed order. ## Shape 2 — off-chain channel (Alipay / WeChat Pay / Stripe / …) A channel is *your* payment link plus a settlement currency. AIPAY fills in the reference and tracks the order; the money never touches AIPAY. ```bash # 1) Register the channel (payUrlTemplate supports {reference} and {amount}). curl -s -X POST "$BASE/v1/channels" \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' -d '{ "channel":"alipay","label":"Store Alipay","settleCurrency":"CNY", "payeeName":"Blue Bottle Coffee", "payUrlTemplate":"https://pay.example.com/checkout?order={reference}&amount={amount}" }' # 2) Verify, then enable. Verification only proves the link is reachable # (status < 500); the payee name still needs a human to check it. curl -s -X POST "$BASE/v1/channels/ch_…/verify" -H "Authorization: Bearer $AIPAY_API_KEY" curl -s -X PATCH "$BASE/v1/channels/ch_…" \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' \ -d '{"enabled":true}' # 3) Create the order with the channel instead of a chain. The amount is in the # channel's settleCurrency (2 decimals); the response carries the rendered payUrl. curl -s -X POST "$BASE/v1/orders" \ -H "Authorization: Bearer $AIPAY_API_KEY" -H 'Content-Type: application/json' \ -d '{"amount":"88.00","channelId":"ch_…"}' ``` Three ways to confirm, one receipt field (`confirmedSource`) — all documented in the [API reference §3.6](merchant-order-service.md): | Source | Who signs | Endpoint | | --- | --- | --- | | `merchant_manual` | merchant API key | `POST /v1/orders/:reference/offchain-confirm` | | `merchant_webhook` | per-channel HMAC secret | `POST /v1/offchain/confirmations` | | `statement` | merchant API key, one row at a time | `POST /v1/offchain/statements?channelId=…` then `/:id/adopt` | A CSV import only **proposes** matches (`confirmed` is always `0`); each row is adopted explicitly. Matching is by `reference`, otherwise by a single pending order with the same amount within ±10 minutes — ambiguity is reported, never guessed. **Do not describe an off-chain confirmation as verified on-chain.** `channel: "onchain"` plus a transaction hash is chain evidence; anything else is the merchant's receipt, and the API says which one it is. ## Shape 3 — an AI agent acting for a merchant An agent can drive shapes 1 and 2 with plain HTTP and a merchant API key. What it must not do is pretend the agent surface covers it: the MCP server and CLI are a **payer-side** surface (quote, pay, order status, local spending policy), and `agent.json` declares `agent_tools.available: false` for channels. Route merchant-side work through the HTTP API, and keep the API key out of prompts and logs. Payer-side agents that need to *pay* an AIPAY link should use the MCP surface instead; see [agent.md](agent.md) and the skill in [SKILL.md](../skills/aipay/SKILL.md). ## How finance knows a payment arrived There are three independent ways to learn that money arrived, and they are deliberately not the same mechanism: 1. **Signed webhook (fast path).** `order.confirmed` on your `webhookUrl`, signed with `sha256=HMAC-SHA256(secret, ".")`. Verify the **raw body** and the timestamp window, then answer `2xx`. A webhook is a notification, not the payment itself: the body carries the reference, the amount, the transaction hash and the confirmation depth, so store the receipt and reconcile against the API, not against your inbox. 2. **Poll / receipt (per order).** `GET /v1/orders/:reference/status` is payer-safe (no key, no PII); `GET /v1/orders/:reference` with the merchant key returns the full record, including which deliveries were attempted and why a delivery failed. 3. **Reconciliation export (books).** `GET /v1/orders/export.csv` returns the same rows as the API as CSV, with a `confirmedFrom` / `confirmedTo` filter so month-end is "what was confirmed in November", not "what I remember polling". ```bash # everything confirmed between two timestamps (epoch ms) curl -s "$BASE/v1/orders/export.csv?status=confirmed\ &confirmedFrom=1794000000000&confirmedTo=1794600000000" \ -H "Authorization: Bearer $AIPAY_API_KEY" -o confirmed-nov.csv ``` Columns: `reference, merchant_order_id, status, created_at, confirmed_at, amount, asset, decimals, amount_base_units, chain_key, token_address, channel, confirmed_source, channel_ref, tx_hash, block_number, confirmations, webhook, description`. Read it like this: - `channel = onchain` plus `tx_hash` is **chain evidence**; `confirmed_source` is then `chain`. Anything else (`merchant_manual`, `merchant_webhook`, `statement`) is the merchant's own receipt and must not be booked as a chain settlement. - `webhook` (`delivered` / `pending` / `failed` / `not_configured` / `none`) is the delivery state for that order. `failed` means your endpoint did not accept the notification after all retries — the payment is still real, so pull the order (or the export) instead of assuming it never happened. - `X-AIPAY-Rows` and `X-AIPAY-Truncated: true` are set on the response. A truncated export means "narrow the window", never "this is everything". - Cells are RFC 4180 quoted, and any value that a spreadsheet would treat as a formula is prefixed with `'`, so a merchant's own `description` cannot execute on the accountant's machine. ### Timing edge cases the books must handle - **Paid after expiry.** The automatic sweep stops at `expires_at`, so a payment that lands later is not picked up by itself. If the money did arrive, the merchant confirms it explicitly with `POST /v1/orders/:reference/confirm`; the order then becomes `confirmed` with `verification.late = true`, `verification.previousStatus = "expired"` and an `confirmed_late` event. The webhook fires as usual, so the books move once — not never. - **Paid after cancellation.** Same path: a cancelled order can be confirmed late. A payment that does not match (wrong amount, recipient or reference) still refuses with `transaction_mismatch`, so a terminal order cannot be resurrected by an unrelated transfer. - **Retries and duplicates.** Deliveries retry with backoff; the same receipt is idempotent, and `merchantOrderId` is idempotent per merchant. Deduplicate on `reference` (and on `merchant_order_id` if you set one) rather than on arrival order. - **Retention.** Orders are kept 90 days. Export anything you need to keep; the export is a read of those same rows, not a second ledger. ## Reading the chain from a browser (optional relay) If your own page watches the chain for a payment (instead of polling us), public nodes will sometimes refuse it: CORS, per-IP rate limits, or "getLogs unsupported on the free plan". AIPAY runs a **read-only** relay for exactly that case: ```http POST https://api.aipay.im/v1/rpc/bsc { "jsonrpc": "2.0", "id": 1, "method": "eth_getLogs", "params": [ … ] } ``` - **Reads only.** The allowlist is `eth_blockNumber`, `eth_chainId`, `eth_getLogs`, `eth_getTransactionReceipt`, `eth_getTransactionByHash`. Signing and broadcasting are not proxied, and batches are refused. - **Bounded.** One `eth_getLogs` window may span at most 5,000 blocks, and the relay shares the same per-IP read budget as the rest of the API (120/min). `GET /v1` publishes both numbers live. - **No verdict.** Anything it returns is raw node output. It never confirms an order; only `POST /v1/orders/:reference/confirm` (and the server's own re-read) can do that. - **EVM only.** Solana and Tron are read through their own protocols, not `eth_*` calls. - Our own checkout page and merchant console use it as a **last resort** after the public endpoints fail, so a healthy public node costs no AIPAY request. - **It is only as strong as the free upstreams behind it.** On 2026-11-15, `eth_getLogs` through the relay answered `200` on Ethereum but `502` on BSC, Polygon and Arbitrum, because those public nodes rate-limit Cloudflare's egress (`HTTP 429` / `limit exceeded`). `eth_blockNumber`, `eth_chainId` and receipt reads kept working. If you depend on this, point the same chain at a free keyed endpoint (`RPC_OVERRIDES` is operator-only) or keep your own RPC. ## A client you can copy (Node and Python) Download the reference clients from `examples.tarball.url` in the [AIPAY download manifest](https://aipay.im/downloads/agent-latest.json). Verify its `sha256` before extracting the archive. If your manifest does not yet list `examples`, that release predates the examples archive. The archive also includes the Node platform client. The merchant clients are one file each, with no dependencies, and they exist because four things are easy to get wrong: retrying a `429` without `Retry-After`, verifying a webhook body you have re-serialised, resuming a reconciliation you cannot restart, and re-inventing idempotency that `merchantOrderId` already provides. | | File | Run the self-check | | --- | --- | --- | | Node 20+ | `examples/merchant-node/aipay.mjs` | `node --test examples/merchant-node/aipay.test.mjs` | | Python 3.9+ | `examples/merchant-python/aipay.py` | `python3 examples/merchant-python/selfcheck.py` | Both expose the same surface: - `createOrder({ amount, asset, merchantOrderId })` → `{ order, idempotent }` (replay-safe: same id and parameters return the original order, changed parameters answer `409 merchant_order_conflict`). Persist the ID before the first attempt. A create request without a stable ID is sent once. If its result is uncertain, reconcile before submitting another request; - `getOrder(reference)`, `listOrders({ cursor, status, limit })`; - `reconcile({ cursor, onPage })` → `{ orders, checkpoint }` (Python uses `on_page`). Use the callback to commit each page of rows and its checkpoint together. Resume a non-null `checkpoint.cursor` with the same filters. The clients prefer `nextPageCursor` and support numeric checkpoints for older servers. A page limit returns the rows read and the current checkpoint. - `verifyWebhook({ rawBody, signature, timestamp, secret })` → `{ ok }` or `{ ok: false, reason }`, over the **raw** body with a ±5-minute tolerance; - `AipayError { status, code, message }`, with `status: 0` for network failures. The CI suite runs both clients against the real Worker handlers over real HTTP, so the examples cannot rot silently. ## Rehearse without moving money `api.aipay.im` is mainnet only. To rehearse locally, install the project dependencies and run this from the repository root with Node.js 22 or later: ```bash npm ci npm run sandbox ``` This starts a Worker on a loopback port with a fresh temporary D1 database, applies the schema and creates a test merchant. It prints the URL and a command for running the Node reference client in another terminal. Clear any existing `AIPAY_BASE_URL` and `AIPAY_API_KEY` in that terminal first. Node gives existing environment variables precedence over `--env-file`. Press Ctrl+C to stop the Worker and discard its local database and test credentials. For a self-contained check that starts and stops the Worker automatically: ```bash npm run sandbox -- --check ``` The check creates an order, replays it with the same `merchantOrderId`, and finds it in the merchant's order list. The launcher skips the background sweeper, so it covers the HTTP order lifecycle without confirming a payment. Use the integration tests with a fake RPC to exercise chain confirmation. The API can return checkout links pointing to `aipay.im`. Leave sandbox orders unpaid and use the local API for the rehearsal. ## Go-live checklist - [ ] Store `apiKey` and `webhookSecret` now — both are shown once. Rotate the key with `POST /v1/merchants/me/keys/rotate {"graceHours":24}` instead of creating a new merchant (history stays with the merchant). - [ ] Verify the webhook signature over the **raw body** (`sha256=HMAC-SHA256(secret, ".")`, ±5 minutes). - [ ] Treat `202` as "not yet", and deduplicate on `reference` / `merchantOrderId` — webhooks retry. - [ ] Send `merchantOrderId`, so a retried create cannot double-charge intent. - [ ] Know the limits: 500 orders per merchant per UTC day, 16 KiB body, TTL 120–3600 s (default 900), 90-day retention. - [ ] Confirm the chains you actually accept with the payer: an asset on the wrong chain is not recoverable (see [chains.md](chains.md)). - [ ] Read the [security model](security.md) before you handle a merchant key: it lists what a stolen key can do, and what stays the merchant's job. ## Verify a deployment yourself The whole path — merchant, on-chain order, channel, off-chain order, manual receipt, CSV import, adoption, key revocation — is scripted and runs against any deployment: ```bash node scripts/api-smoke.mjs --base https://api.aipay.im ``` It creates a throwaway merchant, exercises both shapes above, prints one line per check, and deletes the merchant on the way out. CI runs the same script after every API deploy, so "can a third party use this as a gateway" is a test result rather than an opinion. ## Where the facts live - [API reference](merchant-order-service.md) — every endpoint, error code, and what the verifier checks. - [Platform guide](platforms.md) — you operate many shops and read their orders through one integration (grants, change feed, webhooks, budgets). - `GET https://api.aipay.im/v1` — the same facts as JSON, for code generation. - `GET https://api.aipay.im/v1/health` — live verifier / notification / billing status. - [Merchant guide](merchant.md) — the same capability from the shop UI. - [Supported chains](chains.md) — per-chain rules and confirmation depth. - [llms.txt](../llms.txt) — the whole surface in one file for humans and agents. - `https://aipay.im/agent.json` — machine-readable capability surface, including every fail-closed feature and the config file that gates it. - `https://aipay.im/en/integrate` — the short, bilingual version of this page. --- # Merchant guide AIPAY turns the same wallet into a point of sale, a payment-link generator and an order tracker. Everything is non-custodial: **payments go straight to the receiving address you configure**. AIPAY never holds your funds and takes no cut today. > **Optional cloud tracking.** Merchants can opt in to the hosted AIPAY order > service (section 5). It is non-custodial and takes **zero commission**; until > you enable it, every order stays local to this browser. > > **Not available yet:** receiving merchant payments *on MSGChain via an AIPAY on-chain contract* (the developer gas-share path) is **not open**. See [../llms.txt](../llms.txt). ## 1. Become a merchant AIPAY has no separate merchant signup. The only difference between a user and a merchant is a profile with a shop name and a receiving address. 1. Make sure a wallet exists (see [getting-started.md](getting-started.md)); the merchant tools use your wallet. 2. Open **https://aipay.im/en/merchant/settings**. 3. Set: - **Shop name** — shown to customers. - **Receiving address** — the address that will be paid. Use an address you control, on the chain(s) you want to accept. 4. Save. The merchant dashboard, POS and orders are now usable. Store your shop settings, products and orders locally — include them in your [backup](backup.md). ## 2. Take a payment at the counter (POS) 1. Open **https://aipay.im/en/merchant/pos**. 2. Choose the **chain** and **asset** (for example Base + USDC, or Solana + USDC). If reached from a product, the amount and memo are filled in automatically. 3. Enter the amount. 4. AIPAY creates a payment request with a unique **reference** and shows a **QR code**: - EVM chains use an **EIP-681** payment URI (works with wallet apps that understand it). - Solana uses a **Solana Pay** URI. 5. The customer pays. AIPAY watches the chain for a transfer to your address carrying that reference and **confirms the order automatically** once the chain reaches the expected confirmation depth. 6. If automatic detection is not possible (for example a transfer sent from an unusual contract), paste the **transaction hash** into the manual-confirm field to verify and confirm the order explicitly. Payments are labelled with a reference so two identical amounts from two customers remain distinguishable. ## 3. Share a payment link For online / remote customers: 1. Open **https://aipay.im/en/merchant/dashboard**. 2. Choose **Create payment link** and fill in: - **Amount** - **Currency** (USDC, SOL, ETH or USDT) - **Description** (optional, e.g. invoice number) 3. AIPAY produces a link that opens the **checkout page** — a URL of the form `https://aipay.im//pay?intent=...` containing the amount, asset and a unique reference. 4. Copy it and send it to the customer (chat, email, invoice, QR code). On the checkout page the customer can: - pay directly if their device has an AIPAY wallet with a matching key (unlock → sign → broadcast), or - pay from **any other wallet** by scanning the QR code / copying the address, then pasting the transaction hash; AIPAY verifies the payment on-chain with the reference and confirms the order. Because the link carries a reference, AIPAY can match the payment back to the order without any account. ## 4. Track orders - **https://aipay.im/en/merchant/orders** — every payment request with its status. When cloud orders are enabled, cloud and local rows are merged by reference: server-confirmed state wins, and a cloud outage only adds a warning — it never hides local orders. - A background watcher confirms pending orders by itself: a per-minute Worker cron (plus an in-request tick) polls the chains for the payment and updates the order when it appears. Pending orders expire after the order's TTL — **default 15 minutes, allowed range 2–60 minutes on every chain**, Solana included — to avoid watching stale sales forever. - Confirmed orders carry the transaction hash so you can open the block explorer. - **https://aipay.im/en/merchant/analytics** — simple sales overview for the local data. Since orders live in this browser, keep a backup and do not rely on clearing site data. ## 5. Cloud orders (opt-in, beta) By default orders live only in this browser. Turning on **Merchant → Settings → Cloud orders** creates a merchant on the AIPAY order service (`https://api.aipay.im`). The server then watches the chain for you, so a payment can be confirmed while the shop laptop is closed. - **Non-custodial, zero commission.** Funds still go straight to your receiving address. The service never holds or moves funds; `grep` the code — no fee is computed anywhere. - **The API key is local and sensitive.** It is shown once at creation and stored **unencrypted in this browser's localStorage**, so anyone with access to this browser profile can read it. Enable it only on a device you control. "Remove key from this device" deletes the local copy; "Delete cloud merchant" deletes the merchant and all its orders on the server. - **Scope:** the 8 EVM mainnets (Ethereum, BNB Chain, Polygon, Arbitrum, OP Mainnet, Avalanche C-Chain, Base, X Layer), **Solana** and **Tron**. MSGChain orders are rejected with `unsupported_chain` while its mainnet does not exist. Native-coin orders (BNB/ETH/POL/TRX…) have no transfer log, so they stay pending until a transaction hash is confirmed. - **Order window:** 15 minutes by default (120–3600 s). If money arrives after expiry the transfer is still on-chain, but the order stays `expired` and must be reconciled manually. - **Notifications:** webhook (HMAC-SHA256 over `.`), email and Telegram. Channels whose server credential is missing are reported as `disabled` with a reason instead of pretending to deliver. Edit the profile in **Cloud orders → Edit cloud profile** to change the shop, receiving address, default chain, webhook URL, email or Telegram chat. Rotating the webhook secret invalidates the old one immediately; the new secret is shown once. - **Order detail:** **Orders → Details** on a cloud row opens the server record: append-only events, per-channel delivery status/attempts, automatic check count and the verifier's last error. It is read-only, so it can never claim a payment that the server did not confirm. - **Retention & privacy:** confirmed/expired/cancelled orders (with events and deliveries) are purged after **90 days**. The public receipt and payer status endpoint expose only on-chain facts — no merchant id, key, webhook, email or Telegram id. Client IPs are stored only as a hashed per-day signup counter. Deleting the merchant hard-deletes everything immediately. - **Payer side:** the `/pay` page polls the **public** status endpoint, so a payer needs no key. The page shows "AIPAY confirmed / watching / expired" based on the server's answer and never invents a confirmation. - **Fallback:** if the service cannot be reached, creating a payment link or a POS sale falls back to the local reference and says so. The checkout page keeps working; the merchant list keeps showing local orders. Technical API (there is no SDK and no key is ever needed to read a public receipt): `GET /v1` lists the live endpoints and confirmation depths, `POST /v1/merchants` creates a merchant, `POST /v1/orders` creates an order, `GET /v1/orders/:reference/status` is the public payer poll, and `POST /v1/orders/:reference/confirm` verifies a transaction hash server-side. Every error is `{ "error": { "code", "message" } }`. ## 5b. Off-chain channels (Alipay, WeChat Pay, UnionPay, Stripe, other) AIPAY can also put an order next to the payment link **you** already use. This is orchestration and reconciliation only: AIPAY never calls the provider, never stores a provider credential and never receives the money. Nothing here makes AIPAY a payment institution. 0. **Prerequisite: a cloud merchant.** Channels live with cloud orders, so Settings → Cloud orders must be connected first (that is what returns the API key). Without it the Channels card has nothing to attach to and stays inert, and the API answers `unauthorized`. 1. **Register the link** in **Merchant → Settings → Channels**: kind, label, the `https://…` template (must contain `{reference}`; `{amount}`/`{currency}` are optional), the payee name, the settlement currency (a **3–5 letter** code such as `CNY` or `USDC`) and an instruction for the payer. Limits: **8 channels per merchant**. A static QR code with no placeholder cannot work — every order needs its own reference in the link. 2. **Verify, then enable.** The check only proves the server can reach the link (a 4xx from a link that validates its reference is normal). Who gets paid is still **your** check — compare the payee name and run one small test payment. A new link resets the channel to `pending` and disables it. 3. **Sell.** The POS and the payment-link dialog now ask for the **payment method**: on-chain, or one of your verified + enabled channels. The amount is then in that channel's settlement currency. 4. **Confirm with a receipt.** The order stays `pending` until you (or your system) confirm it — and a receipt that arrives **after the order expired (or after you cancelled it)** still confirms: the response carries `late: true` and `previousStatus`, and the audit trail records `confirmed_late`. That is how a late QR settlement or yesterday's aggregator statement lands. Three ways, one field — `confirmedSource` says which: - **Manual**: Orders → the row → enter the receipt/serial number. Required: a confirmation without a receipt turns reconciliation into guesswork. - **Signed webhook**: give your payment system a per-channel signing secret (Channels → **Signing secret**, shown once). It posts to `POST /v1/offchain/confirmations` with `X-AIPAY-Channel-Signature: sha256=HMAC-SHA256(secret, ".")` and a unix-seconds timestamp; only ±5 minutes is accepted. The signature is checked before any order lookup, so a bad signature and an unknown channel answer identically. - **Statement import**: upload the CSV your finance team exports (`channel_ref, amount, currency, paid_at, reference`). The import **confirms nothing** — it proposes matches (by reference, otherwise by a single pending order of the same amount within ±10 minutes) and you adopt each row. Re-uploading the same file does not duplicate rows. The trust level is not interchangeable: a chain transaction hash is chain evidence; `merchant_manual`, `merchant_webhook` and `statement` are your claim. The receipt and the payer page say so, and AIPAY never presents an off-chain confirmation as "verified on-chain". ## 6. Products and quick charge - **https://aipay.im/en/merchant/products** — maintain a small catalogue (name, price, currency). - Tap **Charge** on a product to open the POS with the amount, currency and memo pre-filled. ## 7. Practical rules - **Do not change your receiving address casually.** Older payment links and QR codes point at the address captured when they were created. - **Match the chain.** Accept on the chains you can actually use; a customer paying on a chain you did not intend may be unrecoverable. See [chains.md](chains.md). - **Keep a little native coin** in the receiving wallet for any outgoing action (refunds, moves). - **Confirm before releasing goods.** On Ethereum and Polygon the confirmation wait can be minutes; Layer 2s and Solana are much faster. - **Test with a small amount** on every new chain or asset before your first real sale. ## What is not enabled - MSG / MSGChain merchant payouts via an AIPAY on-chain contract — not open. - Cloud order verification for MSGChain — the server answers `unsupported_chain` until mainnet parameters exist; MSG sales use the local flow. (Solana cloud orders *are* verified: the sweep scans the merchant's recent signatures and `POST /confirm` re-checks the transaction.) - Fiat on-ramp, NFT gallery and EVM swaps — disabled (they do not affect POS, links or orders). --- # AIPAY merchant order service (HTTP API v1) Server-side order tracking for AIPAY merchants. The service watches the chain for you, so an order can be confirmed while the shop laptop is closed, and it can notify a backend / inbox / Telegram chat when the money actually arrived. - **Non-custodial.** Funds go straight to the merchant's own address. The service never holds, moves or has a key to any funds. - **Zero commission.** There is no fee, no spread and no AIPAY cut in this service. `grep` the source: nothing computes a percentage. - **Verify, don't trust.** A confirmation is only accepted after the server re-reads the receipt, the transfer event, the recipient, the amount and the confirmation depth from an RPC node. - **Opt-in.** Nothing is uploaded unless the merchant explicitly creates a merchant account and an order here. Current deployment: `https://api.aipay.im` (Worker `aipay-api`, custom domain bound through `[[routes]] custom_domain = true` in the dedicated Cloudflare account). Deployment details: [api-deploy-runbook.md](api-deploy-runbook.md). > **Scope of v1.** 8 EVM mainnets plus Solana and Tron (see §9). MSGChain orders > are rejected with `unsupported_chain` until mainnet parameters exist. > Native-coin orders need a transaction hash (there is no ERC-20 log to scan); > Solana orders are swept from the order's own reference account (falling back to > the merchant's recent signatures); Tron orders are swept from TronGrid's > indexed transfer list. Both can also be confirmed by transaction id. --- ## 1. Quickstart ```bash BASE=https://api.aipay.im # 1) Create a merchant. The API key and webhook secret are shown ONCE. curl -s -X POST "$BASE/v1/merchants" \ -H 'Content-Type: application/json' \ -d '{ "shopName": "Blue Bottle Coffee", "recipientAddress": "0xYourReceivingAddress", "chainKey": "bsc", "webhookUrl": "https://shop.example.com/aipay/webhook" }' # => { "merchant": {...}, "apiKey": "aipay_sk_…", "webhookSecret": "aipay_whsec_…", ... } # 2) Create an order (15-minute default window, server-generated reference). curl -s -X POST "$BASE/v1/orders" \ -H "Authorization: Bearer $AIPAY_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"amount":"12.50","asset":"USDT","merchantOrderId":"INV-1042","description":"2x flat white"}' # => { "order": { "reference": "ap_…", "checkoutUrl": "https://aipay.im/en/pay?intent=…", ... } } # 3) Share order.checkoutUrl (QR / link). Poll the payer-safe status endpoint. curl -s "$BASE/v1/orders/ap_…/status" # 4) Manual confirmation from a transaction hash (optional; webhooks/cron do this). curl -s -X POST "$BASE/v1/orders/ap_…/confirm" \ -H "Authorization: Bearer $AIPAY_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"txHash":"0x…"}' ``` The checkout URL encodes the same `StaticPaymentIntent` v1 the AIPAY DApp decodes on `/pay`, so the payer lands on the normal checkout with the amount, chain, asset and recipient already filled in. --- ## 2. Authentication ``` Authorization: Bearer aipay_sk_<43 chars> ``` - Keys are generated with a CSPRNG, 43 URL-safe characters after the prefix. - Only `SHA-256(key)` is stored. The plaintext is returned exactly once, by `POST /v1/merchants`; it can never be re-read. - A wrong/revoked key is `401 unauthorized`. Treat it as "re-create the merchant" — there is no email-based recovery (there is no email account). - The webhook secret (`aipay_whsec_…`) is also shown once. It has to be stored by the service in order to sign deliveries; rotate it with `PATCH /v1/merchants/me {"rotateWebhookSecret": true}` and it is invalid immediately. Public endpoints (no key): `GET /v1/health`, `GET /v1/orders/:reference`, `GET /v1/orders/:reference/status`, `GET /v1`, `OPTIONS`. --- ## 3. Endpoints | Method | Path | Auth | Purpose | | --- | --- | --- | --- | | GET | `/v1` | – | Discovery document (endpoints, chains, confirmations) | | GET | `/v1/health` | – | Liveness + DB + notification readiness + sweep/limiter/RPC state + `usage` (free-tier budget) | | POST | `/v1/merchants` | – (IP-throttled) | Create merchant, returns API key once | | GET | `/v1/merchants/me` | key | Profile, quotas, notification readiness, key grace window | | POST | `/v1/merchants/me/keys/rotate` | key | Issue a new API key; the old one keeps a 1–72h grace window | | PATCH | `/v1/merchants/me` | key | Update shop/recipient/chain/webhook/email/Telegram | | DELETE | `/v1/merchants/me` | key | Hard delete merchant + orders + events + deliveries | | POST | `/v1/orders` | key | Create an order (`merchantOrderId` is idempotent) | | GET | `/v1/orders` | key | List orders (`status`, `limit`, `pageCursor`) | | GET | `/v1/orders/stats` | key | Daily invoice and confirmation totals by evidence | | GET | `/v1/orders/export.csv` | key | Resumable reconciliation CSV | | GET | `/v1/orders/:reference` | optional | Public receipt / merchant detail + notification status | | GET | `/v1/orders/:reference/status` | – | Tiny payer poll (reference, status, paid, expiresAt, txHash) | | POST | `/v1/orders/:reference/confirm` | key, or none for the payer | Verify a tx hash on-chain and confirm (see §3.4) | | POST | `/v1/orders/:reference/cancel` | key | Cancel a pending order (idempotent) | | GET | `/v1/channels` | key | List off-chain channels (Alipay/WeChat/UnionPay/Stripe/other) | | POST | `/v1/channels` | key | Register a channel: your own payment link + payee name | | PATCH | `/v1/channels/:channelId` | key | Edit, enable/disable (a new link revokes verification) | | DELETE | `/v1/channels/:channelId` | key | Remove a channel (historical orders keep their link) | | POST | `/v1/channels/:channelId/verify` | key | Reachability probe → `verified` / `rejected` | | POST | `/v1/orders/:reference/offchain-confirm` | key | Confirm an off-chain order with your receipt reference | | GET | `/v1/merchants/me/automation` | key | Your automation policy and what it confirmed today | | PATCH | `/v1/merchants/me/automation` | key | Write the policy (no policy = nothing is confirmed automatically) | | DELETE | `/v1/merchants/me/automation` | key | Remove the policy (back to no automation) | ### 3.1 Create merchant ```json { "shopName": "Blue Bottle Coffee", "recipientAddress": "0x…", "chainKey": "bsc", "webhookUrl": "https://shop.example.com/aipay/webhook", "telegramChatId": "123456789", "email": "ops@shop.example.com" } ``` - `shopName` 1–80 chars; `recipientAddress` must match the chain family — `0x…` (EVM), base58 (Solana) or `T…` (Tron) — and is stored lowercase); `chainKey` defaults to `ethereum`. - `webhookUrl` must be `https` (plain `http` only for loopback in non-production environments). Providing it generates the webhook secret. - Providing `email` opts into email notifications (`notifyEmail` becomes true). Omit it and nothing personal is stored. - Response: `merchant` (never contains the key or the secret), `apiKey`, `webhookSecret` (when a webhook is configured), `warnings[]` listing channels that are configured but **disabled** server-side (for example `email_provider_not_configured`). ### 3.2 Create order ```json { "amount": "12.50", "asset": "USDT", "chainKey": "bsc", "merchantOrderId": "INV-1042", "description": "2x flat white", "returnUrl": "https://shop.example.com/thanks", "ttlSeconds": 900 } ``` - `amount` is a decimal string (a JSON number is accepted). It is never truncated: more fractional digits than the asset supports is a `400`, and so is an amount whose value cannot be represented exactly by the checkout link. - `asset` / `tokenAddress` are resolved against the AIPAY token registry. Decimals always come from the registry, **never from the request**, so an unknown token is `400 unknown_asset` instead of a spoofed precision. - `chainKey` defaults to the merchant's chain. Recipient is always the merchant's own `recipientAddress`. - `ttlSeconds` 120–3600, default **900** (15 minutes). - `merchantOrderId` (≤120 chars) is unique per merchant. Repeating the same value returns the existing order with `200 {idempotent:true}` — no duplicate, no extra quota. - Response `201` includes `order.reference` (`ap_` + 20 chars), `amountBaseUnits`, `expiresAt`, `checkoutUrl`, `notifications` readiness. ### 3.3 Public receipt `GET /v1/orders/:reference` without a key returns only on-chain payment facts: ```json { "order": { "reference": "ap_…", "status": "pending", "paid": false, "chainKey": "bsc", "chainId": 56, "asset": "USDT", "tokenAddress": "0x55d398326f99059ff775485246999027b3197955", "amount": "12.5", "amountBaseUnits": "12500000000000000000", "decimals": 18, "recipient": "0x1111…", "shopName": "Blue Bottle Coffee", "createdAt": 1794037810845, "expiresAt": 1794038710845, "confirmedAt": null, "txHash": null, "explorerTxUrl": null, "checkoutUrl": "https://aipay.im/en/pay?intent=…" } } ``` It never contains the merchant id, API key, webhook URL, email or Telegram chat id. Sending a key upgrades the response to the merchant view (adds `merchantOrderId`, `checks`, `lastError`, `notifications[]` delivery states and `events[]`); another merchant's key is a `404`, never a `403` (no existence oracle). ### 3.4 Confirm `POST /v1/orders/:reference/confirm {"txHash":"0x…"}` The server (not the caller) decides: 1. `eth_getTransactionReceipt`; missing → `409 transaction_not_found`. 2. `status != 0x1` → `409 transaction_reverted`. 3. ERC-20: the receipt must contain a `Transfer` log of that token, to the order recipient, for **at least** the order amount. Native: `tx.to` must be the recipient and `tx.value` at least the amount. Otherwise `409 transaction_mismatch`. 4. Confirmations = `latest - receipt.block + 1`; below the chain's depth → `202` with `verification.confirmations` / `requiredConfirmations` and the order stays `pending` (poll again again later). 5. An automatic report settles only an open order for an exact amount. For a transfer without an on-chain order reference, the server checks whether another order could accept the transfer. This includes orders from other merchants sharing the address and asset, and orders for smaller amounts. A hold returns `409 payment_attribution_review` and records a review event without confirming the order or queuing a confirmation notification. 6. After settlement, re-confirming with the same hash returns `200 {idempotent:true}`. A different hash on a confirmed order, or a hash already used by another order, is `409 order_conflict`. **Two callers, one verification.** With `Authorization: Bearer aipay_sk_…` this is the merchant (or its watcher SDK) reporting a hash. **Without a header** it is the payer's own browser: the payment page carries the chain, token, recipient and amount, so it can watch the chain with a public RPC and report what it finds. - It is an *attestation*, not a confirmation: the server runs steps 1–5 above and still decides. A payer who lies gets a `409`, never a `confirmed` order. - The response is the payer-safe subset (`reference`, `status`, `paid`, `amount`, `amountBaseUnits`, `decimals`, `recipient`, `expiresAt`, `confirmedAt`, `txHash`, `blockNumber`, `confirmations`) plus `verification.attestedBy: "payer"` / `verifiedBy: "server"`. No shop settings, order ids, webhook targets or notification log — anyone holding a payment link can call this, and the reference is already public through `/status`. - An unknown reference is a `404` **before** any RPC call is paid for; an off-chain order is `409 channel_mismatch` (nothing on chain pays it). - Budget: the same 120/min `confirm` bucket, keyed by the credential when a key is sent and by the caller's IP when it is not (`429` + `Retry-After`). This is the only write endpoint with a budget: it is the one a loop hammers. **Reviewed late payments and overpayments.** After reconciling the transfer, submit `{"txHash":"…","reviewed":true}` with the order owner's merchant key. The merchant console sends this flag when an operator submits a hash manually. A reviewed confirmation still needs valid chain evidence and an unambiguous order. An `expired` or `cancelled` order that settles returns `verification.late: true` and `verification.previousStatus`, records `confirmed_late`, and queues the usual `order.confirmed` notification. Payer reports and existing watcher requests remain subject to the automatic rules. `reviewed:true` cannot select one order from an ambiguous group, even when all orders belong to the same merchant or there are several matching transactions. For those groups, reconcile the receipts and fulfillment in your own system. Closing a competing unpaid order does not remove it from consideration because it can still receive a late payment. Order-specific payment references or separate receiving addresses avoid this ambiguity on future orders. ### 3.5 Cancel Only a `pending` order can be cancelled; cancelling twice is idempotent and a confirmed order returns `409 order_conflict`. ### 3.6 Off-chain channels (orchestration only) AIPAY **never** calls Alipay/WeChat/UnionPay/Stripe, never stores a provider credential and never receives the money. A channel is *your* payment link plus the receipt that proves the money arrived. ```http POST /v1/channels { "channel": "alipay", "label": "Store Alipay", "payUrlTemplate": "https://…/checkout?order={reference}&amt={amount}", "payeeName": "Example Store Ltd", "settleCurrency": "CNY", "instructions": "Put the order number in the payment note." } ``` - `payUrlTemplate` must be `https` and must contain `{reference}` (`{amount}`, `{currency}` optional). Private hosts and IP literals are refused. - New channels are `pending` and **cannot be enabled**. `POST …/verify` does one bounded GET and records `verified` (`verifiedBy: "auto:reachability"`) or `rejected` — it proves reachability **only**. Confirm the payee name yourself and run one small test payment. Changing the template revokes verification. ```http POST /v1/orders { "amount": "12.50", "channelId": "ch_…" } → 201 { "order": { "channel": "alipay", "asset": "CNY", "amount": "12.5", "payUrl": "https://…/checkout?order=ap_…&amt=12.5" } } POST /v1/orders/:reference/offchain-confirm { "channelId": "ch_…", "channelRef": "2026111022001440001", "amount": "12.50" } ``` - `channelRef` (the receipt/serial) is **required**; `amount`, when sent, must cover the order. Repeating the same `channelRef` is idempotent; a **different** receipt after confirmation is `409` with `conflict: true` and a `channel_conflict` event — nothing is overwritten. - One order, one channel: a tx hash on an off-chain order is `409 channel_mismatch`, and the reverse is refused too. - Off-chain orders are **never swept for chain transfers** (`checks` stays 0). - A receipt that arrives **after expiry (or after a cancel)** confirms late — `late: true`, `previousStatus: "expired"|"cancelled"`, `confirmed_late` event. That is what makes a next-day aggregator statement usable: `POST /v1/offchain/statements` proposes the match, `adopt` confirms it, and the confirmed row keeps `confirmedSource: "statement"`. Receipts and `/status` therefore expose `channel` and `payUrl`, and the merchant view adds `channelRef`, `confirmedSource`, `confirmedBy`. `channel: "onchain"` means chain evidence; anything else is the merchant's receipt — a different level of proof, and the receipt says which. ### 3.6b Reconciliation: filtered list and CSV export For `GET /v1/orders`, omit the cursor on the first request. Pass the opaque `nextPageCursor` returned by the server as `pageCursor` on the next request, keeping the same filters. Orders are sorted by `(createdAt, reference)` descending. A null `nextPageCursor` marks the final page. Pages are live. Commit the rows and continuation together when persisting progress. Legacy `nextCursor` (number) and `cursor` still use a strict creation-time cutoff and can skip orders tied at a page boundary. Send only one cursor parameter. Restart a scan with the new cursor if a legacy checkpoint may have skipped rows. `GET /v1/orders` also accepts: | Parameter | Filters on | Notes | | --- | --- | --- | | `from`, `to` | `created_at` (epoch ms, inclusive) | "orders created that day" | | `confirmedFrom`, `confirmedTo` | `confirmed_at` (epoch ms, inclusive) | Orders AIPAY recorded as confirmed in the window; not necessarily when funds moved | `GET /v1/orders/export.csv` takes the same filters and returns a CSV body: ``` Content-Type: text/csv; charset=utf-8 Content-Disposition: attachment; filename="aipay-orders-2026-11-11.csv" X-AIPAY-Rows: X-AIPAY-Truncated: true # only when there is another page X-AIPAY-Next-Cursor: ``` Columns: `reference, merchant_order_id, status, created_at, confirmed_at, amount, asset, decimals, amount_base_units, chain_key, token_address, channel, confirmed_source, channel_ref, tx_hash, block_number, confirmations, webhook, description, asset_id, due_amount_base_units, observed_amount_base_units, confirmed_amount_base_units, amount_evidence_source, amount_evidence_regressed`. An empty amount evidence cell means unknown. - `channel="onchain"` + `tx_hash` = chain evidence (`confirmed_source="chain"`); anything else is the merchant receipt (`merchant_manual`, `merchant_webhook`, `statement`, `statement_auto`). - `webhook` reports that order's delivery state (`delivered`, `pending`, `failed`, `not_configured`, `none`) so a missed notification is visible instead of silent. - Cap `limit` at 5000 rows (default 5000). To export everything, fix the filters, leave `pageCursor` off on the first page, then pass each `X-AIPAY-Next-Cursor` as the URL-encoded `pageCursor` until absent. Keep one CSV header when combining pages. Commit the rows and cursor together; deduplicate by reference when retrying. Do not advance by timestamp alone. Pages are live and only cover retained orders; archive completed pages and reconcile changes that arrive during the export. - You can split history into UTC windows. CSV/list bounds are inclusive, so for a daily stats window `[from,to)` use `to - 1` as the creation or confirmation upper bound. Always check for continuation inside each window. - RFC 4180 quoting, and any cell a spreadsheet would run as a formula is prefixed with `'` (merchant-supplied text never executes on the accountant's machine). ### 3.6c Independent merchant daily reconciliation `GET /v1/orders/stats?from=&to=` with the merchant key returns only that merchant's orders. It uses the same [daily accounting fields](platforms.md#daily-figures-for-your-own-books) as the platform API, without needing a grant. The report has separate creation and confirmation cohorts, with UTC `[from,to)` epoch milliseconds. It distinguishes the order's amount due, the chain verifier's numeric observation, and the independently supported receipt amount. A merchant confirmation, a historical confirmation without numeric evidence, or a chain regression does not provide a confirmed amount. `collectable: false` means no custody, fees collected, or settlement by AIPAY. ### 3.7 Pricing: free usage stage The API is **free** today. A paid subscription (1 / 3 / 6 / 12 months) is planned but **not on sale and has no start date**. `/v1` and `/v1/health` both return: ```json "billing": { "status": "free", "plans": [], "startsAt": null } ``` Nothing meters usage, no card is required, and no existing key stops working. ### 3.8 Rotating an API key `POST /v1/merchants/me/keys/rotate` issues a new key and keeps the old one working for a grace window, so a running integration can roll without downtime: ```http POST /v1/merchants/me/keys/rotate { "graceHours": 24 } → 200 { "apiKey": "aipay_sk_…", // shown once, like creation "previousKeyExpiresAt": 1794298000000, "warnings": ["…"] } ``` - `graceHours` is 1–72 (default 24). `revokeOldImmediately: true` drops the old key at once — use it when the key leaked. - Any key older than the immediate predecessor is revoked by the rotation, so a second rotation shortens the first key's life rather than extending it. - `GET /v1/merchants/me` reports `previousKeyExpiresAt` so an operator can see when the grace window ends. - The server still stores only SHA-256 hashes; a lost new key means another rotation, never a retrieval. ### 3.9 The merchant's automation policy (opt-in, off by default) By default an imported statement row is a **proposal**: `POST /v1/offchain/statements` matches, and the merchant adopts each row by hand (`POST /v1/offchain/statements/:id/adopt`). A merchant who wants fewer clicks can write one policy that says which rows may confirm an order on their own, and up to what limit: ```http GET /v1/merchants/me/automation PATCH /v1/merchants/me/automation DELETE /v1/merchants/me/automation ``` All three take `Authorization: Bearer ` — the merchant's own key. ```json { "v": 1, "statementAutoAdopt": { "enabled": true, "channels": ["ch_…"], "maxPerOrder": "50", "maxPerDay": "500", "minOrderAgeSeconds": 0 } } ``` `GET` answers with the policy and what it did today: ```json { "automation": { "enabled": true, "policy": { "v": 1, "statementAutoAdopt": { … } }, "today": { "autoAdopted": 4, "autoAdoptedAmount": "180.5" }, "updatedAt": 1794037810845 } } ``` `policy` is `null` and `enabled` is `false` when nothing is stored. The `enabled` flag belongs to the view; the stored rule itself carries the channels, the two limits and the age window. What the server does with the policy: - **Off by default.** No policy row means no automation at all: the import proposes, the merchant adopts. `enabled: false` stores nothing — it is the same state as never having written a policy. A policy that cannot be read is treated as absent, never guessed at. - **The policy only adds a gate.** An automatic confirmation runs the *same* matching and the *same* confirmation as a manual adopt. A policy can stop a row from confirming itself; it can never make a weaker confirmation possible. A statement row still cannot confirm an on-chain order. - **Both ceilings are mandatory.** With `enabled: true`, `channels`, `maxPerOrder` and `maxPerDay` are required; anything missing is `400 validation_failed`. A rule without a limit is a blank cheque, not a policy. At most 8 channels, and every id must look like `ch_…`. - **The limits are amounts in the channel's settle currency** (two decimals, the same scale as an off-chain order). `maxPerOrder` caps one order; `maxPerDay` caps everything the policy has confirmed since 00:00 UTC and resets at midnight UTC. - **One settle currency per policy.** The caps are read in that currency, so a policy may only list channels that settle in the same one; a mixed-currency policy is refused with `400 validation_failed`. - **`minOrderAgeSeconds`** (0–86400, default `0`): the order must exist at least this long before a row may confirm it. `0` means no extra wait. - **One policy per merchant, not per key.** It is stored against the merchant, so rotating the API key keeps it and deleting the merchant removes it. An automatic confirmation leaves the same trail as any other one: - the order's `confirmedSource` becomes `statement_auto`; - `order_events` gets `automation_auto_adopt` with the policy reference `policy:v1|maxPerOrder=50|maxPerDay=500|minAge=0`; - `GET /v1/orders/:reference/evidence` shows both in the timeline. The import response says what the policy did with the rows: ```json { "imported": 12, "matched": 9, "confirmed": 4, "autoAdopted": 4, "autoAdoptSkipped": [ { "reason": "over_daily_cap", "count": 1 }, { "reason": "channel_not_in_policy", "count": 2 } ] } ``` `autoAdoptSkipped[].reason` is one of `automation_disabled`, `channel_not_in_policy`, `order_too_new`, `over_per_order_cap`, `over_daily_cap`, `policy_unreadable`, `order_unavailable`, `channel_currency_mismatch`, `order_already_confirmed`, `order_conflict`. The daily ceiling is not a promise the API makes afterwards: it is checked **inside the write that confirms the order**, so two imports that arrive at the same moment cannot both spend it. A row that is skipped stays a candidate — nothing is lost, it waits for you to adopt it by hand. One statement row confirms at most one order. The row is claimed before the order is confirmed and released again if the confirmation did not happen, so a receipt can never end up confirming two orders. **Who carries the risk.** A row the policy confirms is a row the merchant declared, in writing, may be confirmed on its own. AIPAY does not custody money, does not sign for the merchant, and does not check that a third-party payment channel really paid. **A statement confirmation is not chain evidence**: `statement_auto` is neither a chain verification nor a provider callback, it is the merchant's own statement row. If the statement file is wrong, the policy confirms a payment that never happened — that risk is the merchant's, and the two ceilings are the only thing limiting it. --- ## 4. Order lifecycle ``` pending ──confirm / cron ──▶ confirmed ├──── ttl elapsed ──────▶ expired └──── POST /cancel ─────▶ cancelled ``` - `pending` orders are polled by a cron on a backoff (ERC-20 `Transfer` logs for the order recipient, then receipt verification): 60 s, then 120 s, then every 240 s until the order expires. Logs are fetched once per `(chain, token, recipient)` group, not once per order. - `pending` lasts the TTL (default 15 min). The **sweep** never resurrects an expired order, but a payment that arrives late can still be confirmed with evidence: merchant `POST /confirm` with `txHash` and `reviewed:true` for an attributable chain payment, or `offchain-confirm`/`offchain/confirmations` with a receipt for a channel order. Both answer `late: true` + `previousStatus`, write a `confirmed_late` event, and leave the transition compare-and-set. Without that evidence the order stays `expired`. - `confirmed` / `expired` / `cancelled` are terminal. - Every transition writes an append-only `order_events` row (`created`, `confirmed`, `expired`, `cancelled`), visible in the merchant view. ### 4.1 How pending orders are swept (cron + in-request tick + backstop) Three layers. All of them are idempotent — `confirmPendingOrder` is a compare-and-set, and a transaction may confirm only one order — so they can run concurrently without double-confirming or double-notifying. 1. **Worker cron, every minute** (`api/wrangler.toml` → `[triggers] crons`, `CRON_ENABLED="true"`). Runs the full `runCron`: expire, verify every due pending order on each chain, retry notifications, and the daily 90-day purge. This is what makes confirmations independent of traffic. Two cost controls sit inside that sweep, both visible in `orders.checks`: - **Backoff, not a fixed tick.** Each miss stretches the next check 60 s → 120 s → 240 s (cap), so a 15-minute order costs ~5 checks instead of ~15. The price is stated: a payment nobody reports can be discovered up to **4 minutes** late. `/confirm` (payer browser or merchant watcher) is the low-latency path and does not depend on the sweep. - **Grouped logs.** ERC-20 orders that share a `(chain, token, recipient)` — i.e. one payment link — share **one** `eth_getLogs` page per sweep. Only the log fetch is shared: each order still reads its own receipt and confirmation depth, so a shared page can never share a verdict. *History:* the old note said the five Free-plan cron slots were exhausted — that was the previous account. The dedicated account has three Workers and **zero** schedules, so one one-minute trigger fits. 2. **In-request tick** (`api/src/tick.ts`). Any authenticated call, and any payer poll of `GET /v1/orders/:reference` or `/status`, may trigger a **bounded** sweep after the response (5 orders, 10 deliveries, 10 expiries), at most once per 60 s account-wide (D1 compare-and-set lock). It keeps checkout latency at about a minute and covers a delayed or disabled cron. The purge is not part of the tick. 3. **External backstop** (`POST /v1/internal/sweep`, secret-gated, returns `404` without `SWEEP_SECRET`). This repository ships `.github/workflows/api-sweep.yml` (every five minutes, best-effort GitHub schedule) and `scripts/sweep-now.sh` for any crontab/systemd timer: ```bash curl -s -X POST "$BASE/v1/internal/sweep" -H "Authorization: Bearer $SWEEP_SECRET" # => {"ok":true,"sweep":{"expired":…,"scanned":…,"confirmed":…,"deliveriesSent":…,"purged":…}} ``` `GET /v1/health.sweeper` reports what the deployment actually has: `mode` (`"cron"` or `"in-request-tick"`), `intervalMs` (how often the cron runs), `orderCheck` (`{ baseMs, maxMs }` — the backoff that actually decides when an order is re-checked), `scheduledCronConfigured` and `externalSweepEndpoint`. To prove the sweep works, create a pending order and watch `checks` in `GET /v1/orders/:reference` grow **while no client calls the API** (at 20 s, ~80 s, ~200 s, then every 4 minutes — the gaps are the backoff, not a bug). `POST /v1/orders/:reference/confirm` is always available as an immediate, server-verified confirmation path that does not depend on the sweep at all. `GET /v1/health.usage` answers "how much of the free allowance has this deployment actually used?" with counters, not vibes: ```json "usage": { "day": "2026-11-14", "today": { "orders": 412, "events": 430, "deliveries": 55, "scans": 3120, "estimatedWrites": 4017 }, "month": { "…": "same counters, month to date" }, "freeTier": { "requestsPerDay": 100000, "d1WritesPerDay": 100000, "d1ReadsPerDay": 5000000, "cronRunsPerDay": 1440, "daysElapsed": 14 }, "percentOfFreeTier": { "d1WritesToday": 4.0, "d1WritesMonth": 0.3 }, "verdict": "ok", "advice": "At 4% of the free D1 write allowance; nothing to do.", "measured": ["orders", "order_events", "deliveries", "sweep scans"], "notMeasured": ["Worker requests — read them in the Cloudflare dashboard", "D1 reads", "RPC calls — see sweeper.rpc"] } ``` Read it as: **`verdict` is the only field to act on** (`ok` / `watch` at 35% / `upgrade` at 70% of the free D1 write allowance). The counters are rolled up by the cron into one row per UTC day with a watermark, so a retried run does not double count, and the measurement is not itself a per-request D1 write. `scans` is the number of sweep passes (each one writes `orders.checks`), which is what dominates a pending order's write budget. Worker **requests** are deliberately absent: a Worker cannot see the account's usage, so the field says so instead of publishing an invented number. --- ## 5. Notifications On `order.confirmed`, `order.expired` and `order.cancelled` the service queues one delivery per configured channel. **Creation is silent** (no webhook storm for abandoned carts). A cancelled order is only announced when you cancel it, so a receiver must not treat `order.cancelled` as "the customer walked away". | Channel | Requires | Disabled reason (recorded, visible in `notifications[]`) | | --- | --- | --- | | Webhook | `webhookUrl` (+ secret) | `webhook_secret_missing` | | Email | `email` opt-in + server `EMAIL_API_KEY` | `email_provider_not_configured` | | Telegram | `telegramChatId` + server `TELEGRAM_BOT_TOKEN` | `telegram_bot_not_configured` | A disabled channel is stored as a `disabled` delivery row with the reason. The service never reports "delivered" for something it could not send. ### 5.0 Delivery ownership (three sweeps, one sender) Cron, the in-request tick and the external backstop can be in flight at the same time. A delivery is therefore **claimed** before it is sent: a compare-and-set moves the row `pending → sending` and sets a two-minute lease (`claimDelivery` in `api/src/db.ts`). Only the winner sends; the others skip the row. If a Worker dies mid-attempt the lease expires and the next sweep retries, so nothing is lost and nothing is sent twice. `sending` is internal and never appears in the merchant view (it is reported as `pending`). ### 5.1 Webhook contract ``` POST Content-Type: application/json User-Agent: AIPAY-Webhook/1.0 X-AIPAY-Signature: sha256=.")> X-AIPAY-Timestamp: X-AIPAY-Event: order.confirmed | order.expired | order.cancelled X-AIPAY-Delivery: X-AIPAY-Attempt: <1-based attempt> ``` Body: ```json { "event": "order.confirmed", "createdAt": 1794037900, "delivery": { "id": 12, "attempt": 1 }, "order": { "reference": "ap_…", "status": "confirmed", "chainKey": "bsc", "asset": "USDT", "tokenAddress": "0x55d3…", "amount": "12.5", "amountBaseUnits": "12500000000000000000", "decimals": 18, "recipient": "0x1111…", "merchantOrderId": "INV-1042", "description": "2x flat white", "createdAt": 1794037810845, "expiresAt": 1794038710845, "confirmedAt": 1794037900000, "txHash": "0x…", "blockNumber": 61234567, "confirmations": 15 }, "merchant": { "shopName": "Blue Bottle Coffee" } } ``` Verify the signature over the **raw body** (do not re-serialise the JSON): ```js // Node import { createHmac, timingSafeEqual } from 'node:crypto'; const ts = req.headers['x-aipay-timestamp']; const expected = 'sha256=' + createHmac('sha256', process.env.AIPAY_WEBHOOK_SECRET) .update(`${ts}.${rawBody}`).digest('hex'); if (!timingSafeEqual(Buffer.from(expected), Buffer.from(req.headers['x-aipay-signature']))) { return res.status(401).end(); } ``` ```python # Python import hmac, hashlib expected = 'sha256=' + hmac.new(secret.encode(), f"{ts}.{raw_body}".encode(), hashlib.sha256).hexdigest() ok = hmac.compare_digest(expected, request.headers['X-AIPAY-Signature']) ``` Reject timestamps older than a few minutes to blunt replay, and make your handler idempotent on `X-AIPAY-Delivery` (retries **and** an operator-triggered replay reuse the same id — a replay is the same logical notification, not a new one). Deliveries for the same order are attempted in creation order: a later event does not overtake an earlier one that is still pending, so a ledger never sees `order.expired` before `order.confirmed`. Once an event gives up (below), it stops blocking its order's later events — the gap is visible from the delivery ids. Retry schedule after a failure: **1m, 5m, 30m, 2h, 6h** (5 retries, 6 sends max). `2xx` = delivered. `429`/`408`/`5xx`/network errors are retried; other `4xx` fail immediately. Retries reuse the same body and signature inputs, so a handler that rejects a body once will reject it every time. **One delivery per row, and a way to resend it.** `GET /v1/orders/:reference` (merchant view) lists `notifications[]` with the delivery `status`, `attempts`, `lastError` and its `deliveryId`. If the endpoint was down for longer than the retry window (about 9 hours), the delivery is `failed` and nothing will retry it — resend it explicitly: ```http POST /v1/orders/ap_…/notifications/42/replay (merchant key) → 200 { "replayed": true, "delivery": { "deliveryId": 42, "channel": "webhook", "target": "https://…", "status": "sent", "attempts": 1, "lastError": null, "nextAttemptAt": null }, "notifications": [ … ] } ``` The replay keeps the delivery id (dedupe on it), restarts the attempt counter, and is written to `order_events` as `notification_replayed` — including a replay that failed again, so the timeline never claims more than happened. `status` is the honest outcome of *that* attempt: `sent`, `pending` (retryable, rescheduled on the normal backoff) or `failed` (the receiver refused it permanently). A merchant delivery that gave up stays `failed`; replay it one at a time from the order view (there is no bulk replay for merchants — their deliveries include old webhook URLs and other channels, so a blind batch would be a way to leak data to a destination the merchant has already moved on from). Platforms get `POST /v1/platform/deliveries/replay-failed` because one endpoint is unambiguous for them. Refusals: `404 not_found` (unknown delivery / another merchant's order), `409 delivery_in_flight` (a sweep holds the lease — retry in a minute), and `409 channel_not_configured` (the channel has no usable credential; the `reason` is the one recorded at enqueue time). Replays are budgeted at 10 per minute — each one is an outbound request in our name. --- ## 6. Errors Every failure is `{"error":{"code":"…","message":"…","details":{…}}}`. | HTTP | code | Meaning | | --- | --- | --- | | 400 | `validation_failed` | Missing/invalid field (amount, address, ttl, email…) | | 400 | `invalid_json` | Body is not a JSON object | | 400 | `unsupported_chain` | Chain has no server-side verifier yet (MSGChain, testnets) | | 400 | `unknown_asset` | Token/asset not in the AIPAY registry for that chain | | 401 | `unauthorized` | Missing/invalid API key | | 404 | `not_found` | Unknown reference / not owned by this merchant | | 405 | `method_not_allowed` | Wrong verb for the path | | 409 | `order_not_pending` | Terminal order cannot be confirmed/cancelled | | 409 | `merchant_exists` | Same shopName + recipientAddress already exists (retry costs no quota) | | 404 | `channel_not_found` | Unknown off-chain channel for this merchant | | 409 | `channel_not_verified` | Channel is not verified/enabled yet | | 409 | `channel_mismatch` | Wrong channel for this order (chain hash vs receipt) | | 409 | `channel_exists` | Same channel kind + label already registered | | 409 | `delivery_in_flight` | A sweep holds this delivery's lease; retry the replay in a minute | | 409 | `channel_not_configured` | Replaying a `disabled` delivery: the channel has no credential | | 400 | `receipt_amount_too_low` | Receipt covers less than the order amount | | 409 | `order_conflict` | Already confirmed by another tx / tx reused / cancel after pay | | 409 | `transaction_not_found` | RPC does not know the tx yet | | 409 | `transaction_reverted` | Tx reverted (paid nothing) | | 409 | `transaction_mismatch` | Wrong recipient, wrong token or underpayment | | 413 | `payload_too_large` | Body over 16 KiB | | 429 | `rate_limited` | Per-merchant daily order quota or per-IP signup quota | | 500 | `internal_error` | Unexpected failure (retry, then report) | | 503 | `db_unavailable` | D1 temporarily unavailable | | 503 | `rpc_unavailable` | No RPC node answered; retry later | `202` is not an error: it means "payment seen, not deep enough yet" (`verification.confirmations` vs `requiredConfirmations`). --- ## 6a. Evidence bundle (one response for finance/audit) `GET /v1/orders/:reference/evidence` returns everything the service knows about one order in a single read-only payload, so a finance team does not have to assemble it from a receipt, a webhook log and a database export: - `order` — the same shape as the merchant order view; - `evidence` — the trust level (`chain` only when the server re-read a transaction, otherwise `merchant_receipt`), `confirmedSource`, the transaction (hash, block, confirmations vs the chain's required depth, explorer URL), asset, amount, recipient, channel/receipt details, and what the verifier last saw (`checks`); - `timeline` — the append-only `order_events` rows; - `notifications` — one entry per delivery attempt with its state; - `notes` — plain-language statements of what the payload does and does not prove. It requires the merchant key that owns the order (another key answers `404`) and never mutates anything. An off-chain order reports `level: "merchant_receipt"`: the money never passed through AIPAY. ## 6b. Commission (configured, not charged) AIPAY charges nothing today (`GET /v1` → `fees.aipayCommission: 0`). A merchant rate can be **recorded** as a commercial term, but it is not deducted from any payment and the API says so in the same breath: ```json "fees": { "feeBps": 50, "source": "merchant", "collectable": false, "note": "A rate is configured but not charged: direct on-chain transfers go straight to your address." } ``` Why: settlement is non-custodial, so a percentage can only be taken by a contract that splits the transfer (the MSGChain payment contract, switched off) or by an invoice the merchant pays separately. Nothing else can collect it, so nothing pretends to. - rate is operator-set (`POST|GET|DELETE /v1/internal/fees`, `{merchantId, feeBps}`), capped at **5 % (500 bps)**, absent row = zero; - `GET /v1/merchants/me` reports it with `source` (`default` | `merchant`) and `collectable: false`; - configuring a rate never changes an order amount, a quote, or the amount the payer is asked for — matching and confirmation still use the full amount. ## 6c. Merchant-side watcher (opt-in, for latency and scale) A merchant can take its own pending orders out of our sweep: ```http PATCH /v1/merchants/me { "watcher": true } ``` From then on the cron **skips this merchant's pending orders**. The merchant (or its SDK) scans only its own receiving address with its own RPC quota, and hands us the transaction hash: ```http POST /v1/orders/:reference/confirm { "txHash": "0x…" } ``` The server still re-reads the receipt, the transfer, the recipient, the amount and the confirmation depth — a watcher can only make discovery faster, never declare a payment. `/confirm` is the one write endpoint with a budget (120/min per credential), so an SDK loop cannot become an amplifier. Why this exists: our sweep costs one log query per (chain, token, recipient) **group** per pass, and each pending order costs one `orders.checks` write every 60–240 s. Watching on the merchant side still moves that cost to the party that already polls its own chain, and keeps the slower central sweep as the fallback for merchants that do not opt in. **The merchant console does it too, with no install.** While the orders or dashboard page is open, the browser watches this merchant's pending **cloud** (`ap_…`) orders with its own RPC quota — one `eth_getLogs` per pending order per tick, nothing sent to us — and reports a discovered hash to `POST /v1/orders/:reference/confirm` with the stored key. One report per order: a `200` or a `202` both mean "the server has it", a `409` means the hash is not this order's, and a `429` pauses reporting for a minute so the browser cannot amplify its own budget. The order list itself is re-read once a minute (the list budget is 60/min), and off-chain channels, Solana, Tron and native coins are never watched from the browser — those are the server's job, and pretending otherwise would be a lie about what the browser can see. The payer's browser does the same thing without an account: for EVM orders the checkout page runs `eth_getLogs` itself, reports the candidate hash once, and drops its `/status` poll to one heartbeat per minute. For Solana it looks up the order's own **reference account** — the key the checkout link derives from `ap_…` (see §9.1) — which answers "what paid this order" in one call instead of scanning the merchant's history; Tron (indexed differently) stays on the server sweep. Either way, the confirmation is the server's. ## 7. Limits | Limit | Value | | --- | --- | | Orders per merchant per UTC day | 500 | | Merchant signups per IP per UTC day | 50 | | Request body | 16 KiB | | Page size (`limit`) | 1–100, default 50 | | Order TTL | 120–3600 s, default 900 | | Reads: payer status / receipt | 120 per minute **per order** | | Reads: order list / statements | 60 / 30 per minute | | Reads: CSV export | 10 per minute | | Ceiling per address (anonymous payer routes) | 600 per minute (`confirm`: 360) | | Webhook replay | 10 per minute | Read budgets are per credential, and **per order** for the payer routes (`/status`, `/receipt`, `/confirm`) when no key is sent: every tab, device and dashboard watching one order shares that order's budget, and the address is a ceiling rather than the unit. A shared egress address — CGNAT, a campus, an office, a café — is many unrelated payers, so counting them as one client made a busy network look like a scraper and refused the *checkout* page. The ceiling is counted once every four requests (a ceiling is coarse; a D1 write per request is not) and a refusal is remembered per Worker, so the uncounted requests see it too. All of it is counted in a shared table, so a burst spread over many Workers still adds up to one limit. A client that is already refused is refused again without another write (one cheap read still notices an operator change mid-window). Exceeding a budget answers `429 rate_limited` with `details.bucket`, `details.limit`, `details.retryAfterSeconds`, `details.scope` (`order`, `caller` or `credential`) and a `Retry-After` header. The live numbers are published in `GET /v1` under `polling.limits` and `polling.payerLimits`. If a platform legitimately needs more (a per-second poll, say), the operator can raise **one credential** without touching anyone else: ```http POST /v1/internal/read-limits (operator secret, not a merchant key) { "apiKey": "aipay_sk_…", "multiplier": 5, "note": "platform polls every second" } → { "keyHash": "…", "multiplier": 5, "maxMultiplier": 20 } GET /v1/internal/read-limits # list overrides (hashed keys only) DELETE /v1/internal/read-limits # { "keyHash": "…" } to clear ``` The multiplier is capped at 20x, so "raise it" can never mean "off", and it is keyed by the hashed credential — no secret is stored or returned. Deployment-wide ceilings can also be set with `READ_LIMIT_STATUS`, `READ_LIMIT_LIST`, `READ_LIMIT_STATUSCALLER`, … in the Worker `[vars]`. Discovery (`GET /v1`), health and every write are never limited: a limiter must not stand between a merchant and a payment. Quotas return `429 rate_limited` with the limit in `details`. There is no paid tier to raise them; ask the operator. `POST /v1/merchants` also **deduplicates**: creating the same `shopName` at the same `recipientAddress` twice answers `409 merchant_exists` (with the existing `merchantId`) instead of minting a second merchant — one shop, one ledger — and a retry does not consume the daily signup quota. The API key is returned only once, so a lost key is rotated with `POST /v1/merchants/me/keys/rotate` using the old key, not by re-signing up. --- ## 8. Privacy, retention, security **Stored:** merchant id, shop name, receiving address, default chain, webhook URL + secret, Telegram chat id, email (only if opted in), hashed API key, order facts that are already public on-chain (chain, asset, amount, recipient, reference, tx hash), delivery status. The client IP is stored **hashed** and only as a per-day signup counter. **Not stored:** private keys, seed phrases, card data, names, phone numbers, customer identity, cookies, analytics. **Retention:** `confirmed` / `expired` / `cancelled` orders (with their events and deliveries) are purged **90 days** after creation by a daily sweep. `pending` orders are bounded by their TTL and then expire on the next cron tick. `DELETE /v1/merchants/me` hard-deletes the merchant and all dependent rows immediately. **Transport:** CORS is allow-listed to `https://aipay.im`, `https://www.aipay.im` and localhost dev origins. CORS is not authentication; server-to-server calls need no Origin. Responses are `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`. **Keys:** API keys are only stored as SHA-256; webhook secrets must be stored (they sign deliveries) and are returned only at creation/rotation. --- ## 9. Supported chains and confirmation depth | chainKey | Chain | ID | Native | Confirmations used | | --- | --- | --- | --- | --- | | `ethereum` | Ethereum | 1 | ETH | registry value | | `bsc` | BNB Chain | 56 | BNB | **15** | | `polygon` | Polygon | 137 | POL | registry value | | `arbitrum` | Arbitrum One | 42161 | ETH | registry value | | `optimism` | OP Mainnet | 10 | ETH | registry value | | `avalanche` | Avalanche C-Chain | 43114 | AVAX | registry value | | `base` | Base | 8453 | ETH | registry value | | `xlayer` | X Layer (OKX) | 196 | OKB | **10** | | `solana` | Solana | `solana-mainnet` | SOL | **1** (see below) | | `tron` | Tron | `tron-mainnet` | TRX | **19** (see below) | Confirmations come from the same registry the DApp uses (`src/lib/chains/registry.ts` → `finalityConfirmations`); the worker imports it directly, and a test fails if the two ever diverge. Use `GET /v1` for the live table. Tokens per chain come from `src/lib/tokens.ts` (for BSC: BNB, USDT, USDC, BUSD — note BSC USDT/USDC are **18 decimals**). Unlisted tokens are rejected rather than trusted. Solana mints are base58 and case-sensitive, so the resolved `tokenAddress` keeps the registry's canonical spelling (USDC `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`, 6 decimals). ### 9.1 How a Solana payment is verified `POST /v1/orders/:reference/confirm { "txHash": "" }` — the only path, because Solana has no log filter that answers "what was paid to this address": 1. **Reference attribution.** Every order has its own Solana Pay reference: the checkout link carries `solana:?amount=…&spl-token=…&reference=`, and the key is *derived* from the order reference (`sha256`-backed, reproducible by the server, the browser and any wallet) instead of being a random value stored in the database. A transaction whose account keys name **another** order's derived reference is `transaction_mismatch` even when the amount matches — that is what keeps two pending orders for the same amount apart. A transaction with no reference at all still matches by amount (a payer may have copied the address instead of scanning the QR). 2. `getTransaction(sig, { encoding: "jsonParsed" })` — a missing transaction is `transaction_not_found` (never a confirmation), `meta.err` is `transaction_reverted`. 3. **SPL:** sum the positive pre/post balance deltas of every token account whose `mint` is the order's mint **and whose `owner` is the merchant**. A fresh associated token account starts at zero. Paying the merchant's ATA is therefore enough; paying a different owner's ATA is not. **Native SOL:** sum the positive lamport deltas of the merchant's account key. 4. A delta below `amountBaseUnits` is `transaction_mismatch` — there is no partial credit and no overpayment accounting beyond "at least this much". 5. `getSignatureStatuses(sig)` supplies the depth: `processed` is not enough, `confirmed` counts, `finalized` is deep. `slot` becomes the order's `blockNumber`. A pending Solana order **is** swept, in two passes. First the order's own reference account: `getSignaturesForAddress(reference)` (4 newest) → one `getTransaction` — a hit is this order's payment by construction, and it costs one request. Only when that returns nothing does the legacy pass run: `getTokenAccountsByOwner(merchant, mint)` (native SOL uses the merchant address itself) → `getSignaturesForAddress` on each account (8 newest) → `getTransaction` for at most 3 candidates newer than the order, with the reference rule above applied. The amount and depth rules are reused unchanged, so the sweep cannot confirm anything `POST /confirm` would reject. A capped or empty pass stays `pending`, and an RPC failure records a retry instead of clearing the order. `GET /v1` reports this per chain as `"sweep":"signature-scan"`; the order's confirmed event records which pass found it (`source: "reference"` or `"signature-scan"`). ### 9.2 How a Tron payment is verified Tron addresses are base58 with a `0x41` version byte (34 characters, starting with `T`), not EVM hex; the service verifies the checksum on every merchant and order address. USDT TRC20 is `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` (6 decimals), and TRX itself is 6 decimals. `POST /v1/orders/:reference/confirm { "txHash": "<64-hex transaction id>" }`, or the sweep: 1. `wallet/gettransactioninfobyid` — a missing transaction is `transaction_not_found`; `receipt.result !== "SUCCESS"` is `transaction_reverted` (`REVERT`, `OUT_OF_ENERGY`, …). 2. **TRC20:** the `Transfer` log whose `address` is the order's contract, `topics[2]` is the merchant and `data` is the amount. A transfer of another token in the same transaction does not count, and a short amount is `transaction_mismatch` (no partial credit). 3. **TRX:** `wallet/gettransactionbyid` → `TransferContract` with `to_address` = the merchant and `amount` at least the order amount. 4. Depth is `head - blockNumber + 1 >= 19` — Tron's 27 super representatives need **19** blocks (2/3 + 1) to make a block irreversible, about 57 seconds at ~3s blocks. Younger transactions answer `202 insufficient_confirmations`. The sweep reads TronGrid's `/v1/accounts/:address/transactions/trc20` (and `/transactions` for TRX) to find candidates newer than the order, then runs the same checks; `GET /v1` reports `"sweep":"transfer-logs"`. TronGrid is keyless here and rate limited, so a failed read records a retry and never clears the order. Sending, for wallets: a TRC20 transfer is built by the node (`wallet/triggersmartcontract`), signed locally over its 32-byte `txID`, and broadcast. **The sender must hold TRX** for bandwidth/energy — USDT alone cannot move. --- ## 10. Honest limitations (v1) - **MSGChain is not verifiable.** MSG orders are rejected with `unsupported_chain` until mainnet parameters exist. - **Native coins need a transaction hash.** There is no ERC-20 log to scan for BNB/ETH/POL, so those orders stay `pending` (with `lastError=awaiting_manual_tx_hash:…`) and are confirmed through `POST /confirm`. Solana is discovered by the sweep; `POST /confirm` stays available for a node that has not indexed the signature yet. - **One recipient per merchant.** Per-order addresses are not supported. - **Reorgs are recorded, not reversed.** A confirmed EVM order is re-read once 30 min – 6 h later; `order_events` gets `confirmation_regressed` and `last_error` explains it, but the status stays `confirmed` and no webhook is sent. Solana and Tron are not re-read. - **No refunds, no partial payments, no overpayment credit.** An overpayment confirms the order; the difference is not tracked. - **No rate/price conversion.** Amount is in the asset you name. - **Dashboard UI is opt-in.** Merchant → Settings → Cloud orders creates or connects a merchant, and the order page merges local + cloud orders. Nothing is uploaded until an API key is stored there. - **`api.aipay.im` is live** (custom domain on the Worker); the `workers.dev` host still answers and is only useful for smoke tests. - **Sweep latency is about a minute**, and it does not depend on traffic when the Worker cron is scheduled (`GET /v1/health.sweeper` reports `mode`). Use `/confirm` when you need a payment reflected sooner than that. - **No MSG / no on-chain fee split.** MSG stays disabled; this service contains no commission logic. --- ## 10a. Platform order access An operator provisions a platform and delivers its dedicated `aipay_pk_…` key once. The merchant keeps its own `aipay_sk_…` key and explicitly authorizes the platform using `POST /v1/merchants/me/platforms` with `{"platformId":"plt_example1"}`. Use `GET /v1/merchants/me/platforms` to review grants and `DELETE /v1/merchants/me/platforms/plt_example1` to revoke one. The same list/grant/revoke calls are available in the merchant console (**Settings → Platform access**) for merchants who do not want to call the API by hand. The platform runs on its own key and does not need the operator for routine work: - `GET /v1/platform/merchants` lists the merchants that granted it (`merchantId`, `shopName`, `grantedAt`, `revokedAt`), keyset-paginated by `after`. Active grants only; `includeRevoked=1` returns revoked rows too, so a platform can reconcile its own copy with the full history. A revoked grant is a fact, not a deletion. - `POST /v1/platform/keys/rotate` rotates the platform's own key. The response carries the new `aipay_pk_…` exactly once and the previous key stops working **immediately** — there is no grace window, because a second live key would silently widen the read scope after a leak. Persist the new key before the next request; a lost response is recovered by the operator, never by retrying with the old key. - `GET /v1/platform/usage` returns the platform's own budget for the current window (`limit`, `used`, `remaining`, `windowSeconds`, `resetsAt`) for reads and exports, plus `grants: { active, revoked }`. The snapshot includes the request that asked for it, and `used` is `null` (not zero) when the shared counter cannot be read. `ingressPerMinute` is the per-address ceiling in front of the budget; an operator can raise the per-platform budget with `keyHash: "platform:"` (immediately, no restart). The platform calls `GET /v1/platform/orders` with its own bearer key. Optional `merchantId` and `status` filters apply only within the granted scope. Both list endpoints accept `limit` (default 50, maximum 100). The platform list returns `nextCursor` (null at the end). For the merchant list, use `nextPageCursor`. On `429`, honor `Retry-After`. Pages are live, not snapshots. Grants cover retained and future cloud orders. The platform sees order and merchant IDs, references, shop name, amounts and asset details, status, timestamps, recipient and confirmation metadata. `confirmedSource: chain` represents recorded chain verification; off-chain sources are merchant receipts. Revocation stops new aggregate reads but cannot recall downloaded data or invalidate public receipt references that the platform already obtained. Those public receipts may include a description or an off-chain payment link. The platform's own operating manual — grant model, change feed, webhook verifier, budgets and the limits — is [platforms.md](platforms.md). `GET /v1/platform/orders/{reference}` returns a single order in the same read-only scope. Unknown and unauthorized references both return `404`. Start incremental synchronization with `GET /v1/platform/orders/changes?limit=100`. Apply each returned order by `reference`, then persist `epoch` and `nextAfter` together. Pass them as `epoch` and `after` on the next request. Continue while `hasMore` is true, then poll using the last checkpoint. The feed can coalesce multiple updates to the same order. `amount` and `amountBaseUnits` are the requested order amount. A `confirmationRegressed` flag reports a recorded verification anomaly separately from the order status. Every platform order response (list, detail and changes) also carries `anomalies` — `[{ "code": …, "detectedAt": … }]` — plus one order-level `action`. Read it instead of reconstructing a story from the status: | code | what happened | action | | --- | --- | --- | | `late_payment` | paid and confirmed after the order expired or was cancelled | `none` — the books are right | | `unapplied_payment` | a transfer was seen on a closed order and never booked | `review` | | `duplicate_payment` | the transfer matching this order was already claimed by another order | `review` | | `payment_attribution_review` | the server verified payment evidence but held settlement for attribution, amount, or order-state review | `review` | | `duplicate_receipt` | a conflicting off-chain receipt on an already confirmed order | `review` | | `unapplied_receipt` | a receipt arrived for an order in a non-payable status | `review` | | `confirmation_regressed` | a later chain re-read disagreed with the recorded confirmation | `review` | `action` is `review` if any signal requires reconciliation, and `none` otherwise. `refund_from_merchant_wallet` is reserved for API compatibility. An anomaly does not establish a separate refundable payment. Verify actual receipt, amount and order attribution before acting. AIPAY never executes refunds and `collectable` stays `false`. `detectedAt` is epoch milliseconds, or `null` when the signal itself carries no timestamp. Raw event details — RPC errors, receipt references — are not exposed. On `409 platform_sync_reset`, discard the checkpoint and rebuild the platform's authorized dataset from the beginning. Reconcile periodically against the current order list to remove deleted or expired-retention records and refresh shop names. The feed tracks order revisions and does not emit deletion records. ### Platform webhooks `POST /v1/platform/webhook {"url":"https://…"}` registers the platform's endpoint and returns a signing secret **once**; posting again rotates it. `GET /v1/platform/webhook` reports the URL, whether a secret is set, the last success/failure and the event list. `DELETE` removes it. HTTPS is required in production. Events, payload, signature and retry schedule are identical to merchant webhooks, so one verifier covers both: `sha256=HMAC-SHA256(secret, ".")`, headers `X-AIPAY-Signature|Timestamp|Event|Delivery|Attempt`, retries after 1m/5m/30m/2h/6h and a give-up after six sends. One delivery row exists per `(platform, order, event)`, so a retried confirmation cannot send a second copy. Authorization is re-read at send time. If the merchant revoked the grant (or the endpoint was removed) after the event was queued, the delivery is recorded as `disabled` with `grant_revoked` / `webhook_not_configured` and no order data leaves AIPAY. `GET /v1/platform/deliveries?status=&reference=&limit=&before=` is the log; `POST /v1/platform/deliveries/{id}/replay` resends one delivery now (`409 delivery_in_flight` while a sweep holds the lease). ### Reconciliation export `GET /v1/platform/orders/export.csv` returns the same authorized rows as the order list, oldest first, with `status`, `merchantId`, `from`/`to` (created) and `confirmedFrom`/`confirmedTo` filters. Up to 5000 rows; `X-AIPAY-Rows` reports the count and `X-AIPAY-Truncated: true` says more rows exist. Columns: reference, merchant_id, shop_name, merchant_order_id, status, created_at, confirmed_at, expires_at, amount, asset, amount_base_units, decimals, chain_key, token_address, channel, confirmed_source, confirmation_regressed, tx_hash, block_number, confirmations, recipient, collectable, anomalies, action. `anomalies` is a semicolon-separated list of codes and `action` matches the order API. `collectable` stays `false`: AIPAY does not hold or take the money. Platform keys cannot manage orders, authorize other platforms, or move money. Funding still goes directly to the merchant; `collectable` is false and access does not depend on MSG. ## 11. Run it yourself ```bash # Local worker + local D1 (no Cloudflare account needed) npx wrangler d1 execute aipay-api --local --file api/schema.sql --config api/wrangler.toml npx wrangler dev --local --config api/wrangler.toml --port 8788 # Copy-paste clients (no dependencies) + their self-checks node --test examples/merchant-node/aipay.test.mjs python3 examples/merchant-python/selfcheck.py # Unit + integration tests (real handlers, real SQLite, fake chain/webhook) npx playwright test --config tests/playwright.unit.config.ts merchant-service.spec.ts # Deployed smoke (creates and deletes a throwaway merchant) node scripts/api-smoke.mjs --base https://api.aipay.im # Full sweep on demand (only when SWEEP_SECRET is configured) curl -s -X POST https://api.aipay.im/v1/internal/sweep \ -H "Authorization: Bearer $SWEEP_SECRET" ``` Deployment, schema migration and the custom-domain step: [api-deploy-runbook.md](api-deploy-runbook.md). ## 12. Where this fits Start at the [gateway integration guide](integration.md) if you are wiring AIPAY into someone else's platform, and at [../llms.txt](../llms.txt) for the whole surface in one file (wallet, merchant, agent and every fail-closed feature with the config that gates it). --- # You are a platform This page is for a **platform**: a mall, a shop aggregator, a reseller console, or an agency that operates many merchants and wants one integration instead of one per shop. A platform reads order records; it never touches the money, because the money never passes through AIPAY. Machine-readable entry points: [../llms.txt](../llms.txt), [../agent.json](../agent.json), [../openapi.json](../openapi.json). Read [integration.md](integration.md) first if you are the shop itself, and [merchant-order-service.md](merchant-order-service.md) §10a for the exact field list. This page is the platform's own operating manual. ## What the model is 1. **AIPAY provisions the platform** and hands it one key, `aipay_pk_…`, plus a `platformId` (`plt_…`). The platform key is **read-only** — it cannot create an order, authorize another platform, or move funds. 2. **Each merchant opts in.** The merchant keeps its own `aipay_sk_…` key and authorizes your `platformId` in the console (**Settings → Platform access**) or with `POST /v1/merchants/me/platforms`. Authorizing does not notify you and needs no action from your side. 3. **You read what was granted.** Orders, amounts, status, confirmation evidence and structured anomalies, across every merchant that granted you. Revocation stops future reads; it cannot recall what you already downloaded. Funding always goes straight to the merchant's own wallet. `collectable` is `false` in every response, and no endpoint can pay out. ## Five-minute flow ```bash export PLATFORM_KEY=aipay_pk_… # from AIPAY, once BASE=https://api.aipay.im # Who granted me? (active grants; includeRevoked=1 for the full history) curl -s "$BASE/v1/platform/merchants" -H "Authorization: Bearer $PLATFORM_KEY" # Their orders (also: /orders/{reference}, /orders/changes, /orders/export.csv) curl -s "$BASE/v1/platform/orders?limit=50" -H "Authorization: Bearer $PLATFORM_KEY" # My own budget for this minute, plus grant counts curl -s "$BASE/v1/platform/usage" -H "Authorization: Bearer $PLATFORM_KEY" ``` Every order carries `status`, `confirmedAt`, `txHash`, `confirmations`, `confirmedSource` (`chain` = recorded chain verification, anything else = a merchant receipt) and `anomalies`, so you do not have to reconstruct "did the money really arrive?" from a timestamp. ## Synchronize instead of polling everything `GET /v1/platform/orders` is a keyset page over a live list — fine for a dashboard, wasteful for a ledger. For continuous sync use the change feed: ```text GET /v1/platform/orders/changes?epoch=&after=&limit=100 → { changes: [...], epoch, nextAfter, hasMore, collectable: false } ``` - Apply each change by `reference` (upsert, not insert — the feed coalesces repeated updates to the same order). - Persist `epoch` **and** `nextAfter` together, then continue while `hasMore`. - `409 platform_sync_reset` means the merchant authorization set changed (a grant or revoke, possibly not yours). Drop the checkpoint and rebuild from the beginning; never reuse the old `epoch`. - The feed emits revisions, not deletions. Reconcile periodically against the order list (or the CSV) to drop orders that aged out of the 90-day retention. Push instead of pull with a signed webhook: ```bash curl -s -X POST "$BASE/v1/platform/webhook" -H "Authorization: Bearer $PLATFORM_KEY" \ -H 'content-type: application/json' -d '{"url":"https://platform.example/aipay"}' # → { webhook: {…}, secret: "aipay_whsec_…" } — shown once; posting again rotates it ``` Events are `order.confirmed`, `order.expired`, `order.cancelled`. The signature, retry schedule and payload are **identical to merchant webhooks**, so one verifier covers both: `sha256=HMAC-SHA256(secret, ".")`, verify over the raw body. Delivery is at least once: persist `X-AIPAY-Delivery` to deduplicate retries. If delivery is delayed, verify the current order through its detail endpoint before acting. `GET /v1/platform/deliveries` is the log; `POST /v1/platform/deliveries/{id}/replay` re-sends one (budgeted, 10/min). Authorization is re-read at send time, so a revoked grant turns queued deliveries into `disabled` instead of leaking an order. ## Onboarding merchants at scale (invite and claim) A platform does not create merchants — it **invites** them. That is the one boundary that keeps AIPAY non-custodial: a merchant key can change the payout address, so the platform must never hold one. ```bash # 1) the platform mints a one-time token (shown once, default 7 days, max 30) curl -s -X POST "$BASE/v1/platform/merchants/invites" -H "Authorization: Bearer $PLATFORM_KEY" \ -H 'content-type: application/json' -d '{"shopName":"Corner Shop","note":"mall #12"}' # -> { invite: { inviteId, shopName, status: "pending", expiresAt }, token: "aipay_inv_…", claim: {…} } # 2) hand the token to the merchant. The merchant claims it with its OWN address: curl -s -X POST "$BASE/v1/merchants/claim" -H 'content-type: application/json' \ -d '{"token":"aipay_inv_…","recipientAddress":"0x…","chainKey":"bsc"}' # -> { merchant, apiKey, platform: { platformId, inviteId, granted: true }, warnings } ``` - The claim creates the merchant, its API key (returned **to the merchant**, once) and the platform grant in one transaction. Only the merchant receives the key. The grant lets the platform read the receiving address on accessible orders. - Tokens are stored hashed, are single use (`409 invite_already_claimed`), and expire (`409 invite_expired`). An unclaimed invite can be revoked (`DELETE /v1/platform/merchants/invites/{id}`); a claimed one cannot — revoke the grant instead. - `GET /v1/platform/merchants/invites?status=pending|claimed|revoked|expired` is the reconciliation list (`before` keyset, newest first). - A failed transaction leaves the invite available. After a successful claim, the token stays consumed even if the merchant is deleted. If the success response is lost and the key was never saved, contact the platform. - Per-IP signup limits still apply, and the merchant can revoke the platform's read access at any time in the console. ### Delivery order and dead letters Deliveries for the **same order** are attempted in creation order: a later event never overtakes an earlier one that is still pending. That is deliberate — a balance-driven ledger must not see `order.expired` before `order.confirmed`. - Ordering is per `(platform, order)`, not global. Two different orders are delivered in parallel. - A delivery that keeps failing is retried on 1m/5m/30m/2h/6h, then marked `failed` (6 attempts, ~9 hours). Once dead-lettered it **stops blocking** later events for that order — holding them forever would be worse than a gap you can see from the delivery ids. - `GET /v1/platform/deliveries?status=failed` is the dead-letter list. `POST /v1/platform/deliveries/replay-failed {"limit":10}` re-queues the oldest page (maximum 25 per call) and reports `remainingFailed`; the sender picks them up in the next sweep, so ordering is preserved and nothing is sent inside the request. Each delivery keeps its id, so dedupe on `X-AIPAY-Delivery`. - A manual `POST /v1/platform/deliveries/{id}/replay` is out of band by design: it can reorder one delivery, and the id tells your consumer which one it is. ## Daily figures for your own books `GET /v1/platform/stats?from=&to=&merchantId=` reports UTC windows `[from,to)` in epoch milliseconds. The default is the last seven days. The maximum is 92 days and requests spend the export budget. `GET /v1/orders/stats` gives an independent merchant the same figures using their merchant key. - `created` counts orders by creation day and their current status. `amounts` sums their invoice amounts by asset, including pending and expired orders. `amountBaseUnits` is the legacy alias for `dueAmountBaseUnits`. - `confirmed` counts currently confirmed orders by confirmation day. `confirmedAmounts` groups those orders by UTC day, asset identity, decimals, `confirmedSource`, `amountEvidenceSource` and the regression flag. An order created yesterday and confirmed today contributes to different days. - Group by `assetId` and `decimals`. On-chain IDs use `onchain::` or `onchain::native`. Off-chain currencies use `offchain:`. Symbols are display labels. Sum integer strings with arbitrary precision within a group. - `dueAmountBaseUnits` is the invoice total. `observedAmountBaseUnits` records the numeric observation the chain verifier used. Token transfer logs and Solana balance deltas stay in the observed column. `confirmedAmountBaseUnits` contains independently verified native receipt amounts for supported EVM and Tron transactions where transaction identity and payer can be checked. Off-chain merchant receipts and legacy confirmations have unknown numeric evidence. A recorded chain regression preserves the historical observation and clears the confirmed amount. `observedAmountOrders`, `verifiedAmountOrders` and `unknownConfirmedAmountOrders` show coverage. A null amount indicates unknown evidence. - Each amount cohort has an independent 5,000-order limit. The corresponding amount array is `null` when `amountsTruncated` or `confirmedAmountsTruncated` is true. Counts still cover the window. For a complete export, use the procedure below. ### Export all matching orders 1. Set a fixed window and optional `merchantId` on `GET /v1/platform/orders/export.csv?limit=5000`. For creation time use `from` and `to`. For confirmation time use `status=confirmed&confirmedFrom=…&confirmedTo=…`. CSV timestamp bounds are both inclusive, so use `to - 1` for the upper bound when matching a stats window. Adjacent windows must not share an endpoint. 2. Save the CSV rows and `X-AIPAY-Next-Cursor` together. If `X-AIPAY-Truncated: true` is present, repeat the request with the same filters and the URL-encoded continuation as `cursor`. Continue until the header is absent. The cursor includes the creation millisecond and reference, including when thousands of rows share one millisecond. The export is ordered by `(createdAt, reference)` ascending. Honor `Retry-After` on `429`. 3. When combining pages, parse CSV, keep one header and deduplicate by `reference` if retrying. Empty evidence cells mean unknown. Exports are live and cover retained orders. Archive completed pages and reconcile late changes with `/v1/platform/orders/changes`. Restart for the current grant set if authorization changes while exporting. ## Running in production - **Rotate your key yourself**: `POST /v1/platform/keys/rotate` returns the new key once. The previous key stops working immediately; persist the new one before the next request. If the response is lost, ask AIPAY's operator to rotate for you — do not retry with the old key. - **Budget**: ordinary reads use the `read` budget (60/min by default). CSV and daily stats share `export` (10/min); individual and batch webhook replays share `replay` (10/min). These counters follow the platform ID across key rotation. A separate 240/min per-source-address limit applies before authentication. `GET /v1/platform/usage` reports the current window. On `429`, honor `Retry-After`. An operator can change the per-platform limits in the current window. - **Rehearse without money**: there is no hosted sandbox — run the Worker locally and point the reference client at it (`examples/platform-node/aipay-platform.mjs`, self-check included). See [integration.md](integration.md#rehearse-without-moving-money). ## What this does not do - **No sub-merchant provisioning.** Each merchant signs up and grants you itself; AIPAY does not create merchants on a platform's behalf. That is the honest boundary today: it keeps every merchant's key with the merchant. - **No refunds, payouts or settlement.** AIPAY never holds the money. An anomaly that needs reconciliation returns `review`. Verify the actual receipt, amount and order attribution before taking any action. - **No SLA or status page**, and no per-platform analytics roll-up — pull the CSV or the change feed and aggregate on your side. - **Shared recipients.** The automatic sweep requires an exact amount and holds the match for review if the same transfer could cover another order for the same recipient and asset in the discovery window. --- # Watcher SDK: faster confirmations with your own RPC `aipay-watch` is a small Node library and CLI that watches **your own receiving address** and tells AIPAY the moment it sees the money. You do not poll the AIPAY API, and the SDK cannot confirm anything by itself. - **Distribution:** `https://aipay.im/downloads/sdk-latest.json` (version, tarball, sha256, file list). Tarball + `install-sdk.sh`; no npm package, no registry. - **Also readable as source:** `sdk/aipay-watch/` in (canonical), mirrored at . - **Node:** ≥ 22.18. Nothing else to install. - **Where this doc sits:** it is indexed in [`/llms.txt`](../llms.txt) and mirrors the merchant API section on `POST /v1/orders/:reference/confirm`. ## Why it exists AIPAY's own sweep reads the chain once a minute per pending order. That is fine for one shop and expensive for ten thousand, so the work can move to the party that already runs an RPC: you scan your own address, we verify what you found. | | our sweep | this SDK | | --- | --- | --- | | discovery latency | ~10–60 s | ~2–8 s | | whose RPC quota | ours | yours | | who decides "paid" | the server | the server (unchanged) | ## What it can and cannot do It can: read your pending orders once at start-up, scan your address, and hand AIPAY a transaction hash. It cannot: confirm a payment, hold a key, move funds, or skip verification. Every report is re-read by the server — receipt, recipient, amount, confirmation depth — before an order becomes `confirmed`. A wrong hash is rejected with `409`; it is never "trusted faster". ## Install and run ```bash # Preferred: the installer from the canonical host (verifies the sha256, then installs) curl -fsSL -o install-sdk.sh https://aipay.im/downloads/install-sdk.sh AIPAY_WATCH_VERSION= bash install-sdk.sh # Or by hand: curl -fsSL https://aipay.im/downloads/aipay-watch-.tgz -o sdk.tgz sha256sum sdk.tgz # compare with /downloads/sdk-latest.json tar -xzf sdk.tgz node package/bin/aipay-watch.mjs \ --api-key "$AIPAY_API_KEY" \ --rpc bsc=https://bsc-dataseed.binance.org \ --state .aipay-watch-state.json ``` Useful flags: `--read-only` (discover and print, never report — no API key needed), `--once` (single pass, for cron), `--register-watcher` (also calls `PATCH /v1/merchants/me {"watcher": true}`), `--interval`, `--reconcile`, `--chains`, `--tron-api-key`, `--json`. A Tron merchant needs no JSON-RPC endpoint: `--chains tron` alone watches the public index, or `--rpc tron=https://api.trongrid.io` to be explicit. Mixing chains is one flag: `--rpc bsc=https://…,tron=https://api.trongrid.io`. ## What it reports, and what the server answers ```http POST /v1/orders/ap_…/confirm { "txHash": "0x…" } ``` | answer | meaning | | --- | --- | | `200` | verified and confirmed (idempotent when the hash is repeated) | | `202` | the transaction exists but is not deep enough yet — retry later | | `409` | that transaction does not pay this order (wrong amount/recipient, already used) | | `429` | the confirm budget (120/min per credential) is spent — back off | ## `watcher: true` changes who is responsible `PATCH /v1/merchants/me {"watcher": true}` makes AIPAY **stop** sweeping your pending orders, because someone else is already watching them. Turn it on only while this SDK (or a payer's browser) is actually running: without the flag both paths work at the same time, which is slower but harmless; with it, the SDK is the fast path and the cron is silent for you. ## Coverage and limits - **EVM:** ERC-20 transfers are found with `eth_getLogs` (token + recipient + amount). Native-coin orders have no logs, so they still need a transaction hash — the CLI says so once per chain. - **Solana:** recent signatures of your address, parsed and matched on the received balance delta (SPL mint or native lamports). An `ap_…` order has no per-order on-chain reference, so **two pending orders with the same amount to one address are ambiguous** — use distinct amounts. - **Tron (TRC20 and native TRX):** TronGrid's account index — `GET /v1/accounts/
/transactions/trc20` for TRC20 and `GET /v1/accounts/
/transactions` for TRX — read from the oldest still pending order's time minus 60 s, filtered to incoming rows. Native TRX is covered here because Tron's index lists transfers, not only contract logs. Tron has no per-order on-chain reference either, so the same **same-amount ambiguity** applies. `--rpc tron=` is an **HTTP index base** (TronGrid, or a mirror speaking the same `/v1/accounts/…` API), not a JSON-RPC endpoint; it may be omitted to use `https://api.trongrid.io`. The keyless index is rate limited under load (HTTP 429/451), so pass `--tron-api-key` (or `TRON_PRO_API_KEY`) if you watch more than a few orders a minute. - **Public RPC blocked?** AIPAY exposes a read-only relay for the same five `eth_*` methods (`POST https://api.aipay.im/v1/rpc/`, 5,000-block `eth_getLogs` cap, 120 requests/min per IP, no signing). Passing `--rpc bsc=https://api.aipay.im/v1/rpc/bsc` keeps a watcher running when a public node starts rejecting browsers or your server's IP — it is a fallback, not a replacement for your own endpoint. - **One tarball, one sha256:** `sdk-latest.json` lists every file and its hash, so a release can be diffed. `install-sdk.sh` verifies the checksum before it extracts anything. - **No sandbox:** the API is mainnet-only, so a test order is a real (small) order. Use `--read-only` to try discovery without reporting anything. --- # AIPAY as a payment provider — answers to a capability assessment Audience: a platform evaluating AIPAY as its payment channel. This document answers the ten questions in the assessment dated 2026-11-11 one by one, with the exact endpoints and the parts that are genuinely missing. It is written to be read as evidence, not as sales material: every limit below is also stated in the public docs it links to. Canonical URLs: · · · live discovery · agent index · machine index for crawlers (relative: ../llms.txt). ## 0. First, why the assessment could not see the merchant product The assessment was written from **MCP tool contracts** exposed in a local Pi environment. Those tools are the *payer-side* surface: they let an agent read a wallet, quote a payment, create a payment request and look at its own orders. The merchant product is a separate HTTP API at `https://api.aipay.im/v1` (API key auth) and it is deliberately **not** exposed through those tools — `agent.json` says so explicitly (`agent_tools.available = false`, with `not_available` listing the merchant-channel tools). So "no webhooks / no automatic confirmation / no state machine" was a correct reading of the tool list and an incorrect reading of the product. Everything in §1–§7 below exists today; §8 lists what really is missing. ## 1. What AIPAY is, as a merchant Non-custodial crypto payment requests plus chain reconciliation, with an off-chain (fiat) orchestration layer that **never touches the money**. | Endpoint | Auth | Purpose | | --- | --- | --- | | `POST /v1/merchants` | none (5/day/IP) | create a merchant, returns `apiKey` (+ `webhookSecret`) once | | `GET \| PATCH \| DELETE /v1/merchants/me` | key | profile, quota, notification readiness; delete = hard delete | | `POST /v1/merchants/me/keys/rotate` | key | new key, old key keeps 1–72 h grace | | `POST /v1/orders` | key | create an order (idempotent on `merchantOrderId`) | | `GET /v1/orders` | key | list with `status`, `from`/`to`, `confirmedFrom`/`confirmedTo`, cursor | | `GET /v1/orders/export.csv` | key | reconciliation CSV (19 columns, see §7) | | `GET /v1/orders/:reference` | key (richer) / none | receipt; merchant view adds notifications | | `GET /v1/orders/:reference/status` | none | payer-side poll | | `POST /v1/orders/:reference/confirm` | key | server-verified confirmation from a tx hash | | `POST /v1/orders/:reference/cancel` | key | idempotent cancel | | `GET \| POST /v1/channels`, `PATCH \| DELETE /v1/channels/:id` | key | register the merchant's own off-chain channel | | `POST /v1/orders/:ref/offchain-confirm`, `POST /v1/offchain/confirmations` | key / channel HMAC | merchant receipt confirms an off-chain order | | `GET \| POST /v1/offchain/statements` + `adopt`/`ignore` | key | CSV statement import (proposes only) | | `GET /v1`, `GET /v1/health` | none | discovery + liveness/sweeper mode | **Fiat money is not collected by AIPAY.** On an off-chain channel, AIPAY stores *your* payment link and *your* settlement currency, and records the order. The customer pays through your provider; you confirm with a receipt (manual, signed webhook with a channel secret, or an adopted statement row). The fiat on-ramp feature is shipped disabled. ## 2. Order state machine Statuses: `pending`, `confirmed`, `expired`, `cancelled`. There is **no** `partial`, `overpaid`, `wrong_asset`, `failed`, `refunded` or `disputed` status. ``` pending ──► confirmed │ └───► expired ├──────► cancelled expired | cancelled ──► confirmed (late payment, only with the observed status) ``` Guarantees: a terminal order never leaves its terminal state through the normal path; every transition is a compare-and-set in the database (so two concurrent confirmations cannot both win); `expired` is also reported lazily by `/status` for a stale pending row. Late confirmation requires the caller to name the status it observed and re-verifies the transaction, and it is recorded as a `confirmed_late` event so your ledger can distinguish it. ## 3. What "confirmed" means At confirm time the server re-reads the receipt and requires all of: - receipt exists and `status == 0x1`; - token orders: a `Transfer` log with **this order's token**, **this order's recipient** and `amount >= expected`; native orders: `tx.to == recipient` and `tx.value >= amount`; - `latest_block - tx_block + 1 >= chain.confirmations`; - the transaction is not already used by another order. An RPC error can never confirm anything (fail-closed). Confirmation depths come from the chain registry and are visible in `GET /v1`: ethereum 12, bsc 15, polygon 30, arbitrum 1, optimism 1, avalanche 1, base 1, xlayer 10, solana 1 (commitment level), tron 19. **Post-confirmation re-check (warning only).** Each confirmed **EVM** order is re-read once, 30 minutes to 6 hours after confirmation. If the transaction is gone or its depth dropped, we append a `confirmation_regressed` event and set `last_error`; the status stays `confirmed` and **no webhook is sent**, because a merchant may already have shipped and because no one wants an integration that can be un-paid by a notification. Solana and Tron rely on the depth taken at confirm time. Choose depths accordingly; if you need stronger finality, wait longer on your side before releasing value. ## 4. Matching and edge cases An order is bound to chain + token/asset + recipient + **minimum** amount + a time window derived from creation, and there is one recipient per merchant. **On Solana, every order also carries its own on-chain reference.** The reference is *derived* from the order id (`sha256`-backed, reproducible by the server, the browser and any wallet — no stored secret), and the checkout link hands it to the payer, who attaches it to the transaction as a read-only account. Two pending orders for the same amount are therefore told apart on chain: a transaction that names **another** order's reference is rejected even when the amount matches. A payment that carries no reference at all still matches by amount (someone may have copied the address instead of scanning the QR) — so on **EVM and Tron**, two pending orders for the same amount and recipient remain ambiguous: use distinct amounts or confirm explicitly when that matters. | Case | Behaviour | | --- | --- | | Tx used by another order | `409 order_conflict` | | Re-confirm same hash | `200 { idempotent: true }` | | Wrong token / recipient / too little | `409 transaction_mismatch` | | Overpayment | confirmed; the difference is not tracked or credited | | Too shallow | `202 insufficient_confirmations` — keep polling | | Payment after expiry | chain: `POST /confirm` with the hash still confirms (`late: true`); off-chain: a receipt/statement still confirms (`late: true`, `previousStatus`) — only the automatic sweep refuses to resurrect it | | Native coins (ETH/BNB/POL…) | no transfer log to scan: stays `pending` until you `POST /confirm` with the hash | | Off-chain receipt replayed twice | idempotent; a different receipt on the same order is `409 channel_conflict` | ## 5. Push: signed webhooks exist ``` POST X-AIPAY-Signature: sha256=.")> X-AIPAY-Timestamp: X-AIPAY-Event: order.confirmed | order.expired | order.cancelled X-AIPAY-Delivery: X-AIPAY-Attempt: <1-based> User-Agent: AIPAY-Webhook/1.0 ``` - The signature covers `.` — no scheme, no headers. Verify against the **raw** body bytes, then reject timestamps older than ~5 minutes. - Events: `order.confirmed`, `order.expired` (customer never paid), and `order.cancelled` (you cancelled). Creation is silent. - Retries: 60 s, 5 min, 30 min, 2 h, 6 h (6 attempts). Retried on 408/425/429/5xx and network errors; other 4xx are terminal. - Duplicates: one delivery row per `(reference, event, channel, target)`, claimed with a compare-and-set lease before sending, so a concurrent sweep cannot send twice. - Delivery log: `order.notifications[]` in the merchant view (`delivered`, `pending`, `failed`, `disabled` + reason) and the CSV `webhook` column. - **There is a resend endpoint for one delivery, but no separate event stream.** `POST /v1/orders/:reference/notifications/:deliveryId/replay` (merchant key) re-sends one recorded delivery now: it keeps the same delivery id (so a receiver dedupes on `X-AIPAY-Delivery`), restarts that delivery's retry budget, and writes `notification_replayed` to the order's timeline — including when the replay fails again. It is limited to 10/min. There is still **no event stream** and no bulk replay: bulk recovery is still pull-based (`GET /v1/orders` + `GET /v1/orders/export.csv`). ## 6. Polling, quotas, idempotency - Poll `GET /v1/orders/:reference/status` (no key) or the merchant list. - The server sweeps pending orders on a backoff: 60 s, then 120 s, then every 240 s (a Worker cron; `GET /v1/health.sweeper` reports `mode`, and `GET /v1` documents the push + poll contract). Worst-case discovery for a payment nobody reports is therefore about 4 minutes; `/confirm` (from your own watcher) and the payer's browser check are immediate. **30 s polling is enough**; faster polling only burns quota. - Quotas: 500 orders per merchant per UTC day, **50** merchant signups per IP per day, 16 KiB request body, TTL 120–3600 s (default 900), 10 webhook replays per minute. - Payer-facing reads are counted **per order**: 120/min for `status` and `receipt` (so a shared egress address — an office, a campus, a café — cannot spend another payer's budget), 60/min for the order list, 30/min for statements, 10/min for the CSV export. On top of that there is a **per-address ceiling** of 600/min (360/min for `confirm`) so one address cannot spray references; it is counted once every four requests and a refusal is remembered per Worker, so the ceiling is hard without a write per request. Authenticated callers keep one bucket per credential. `GET /v1` publishes all of this under `polling.limits` and `polling.payerLimits`. - Idempotency: `merchantOrderId`, unique per merchant. Replaying the same id with the **same** parameters returns the original order (`200 idempotent`). Replaying it with a different amount/asset/chain/channel is now `409 merchant_order_conflict` (this was silently reusing the old order until 2026-11-11, so check your client version notes). There is no `Idempotency-Key` header. ## 7. Reconciliation evidence - `GET /v1/orders/export.csv` → RFC 4180 CSV, 19 columns: `reference, merchant_order_id, status, created_at, confirmed_at, amount, asset, decimals, amount_base_units, chain_key, token_address, channel, confirmed_source, channel_ref, tx_hash, block_number, confirmations, webhook, description`. Response headers `X-AIPAY-Rows` and `X-AIPAY-Truncated` (5 000 row cap). Formula-injection prefixes are neutralised. - Every state change appends to an `order_events` audit trail (`created`, `channel_selected`, `confirmed`, `confirmed_late`, `expired`, `cancelled`, `channel_confirmed`, `channel_conflict`, `statement_matched`). - References are stable; terminal orders are purged 90 days after creation (`/v1` reports `retentionDays`). ## 8. What is genuinely missing (read before designing around it) 1. **No refunds, reversals, chargebacks or disputes.** No endpoint, no state. You refund from your own wallet and record it in your own ledger; AIPAY cannot move or claw back funds. 2. **Reorg handling is a warning, not a rollback** (see §3): a regressed confirmation is recorded for EVM only and never changes the order. 3. **No event stream and no bulk replay** (§5). One delivery can be re-sent on demand; a whole day of deliveries cannot. 4. **No sandbox or test mode that cannot receive real funds.** Every accepted chain is mainnet. To rehearse: run the Worker locally (`wrangler dev` with `RPC_OVERRIDES`, see §11 of `merchant-order-service.md`) and drive it with the copy-paste clients in the source repository (`examples/merchant-node/aipay.mjs`, `examples/merchant-python/aipay.py`), or create a deliberately small live order on a cheap chain and refund it from your wallet. 5. **No SLA / uptime commitment and no status page.** 6. **One API key = full merchant scope**, no scopes, no 2FA on the recipient address change (the docs state this as a residual risk; treat the key like a wallet-level secret and rotate with `POST /v1/merchants/me/keys/rotate`). 7. **No documented read-side rate limit** (order and signup quotas only). 8. **No per-order deposit address** (§4), so amount+recipient matching is the only routing signal. 9. **No partial payments / overpayment credit** (§4). ## 9. How this maps onto your own settlement rules Your assessment already requires an authoritative internal ledger and forbids crediting spendable value from an unverified notification. AIPAY fits that model if you treat it as **evidence**, not as a wallet: 1. Create the order with **your** `merchantOrderId` = your business reference; persist `reference` ↔ your order **before** the customer pays. 2. Credit only on a verified signal: a `confirmed` webhook whose signature, timestamp and `reference` you checked, or a `GET /v1/orders/:reference` response re-read at least twice with the same terminal state. 3. Never mint on `order.expired`, `order.cancelled`, or on a 202/insufficient confirmations answer. Late payments arrive as `confirmed` with a `confirmed_late` event — decide explicitly whether to honour them. 4. Keep your own state machine (`received` → `credited` → `held` → `settled`); AIPAY's `confirmed` is a receipt, not match finality, and not permission to sell a regulated product. 5. Reconcile daily with `export.csv` against your ledger; anything unexplained stays open on your side and is resolved by `reference`, never by creating a replacement order. ## 10. Question-by-question index 1. **Production provider or agent tool?** Both: a merchant HTTP API (this document) and a payer-side agent surface. Jurisdictions/customer types: we do not restrict or vet them today; we also do not collect or transmit fiat, and MSGChain payouts are disabled. Legal/AML/sanctions obligations of the product you sell are yours — we do not claim to cover them. 2. **Fiat?** No fiat collection. On-chain assets only, per chain: ETH/USDT/USDC/DAI (ethereum), BNB/USDT/USDC/BUSD (bsc), POL/USDT/USDC (polygon), ETH/USDT/USDC/ARB (arbitrum), ETH/USDT/USDC/OP (optimism), AVAX/USDT/USDC (avalanche), ETH/USDC (base), OKB/USDT/USDC (xlayer), SOL/USDT/USDC (solana), TRX/USDT-TRC20 (tron). Decimals come from the registry; anything else is `400 unknown_asset`. 3. **State machine?** §2. A confirmed order never reverts in the API. 4. **Depth/finality, reorgs, matching uniqueness?** §3 and §4. 5. **Signed webhooks, rotation, replay, retries, SLA, recovery?** §5. Key rotation exists (`POST /v1/merchants/me/keys/rotate`); the webhook secret is returned once at signup and can be re-issued with `POST /v1/channels/:id/secret` for channel receipts only. 6. **What makes an order confirmed?** Receipt + transfer + depth, re-read from an RPC at confirm time; independently reproducible with the `tx_hash` and `block_number` recorded on the order. 7. **Refunds?** Not implemented (§8.1). 8. **Custody, recipient change, MFA?** Non-custodial; recipient changes with the API key, no second factor, no delay; address changes never rewrite existing orders (each order snapshots its recipient). Keys are hashed at rest; the dashboard keeps your key in `localStorage`, so use the CLI/API from a trusted machine for production keys. 9. **Fees, limits, availability, retention, sandbox?** Zero commission; `billing.status = "free"` and paid plans are **not on sale** (no start date); limits in §6; retention 90 days; no sandbox (§8.4); no SLA (§8.5). 10. **Export/replay and outstanding links?** §7. A single delivery can be re-sent with `POST /v1/orders/:reference/notifications/:deliveryId/replay` (§5); there is no bulk replay and no event stream. Old checkout links keep rendering; after expiry they show `expired` and cannot confirm except through an explicit late `confirm`. Deleting the merchant hard-deletes orders, events, deliveries and keys, so export first. ## 11. What we changed because of this assessment (2026-11-11) - `GET /v1` now publishes the notification contract (headers, canonical signed string, events, retry schedule, duplicate protection) and a polling block with a recommended interval, so an agent reading discovery cannot conclude "no push mechanism". - Replaying `merchantOrderId` with different parameters is now `409 merchant_order_conflict` instead of silently returning the old order (the docs already promised this behaviour). - `order.cancelled` is documented, listed in `agent.json`, and no longer reported as "order expired" in webhook/email text. - Doc drift fixed: the 24-hour Solana TTL claim, the "Solana cloud verification unsupported" claim, and the "in-request sweep, not a cron" limitation. ### 2026-11-15 → 2026-11-18 (what this document now says that it did not before) - **Solana orders carry a per-order on-chain reference** (derived from the order id, no stored secret) and the server rejects a transaction that names another order's reference, even when the amount matches. Before this, two pending Solana orders for the same amount were ambiguous (§4). - **A webhook delivery can be re-sent** with `POST /v1/orders/:reference/notifications/:deliveryId/replay` (§5). Before this, recovery was pull-only. - **Payer reads are counted per order** with a per-address ceiling on top (§6). Before this, every anonymous caller on one address shared one bucket, which made a shared network look like a scraper and refused checkout pages. - **One transaction can no longer confirm two orders.** The uniqueness check used to be a read followed by a write, so two concurrent confirmations of the same transfer could both succeed; it is now decided inside the write itself. - **A receipt without a status is no longer treated as a success**, and the server now checks that the node answered about the transaction it asked for. - Two public pages were added for the questions this document answers: (what we never touch, and how to check the rest) and (the limits the service actually enforces). lists every developer surface in one place. If something you need is not in this document, ask for it by endpoint name — the API is small enough that a concrete gap can usually be answered with a test. --- # Security model AIPAY is a non-custodial payment gateway. This page states what protects the money, what a compromise can and cannot do, and which duties stay with the merchant. It is written for the person who has to answer "is it safe to route our payments through this?" — not marketing. ## What AIPAY never holds - No private key, seed phrase or signing device of any merchant, payer or agent. - No card data, no bank credential, no provider (Alipay / WeChat Pay / UnionPay / Stripe) credential. Off-chain money never reaches AIPAY. - Payments go from the payer's wallet straight to the merchant's own address. AIPAY watches the chain; it cannot move, freeze or redirect funds that already arrived. ## The credential that matters: the merchant API key Everything an attacker would want sits behind one bearer token. Be precise about it. | If someone steals a merchant API key, they can… | …and cannot | | --- | --- | | Create orders (and burn the merchant's daily quota) | Move funds out of the merchant's wallet | | Read that merchant's orders (already public on-chain, plus shop/description) | Sign a transaction or a wallet operation | | Confirm **off-chain** orders (declare "the money arrived") | Confirm an **on-chain** order without a matching transaction: the server re-reads the receipt, the transfer event, the recipient, the amount and the depth | | **Change the receiving address**, so future payments go to them | Rewrite past orders: each order stores the recipient it was created with | | Change the webhook URL / rotate its secret | Read or recover the key itself: only its SHA-256 is stored, the plaintext is shown once | | Rotate or delete the merchant | Access another merchant, or the wallet app | So the honest answer to "can a breach cost a merchant money?" is: **not from the wallet, and not retroactively — but yes, a stolen key can redirect future payments and can fake an off-chain receipt.** Both are addressed below. ## Controls in place - **Keys**: 43 URL-safe CSPRNG characters, stored as SHA-256 only, returned once; rotation keeps the old key valid for 1–72 hours (default 24) so a live integration can roll without downtime, and `revokeOldImmediately` exists for a leak. - **On-chain verification**: receipt status, `Transfer` log (token, recipient, amount ≥ order amount), confirmation depth per chain (Tron: 19 blocks; Solana: commitment level). Unknown transaction, reverted transaction and mismatch are distinct refusals — never a silent confirmation. - **Off-chain separation**: a chain hash cannot confirm an off-chain order and a receipt cannot confirm an on-chain one (`409 channel_mismatch`). Every confirmed off-chain order records `confirmedSource` (`merchant_manual`, `merchant_webhook`, `statement`) and is labelled as a receipt, never as chain evidence. - **Webhook integrity**: `sha256=HMAC-SHA256(secret, ".")`, ±5 minutes, constant-time comparison, retries with a claim/lease so two sweeps cannot double-send. - **Channel secrets**: per-channel HMAC secret, rotated/revoked independently; the signature is verified **before** any order lookup, so an unsigned request cannot enumerate references. - **References**: `ap_` + 20 characters from a 32-character alphabet (100 bits, CSPRNG) — not guessable, not sequential. - **Request handling**: 16 KiB body cap, strict validation, parameterised SQL, CORS limited to `aipay.im`, `no-store` responses, per-merchant daily order quota and per-IP signup quota. - **Browser surface**: static export, no session cookie, no third-party script on the payer page, CSP with `object-src 'none'` and `frame-ancestors 'none'`, `X-Frame-Options: DENY`, `nosniff`. - **Data minimisation**: the API key is hashed; the client IP is stored only as a per-day hash for the signup counter; email is optional; orders are kept 90 days. ## Residual risks, and what the merchant must do 1. **Key theft → recipient redirect.** *Highest-impact gap.* Mitigations today: rotate the key, keep it server-side, never paste it into chat or a repo. There is no second factor on a recipient change yet, and no alert. Treat the key as the bank credential it is; if it may have leaked, rotate immediately and check `GET /v1/merchants/me` for an address you do not recognise. 2. **Fake off-chain confirmation.** Only your own system or your key can mark an off-chain order paid, and AIPAY cannot verify it. If your backend consumes `order.confirmed` for off-chain orders, read `confirmedSource` and treat it as bookkeeping, not as settlement proof. 3. **Webhook forgery.** Verify the HMAC over the raw body and reject timestamps outside ±5 minutes. Never trust an unsigned POST to your webhook URL. 4. **RPC trust.** AIPAY verifies against allow-listed RPC endpoints per chain with failover. A lying RPC could misreport a payment; confirmation depth reduces, but does not remove, that risk. For very large amounts, reconcile against a second source (your own node or the explorer) before shipping. 5. **Chain reorganisations.** Depth thresholds are per chain; on cheap/fast chains a deep reorg is unlikely but not impossible. The order keeps the depth it was confirmed at. 6. **Availability.** Free-tier quotas are finite (see [merchant-order-service.md](merchant-order-service.md) §7). A flood of requests can exhaust them; refusals are explicit (`429 rate_limited`), and nothing is silently dropped. 7. **Your own systems.** The keys to your webhook handler, your order database and your staff devices are outside AIPAY's control. Most real-world losses in payment integrations happen there. 8. **A capability is signed, but the machine around it is not.** The agent's spending policy now stores each capability with the human's **signature** over every field (the same `aipay-grant-v1` envelope used to move one), and the engine refuses a capability with no signature, one signed by a key this machine does not trust, or one edited after it was signed. A delegated capability is checked against its parent on every payment as well: the parent's signature, the parent's life, and every bound (scope, budgets, window length, approval mode, timelock, stream ceiling) must still hold, and a delegation shares the parent's allowance rather than copying it. So a capability is a checkable consent, not a claim. What is still outside that guarantee: the **trust anchor** lives in a file on the agent's machine (`~/.aipay/agent/approval.json`), and the agent process runs as you — someone who can rewrite your home directory can move that anchor, and can edit the local spend ledger. Keep the approval key's passphrase **different** from the wallet keystore's (`AIPAY_AGENT_APPROVAL_PASSPHRASE`), keep the agent on a machine you control, and treat the local store as untrusted. When you need consent that anyone can check, issue a **mandate** (`aipay-mandate-v1`, the user's key, covering scope and every cap) as well. See [Automatic payments, spending limits and mandates](automation.md). 9. **What is still not signed.** The **local spend ledger** (who spent what) and the state file itself are plain local state: a machine owner can delete a recorded spend, and the guard marker only stops the accident. The **approval token** (the human's key, for one escalated payment) and the **mandate** are signed; a capability is signed as well. ## What AIPAY will never claim - That a confirmed payment means goods were delivered: `delivery` is `not_tracked`. - That an off-chain confirmation is chain evidence. - That funds are held, insured or reversible. - That a local agent policy is enforced on-chain. If you find a way to contradict any of the above, that is a security report: contact the operator before publishing it. See also: [integration guide](integration.md), [API reference](merchant-order-service.md), and [llms.txt](../llms.txt) for the whole surface in one file. --- # Supported chains and per-chain rules AIPAY talks to public blockchains directly. This page lists every chain AIPAY supports today, what works on each, and the mistakes that can cost you funds. ## Chain list | Chain | Chain ID | Native coin | Tokens | Status | |---|---|---|---|---| | Ethereum | `eip155:1` | ETH | USDT, USDC, DAI | Available | | BNB Chain | `eip155:56` | BNB | USDT, USDC, BUSD | Available | | Polygon | `eip155:137` | POL | USDT, USDC | Available | | Arbitrum One | `eip155:42161` | ETH | USDT, USDC, ARB | Available | | Optimism | `eip155:10` | ETH | USDT, USDC, OP | Available | | Avalanche C-Chain | `eip155:43114` | AVAX | USDT, USDC | Available | | Base | `eip155:8453` | ETH | USDC | Available | | X Layer (OKX) | `eip155:196` | OKB | USDT, USDC | Available | | Solana | `solana-mainnet` | SOL | USDT, USDC | Available | | Tron | `tron-mainnet` | TRX | USDT (TRC20) | Available | | MSG (MSGChain) | — | MSG | — | **Not enabled** | The only chain intentionally missing from the app is MSG: `public/msg-config.json` ships with `enabled: false`, and MSG is excluded from the chain list until MSGChain mainnet parameters are configured. Everything above it is live mainnet. Tron is its own world too: your Tron address starts with `T`, is base58, and is **not** the same string as your `0x…` or Solana address (same mnemonic, different curve path). Sending TRC20 USDT needs a little **TRX** in that address for the fee; a USDT-only address cannot move anything. Confirmation uses Tron's 19-block irreversibility rule (~57s), so the UI says "waiting" longer than on the EVM L2s. Test networks (Sepolia, Solana Devnet) exist in the code for development but are not part of the released mainnet app. ## The five rules that prevent lost funds ### 1. Same `0x` address, different balances — per chain Because all EVM chains share one derivation path, your Ethereum address is also your Base, X Layer, Polygon, Arbitrum, Optimism, BNB Chain and Avalanche address. - This is convenient, but **assets are not shared**. Your USDC on Base and your USDC on Ethereum are two different balances. - The **Receive** page lets you pick a chain; the address stays the same but the network you tell the sender matters. ### 2. The network must match — always Only send an asset **on the chain the receiving wallet expects**. - Sending ETH on Base to an address that only supports Ethereum Mainnet does not deliver ETH to that wallet's Ethereum balance. - Many exchanges, exchanges' deposit pages and other wallets do **not** auto-migrate cross-chain deposits. If they do not support the network you used, the funds may be unrecoverable. - **Rule of thumb:** when paying someone, use the chain *they* asked for. When using an exchange deposit address, use the exact network the exchange lists. ### 3. Solana is a different world - Your Solana address (base58, ed25519) is **not** usable on any EVM chain, and your `0x...` address is not usable on Solana. Sending across the boundary loses funds. - Solana tokens are SPL tokens, not ERC-20. The IDs are different even for "the same" USDC/USDT. - Solana transaction fees are paid in SOL; EVM fees are paid in that chain's native coin (ETH, BNB, POL, AVAX). ### 4. You need the native coin for gas Every transfer costs a small fee paid in the **native** coin of that chain: - To move USDC on Base you need a little **ETH** on Base. - To move USDT on Polygon you need a little **POL**. - To move anything on Solana you need a little **SOL**. A wallet with tokens but no native coin cannot transact. The Send page estimates the fee in advance and refuses to build a payment you cannot afford. ### 5. Confirmations take time — and differ by chain AIPAY checks pending payments against each chain's expected finality: | Chain | Confirmations used for confirmation | |---|---| | Ethereum | 12 | | BNB Chain | 15 | | Polygon | 30 | | Arbitrum One | 1 | | Optimism | 1 | | Avalanche C-Chain | 1 | | Base | 1 | | X Layer | 10 | | Solana | Slot-based | A payment is shown as **confirmed** only after the chain reaches the expected depth, so a merchant may see a short wait on Ethereum or Polygon and a nearly instant one on a Layer 2. Always verify by transaction hash when the amount is significant — AIPAY links out to the chain's block explorer (Etherscan, BscScan, Polygonscan, Arbiscan, Optimistic Etherscan, Snowtrace, BaseScan, OKLink, Solana Explorer). ## Where the data comes from AIPAY reads chain data from public RPC endpoints, with failover between providers: - No AIPAY-run node and no AIPAY API. If every public RPC for a chain is unreachable, balances for that chain can temporarily fail to load; your funds are unaffected. - Transaction status is re-checked from the chain itself, so confirmation does not depend on AIPAY staying online. - Because everything is client-side, your IP address is visible to the RPC providers you query, exactly as in any wallet using public endpoints. ## What is not enabled - **MSG (MSGChain):** adapter ready, disabled. No MSG address, balance or payment appears in the app. - **Fiat on-ramp (`/buy`):** disabled — you cannot buy crypto with a card inside AIPAY yet. - **EVM token swaps:** disabled — use Solana swaps on the `/swap` page if you need a swap today. - **NFT gallery:** disabled. See [../llms.txt](../llms.txt) for the authoritative status list. --- # Wallets and keys in AIPAY AIPAY is a **non-custodial** wallet. "Non-custodial" means AIPAY never holds your funds and never holds your keys. Everything below happens inside your browser. ## The two things you must never lose ### 1. The recovery phrase (12 words) When AIPAY creates a wallet it generates a standard **BIP-39** recovery phrase of **12 words** and shows it once. - It is the master secret behind **every** address AIPAY shows you, on every chain. - It is the only way to rebuild the wallet from scratch. - Anyone who reads these 12 words owns the funds. There is no password on the phrase itself. - Write it on paper, offline, and store it somewhere safe. Do not photograph it, do not paste it into chat apps, cloud notes or password managers you do not control. If the phrase is lost, funds are lost. AIPAY has no server, no account, and no recovery process. Neither AIPAY nor anyone else can restore it. ### 2. The local wallet password (PIN) This is the password you type to **unlock the wallet on this device** and to **sign transactions**. - Minimum length: **10 characters**. - It is **never stored anywhere** — not on a server, not in a backup file. - Technically it wraps the stored recovery phrase: the phrase is encrypted with a key derived from your password (PBKDF2-SHA256, 310,000 iterations, then AES-256-GCM) and only decrypted in memory while the wallet is unlocked. - If you forget it, you cannot unlock the wallet **even though the files are still on your device**. The only way back is to re-import your recovery phrase (or restore a backup and then still supply the original password — see [backup.md](backup.md)). The wallet password is **not** the same as the backup password. See [backup.md](backup.md). ## Continuing on another device (key login) AIPAY has **no account and no email**, so there is no "log in" — but there is a key, and for most people it is the **backup file plus the backup password**: > carrier (`.ckx` file, PNG image, or AIPAY `.json`) + the password you chose for it = the wallet again, on a new device Open **https://aipay.im/en/import-wallet** and the first option is **"I have a backup — restore it"**. Pick the carrier, type the password where the page asks, and the wallet, your local orders and your merchant identity come back — offline, without registering anything. - The **12-word phrase** is the other door into the same wallet: it rebuilds it (same address) when you have the words but not the backup file, or when you cannot remember the old wallet password. - There is **no third door**. No password reset, no support, no "recover my account" — a non-custodial wallet that has lost both the carrier and the phrase is simply gone. That is the trade for never handing your keys to a server. - Two devices are two independent copies. Restoring on a second phone does not link them, and a new order on one does not appear on the other. ## Address derivation AIPAY derives addresses from the single recovery phrase, using standard BIP-32/BIP-44 paths: | Chain family | Derivation path | Address type | Notes | |---|---|---|---| | EVM (Ethereum, BNB Chain, Polygon, Arbitrum, Optimism, Avalanche, Base) | `m/44'/60'/0'/0/0` | `0x...` | **The same address on all EVM chains.** | | Solana | `m/44'/501'/0'/0'` | base58, ed25519 | A **different** address from your EVM one. | | MSG (MSGChain) | from the same phrase (Dilithium-5) | MSG address | Implemented, but **not enabled today**. | Two consequences that matter: 1. **One EVM address, many networks.** Your `0x...` address on Ethereum is identical on Base, Polygon, Arbitrum and so on. That does not mean the funds are shared: each network holds a separate balance. Sending USDC on Base to your address does **not** put USDC on Ethereum. 2. **Solana is a separate address.** Never send funds to your Solana address on an EVM chain, or vice versa. ## Where keys live - The **encrypted** recovery phrase (and, for EVM, the derived private key) is stored in your browser's local database — IndexedDB — on this device only. - Signing happens locally in the browser. AIPAY broadcasts the signed transaction directly to a public RPC endpoint, or the chain's RPC, without a middleman. - AIPAY can show your **raw private key** from **Settings → Export Private Key** if you need to move to another wallet. Treat that value exactly like the recovery phrase: whoever has it owns the funds. - Because everything is local, the wallet does **not** sync across devices by itself. To use the same wallet on a phone and a laptop you must import the recovery phrase (or restore a backup) on each device. ## Unlocking conveniences and their limits - **Biometric unlock** (fingerprint / face) can replace typing the password on a specific device. It is a convenience wrapper around the same local key material and is **not** part of a backup — a restored device must re-enable it. - **Auto-lock / in-memory only**: secrets are decrypted into memory while the wallet is unlocked. Closing the app or reloading clears them; you unlock again. - **The install/“banner dismissed” state, theme, and biometric settings are per device** and are deliberately excluded from backups. ## Multiple wallets AIPAY can hold more than one wallet (for example a personal one and a business one) and lets you switch between them. Each wallet has its own recovery phrase and its own local password, and only the **active** wallet is unlocked at a time. Backups include all stored wallets. ## Safety checklist - [ ] Recovery phrase written on paper, stored offline, and readable. - [ ] Local wallet password is at least 10 characters and not reused from another service. - [ ] An [encrypted backup](backup.md) exists on a second device or a drive you control. - [ ] I know the difference between my EVM address and my Solana address. - [ ] I have tested a small receive and a small send before using large amounts. ## What is not available MSG/MSGChain addresses and keys are derived from the same recovery phrase but are hidden while MSG is disabled. Do not expect a working MSG address in the UI today. See [chains.md](chains.md) and the authoritative status list in [../llms.txt](../llms.txt). --- # Encrypted backup and restore AIPAY lives entirely on your device. That is why a backup is not optional — it is the only way to survive a lost phone, a wiped laptop, or "clear browsing data". ## Key login: your backup is your login AIPAY has **no account and no email**, so there is nothing to log in to. What a non-custodial wallet has instead is a **key**, and for a normal person that key is exactly two things: > **the backup carrier (a `.ckx` file, a PNG image, or an AIPAY `.json` file) + the password you chose for it** Keep those two together and you can unlock the wallet you already have on a new phone, a new laptop or a new browser — in seconds, without an account, without an email, without a server call. This is the "login" AIPAY offers, and it is the same idea as a hardware wallet or a password manager: the secret lives with you, not with us. Two things follow from that, and both are deliberate: - **Nothing is synced automatically.** Two devices holding the same wallet are two independent copies; each one needs the carrier and the password once. - **Losing the carrier *and* the password means losing the wallet.** There is no reset link, no support ticket, no "forgot password" — AIPAY does not have your key and cannot get it back. The 12-word recovery phrase is the only other way in. To restore on a new device, open **https://aipay.im/en/import-wallet** (Chinese: `/zh/import-wallet`). The first thing on that page is **"I have a backup — restore it"**: pick the carrier, type the password where it asks (inside CryptoKey for a `.ckx`/PNG, in the page for a `.json`), and the page tells you exactly what came back. ## Why you must take a backup - The wallet, its encrypted recovery phrase, your contacts, merchant settings and order history are stored in your browser's local database (IndexedDB) on **this device only**. - If that data disappears — new phone, new browser, reinstall, site data cleared, failed OS update — the wallet is gone from that device. - Nothing is synced to a server. There is no AIPAY account that could put it back. - Receiving the 12-word recovery phrase is still the ultimate fallback, but a backup also carries your contacts, merchant configuration, products and orders, which the phrase alone cannot restore. **Take a backup at least once, and again after any significant change** (new wallet, new shop settings, important order history). Store it on a device or drive you control, ideally a second one. ## What a backup contains One encrypted file, covering both local databases: | Included | Not included (deliberately) | |---|---| | Your wallet(s): encrypted recovery phrase, key material, name, addresses | The **local wallet password (PIN)** — it is never stored anywhere | | App settings (sanitized copy) | **Biometric** unlock data (`bio_data`, `bio_pin`) and the biometric-enabled flag | | Contacts | The "install banner dismissed" flag | | Transaction history | The AI assistant's local password and related local secrets | | Merchant: shop settings, products, orders | Theme / display preference | | Merchant cloud identity: your merchant API key, merchant id, shop name, chain | — | The result: a restored device gets the wallet back, but biometric unlock, the install banner state, the AI local password and the theme must be set up again there. That is intentional — those are per-device conveniences, not wallet data. **The merchant API key travels with the backup on purpose.** It lives in this browser's local storage, so without it a merchant who moved to a new phone would get their local orders back but lose their merchant account (server-side orders, webhooks, the automation policy) and have to register a new one. The key is a bearer credential: **whoever holds the backup file *and* the backup password can act as your merchant.** Guard the backup exactly like the wallet, and rotate the key in **Settings → Merchant API key** if you ever think it leaked. A backup taken before this feature existed (v1/v2) simply has no merchant key in it, and restoring it leaves whatever is on this device untouched. **Who can read the backup before it is encrypted — and that depends on the carrier:** | Carrier | Who sees the plaintext | Who can restore it | |---|---|---| | **`.json` (Local Backup)** | Nobody outside this browser. AIPAY encrypts and decrypts it here. | Anyone with the file **and** the backup password | | **`.ckx` / PNG (CryptoKey)** | **CryptoKey.im** — it has to read the backup to encrypt it. That includes the merchant API key. | Anyone with the carrier **and** the backup password | If you do not want a third party to see even your merchant API key, take the offline `.json` backup instead: it is encrypted by AIPAY in the browser and never leaves the device. One more consequence of "the backup carries the merchant identity": **the backup decides which merchant this device talks to.** A backup is not a neutral data dump — restoring one binds this device to the merchant inside it. That is also why the restore screen shows you the shop name it is about to activate. ## The two passwords (do not confuse them) There are **two different passwords**, and neither is stored by AIPAY: | | Local wallet password (PIN) | Backup password | |---|---|---| | What it protects | Unlocking the wallet on this device; signing transactions | Encrypting/decrypting the exported backup file | | Where it is used | Numeric input in the app | The export dialog, or inside CryptoKey.im | | Length | at least 10 characters | at least 10 characters | | Set when | Creating / importing a wallet | Taking / restoring a backup | | Stored anywhere? | No | No — in the CryptoKey flow, AIPAY never even sees it | **The backup does not contain the wallet password.** So a restored device has the encrypted recovery phrase but still needs the **original wallet password** to unlock it. If you took the backup with one password and have forgotten your wallet password, restoring alone will not help: re-import the 12-word phrase instead. You may reuse the same string for both, but you lose the benefit of a second, independent secret. A lost backup password means the backup cannot be decrypted — but the recovery phrase can still restore the wallet. ## Export a backup 1. Open **https://aipay.im/en/settings**. 2. Choose **Local Backup** for the plain, offline approach, or **Encrypted Import / Export** for the encrypted file. ### Option A — encrypted JSON file (Local Backup) 1. Enter a **backup password** (at least 10 characters). 2. Tap **Export encrypted backup**. 3. Desktop browsers download the JSON file. On phones and tablets you can use system sharing to save it to Files, a cloud drive, or send it to another device. The file is encrypted with PBKDF2-SHA256 (310,000 iterations) plus AES-256-GCM. Without the password it is useless — which also means **a lost backup password cannot be recovered**. ### Option B — CryptoKey.im encrypted backup AIPAY can hand the backup to [CryptoKey.im](https://cryptokey.im) inside an embedded window. The **password is typed inside CryptoKey and never reaches AIPAY**. CryptoKey offers two carriers: - **`.ckx` file (recommended):** the backup, byte for byte, marked as a CryptoKey file. - **PNG image:** the encrypted data is hidden in the pixels of a cover image (yours, or one CryptoKey generates). AIPAY checks that the image is big enough before you proceed. **Keep the carrier as the original file.** Chat apps, social apps, screenshot tools and photo hosting **re-compress images and destroy the hidden data**. If you use the PNG carrier, send/save it only as the original `.png` file (cloud drives and email attachments as files are fine; an image bubble in a chat app is not). When in doubt, use `.ckx`. ## Restore a backup 1. On the new device, open **https://aipay.im/en/import-wallet**. 2. Tap **"I have a backup — restore it"** and pick the carrier you saved: - **`.ckx` file or PNG image** — the password is typed **inside CryptoKey**, which AIPAY never sees; - **`.json` file** (the offline "Local Backup" export) — the backup password is typed on the page. 3. For a `.json` backup, enter the **backup password** you set when you exported it and tap **Restore**. 4. The page shows what came back — wallet, address, local orders, merchant identity — before you continue. 5. Unlock the wallet with your **original wallet password** (the wallet password, not the backup password). If CryptoKey reports a wrong password or a damaged file, AIPAY cannot tell those two cases apart — re-check the file and the password against another copy before assuming the backup is broken. **No backup file at all?** On the same page, open **"Another way (recovery phrase)"** and type your 12 words. That rebuilds the *same* wallet (the same address) on this device, and you choose the local wallet password for it. This is the path to take when you have the words but lost the backup — or when you cannot remember the old wallet password. ## Single-device boundaries to remember - **No automatic sync.** Two devices with the same wallet are independent copies; the same phrase on both is expected. - **Biometrics, install state, AI password and theme do not travel** with a backup. - **Never test a restore on your only copy.** Verify the backup opens on a second device (or at least that the file is intact) before you rely on it. - **The safest backup is the one that is both offline and readable.** An encrypted file you cannot remember the password for is worse than no backup at all. - **The recovery phrase alone is enough** to rebuild the wallet on a new device, even with no backup file. Write it down as well. ## What is not enabled The MSG/MSGChain adapter is disabled, so there is nothing MSG-specific to back up today. See [../llms.txt](../llms.txt) for the authoritative feature status. --- # AIPAY for AI agents (human-readable guide) This page is for the human who runs an agent. The machine-readable versions are [`/llms.txt`](../llms.txt), [`/agent.json`](../../agent.json) and the [skill file](../../skills/aipay/SKILL.md); this one explains the same thing in prose. ## What the agent surface is — and is not AIPAY's web app is for people: it holds a browser wallet and shows payment pages. The **agent surface** is a separate, local process with its **own** wallet: - a stdio MCP server (`agent/mcp-server.mjs`) and a CLI (`agent/cli.mjs`), - state and keys under `AIPAY_AGENT_HOME` (default `~/.aipay/agent`), - a local spending-policy engine, enforced by that process — **not** by a chain. It is not a hosted API. `aipay.im` serves static files; it cannot sign, pay or store anything for you. If a tool is missing, the correct behaviour is to say so, not to guess an endpoint. ## Install The runtime is published as a sanitized, allowlisted tarball. **aipay.im is the canonical download host**; the GitHub repository is a mirror of the same bytes (same sha256): - canonical: `https://aipay.im/downloads/` (`install.sh`, `CHECKSUMS.txt`, the tarballs) - current version, sha256 and file list: - mirror: ```bash curl -fsSL -o install.sh https://aipay.im/downloads/install.sh AIPAY_AGENT_VERSION= bash install.sh ``` The script verifies the tarball's sha256 (aipay.im, then the GitHub release) before extracting, then installs the runtime dependencies. Nothing else is downloaded. Requirements: **Node.js ≥ 22.18**. The runtime is the agent tool registry and CLI, published as two bundled `.mjs` files (plus the watcher SDK source `aipay watch` runs). The implementation is compiled into those bundles, not shipped as readable modules: the tarball contains no `.ts` file and no `src/` tree, and the build fails if a published file matches a credential shape. The bundles are **not minified** — a program that derives keys and signs transactions should stay reviewable, and an obfuscated one is indistinguishable from a payload. ## First run ```bash export AIPAY_AGENT_HOME="$HOME/.aipay/agent" export AIPAY_AGENT_PASSPHRASE='a strong passphrase' node ~/.aipay/agent-dist/package/agent/cli.mjs keystore init --generate # prints the phrase once node ~/.aipay/agent-dist/package/agent/cli.mjs address node ~/.aipay/agent-dist/package/agent/cli.mjs config ``` Tool discovery works without a wallet or a merchant key. To see what your installed version supports, run `node ~/.aipay/agent-dist/package/agent/cli.mjs tool --list` or send `tools/list` to the installed stdio server. Compare names against `tool_names` in [the download manifest](https://aipay.im/downloads/agent-latest.json) when the field is present. Cloud tools require a merchant key. Wallet operations that sign require an unlocked keystore. ## Watching for a payment (no API polling) An agent that just sent a payment link usually has to ask "has it arrived yet?". The runtime ships a watcher instead: it reads your pending cloud orders **once**, then scans your own receiving address with the RPC endpoint you configure, and reports nothing but the transaction hash. AIPAY re-reads the chain and confirms — the watcher cannot, because the party running it is the merchant. ```bash node ~/.aipay/agent-dist/package/agent/cli.mjs watch \ --api-key "$AIPAY_API_KEY" \ --rpc bsc=https://bsc-dataseed.binance.org \ --once --json ``` Flags: `--chains `, `--interval ` (chain scan, default 8s), `--reconcile ` (re-read the order list, default 5min; `0` = start-up only), `--lookback `, `--state ` (last scanned block, so a restart does not re-read history), `--tron-api-key `, `--read-only` (print discoveries, never report — no key needed). Tron needs no RPC flag: its public index is the default, so `--chains tron` alone works. The same module is published as the standalone `aipay-watch` SDK, so the two cannot drift. ## Hosted orders (the merchant HTTP API) The local tools above never leave the machine. The **hosted** order service is a different surface: it sweeps the chain, sends signed webhooks, keeps 90 days of history and is what a shop's backend integrates. Five tools wrap it, so an agent can run the merchant side without writing curl: | Tool | What it does | | --- | --- | | `aipay_cloud_profile_get` | Shop, receiving address, quotas, which notification channels are on | | `aipay_cloud_orders_create` | Create a hosted order → `checkoutUrl` / QR. Send `merchantOrderId`: the same id and parameters return the original order, changed parameters answer `merchant_order_conflict` | | `aipay_cloud_orders_list` | One page, newest first. Persist `nextPageCursor` and pass it as `pageCursor` with the same filters to resume. Use numeric `nextCursor` only with older servers. | | `aipay_cloud_orders_get` | Status, `confirmedSource` (`chain` vs merchant receipt), events, notification attempts | | `aipay_cloud_orders_cancel` | Cancel a pending order only | Every tool reads its credential from `AIPAY_API_KEY` (and optionally `AIPAY_BASE_URL`), or from the 0600 merchant file written by `merchant onboard` — **never from a tool argument**, which would put the key in the transcript. A missing key is a `credentials_unavailable` error, not an anonymous call. Creating an order moves no money, and `confirmed` is a receipt, not settlement. ## Connect it to your agent host ```json { "mcpServers": { "aipay": { "command": "node", "args": ["/home/you/.aipay/agent-dist/package/agent/mcp-server.mjs"], "env": { "AIPAY_AGENT_HOME": "/home/you/.aipay/agent", "AIPAY_AGENT_PASSPHRASE": "…" } } } } ``` Tool failures come back as results with `isError: true` and `structuredContent: { code, nextAction, retryable }`. Branch on those, never on prose. ## What the agent may spend Nothing, until a human grants a **capability**: scope (chains / assets / recipients / merchants), budget (per payment, per window, lifetime), expiry, and an approval mode (`auto`, `escalate`, `human`). The human's approval key is a separate key that can only sign approvals and grants: ```bash node agent/cli.mjs approval keygen # address = the capability issuer node agent/cli.mjs capabilities grant \ --holder 0x…the-agent-wallet \ --chain base --asset USDC --to 0x…merchant \ --per-payment 25 --per-window 100 --window-seconds 86400 --total 500 \ --expiry 2026-12-31T00:00:00Z --approval-mode escalate --escalate-above 25 ``` The command **signs** the capability with that key (the issuer is the key's own address), so the agent can spend exactly what you signed and nothing else. Use a passphrase for the approval key that is **not** the wallet's: the agent process reads the wallet passphrase, and it must never be able to unlock the approval key. A capability made before signing existed can be signed once with `node agent/cli.mjs capabilities sign --id ` — read it first, because you are signing what is stored. `--holder` names the address allowed to spend *and delegate*. A holder can hand out a narrower child capability (`aipay_capability_delegate`): same issuer (the human), same subject, only smaller scope/expiry/budget, one level deep. Delegating never transfers approval authority — an escalated payment still needs the human's key. `policy` (and `aipay_policy_status`) also lists lifecycle `warnings[]`: `kill_switch_on`, `capability_unsigned`, `capability_untrusted`, `capability_revoked`, `capability_expired`, `capability_expiring`, `delegation_expiring` (a child dies with the earlier of itself and its parent) and `budget_exhausted` (per asset). The "expiring soon" horizon is seven days by default and parameterisable (`expiringWithinSeconds`). A warning never changes a decision; the engine stays the only authority. The same list is rendered read-only at : paste the JSON `policy` printed and the page translates the codes it knows, printing any newer code as is. The kill switch (`aipay_spending_kill`) denies every payment immediately, and both directions are audited with `actor: human | agent`. Chains: the same mnemonic yields the agent's EVM address, Solana address and Tron address (`m/44'/195'/0'/0/0`). `aipay_wallet_addresses` and `aipay_wallet_balances` cover all three; Tron sends are signed locally over the node-built transaction id, and the address needs a little **TRX** for fees. Migrating or handing over an agent is one file, and it grants nothing new: ```bash node agent/cli.mjs capabilities export --all --out bundles/agent-a.json node agent/cli.mjs capabilities import --bundle bundles/agent-a.json ``` The bundle (`aipay-grant-bundle-v1`) carries the same signed `aipay-grant-v1` envelopes, verified on both sides, parents before children. Revoked capabilities are skipped and reported; re-imports are idempotent. ### A second, independent limit: the mandate A capability says *what the agent may do*. A **mandate** says *how much the user is willing to have spent automatically* — per payment, per window, per day, per total, with an expiry, signed by the user on their own machine (`aipay-mandate-v1`). Both gates must pass before a payment is signed, and a mandate can only narrow a capability, never widen it. ```bash node agent/cli.mjs mandate create --chain base --asset USDC --to 0x…merchant \ --per-payment 25 --per-window 100 --window 1h --total 500 --expires-in 2592000 node agent/cli.mjs mandate list # what the agent may spend automatically node agent/cli.mjs mandate revoke --id mandate_… ``` The mandate is created by the human (the approval key signs it; the agent cannot), it lives in the local state, and nothing about it is known to AIPAY's servers. When a payment is outside a limit it is **not** paid: it is handed back to the human for a one-off approval. The format, a copy-paste verifier and the full rule set are in [Automatic payments, spending limits and mandates](./automation.md). ## Operating rules that prevent loss - **Quote first.** `aipay_quote` reports the policy verdict for exactly that payment. - **Pay once.** Always pass `idempotencyKey`; a retry with the same key returns the first result instead of paying twice. - **Do not re-create requests.** `merchantOrderId` makes creation idempotent; the same id with different parameters is a conflict, and an expired id is terminal. - **Confirmed is not delivered.** A chain-verified confirmation proves the payment; `Order.delivery` is always `not_tracked`. - **Never print keys or phrases.** The keystore is encrypted with scrypt + AES-GCM and written with mode 0600. ## Troubleshooting | Symptom | Cause | What to do | |---|---|---| | `credentials_unavailable` | no keystore / wrong passphrase | `keystore init` or set `AIPAY_AGENT_PASSPHRASE` | | `policy_denied` | outside every granted capability | ask the human to widen the grant (it cannot be done by the agent) | | `policy_escalated` | inside scope but needs sign-off | get the single-use `approvalToken` from the human, then pay once | | `idempotency_conflict` | same key, different payment | keep the original; check `aipay_orders_get` | | `unknown_chain` | wrong `chainKey` | read `aipay_chains_list` first | | MSG missing from `aipay_chains_list` | MSG is not enabled | expected: `msg-config.json` ships `enabled: false` | ## Where to read more - Skill file (step-by-step for the agent): [`/skills/aipay/SKILL.md`](../../skills/aipay/SKILL.md) - Machine surface: [`/agent.json`](../../agent.json) and [`/llms.txt`](../llms.txt) - Web planner / signer: [`/en/agent`](https://aipay.im/en/agent) - Download host (canonical): - Mirror: --- # Automatic payments, spending limits and mandates This page is for two readers: the **human** who wants an agent to spend money without asking every time, and the **integrator** whose platform runs the agent. It describes exactly what AIPAY enforces, what it does not, and who carries which risk. Everything here is **local**. AIPAY holds no keys, signs nothing on a user's behalf, and has no "payout API" for somebody else's agent. That is a product boundary, not a missing feature: it is the reason an attacker who reaches our servers still cannot move a user's money. The machine-readable versions are [`/llms.txt`](../llms.txt) and [`/agent.json`](../../agent.json); this page is the prose version of the same rules. ## What "automatic payment" means here The agent surface (`agent/mcp-server.mjs`, `agent/cli.mjs`) is a local process with its **own** wallet. It can already: - create a payment request (a static link + QR payload) and reconcile it, - **pay out** — `aipay_pay` signs with the agent's own key and broadcasts, on 8 EVM mainnets, Solana and Tron, - watch for incoming payments with its own RPC quota (`aipay watch`). What it may spend is decided by **two independent gates**, and a payment must pass **both**: | Gate | What it is | Signed by | Where it lives | |---|---|---|---| | **capability** | What the human granted: chains, assets, recipients/merchants, per-payment / per-window / lifetime budget, expiry, approval mode | the human's approval key (over every field) | the local state store | | **mandate** | The user's own limit on *automatic* spending: scope, per-payment / per-window / total / daily caps, expiry, anti-replay nonce | the user's own key (the "authorization key") | the local state store | A mandate can only **narrow** what the capability allows. It can never widen it, and no server can widen either one. Without a capability, nothing is paid at all — a mandate is an additional limit, never a licence. Both gates are **signed**, and the engine refuses what it cannot check: a capability with no signature, or one signed by a key this machine does not trust, is not a capability (the payment is denied with `capability_unsigned` / `capability_untrusted`). A capability is created and signed by the human: ```bash aipay-agent approval keygen # the human's approval key (its own passphrase!) aipay-agent capabilities grant \ --chain base --asset USDC --to 0x…merchant \ --per-payment 25 --per-window 100 --window-seconds 86400 --total 500 \ --expiry 2026-12-31T00:00:00Z # → the issuer is that key's address, and the command signs it ``` The agent cannot do this: it holds no approval key. A capability made before signing existed can be signed once with `aipay-agent capabilities sign --id ` — look at it first, because you are signing what is stored. Use a passphrase for the approval key that the agent process does **not** have: `AIPAY_AGENT_APPROVAL_PASSPHRASE` (or `--passphrase`). The agent reads `AIPAY_AGENT_PASSPHRASE` for the wallet, and `approval keygen` refuses to create an approval key with that one. **Delegation shares the allowance.** A capability may name a `holder`, and that holder may hand on a narrower child (`aipay_capability_delegate`). The child is signed by the holder, keeps the human as the approval authority, and may only be narrower in every dimension — scope, expiry, budgets, the rolling-window length, the approval mode, the timelock and the stream ceiling. What the children spend counts against the **parent**, and a revoked or expired parent withdraws the delegation. The engine re-checks all of it on every payment, not only when the child is imported. ## The mandate object — `aipay-mandate-v1` ```jsonc { "v": 1, "id": "mandate_…", // local id, unpredictable "issuer": "0x…", // the key that signed it (the user) "audience": "aipay-agent", // which runtime may act on it "scope": { "chains": ["bsc"], // allowed chains (chain keys) "assets": ["USDT"], // allowed assets "operations": ["pay"], // "pay" and/or "refund" — never both "merchants": ["0x…"], // allowed merchants; [] means "any" "maxPerPayment": { "USDT": "25.00" }, "maxPerWindow": { "window": "1h", "USDT": "100.00" }, "maxTotal": { "USDT": "500.00" }, "dailyCap": { "USDT": "200.00" } }, "windowStart": 1763000000, // start of the accounting window "expiresAt": 1763003600, // hard expiry (unix seconds) "nonce": "…", // consumed once, at registration "issuedAt": 1763000000, "riskAccepted": true, // the user said yes; there is no default "signature": "0x…" // EIP-191 personal_sign over everything above } ``` Field notes: - `issuer` **is** the signing key's address. It cannot be set to somebody else. - `riskAccepted` must be `true`. Automation is never enabled by omission. - `operations` may not contain both `pay` and `refund`: a refund is a separate decision with smaller caps (see *Refunds* below). - `maxPerPayment` and `maxTotal` are **required for every asset in `assets`**. `maxPerWindow` and `dailyCap` are optional (without them, only the per-payment and total caps bound the spend). - `maxPerWindow.window` is a duration: `30m`, `1h`, `7d`, `3600s`. `dailyCap` is a rolling 24 hours. ## The bytes that get signed The signature covers **every field**, including the scope and the caps: change one byte and verification fails. The signed message is ``` aipay-mandate-v1\n{"schema":"aipay-mandate-v1","v":1,…} ``` where the JSON is built with fixed key order and canonicalised values: | Field | Canonical form | |---|---| | `chains` | trimmed, lower-cased, de-duplicated, sorted | | `assets` | trimmed, **upper-cased**, de-duplicated, sorted | | `operations` | trimmed, lower-cased, de-duplicated, sorted | | `merchants` | trimmed, de-duplicated, sorted (case preserved) | | `maxPerPayment`, `maxTotal`, `dailyCap` | keys trimmed + upper-cased, values trimmed, sorted by key | | `maxPerWindow` | `{ "window": , …the same amount map, minus the "window" key… }` | | everything else | as written (numbers, ids, addresses, the nonce) | `signature` is a 65-byte EIP-191 `personal_sign` — the same scheme any EVM wallet can produce, so the user can sign a mandate with the wallet they already have (or with a hardware signer), not only with our CLI. ### A verifier you can copy This checks authenticity and expiry. The limit checks are the rules below. ```js import { verifyMessage } from 'ethers'; const SCHEMA = 'aipay-mandate-v1'; function canonical(m) { const upper = (s) => s.trim().toUpperCase(); const sorted = (list) => [...new Set(list.map((x) => x.trim()))].sort(); const amounts = (map) => Object.fromEntries( Object.entries(map ?? {}) .map(([k, v]) => [upper(k), String(v).trim()]) .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), ); const windowAmounts = Object.fromEntries( Object.entries(m.scope.maxPerWindow ?? {}).filter( ([k]) => k.trim().toLowerCase() !== 'window', ), ); return JSON.stringify({ schema: SCHEMA, v: m.v, id: m.id, issuer: m.issuer, audience: m.audience, scope: { chains: sorted(m.scope.chains.map((c) => c.toLowerCase())), assets: sorted(m.scope.assets.map((a) => upper(a))), operations: sorted(m.scope.operations.map((o) => o.toLowerCase())), merchants: sorted(m.scope.merchants), maxPerPayment: amounts(m.scope.maxPerPayment), maxTotal: amounts(m.scope.maxTotal), ...(m.scope.maxPerWindow ? { maxPerWindow: { window: String(m.scope.maxPerWindow.window).trim(), ...amounts(windowAmounts), }, } : {}), ...(m.scope.dailyCap ? { dailyCap: amounts(m.scope.dailyCap) } : {}), }, windowStart: m.windowStart, expiresAt: m.expiresAt, nonce: m.nonce, issuedAt: m.issuedAt, riskAccepted: m.riskAccepted, }); } export function verifyMandate(mandate, { now, issuer } = {}) { if (!mandate || mandate.v !== 1 || mandate.riskAccepted !== true) { return { ok: false, reason: 'mandate_malformed' }; } let recovered; try { recovered = verifyMessage(`${SCHEMA}\n${canonical(mandate)}`, mandate.signature); } catch { return { ok: false, reason: 'mandate_signature_invalid' }; } if (recovered.toLowerCase() !== mandate.issuer.toLowerCase()) { return { ok: false, reason: 'mandate_issuer_mismatch' }; } if (issuer && issuer.toLowerCase() !== mandate.issuer.toLowerCase()) { return { ok: false, reason: 'mandate_issuer_mismatch' }; } if (now !== undefined && now >= mandate.expiresAt) { return { ok: false, reason: 'mandate_expired' }; } return { ok: true }; } ``` ## The rules a mandate must enforce 1. **Signature first.** An unverifiable mandate is not a mandate. Nothing about scope or budget is even looked at before the signature checks out. 2. **Expiry is judged against chain time as well as the local clock.** The later of the two wins, and the chain timestamp is remembered — so rewinding the local clock cannot extend a window or resurrect an expired mandate. Moving the clock *forward* is always conservative. The agent's payment path reads the chain's own clock (the latest block timestamp) once per payment when a mandate is in force; on EVM and Solana that is one read-only RPC call. On chains without such a call yet (Tron, MSG) the last timestamp seen is kept — the floor never moves backwards. 3. **Spend is reserved, then settled.** The amount is held before the payment is signed, turned into a spend when the money moved, and released when the payment failed. Two concurrent payments cannot spend the same allowance. 4. **The limits are per operation.** A payment is checked against every mandate that authorizes that operation; the strictest one wins. 5. **Out of limits ⇒ a human, not a refusal and not a pass.** Exceeding the per-payment, window, total or daily cap, using another chain, asset or merchant, or a mandate that is not yet active all produce `needs-human`: the request is handed back to the person, who signs a single-use approval for **that one payment**. 6. **A revoked or expired mandate is still a gate.** A revoked mandate refuses automatic payments (the unused allowance does not survive the revocation); an expired one means every payment needs a human until a new mandate is issued. A human's one-off approval is a separate authority and still works. 7. **Refunds need their own mandate**, with caps of at most **20 %** of the payment mandate it refunds. A refund mandate cannot be registered before the payment mandate it refunds exists, and registering one above that ratio is refused. 8. **The verdict never leaks the quota.** It carries stable reason codes and nothing else — no remaining budget, no "you are short by X". ### Reason codes `within_mandate`, `mandate_malformed`, `mandate_signature_invalid`, `mandate_issuer_mismatch`, `mandate_unknown`, `mandate_revoked`, `mandate_expired`, `mandate_not_active`, `operation_unknown`, `operation_not_allowed`, `chain_not_allowed`, `asset_not_allowed`, `merchant_not_allowed`, `per_payment_cap_exceeded`, `window_cap_exceeded`, `total_cap_exceeded`, `daily_cap_exceeded`, `amount_invalid`, `request_conflict`. Branch on these, never on prose. ## Who carries which risk | Step | Who signs | If it is breached | |---|---|---| | Private key | only the user's device (optionally a hardware signer) | the user's own funds are at risk — AIPAY never had them | | Authorization (the mandate) | the user, on their own machine | the user's limit can be exceeded **by their own agent**, not by AIPAY | | A single payment | the agent's key, inside the limits | the user's funds move — that is what they authorized | | A refund | a separate, smaller mandate | same, with a smaller ceiling | | Order status | AIPAY's server | the server can lie about a confirmation; the money still moves on-chain | | The mandate itself | nobody but the user | AIPAY stores nothing, so there is nothing to steal | | A *capability record* | the human's approval key, over every field | an unsigned or foreign-signed capability is refused by the engine (`capability_unsigned` / `capability_untrusted`), so the agent cannot widen its own limits | | The trust anchor and the spend ledger | nobody — they are local state on the agent's machine | whoever can rewrite the agent's home directory can move the anchor or delete a recorded spend; keep the approval key's passphrase different from the wallet's | Concretely: **a compromise of AIPAY's servers cannot spend a user's money, mint an authorization, or widen a limit.** The limits live on the user's machine, signed by the user's key. ## What AIPAY deliberately does not do - no custody, no server-side signing, no "one switch to enable automatic spending"; - no unlimited switch, and no using our server as the quota ledger (that would make us a critical path for every payment); - no deriving a refund permission from a payment permission; - no way for support or operations to widen a user's limit; - no quota details in an error message shown to anyone but the user. ## Using this in your own agent You do not need our runtime to use a mandate — it is a document, and the format is public. The reference implementation lives in the project checkout (`src/lib/core/policy/mandate.ts`, with the ledger next to it), and the CLI wraps it: ```bash # The human signs a mandate (needs the approval key; the agent cannot do this) node agent/cli.mjs mandate create --chain bsc --asset USDT --merchant 0xMerchant \ --per-payment 25 --total 500 --per-window 100 --window 1h --expires-in 2592000 node agent/cli.mjs mandate list # what the agent may spend automatically node agent/cli.mjs mandate show --id # one mandate, with what is left node agent/cli.mjs mandate revoke --id ``` If your platform runs the agent, the flow is: 1. the user signs a mandate on their machine and hands you the object; 2. you verify it (the snippet above) and **store it locally** — it is the user's limit, so it belongs on the user's side, not on yours; 3. before every payment you check the limits yourself, keep your own reserved / settled ledger, and when a limit is exceeded you ask the human (do not pay and reconcile later); 4. you can optionally publish the mandate's **hash** to AIPAY so a merchant can audit afterwards. That is an audit trail, not an execution path: our server never widens a limit because of it. The MCP server also exposes a read-only view of the limits in force (`aipay_mandate_list`), so an agent can see its own budget before it asks. ## Related - [Agent surface](./agent.md) — install, tools, capabilities, the audit trail. - [Security model](./security.md) — what protects the money, and the residual risks we do not hide. - [Provider assessment answers](./provider-assessment-answers.md) — the point-by-point answers a third-party review asks for.