# 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, "<timestamp>.<raw body>")`. 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, "<timestamp>.<raw body>")`, ±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.
