{
  "openapi": "3.1.0",
  "info": {
    "title": "AIPAY merchant order API",
    "version": "1.0.0",
    "summary": "Non-custodial crypto payment requests, chain reconciliation and signed webhooks.",
    "description": "Create orders, hand the payer a hosted checkout link, receive signed webhooks (or poll), and reconcile with CSV. AIPAY never holds keys or funds: the payment goes from the payer's wallet to the merchant's own address. There is no sandbox and no testnet behind api.aipay.im — a test order is a real order for a small amount. No refunds, reversals or disputes exist in the API, by design: the merchant refunds from their own wallet. An off-chain channel confirmation is the merchant's own receipt, not chain evidence. Full prose: https://aipay.im/docs/merchant-order-service.md and https://aipay.im/docs/provider-assessment-answers.md. Read endpoints are rate limited per credential (status/receipt 120/min, list 60/min, statements 30/min, CSV export 10/min) and answer 429 rate_limited with Retry-After; discovery, health and writes are never limited. The counters are per Worker isolate, so the effective limit is looser than the published number. Commission: zero today; a per-merchant rate can be recorded (max 500 bps) but is never deducted from a payment — see /v1.internal/fees and the merchants/me fees block.",
    "contact": {
      "name": "AIPAY",
      "url": "https://aipay.im/integrate"
    },
    "license": {
      "name": "Proprietary",
      "identifier": "LicenseRef-Proprietary"
    }
  },
  "servers": [
    {
      "url": "https://api.aipay.im",
      "description": "Production. Mainnet only."
    }
  ],
  "security": [
    {
      "merchantKey": []
    }
  ],
  "tags": [
    {
      "name": "discovery",
      "description": "Unauthenticated documents."
    },
    {
      "name": "merchant",
      "description": "Merchant profile and keys."
    },
    {
      "name": "orders",
      "description": "Order lifecycle, receipts and reconciliation."
    },
    {
      "name": "channels",
      "description": "Off-chain channels the merchant already owns."
    },
    {
      "name": "platform",
      "description": "Merchant-authorized platform reads, webhooks and reconciliation."
    }
  ],
  "paths": {
    "/v1": {
      "get": {
        "tags": [
          "discovery"
        ],
        "summary": "Discovery document: endpoints, chains, confirmation depths, webhook contract, polling, billing.",
        "security": [],
        "responses": {
          "200": {
            "description": "Capability document.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true
                }
              }
            }
          }
        }
      }
    },
    "/v1/health": {
      "get": {
        "tags": [
          "discovery"
        ],
        "summary": "Liveness, database and sweeper mode.",
        "security": [],
        "responses": {
          "200": {
            "description": "Healthy."
          },
          "503": {
            "description": "Degraded."
          }
        }
      }
    },
    "/v1/merchants": {
      "post": {
        "tags": [
          "merchant"
        ],
        "summary": "Create a merchant. Returns the API key once.",
        "description": "Rate limited to 5 signups per IP per day. Only the SHA-256 of the key is stored; the plaintext is returned exactly once.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "shopName",
                  "recipientAddress"
                ],
                "properties": {
                  "shopName": {
                    "type": "string",
                    "maxLength": 80
                  },
                  "recipientAddress": {
                    "type": "string",
                    "description": "The merchant's own receiving address, in the chain's own format: `0x` + 40 hex for EVM chains, base58 for Solana, base58 starting with `T` for Tron. It must match `chainKey`'s family (a Solana address with chainKey bsc is 400 validation_failed). AIPAY cannot change it for you."
                  },
                  "chainKey": {
                    "type": "string",
                    "description": "Default chain for this merchant, e.g. bsc."
                  },
                  "webhookUrl": {
                    "type": "string",
                    "format": "uri",
                    "description": "Where signed order events are delivered."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created; body carries apiKey (and webhookSecret when a webhook was configured)."
          },
          "429": {
            "description": "rate_limited"
          }
        }
      }
    },
    "/v1/merchants/me": {
      "get": {
        "tags": [
          "merchant"
        ],
        "summary": "Profile, quota and notification readiness.",
        "responses": {
          "200": {
            "description": "Merchant view."
          },
          "401": {
            "description": "unauthorized"
          }
        }
      },
      "patch": {
        "tags": [
          "merchant"
        ],
        "summary": "Update shop name, default chain, recipient address, webhook, email or Telegram.",
        "description": "Existing orders keep the recipient they were created with.",
        "responses": {
          "200": {
            "description": "Updated merchant view."
          }
        }
      },
      "delete": {
        "tags": [
          "merchant"
        ],
        "summary": "Hard delete the merchant, its orders, events, deliveries and keys.",
        "description": "Export first: nothing survives.",
        "responses": {
          "200": {
            "description": "Deleted."
          }
        }
      }
    },
    "/v1/merchants/me/keys/rotate": {
      "post": {
        "tags": [
          "merchant"
        ],
        "summary": "Rotate the API key; the old key keeps a 1–72 h grace window.",
        "responses": {
          "201": {
            "description": "New key returned once."
          }
        }
      }
    },
    "/v1/merchants/me/automation": {
      "security": [
        {
          "merchantKey": []
        }
      ],
      "get": {
        "tags": [
          "merchant"
        ],
        "summary": "The merchant's own automation policy and what it confirmed today.",
        "description": "Off by default: without a policy an imported statement row is only a proposal and the merchant adopts each row by hand. The policy is stored per merchant, not per API key, so a key rotation keeps it.",
        "responses": {
          "200": {
            "description": "`{ automation: { enabled, policy, today: { autoAdopted, autoAdoptedAmount }, updatedAt } }`. `policy` is null and `enabled` is false when nothing is stored."
          },
          "401": {
            "description": "unauthorized"
          }
        }
      },
      "patch": {
        "tags": [
          "merchant"
        ],
        "summary": "Write the automation policy: which imported statement rows may confirm an order on their own, and up to what limit.",
        "description": "`enabled: false` stores nothing — the default is no automation at all, and it always works: a stale or malformed field in the body cannot stop a merchant from switching automation off. With `enabled: true`, `channels` and both ceilings are required; a rule without a limit is refused (400 validation_failed). The ceilings are amounts in the channel's settle currency (2 decimals, the off-chain order scale) and the daily ceiling resets at 00:00 UTC; one policy covers one settle currency, so channels with different currencies are refused. The policy only adds a gate: an automatic confirmation runs the same matching and the same confirmation as a manual adopt, and a statement row still cannot confirm an on-chain order. A statement confirmation is not chain evidence — `statement_auto` is the merchant's own statement row, and the risk of a wrong statement file stays with the merchant.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "v": {
                    "type": "integer",
                    "enum": [
                      1
                    ],
                    "description": "Policy version. Only 1 is understood."
                  },
                  "statementAutoAdopt": {
                    "type": "object",
                    "description": "Omit it (or send `enabled: false`) to store no rule at all.",
                    "properties": {
                      "enabled": {
                        "type": "boolean",
                        "default": false,
                        "description": "False stores nothing: the policy is off."
                      },
                      "channels": {
                        "type": "array",
                        "maxItems": 8,
                        "items": {
                          "type": "string",
                          "pattern": "^ch_[0-9a-z]{6,32}$"
                        },
                        "description": "Channel ids (`ch_…`) the rule covers. Required when the rule is enabled."
                      },
                      "maxPerOrder": {
                        "type": "string",
                        "description": "Per-order ceiling, in the channel's settle currency (2 decimals). Required when the rule is enabled."
                      },
                      "maxPerDay": {
                        "type": "string",
                        "description": "Daily ceiling across the rows the rule confirmed, same units; resets at 00:00 UTC. Required when the rule is enabled."
                      },
                      "minOrderAgeSeconds": {
                        "type": "integer",
                        "minimum": 0,
                        "maximum": 86400,
                        "default": 0,
                        "description": "How long the order must exist before a row may confirm it. 0 = no extra wait."
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "The stored policy: `{ automation: { enabled, policy, today: { autoAdopted, autoAdoptedAmount }, updatedAt } }`."
          },
          "400": {
            "description": "validation_failed (unknown policy version, malformed channel id, missing channels or missing ceilings while the rule is enabled, a channel the merchant does not have, or channels with different settle currencies)"
          },
          "401": {
            "description": "unauthorized"
          }
        }
      },
      "delete": {
        "tags": [
          "merchant"
        ],
        "summary": "Remove the automation policy: back to no automation.",
        "description": "The stored rule is deleted, so imported statement rows are proposals again. Orders already confirmed under the policy keep their `statement_auto` receipt and their `automation_auto_adopt` event.",
        "responses": {
          "200": {
            "description": "`{ automation: { enabled: false, policy: null, today: { autoAdopted: 0, autoAdoptedAmount: \"0\" }, updatedAt: null } }`."
          },
          "401": {
            "description": "unauthorized"
          }
        }
      }
    },
    "/v1/orders": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Create an order.",
        "description": "`merchantOrderId` is the idempotency key: the same id with the same parameters returns the original order, a different amount/asset/chain/channel is 409 merchant_order_conflict. `checkoutUrl` is the payer page; `reference` is what you store on your side.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "amount"
                ],
                "properties": {
                  "amount": {
                    "type": "string",
                    "description": "Positive decimal string, e.g. \"12.50\"."
                  },
                  "asset": {
                    "type": "string",
                    "description": "Token symbol from the chain registry; defaults to the chain coin."
                  },
                  "tokenAddress": {
                    "type": "string"
                  },
                  "chainKey": {
                    "type": "string"
                  },
                  "channelId": {
                    "type": "string",
                    "description": "Sell on an off-chain channel instead of on chain."
                  },
                  "merchantOrderId": {
                    "type": "string",
                    "maxLength": 120,
                    "description": "Your own order id (idempotency key). Longer values are truncated to 120 characters by the server."
                  },
                  "description": {
                    "type": "string",
                    "maxLength": 200
                  },
                  "returnUrl": {
                    "type": "string",
                    "format": "uri"
                  },
                  "ttlSeconds": {
                    "type": "integer",
                    "minimum": 120,
                    "maximum": 3600,
                    "default": 900
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Created.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OrderEnvelope"
                }
              }
            }
          },
          "200": {
            "description": "Idempotent replay of the same merchantOrderId."
          },
          "400": {
            "description": "validation_failed / unknown_asset"
          },
          "409": {
            "description": "merchant_order_conflict"
          },
          "429": {
            "description": "rate_limited (500 orders per merchant per UTC day)"
          }
        }
      },
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "List orders with filters and a keyset cursor.",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "confirmed",
                "expired",
                "cancelled"
              ]
            }
          },
          {
            "name": "from",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794000000000
            },
            "description": "created_at lower bound, inclusive, as **unix milliseconds** (13 digits). Non-numeric values are 400 validation_failed."
          },
          {
            "name": "to",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794600000000
            },
            "description": "created_at upper bound, inclusive, unix milliseconds."
          },
          {
            "name": "confirmedFrom",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794000000000
            },
            "description": "confirmed_at lower bound, inclusive, unix milliseconds. Orders that are not confirmed never match."
          },
          {
            "name": "confirmedTo",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794600000000
            },
            "description": "confirmed_at upper bound, inclusive, unix milliseconds."
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          },
          {
            "name": "cursor",
            "in": "query",
            "schema": {
              "type": "number"
            },
            "description": "Legacy epoch-millisecond nextCursor. Skips other orders at the same millisecond. Do not send with pageCursor."
          },
          {
            "name": "pageCursor",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "Opaque nextPageCursor from the previous page. Keep the same filters and omit cursor."
          }
        ],
        "responses": {
          "200": {
            "description": "{ orders, limit, nextPageCursor, nextCursor }. Both continuation fields are null at the end. Orders are sorted by (createdAt, reference) descending. Pages are live."
          },
          "400": {
            "description": "validation_failed — invalid filters or cursor, or both cursor parameters were sent."
          },
          "429": {
            "description": "rate_limited — per-credential read budget exhausted (Retry-After header)."
          }
        }
      }
    },
    "/v1/orders/export.csv": {
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "Resumable reconciliation CSV (up to 5,000 rows per page).",
        "description": "Timestamp filters are inclusive epoch milliseconds. Keep filters fixed; follow X-AIPAY-Next-Cursor as pageCursor until absent. Rows are ordered by (createdAt, reference) descending. Pages are live. 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 evidence cell means unknown.",
        "responses": {
          "200": {
            "description": "CSV. X-AIPAY-Rows gives row count; X-AIPAY-Truncated and X-AIPAY-Next-Cursor indicate a continuation.",
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "429": {
            "description": "rate_limited — per-credential read budget exhausted (Retry-After header)."
          },
          "401": {
            "description": "Invalid merchant key."
          }
        },
        "security": [
          {
            "merchantKey": []
          }
        ],
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "confirmed",
                "expired",
                "cancelled"
              ]
            }
          },
          {
            "name": "from",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794000000000
            },
            "description": "created_at lower bound, inclusive, as **unix milliseconds** (13 digits). Non-numeric values are 400 validation_failed."
          },
          {
            "name": "to",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794600000000
            },
            "description": "created_at upper bound, inclusive, unix milliseconds."
          },
          {
            "name": "confirmedFrom",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794000000000
            },
            "description": "confirmed_at lower bound, inclusive, unix milliseconds. Orders that are not confirmed never match."
          },
          {
            "name": "confirmedTo",
            "in": "query",
            "schema": {
              "type": "integer",
              "example": 1794600000000
            },
            "description": "confirmed_at upper bound, inclusive, unix milliseconds."
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 5000
            }
          },
          {
            "name": "pageCursor",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "URL-encoded X-AIPAY-Next-Cursor from the previous CSV page. Omit for the first page."
          }
        ]
      }
    },
    "/v1/orders/stats": {
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "Daily reconciliation for the authenticated merchant only.",
        "description": "UTC [from,to) window, maximum 92 days. created counts by creation day, confirmed by confirmation day. amounts sums invoices created in the window, including pending orders. confirmedAmounts groups by confirmation day, assetId, decimals, confirmedSource, amountEvidenceSource and amountEvidenceRegressed. Group totals separate dueAmountBaseUnits, observedAmountBaseUnits and confirmedAmountBaseUnits. Unknown amounts stay null. Asset identity is chain plus contract/mint/native marker, or off-chain currency. Each amount cohort has an independent 5,000-order cap; counts cover the window. Spends the export budget.",
        "security": [
          {
            "merchantKey": []
          }
        ],
        "parameters": [
          {
            "name": "from",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer"
            },
            "description": "Epoch ms, inclusive. Defaults to 7 days before `to`."
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer"
            },
            "description": "Epoch ms, exclusive. Defaults to now."
          }
        ],
        "responses": {
          "200": {
            "description": "{ from, to, timezone: 'UTC', created: { totals, days }, confirmed: { total, days }, amounts, amountsTruncated, confirmedAmounts, confirmedAmountsTruncated, collectable: false }. Each amount array is null if truncated; evidence amounts within a group may also be null."
          },
          "400": {
            "description": "Invalid window (from >= to, > 92 days) or timestamps."
          },
          "401": {
            "description": "Invalid merchant key."
          },
          "429": {
            "description": "Export budget exhausted; honor Retry-After."
          }
        }
      }
    },
    "/v1/orders/{reference}": {
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "Public receipt; with a merchant key it also carries the delivery log.",
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Receipt."
          },
          "404": {
            "description": "Unknown reference."
          },
          "429": {
            "description": "rate_limited — per-credential read budget exhausted (Retry-After header)."
          }
        }
      }
    },
    "/v1/orders/{reference}/status": {
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "Payer-side status poll (no key).",
        "security": [],
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "`{ reference, status, paid, expiresAt, txHash, channel, payUrl? }`. `channel` is `onchain` for chain payments; for an off-chain order it is the channel kind (alipay / wechat / …) and `payUrl` is the rendered payment link the payer should open (omitted only when the channel has no rendered link). An expired pending row is reported as `expired` here without being written."
          },
          "429": {
            "description": "rate_limited — per-credential read budget exhausted (Retry-After header)."
          }
        }
      }
    },
    "/v1/orders/{reference}/confirm": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Confirm from a transaction hash (server re-verifies receipt, transfer, recipient, amount and depth).",
        "description": "Works with a merchant key or without one. With `Authorization: Bearer aipay_sk_…` the merchant (or its watcher SDK) reports a hash. Without a header the payer's own browser attests one: the page carries the chain, token, recipient and amount, watches the chain with a public RPC and reports the candidate once. It is an attestation, never a confirmation — the server runs the same verification and decides, the response is the payer-safe subset plus `verification.attestedBy: \"payer\"`, and an unknown reference is a 404 before any RPC call is paid for. The `confirm` budget is 120 requests per minute, keyed by credential or by caller IP, answering 429 + `Retry-After`. 202 means seen but not deep enough. Automatic reports settle only open orders for exact, attributable payments. A 409 payment_attribution_review holds settlement and queues no confirmation. An authenticated merchant may send reviewed:true to settle an unambiguous late or oversized transfer. A successful late confirmation carries `verification.late: true` and `verification.previousStatus` with a `confirmed_late` event.",
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "txHash"
                ],
                "properties": {
                  "txHash": {
                    "type": "string"
                  },
                  "reviewed": {
                    "type": "boolean",
                    "description": "Optional merchant-only review for a late or oversized payment. Still requires unambiguous attribution."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Confirmed."
          },
          "202": {
            "description": "insufficient_confirmations — keep polling."
          },
          "409": {
            "description": "order_conflict / transaction_mismatch / channel_mismatch / order_not_pending / payment_attribution_review"
          },
          "429": {
            "description": "rate_limited — the per-credential or per-IP confirm budget (120/min) is spent; retry after `Retry-After`."
          }
        },
        "security": [
          {},
          {
            "merchantKey": []
          }
        ]
      }
    },
    "/v1/orders/{reference}/cancel": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Cancel a pending order (idempotent). Emits order.cancelled.",
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Cancelled."
          },
          "409": {
            "description": "A confirmed payment cannot be cancelled."
          }
        }
      }
    },
    "/v1/channels": {
      "get": {
        "tags": [
          "channels"
        ],
        "summary": "List off-chain channels (max 8).",
        "responses": {
          "200": {
            "description": "Channels."
          }
        }
      },
      "post": {
        "tags": [
          "channels"
        ],
        "summary": "Register a channel you already own (alipay / wechat / unionpay / stripe / other).",
        "description": "Stores a label, a payUrl and a settlement currency — no provider credential, ever. Money never reaches AIPAY. Requires a merchant API key first (the app's Channels card is inert until Cloud orders is on). Constraints: at most **8 channels per merchant** (429 rate_limited), `settleCurrency` is a **3–5 letter uppercase code** (e.g. CNY / USDT), and `payUrlTemplate` must be `https` (public host, no IP literal) and must contain `{reference}` — `{amount}` / `{currency}` are optional. A static QR link with no placeholder cannot work: AIPAY cannot tell one payment from another. New channels start `pending` and cannot be enabled until `POST /v1/channels/{channelId}/verify` records `verified`.",
        "responses": {
          "201": {
            "description": "Channel created."
          }
        }
      }
    },
    "/v1/channels/{channelId}": {
      "patch": {
        "tags": [
          "channels"
        ],
        "summary": "Edit, enable or disable a channel.",
        "parameters": [
          {
            "name": "channelId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated."
          }
        }
      },
      "delete": {
        "tags": [
          "channels"
        ],
        "summary": "Delete a channel.",
        "parameters": [
          {
            "name": "channelId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted."
          }
        }
      }
    },
    "/v1/channels/{channelId}/secret": {
      "post": {
        "tags": [
          "channels"
        ],
        "summary": "Issue (or replace) the channel HMAC secret used by POST /v1/offchain/confirmations.",
        "description": "The secret is returned **once** and cannot be retrieved later; issuing another replaces it immediately and the old one stops working (store it before you respond). Signing rule: `X-AIPAY-Channel-Signature: sha256=<hex HMAC-SHA256(secret, \"<timestamp>.<raw body>\")>` with `X-AIPAY-Channel-Timestamp` in unix seconds, accepted within ±5 minutes.",
        "parameters": [
          {
            "name": "channelId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "`{ channelId, channelSecret, endpoint, signature: { algorithm, header, timestampHeader, headerValue, signedPayload, windowSeconds }, channel, warnings[] }`."
          },
          "404": {
            "description": "channel_not_found"
          }
        }
      },
      "delete": {
        "tags": [
          "channels"
        ],
        "summary": "Revoke the channel HMAC secret; signed confirmations stop being accepted.",
        "parameters": [
          {
            "name": "channelId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "`{ channelId, revoked, channel }`."
          },
          "404": {
            "description": "channel_not_found"
          }
        }
      }
    },
    "/v1/channels/{channelId}/verify": {
      "post": {
        "tags": [
          "channels"
        ],
        "summary": "Reachability probe only (it does not prove the link can be paid).",
        "parameters": [
          {
            "name": "channelId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Verified."
          }
        }
      }
    },
    "/v1/orders/{reference}/offchain-confirm": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Confirm an off-chain order with the merchant's own receipt reference.",
        "description": "confirmed_source becomes `merchant_manual`; the order is not chain evidence. `channelId` is required (and must be the order's channel when it was created for one) and `channelRef` (the receipt/serial, 3–120 chars) is required — a confirmation without a receipt is refused. `amount`, when sent, must cover the order. An expired or cancelled order still confirms: the response carries `late: true` and `previousStatus`, and `order_events` gets `confirmed_late`. A different receipt on an already-confirmed order is 409 with `conflict: true` (nothing is overwritten); the same receipt is idempotent.",
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "channelId",
                  "channelRef"
                ],
                "properties": {
                  "channelId": {
                    "type": "string",
                    "description": "`ch_…` channel the order was sold on."
                  },
                  "channelRef": {
                    "type": "string",
                    "minLength": 3,
                    "maxLength": 120,
                    "description": "The provider's receipt/serial number — what makes this auditable."
                  },
                  "amount": {
                    "type": "string",
                    "description": "Optional. When present it must be at least the order amount (receipt_amount_too_low otherwise)."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Confirmed by receipt.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Confirmation"
                }
              }
            }
          },
          "400": {
            "description": "validation_failed / receipt_amount_too_low"
          },
          "409": {
            "description": "channel_mismatch / order_conflict (already confirmed by a different receipt → `conflict: true`)"
          }
        }
      }
    },
    "/v1/offchain/confirmations": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Channel-HMAC signed receipt: confirm an off-chain order from the merchant's own payment system.",
        "description": "No API key travel through your payment system: authentication is HMAC only, per channel (`POST /v1/channels/{channelId}/secret`). The signature is verified **before** any order lookup, so a bad signature and an unknown channel answer identically (401 unauthorized) and an unauthenticated caller cannot discover references. `confirmed_source` becomes `merchant_webhook`; the signature proves who sent the receipt, not that the money moved. `amount`, when present, must cover the order; `currency`, when present, must equal the channel's `settleCurrency` (receipt_currency_mismatch otherwise). An expired or cancelled order still confirms: the response carries `late: true` and `previousStatus`, and `order_events` gets `confirmed_late`. Timestamps outside ±5 minutes are 401 receipt_replayed.",
        "security": [],
        "parameters": [
          {
            "name": "X-AIPAY-Channel-Signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "example": "sha256=<hex>"
            },
            "description": "`sha256=` + hex HMAC-SHA256(secret, \"<timestamp>.<raw body>\")."
          },
          {
            "name": "X-AIPAY-Channel-Timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "example": "1794037900"
            },
            "description": "Unix **seconds**; must be within ±300 s of the server clock."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "channelId",
                  "reference",
                  "channelRef"
                ],
                "properties": {
                  "channelId": {
                    "type": "string",
                    "description": "`ch_…` channel whose secret signed this body. It must be the order's channel."
                  },
                  "reference": {
                    "type": "string",
                    "description": "AIPAY order reference (`ap_…`)."
                  },
                  "channelRef": {
                    "type": "string",
                    "minLength": 3,
                    "maxLength": 120,
                    "description": "The provider's receipt/serial number."
                  },
                  "amount": {
                    "type": "string",
                    "description": "Optional. Must be at least the order amount when sent."
                  },
                  "currency": {
                    "type": "string",
                    "description": "Optional. Must equal the channel's settleCurrency (case-insensitive: it is uppercased)."
                  },
                  "paidAt": {
                    "type": "integer",
                    "description": "Optional, unix **milliseconds**. Rejected if further in the future than the signature window."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Confirmed by receipt.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Confirmation"
                }
              }
            }
          },
          "400": {
            "description": "validation_failed / receipt_amount_too_low / receipt_currency_mismatch"
          },
          "401": {
            "description": "unauthorized (bad signature, unknown channel, no secret issued) / receipt_replayed"
          },
          "404": {
            "description": "not_found (unknown reference, or not this channel's merchant)"
          },
          "409": {
            "description": "channel_mismatch (on-chain order, or a different channel than the order's)"
          }
        }
      }
    },
    "/v1/offchain/statements": {
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "List imported statement rows and their match state (all channels of this merchant).",
        "description": "Filters by `status` and `limit` only; `channelId` is not a filter on this route (the import pins the channel). For a per-channel view, match `candidates[].channelId` in the response.",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "candidate",
                "adopted",
                "ignored"
              ]
            },
            "description": "Omit to list every state."
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 200,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "`{ candidates[], limit }`. Each row: `{ id, channelId, channelRef, amount, currency, paidAt, reference, match, note, status, adoptedReference, createdAt, updatedAt }`."
          },
          "429": {
            "description": "rate_limited — per-credential read budget exhausted (Retry-After header)."
          }
        }
      },
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Import a CSV statement (raw body, 2 MB / 10 000 rows) — proposes matches; confirms only what the merchant's own automation policy covers.",
        "description": "Body is the raw CSV (`channel_ref,amount,currency,paid_at,reference`; `text/csv` or `text/plain`). Matching is by `reference`, otherwise by a single pending order of the same amount within ±10 minutes of `paid_at`; ambiguity is reported, never guessed. Without a policy `confirmed` is `0` and every row must be adopted explicitly. With a policy (PATCH /v1/merchants/me/automation) the rows the policy covers are confirmed by the import itself: `autoAdopted` counts them, `autoAdoptSkipped` says why the others were not, and the receipt says `statement_auto` — a statement confirmation is not chain evidence.",
        "parameters": [
          {
            "name": "channelId",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "**Required** (`ch_…`): the channel the statement rows belong to, and the currency they are matched against."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "text/csv": {
              "schema": {
                "type": "string",
                "description": "Header: channel_ref,amount,currency,paid_at,reference. Max 2 MB / 10 000 rows."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "`{ channelId, rows, imported, duplicates, matched, confirmed, autoAdopted, autoAdoptSkipped[{ reason, count }], errors[], warnings[] }`. `confirmed` and `autoAdopted` are the number of rows this import confirmed by itself (0 without a policy). `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`. A skipped row stays a candidate: it can still be adopted by hand."
          },
          "400": {
            "description": "validation_failed (missing/invalid `channelId`, wrong content type)"
          },
          "404": {
            "description": "channel_not_found"
          },
          "413": {
            "description": "payload_too_large (over 2 MB)"
          }
        }
      }
    },
    "/v1/offchain/statements/{id}/adopt": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Adopt a statement row — this is the confirmation.",
        "description": "Runs the same confirmation path as a manual receipt; `confirmed_source` becomes `statement`. A row the import could not match needs an explicit `reference`. A late (expired/cancelled) order still confirms here: the response carries `late: true` and `previousStatus`, and `order_events` gets `confirmed_late`. The row is claimed before the order is confirmed and released again if the confirmation did not happen, so one statement row can never confirm two orders.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer"
            },
            "description": "Statement row id."
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "reference": {
                    "type": "string",
                    "description": "Required when the row was not matched: the `ap_…` order to confirm."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Confirmed.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Confirmation"
                }
              }
            }
          },
          "400": {
            "description": "validation_failed (row unmatched and no `reference` was passed)"
          },
          "404": {
            "description": "not_found (unknown row or order)"
          },
          "409": {
            "description": "statement_already_decided / channel_mismatch / order_conflict"
          }
        }
      }
    },
    "/v1/offchain/statements/{id}/ignore": {
      "post": {
        "tags": [
          "orders"
        ],
        "summary": "Ignore a statement row (no confirmation, no order change).",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "`{ id, status: \"ignored\" }`."
          },
          "404": {
            "description": "not_found"
          },
          "409": {
            "description": "statement_already_decided"
          }
        }
      }
    },
    "/v1/internal/read-limits": {
      "get": {
        "tags": [
          "discovery"
        ],
        "summary": "List per-credential read-budget overrides (operator secret).",
        "description": "Requires the operator secret, not a merchant key. Returns hashed keys only.",
        "security": [],
        "responses": {
          "200": {
            "description": "{ overrides: [...], maxMultiplier }"
          },
          "404": {
            "description": "Not configured / wrong secret (no oracle)."
          }
        }
      },
      "post": {
        "tags": [
          "discovery"
        ],
        "summary": "Raise one credential's read budget (operator secret).",
        "description": "Body: { apiKey | keyHash, multiplier (1..20), note? }. Applies immediately, affects only that credential.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "apiKey": {
                    "type": "string"
                  },
                  "keyHash": {
                    "type": "string"
                  },
                  "multiplier": {
                    "type": "number",
                    "minimum": 1,
                    "maximum": 20
                  },
                  "note": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "{ keyHash, multiplier, maxMultiplier }"
          },
          "400": {
            "description": "validation_failed"
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      },
      "delete": {
        "tags": [
          "discovery"
        ],
        "summary": "Clear an override (operator secret).",
        "security": [],
        "responses": {
          "200": {
            "description": "{ cleared: boolean }"
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      }
    },
    "/v1/internal/fees": {
      "get": {
        "tags": [
          "discovery"
        ],
        "summary": "List recorded merchant commission rates (operator secret).",
        "description": "Rates are recorded commercial terms, not charges: `collectable` is false while no settlement path can split a payment.",
        "security": [],
        "responses": {
          "200": {
            "description": "{ fees: [...], maxFeeBps, collectable }"
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      },
      "post": {
        "tags": [
          "discovery"
        ],
        "summary": "Record a commission rate for one merchant (operator secret).",
        "description": "Body: { merchantId, feeBps (0..500) }. Changing a rate never alters an order amount or a payer invoice.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "merchantId",
                  "feeBps"
                ],
                "properties": {
                  "merchantId": {
                    "type": "string"
                  },
                  "feeBps": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 500
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "{ merchantId, feeBps, source, collectable, note }"
          },
          "400": {
            "description": "validation_failed"
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      },
      "delete": {
        "tags": [
          "discovery"
        ],
        "summary": "Clear a recorded rate (back to zero commission).",
        "security": [],
        "responses": {
          "200": {
            "description": "{ cleared }"
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      }
    },
    "/v1/internal/platforms": {
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Operator-provision a platform and return its read-only key once.",
        "security": [
          {
            "operatorSecret": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name"
                ],
                "properties": {
                  "platformId": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Platform and one-time API key."
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      }
    },
    "/v1/internal/platforms/{id}/rotate": {
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Rotate a platform key. The previous key stops working immediately.",
        "security": [
          {
            "operatorSecret": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "New key."
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      }
    },
    "/v1/internal/platforms/{id}/disable": {
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Permanently disable a platform.",
        "security": [
          {
            "operatorSecret": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Disabled."
          },
          "404": {
            "description": "Not configured / wrong secret."
          }
        }
      }
    },
    "/v1/merchants/me/platforms": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "List platform grants for this merchant.",
        "responses": {
          "200": {
            "description": "Grant list."
          }
        }
      },
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Grant an active platform read access to this merchant's orders.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "platformId"
                ],
                "properties": {
                  "platformId": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Grant created."
          }
        }
      }
    },
    "/v1/merchants/me/platforms/{id}": {
      "delete": {
        "tags": [
          "platform"
        ],
        "summary": "Revoke a platform grant.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Grant revoked."
          },
          "404": {
            "description": "Grant not found."
          }
        }
      }
    },
    "/v1/platform/merchants": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "List the merchants that granted this platform read access.",
        "description": "Active grants only by default. `includeRevoked=1` returns revoked grants too, so a platform can reconcile a local copy with the full history. Pagination is a `merchantId` keyset; `nextCursor` is null at the end.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "includeRevoked",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "1",
                "true"
              ]
            }
          },
          {
            "name": "after",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "maximum": 100
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ merchants: [{ merchantId, shopName, grantedAt, revokedAt }], limit, nextCursor, collectable: false }. A revoked grant is a fact (revokedAt), not a deletion."
          },
          "400": {
            "description": "Invalid cursor, limit or includeRevoked value."
          },
          "401": {
            "description": "Unknown or disabled platform key."
          },
          "429": {
            "description": "Read budget exhausted; honor Retry-After."
          }
        }
      }
    },
    "/v1/platform/keys/rotate": {
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Rotate the platform's own API key.",
        "description": "The platform rotates itself, without the operator. The previous key stops working immediately (no grace window); the new key is returned exactly once, so persist it before the next request. A lost response is recovered by the operator, never by retrying with the old key.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ platform, apiKey, note }. apiKey is the new aipay_pk_ key, shown once."
          },
          "401": {
            "description": "Invalid, rotated-out or disabled platform key."
          },
          "409": {
            "description": "platform_changed: a concurrent rotation won; re-read and try again."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/platform/usage": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "This platform's own read budget and grant counts.",
        "description": "{ platform, budgets: { read, export, replay }, grants: { active, revoked }, ingressPerMinute, keyPrefix }. Each budget reports limit, used, remaining, windowSeconds and resetsAt for the current window; the snapshot includes this request, and `used` is null (not zero) when the shared counter is unavailable.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "Budget snapshot plus grant counts."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/merchants/claim": {
      "post": {
        "tags": [
          "merchants"
        ],
        "summary": "Redeem a platform invitation and become a merchant.",
        "description": "No API key: the one-time `aipay_inv_…` token is the authority. Creates the merchant, its API key (returned once) and the platform grant in one transaction. The platform never sees the merchant's key or its receiving address. Single use; the same token answers `409 invite_already_claimed`.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "token": {
                    "type": "string"
                  },
                  "shopName": {
                    "type": "string"
                  },
                  "recipientAddress": {
                    "type": "string"
                  },
                  "chainKey": {
                    "type": "string"
                  },
                  "webhookUrl": {
                    "type": "string"
                  },
                  "email": {
                    "type": "string"
                  },
                  "telegramChatId": {
                    "type": "string"
                  }
                },
                "required": [
                  "token",
                  "recipientAddress"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "{ merchant, apiKey, webhookSecret?, platform: { platformId, inviteId, granted }, warnings, docs }. apiKey is shown once."
          },
          "400": {
            "description": "Malformed token, or a recipient address for the wrong chain."
          },
          "404": {
            "description": "invite_not_found."
          },
          "409": {
            "description": "invite_already_claimed, invite_expired, invite_revoked, or merchant_exists."
          },
          "429": {
            "description": "Too many merchant signups from this IP today."
          }
        }
      }
    },
    "/v1/platform/merchants/invites": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "List this platform's invitations.",
        "description": "Newest first, `before` keyset. Status is derived: `pending`, `claimed`, `revoked`, or `expired`. A claimed invite reports `claimedMerchantId`, so a platform can reconcile without guessing.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "claimed",
                "revoked",
                "expired"
              ]
            }
          },
          {
            "name": "before",
            "in": "query",
            "schema": {
              "type": "integer"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "maximum": 100
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ invites: [{ inviteId, shopName, note, status, createdAt, expiresAt, claimedAt, claimedMerchantId, revokedAt }], limit, nextBefore }."
          },
          "400": {
            "description": "Invalid status, cursor or limit."
          },
          "401": {
            "description": "Invalid platform key."
          }
        }
      },
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Mint a one-time invitation for a merchant.",
        "description": "Returns the `aipay_inv_…` token exactly once. Hand it to the merchant; claiming creates the merchant (with its own key and receiving address) and grants this platform read access. Default TTL 7 days, maximum 30.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "shopName": {
                    "type": "string"
                  },
                  "note": {
                    "type": "string"
                  },
                  "ttlHours": {
                    "type": "number"
                  }
                },
                "required": [
                  "shopName"
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "{ invite, token, claim: { method, path, body, note } }. The token is shown once."
          },
          "400": {
            "description": "Invalid shop name or TTL."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/platform/merchants/invites/{id}": {
      "delete": {
        "tags": [
          "platform"
        ],
        "summary": "Revoke an unclaimed invitation.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ inviteId, revoked: true } (idempotent: alreadyRevoked on a second call)."
          },
          "404": {
            "description": "Not found in this platform's scope."
          },
          "409": {
            "description": "invite_claimed: the merchant already redeemed it; revoke the grant instead."
          },
          "401": {
            "description": "Invalid platform key."
          }
        }
      }
    },
    "/v1/platform/stats": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Daily figures for granted merchants: created vs confirmed, per asset.",
        "description": "UTC [from,to) window, maximum 92 days. created counts by creation day, confirmed by confirmation day. amounts sums invoices created in the window, including pending orders. confirmedAmounts groups by confirmation day, assetId, decimals, confirmedSource, amountEvidenceSource and amountEvidenceRegressed. Group totals separate dueAmountBaseUnits, observedAmountBaseUnits and confirmedAmountBaseUnits. Unknown amounts stay null. Asset identity is chain plus contract/mint/native marker, or off-chain currency. Each amount cohort has an independent 5,000-order cap; counts cover the window. Spends the export budget.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "from",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer"
            },
            "description": "Epoch ms, inclusive. Defaults to 7 days before `to`."
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer"
            },
            "description": "Epoch ms, exclusive. Defaults to now."
          },
          {
            "name": "merchantId",
            "in": "query",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ from, to, timezone: 'UTC', merchantId?, created: { totals, days }, confirmed: { total, days }, amounts, amountsTruncated, confirmedAmounts, confirmedAmountsTruncated, collectable: false }. Each amount array is null if truncated; evidence amounts within a group may also be null."
          },
          "400": {
            "description": "Invalid window (from >= to, > 92 days), merchantId or timestamps."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "429": {
            "description": "Export budget exhausted; honor Retry-After."
          }
        }
      }
    },
    "/v1/platform/orders": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Read minimal orders for merchants that granted this platform access.",
        "description": "Read-only platform key. Stable keyset pagination by createdAt and reference. Revoked grants are excluded in the same query.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "merchantId",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "maximum": 100
            }
          },
          {
            "name": "cursor",
            "in": "query",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ orders, limit, nextCursor, collectable: false }. Each order distinguishes recorded chain verification from off-chain merchant receipts using confirmedSource, and carries `anomalies` ([{ code, detectedAt }]) plus an order-level `action` (none | review | refund_from_merchant_wallet). Unresolved anomalies return review. refund_from_merchant_wallet is a reserved legacy value. AIPAY never executes refunds."
          },
          "400": {
            "description": "Invalid filter, limit or cursor."
          },
          "401": {
            "description": "Unknown or disabled platform key."
          },
          "429": {
            "description": "Read budget exhausted; honor Retry-After."
          }
        }
      }
    },
    "/v1/platform/orders/{reference}": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Read one authorized cloud order.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ order, collectable: false }. `order.anomalies` lists structured payment anomalies ([{ code, detectedAt }]) and `order.action` is the suggested human action; event details stay inside AIPAY."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "404": {
            "description": "Order unavailable in this platform's scope."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/platform/orders/changes": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Read the latest changed order snapshots in revision order.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "after",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 0
            }
          },
          {
            "name": "epoch",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 0
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ changes, epoch, nextAfter, hasMore, collectable: false }. Upsert by reference. Multiple updates can coalesce. Each change carries the same `anomalies` and `action` fields as the order list. Reconcile retained orders periodically for deletions."
          },
          "400": {
            "description": "Invalid checkpoint or limit."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "409": {
            "description": "platform_sync_reset. Rebuild the authorized snapshot without the old checkpoint."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/orders/{reference}/evidence": {
      "get": {
        "tags": [
          "orders"
        ],
        "summary": "One read-only response for finance/audit: order + timeline + notification attempts + what was verified.",
        "description": "`evidence.level` is `chain` only when the server re-read a transaction; an off-chain order reports `merchant_receipt` because the money never passed through AIPAY. Requires the owning merchant key (another key answers 404). Never mutates the order.",
        "parameters": [
          {
            "name": "reference",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ reference, status, order, evidence, timeline, notifications, notes }"
          },
          "401": {
            "description": "unauthorized"
          },
          "404": {
            "description": "not_found"
          }
        }
      }
    },
    "/v1/platform/webhook": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Read the platform webhook configuration (never the secret).",
        "security": [
          {
            "platformKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ webhook: { configured, url, secretSet, events, retry schedule } }."
          },
          "401": {
            "description": "Invalid platform key."
          }
        }
      },
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Set the webhook URL and issue a new signing secret (returned once).",
        "security": [
          {
            "platformKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "url"
                ],
                "properties": {
                  "url": {
                    "type": "string",
                    "description": "https endpoint that accepts a signed POST."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "{ webhook, secret }. Posting again rotates the secret and invalidates the previous one."
          },
          "400": {
            "description": "Invalid URL."
          },
          "401": {
            "description": "Invalid platform key."
          }
        }
      },
      "delete": {
        "tags": [
          "platform"
        ],
        "summary": "Remove the webhook and stop queueing deliveries.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ webhook: { configured: false } }."
          },
          "401": {
            "description": "Invalid platform key."
          }
        }
      }
    },
    "/v1/platform/deliveries/replay-failed": {
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Re-queue this platform's dead letters, oldest first.",
        "description": "Only `failed` deliveries are touched (a `sending` row holds its lease; a `sent` row is not resurrected). At most 25 per call; the sender delivers them in the next sweep, so per-order ordering is preserved and nothing is sent inside this request. Each delivery keeps its id.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "limit": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 25
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "{ replayed, limit, remainingFailed, nextSweep }."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/platform/deliveries": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Read the platform delivery log.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "pending",
                "sent",
                "failed",
                "disabled"
              ]
            }
          },
          {
            "name": "reference",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100
            }
          },
          {
            "name": "before",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ deliveries, limit, nextBefore }. Newest first."
          },
          "400": {
            "description": "Invalid filter."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "429": {
            "description": "Read budget exhausted."
          }
        }
      }
    },
    "/v1/platform/deliveries/{id}/replay": {
      "post": {
        "tags": [
          "platform"
        ],
        "summary": "Resend one recorded delivery now.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ delivery, outcome: sent|failed|pending|disabled }."
          },
          "404": {
            "description": "Unknown delivery."
          },
          "409": {
            "description": "delivery_in_flight — a sweep holds the lease."
          },
          "429": {
            "description": "Replay budget exhausted."
          }
        }
      }
    },
    "/v1/platform/orders/export.csv": {
      "get": {
        "tags": [
          "platform"
        ],
        "summary": "Reconciliation CSV for granted merchants.",
        "security": [
          {
            "platformKey": []
          }
        ],
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "merchantId",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "from",
            "in": "query",
            "schema": {
              "type": "integer"
            }
          },
          {
            "name": "to",
            "in": "query",
            "schema": {
              "type": "integer"
            }
          },
          {
            "name": "confirmedFrom",
            "in": "query",
            "schema": {
              "type": "integer"
            }
          },
          {
            "name": "confirmedTo",
            "in": "query",
            "schema": {
              "type": "integer"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "maximum": 5000
            }
          },
          {
            "name": "cursor",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "URL-encoded X-AIPAY-Next-Cursor from the preceding CSV page. Omit for the first page."
          }
        ],
        "responses": {
          "200": {
            "description": "CSV. Row count in X-AIPAY-Rows; X-AIPAY-Truncated when 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 (semicolon-separated codes), action, asset_id, due_amount_base_units, observed_amount_base_units, confirmed_amount_base_units, amount_evidence_source, amount_evidence_regressed. X-AIPAY-Next-Cursor is present when another page exists; an empty evidence cell means unknown."
          },
          "400": {
            "description": "Invalid filter."
          },
          "401": {
            "description": "Invalid platform key."
          },
          "429": {
            "description": "Export budget exhausted."
          }
        },
        "description": "Inclusive epoch millisecond filters. Keep filters fixed and follow X-AIPAY-Next-Cursor as cursor until absent. Rows are ordered by (createdAt, reference) ascending. Pages are live."
      }
    }
  },
  "components": {
    "securitySchemes": {
      "merchantKey": {
        "type": "http",
        "scheme": "bearer",
        "description": "Merchant API key returned once by POST /v1/merchants (`aipay_sk_…`). Only its SHA-256 is stored. Rotate with POST /v1/merchants/me/keys/rotate."
      },
      "platformKey": {
        "type": "http",
        "scheme": "bearer",
        "description": "Read-only platform key returned once by operator provisioning (`aipay_pk_…`)."
      },
      "operatorSecret": {
        "type": "http",
        "scheme": "bearer",
        "description": "Independent platform administration credential (PLATFORM_OPERATOR_SECRET)."
      }
    },
    "schemas": {
      "Order": {
        "type": "object",
        "properties": {
          "reference": {
            "type": "string",
            "description": "Stable order id; store it next to your own."
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "confirmed",
              "expired",
              "cancelled"
            ]
          },
          "chainKey": {
            "type": "string"
          },
          "asset": {
            "type": "string"
          },
          "amount": {
            "type": "string"
          },
          "amountBaseUnits": {
            "type": "string"
          },
          "recipient": {
            "type": "string",
            "description": "Snapshot of the merchant address at creation time."
          },
          "checkoutUrl": {
            "type": "string",
            "description": "Hosted payer page; no account needed."
          },
          "txHash": {
            "type": [
              "string",
              "null"
            ]
          },
          "blockNumber": {
            "type": [
              "integer",
              "null"
            ]
          },
          "confirmations": {
            "type": [
              "integer",
              "null"
            ]
          },
          "expiresAt": {
            "type": "integer"
          },
          "merchantOrderId": {
            "type": [
              "string",
              "null"
            ]
          },
          "channel": {
            "type": "string",
            "description": "`onchain`, or the off-chain channel kind (alipay / wechat / unionpay / stripe / other)."
          },
          "payUrl": {
            "type": "string",
            "description": "Present on off-chain orders: the merchant's payment link, rendered for this order."
          },
          "confirmedSource": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "chain",
              "merchant_manual",
              "merchant_webhook",
              "statement",
              null
            ],
            "description": "How the payment was confirmed. Chain-verified is `chain` (never `onchain`); `merchant_manual`, `merchant_webhook` and `statement` are the merchant's own receipt. The field is set on off-chain orders (and in the CSV `confirmed_source` column for on-chain rows)."
          }
        }
      },
      "OrderEnvelope": {
        "type": "object",
        "properties": {
          "order": {
            "$ref": "#/components/schemas/Order"
          },
          "idempotent": {
            "type": "boolean"
          }
        }
      },
      "Confirmation": {
        "type": "object",
        "description": "Answer of every off-chain confirmation path (manual receipt, signed webhook, adopted statement row).",
        "required": [
          "order"
        ],
        "properties": {
          "order": {
            "$ref": "#/components/schemas/Order"
          },
          "warnings": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Says out loud that this is the merchant's receipt, not chain evidence."
          },
          "late": {
            "type": "boolean",
            "description": "Present (true) only when the order had expired or been cancelled and was confirmed from a receipt that arrived afterwards."
          },
          "previousStatus": {
            "type": "string",
            "enum": [
              "expired",
              "cancelled"
            ],
            "description": "The closed status the order had before the late confirmation."
          },
          "idempotent": {
            "type": "boolean",
            "description": "True when the same receipt was replayed on an already-confirmed order."
          },
          "conflict": {
            "type": "boolean",
            "description": "409 only: a different receipt arrived for an already-confirmed order; nothing was overwritten."
          },
          "message": {
            "type": "string",
            "description": "409 only: human-readable explanation."
          }
        }
      },
      "WebhookHeaders": {
        "type": "object",
        "description": "Every delivery carries these. Verify sha256=HMAC-SHA256(secret, \"<X-AIPAY-Timestamp>.<raw body>\") and reject timestamps older than 5 minutes.",
        "properties": {
          "X-AIPAY-Signature": {
            "type": "string"
          },
          "X-AIPAY-Timestamp": {
            "type": "string"
          },
          "X-AIPAY-Event": {
            "type": "string",
            "enum": [
              "order.confirmed",
              "order.expired",
              "order.cancelled"
            ]
          },
          "X-AIPAY-Delivery": {
            "type": "string"
          },
          "X-AIPAY-Attempt": {
            "type": "string"
          }
        }
      }
    }
  }
}
