# 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: <rows in this file>
X-AIPAY-Truncated: true      # only when there is another page
X-AIPAY-Next-Cursor: <opaque token>
```

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 <key>` — 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 <your webhookUrl>
Content-Type: application/json
User-Agent: AIPAY-Webhook/1.0
X-AIPAY-Signature: sha256=<hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>
X-AIPAY-Timestamp: <unix seconds>
X-AIPAY-Event: order.confirmed | order.expired | order.cancelled
X-AIPAY-Delivery: <delivery id>
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": "<base58 signature>" }` —
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:<merchant>?amount=…&spl-token=…&reference=<key>`, 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:<id>"` (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, "<X-AIPAY-Timestamp>.<raw body>")`, 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).
