# 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=<epoch>&after=<nextAfter>&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, "<X-AIPAY-Timestamp>.<raw body>")`, 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:<chainKey>:<contract-or-mint>` or `onchain:<chainKey>:native`. Off-chain currencies use `offchain:<currency>`. 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.
