Refunds

Refunds are a core APay capability shared by all themes. A unique refunds.order_id locks each order to one stable refund ID. The amount, payment currency, original method and transaction are copied from the paid order; callers cannot supply amounts, recipients or gateway results. Only positive-value paid orders qualify. Partial refunds and automatic approval are not supported.

User APIs

Both endpoints require the authenticated owner of the order. Other users receive 404. A read-only orders token cannot submit refund applications.

  • GET /api/users/orders/:id/refund: { data: Refund | null }.
  • POST /api/users/orders/:id/refund: { "reason": "Reason for requesting a refund" } (1–500 characters). Creates a requested record; no money moves. Repeated submissions return the existing record. A rejected or failed record is retained, not replaced by another payment request.

Public fields: id, orderId, amount, currency, reason, status, reviewNote, createdAt, updatedAt, succeededAt. Dates are UTC ISO strings. Merchant configuration, provider errors and internal follow-up state are not returned to users.

The core user order-detail page includes the application/status panel. Themes with custom order pages can reuse OrderRefundPanel or these endpoints.

Administrator APIs

These paths use the existing orders:view / orders:edit permission boundary and administrator authentication.

EndpointPurpose
GET /api/admin/orders/refunds?status=requested&page=1&pageSize=20Paginated queue; omit status for all records. Maximum page size: 100.
GET /api/admin/orders/:id/refundRefund record, including provider ID, lastError, effectsStep, effectsError.
POST /api/admin/orders/:id/refundPerform one of the actions below. Returns { data: Refund }.
{ "action": "refund", "reason": "Administrator-approved full refund" }
  • refund: create a request if absent, then approve it. A reason is required when creating the record.
  • approve: approve an existing user request.
  • reject: reject a pending request; reason is required and becomes the public reviewNote.
  • reconcile: query an in-flight/uncertain gateway result or retry incomplete consequences after money was refunded. Never submits a second money request.

Approval with subscription collateral impact returns 409 with data.code = "SUBSCRIPTION_REFUND_IMPACT" and an impact description. After reviewing that impact, the administrator may repeat with confirmSubscriptionImpact: true.

PUT /api/admin/orders/:id no longer accepts payStatus: refunded. Paid orders cannot be closed by changing their payment status. Editing or manually fulfilling an order with an active refund is blocked. Orders with refund records cannot be permanently deleted. The administration order page exposes the queue and per-order actions.

Legacy orders already marked refunded without a refund ledger remain historical, unverified records. They are not automatically converted into proof of gateway repayment; reconcile them with merchant statements before importing verified evidence. No migration issues refunds or invents successful financial history.

State and recovery

requested → rejected or requested → processing → succeeded / failed / unknown.

  • processing is acceptance/processing, not proof that money was returned.
  • Transport errors, malformed responses and identity/amount/currency mismatches produce unknown. Reconciliation queries the original gateway only; it never switches payment channels or resends the refund.
  • A confirmed gateway failure is retained for manual review. There is no automatic reset or redispatch, including after provider idempotency retention expires.
  • Only confirmed full refunds set the order to refunded. Authenticated, order-bound full-refund callbacks also enter the same ledger, including refunds initiated in the merchant portal. Missing or partial amounts and mismatching original transaction IDs are rejected.
  • Original configuration/script fingerprints are pinned at dispatch. Changing them blocks reconciliation until the original configuration is restored. Credential rotation for unresolved refunds requires an explicit operational review.

Consequences are independent, retryable bits in effectsStep: 1 order state, 2 commission cancellation, 4 subscription revocation, 8 credited-wallet recovery, 16 notification, and v2 32 extension-asset recovery (63 means all completed). V1 bits keep their meanings. A historical 31 record only gains the new asset phase; successful money transfers, wallet steps and notifications are not replayed. Missing historical ownership/credit evidence remains pending review. A wallet shortfall or uncertain recovery remains visible in both ledgers; no negative balance is manufactured. Subscription delivery receipts are retained in subscription metadata. Previously issued keys and downloaded files cannot be recalled.

order.refund.assets is a required internal recovery hook when an extension owns the original asset. It runs independently of notifyUrl. A real new paid transition captures orders.metaData.apayRefundAssetPolicy (original owner and extension requirement); paid callback replays never invent a legacy policy. Extension issuance freezes orders.metaData.apayCreditReceipt before sending credit: operation ID, user/wallet identities, amount in 1e8 units and pool are immutable. Legacy recovery queries the authoritative original credit receipt, never today's product type or price. Receipt and notification writes update only their owned JSON paths, preserving concurrent metadata. Externally owned legacy relay carriers without local member/subscription assets may be attested by the authenticated receiver protocol; this is not a blanket assumption for other legacy orders.

For checkout relay orders with a dedicated notifyUrl, only signed minimal.checkout.refunded is delivered. A failed delivery never falls through to another channel. Other orders emit order.refunded with stable eventId = refund:<refundId>; refund flows wait for registered async handlers and configured webhook actions. Downstream consumers must deduplicate this ID because a success response may be lost. No distributed exactly-once delivery is claimed.

V2 notification payloads include refundEffectsVersion: 2. The old event remains compatible; the built-in legacy credit listener delegates for v1 callers and skips duplicate asset work for v2 notifications. An unavailable original owner or mandatory recovery handler is not treated as success.

Gateways and extension contract

Built-in adapters ship in the core bundle:

All create/callback/payment-query/refund operations resolve through server/payments/adapters.ts, preserving DB/file script priority and the explicitly named legacy payment-query config profile. Compiled provider protocols live under server/payments/providers/; old server/utils/refundProviders.ts and refundAlipay.ts are compatibility exports only. The v1 refund fingerprint projection/version is retained, so relocating source files does not strand unresolved refunds.

  • Stripe: captured PaymentIntent (or a Checkout Session linked to one), full amount, idempotency header, refund metadata and authoritative refund queries. Subscription invoice-only IDs are not accepted.
  • PayPal: stored Checkout order, one purchase unit/capture, full amount and stable PayPal-Request-Id / custom_id; queries recover the refund ID from the order when available. If PayPal cannot expose sufficient matching evidence, the record remains unknown for manual reconciliation.
  • Wechat Pay V3 domestic: CNY, original transaction, out_refund_no, signed requests and verified response signatures. Requires existing mchid, serialNo, privateKey, platformPublicKey, platformSerialNo configuration (snake_case aliases also accepted).
  • Alipay domestic OpenAPI (RSA2): CNY, the stored transaction/order and stable out_request_no. Signs alipay.trade.refund, then confirms this request through alipay.trade.fastpay.refund.query (REFUND_SUCCESS, per-request amount and original total). The cumulative refund_fee or HTTP success alone never proves this refund. Verifies the exact raw response bytes with alipayPublicKey (aliases supported); an absent success status stays unknown. The provider refund reference is Alipay's echoed out_request_no.

Other payment methods require both payments/<code>/refund.js and refund-query.js; they are explicitly unsupported without them. A single custom script does not activate refunds. Files must be included with the deployed payment plugin. Optional refund-capabilities.json declares required configuration (key, minimum length, optional HTTPS URL); requirements are checked before consuming the one-way dispatch claim.

Signed relay refunds (all source themes)

The external relay plugin now includes both refund scripts. A source administrator approves once; the receiving minimal site authenticates a separately authorized refund client and refunds its own original Wechat/Alipay transaction. It does not modify source-site entitlements or replace the stored notification URL.

Receiver endpoints: POST /api/minimal/checkout/refund (request/execute) and POST /api/minimal/checkout/refund-query (query only). Both accept the same strict body:

{"refundId":"rf_source_id","orderId":"relay_order_id_or_legacy_native_transaction","externalOrderId":"source_order_id","amount":10,"currency":"USD","reason":"Full refund"}

The receiver locates only source=minimal_checkout + external_order_id, requires the supplied reference to match that order's relay ID or original native transaction ID, verifies the source amount/currency snapshot and checks the stored notification origin against the refund client's authorized origins. Local-wallet/storefront/subscription carrier orders cannot use this delegation. The native refund always uses the stored settlement amount, for example CNY 70 for a source order of USD 10. Rejected or mismatching requests never send money.

Source payment-method private configuration must include new dedicated refundClientId, refundSecret (32+ characters), and checkoutBaseUrl (HTTPS). The checkout secret alone does not confer refund authority. Missing configuration returns 409 before dispatch and leaves the request awaiting review, so configuration can be corrected safely.

Configure receiver-only runtime environment (never public domains.env):

MINIMAL_CHECKOUT_REFUND_CLIENTS=[{"id":"source-site","secret":"<independent-random-secret-32+-characters>","origins":["https://source.example.com","https://source.example.net"]}]

Each source deployment gets its own client/secret and exact HTTPS origin allowlist. Register all legitimate locale domains. No registration means delegation is disabled (503), not anonymous access.

Headers: X-APay-Refund-Client, X-APay-Refund-Timestamp (13-digit milliseconds), X-APay-Refund-Signature (lowercase HMAC-SHA256 hex). Request canonical text is refund:v1\n<clientId>\n<timestamp>\nPOST\n<path>\n<SHA256(rawBody)>. Freshness tolerance is five minutes. Paths cannot carry query parameters. Responses are signed over refund-response:v1\n<clientId>\n<timestamp>\n<SHA256(requestRawBody)>\n<responseRawBody> with timestamp/signature response headers of the same names. The source verifies the exact response bytes and refund/order/amount/currency before trusting money success.

The receiver has its own unique refund record. Repeated requests query that record; they never create another native refund. Signed minimal.checkout.refunded notifications and signed query results converge on the source's same unique ledger. Notification failure is retained and retried on the receiver without switching notification channels. The plugin callback preserves a stored relay reference for new orders and safely accepts matching historical native references.

Deployment order: core migrations and receiver code → receiver private client registration → source core/plugin code and private credentials → merchant sandbox/small-value acceptance. Revert code only after reviewing unresolved records; do not remove the original credentials while a refund is unresolved.

Theme coverage

External service-credit recovery is distinct from payment money. The qingpu theme registers order.refund.assets and uses AINode GET /api/tenant/users/{userId}/credits/{originalOperationId} to recover authoritative legacy facts before POST .../{originalOperationId}/refund. Current catalogue classification is never used for recovery. New logic lives in the theme's server/credits/; old import paths remain thin re-exports. The gateway cancels unissued frozen plans or returns a durable recovery/shortfall receipt. A shortfall, invalid receipt, missing gateway version or unresolved cache delivery keeps follow-up incomplete; it cannot trigger another Wechat/Alipay refund. Deploy AINode before the source handler. Tenant prepaid-deposit accounting remains separate. Gateway protocol: ainode/docs/ai/tenant-credit-refunds.md.

ainode, qingpu and shopark custom detail pages embed OrderRefundPanel; the other ten installed themes use the core order-detail fallback. The core and official lists keep detail links available after refund, and billing/wallet pages can reuse OrderRefundsLink. npm run check:refund-themes resolves real host routes for every mounted theme, compiles its actual panel and tests that removing the panel fails the guard. No copied theme-specific refund engine is introduced.

The list guard also evaluates the actual core/official template conditions for paid, pending, failed, refunded and deleted orders. Refunded orders retain their detail links and use a refund-specific badge instead of “Completed”. Common Wechat/Alipay executable assets are versioned separately from private merchant configuration. Plugin-specific public names/icons come from payments/<code>/metadata.json (name, iconUrl or iconSvg), copied with the release assets; the host no longer statically imports ignored payment metadata source.

npm run check:refund-relay runs two real in-memory SQLite ledgers and both actual native adapters with RSA/HMAC fixtures: original settlement/source currency binding, legacy references, response loss, one dispatch, independent notification recovery and rejected credentials/origins/amounts. npm run check:refund-builds -- --themes minimal,shopark runs selected production builds serially using each theme's own public build configuration.

Custom scripts use the existing trusted-administrator payment host (not a security sandbox):

// payload.operation: 'refund' or 'query'
// payload.order: { id, amount, currency, tradeNo }
// payload.refund: { id, orderId, amount, currency, reason, providerRefundId }
return {
  status: 'succeeded', // pending | failed | unknown are also accepted
  refundId: payload.refund.id,
  orderId: payload.order.id,
  amount: payload.refund.amount,
  currency: payload.refund.currency,
  providerRefundId: verifiedGatewayRefund.id
}

Scripts must verify the original transaction, refund identity, currency, full amount and authoritative status before returning success. A successful response requires a genuine provider refund ID. Query scripts must only query and must never issue money transfers. Gateway errors should return unknown or throw; never fabricate a successful result. Existing callback scripts must authenticate and currency-bind gateway refund evidence before returning status: refunded.

Operations and verification

Node deployments automatically reconcile every minute through the existing core scheduler. Serverless deployments must schedule authenticated POST /api/cron/process-refunds with Authorization: Bearer <CRON_SECRET>; no secret means rejection. Database leases prevent concurrent dispatch/recovery workers; expired money-processing leases allow querying only.

Apply the appended three-dialect migrations using the normal migration runner before enabling these APIs. Never run against production as a test. Money already returned cannot be undone by reverting code; rollback retains the additive ledger/table and requires reviewing unresolved refunds. Do not restore an old database snapshot over completed gateway refunds without reconciling real transactions.

Run npm run check:refunds, the subscription/migration checks and the normal build. The refund suite uses real temporary SQLite and mock external providers, including real Wechat response-signature cryptography; it does not issue live refunds.

Protocol references: Stripe refunds, PayPal captured-payment refunds, Wechat refund application, Wechat refund query.