---
title: "Orders & Webhook API"
canonical_url: "https://ainode.run/docs/orders"
type: "doc"
locale: "en"
description: "Create orders and receive payment callbacks via API"
---

# Orders & Webhook API
> Create orders and receive payment callbacks via API

Although APayShop provides a complete frontend shopping flow, if you wish to silently create an order in your own third-party system, or need to receive status notifications of successful order payments, you can refer to the interfaces in this chapter.

## Create Guest Order

Allows you to initiate a purchase request directly through the interface without requiring the user to register.

`POST /api/orders/checkout`

### Request Body

```json
{
  "email": "customer@example.com",
  "locale": "zh-CN",
  "items": [{ "productId": 1, "productNum": 1 }],
  "metaData": {
    "server_ip": "192.168.1.1"
  }
}
```

### Parameters

| Field Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | array | Yes | One item containing `productId` and positive integer `productNum`. Multi-product checkout is not supported yet. |
| `email` | string | No | Customer email. The signed-in account email is used when omitted. |
| `locale` | string | No | Current storefront locale, such as `en`, `zh-CN`, or `ru`; used to resolve settlement currency. |
| `payMethod` | string | No | Preferred payment plugin code. It can be selected later when omitted. |
| `metaData` | object | No | Additional service-form data. Accounting and currency snapshot keys are server-controlled. |

### Response Example

The API returns the locked order amount and settlement currency. Payment initiation is a separate step.

```json
{
  "code": 0,
  "message": "Order created successfully",
  "data": {
    "id": "BA20260728123456ABCD1234",
    "amount": 72,
    "currency": "CNY",
    "isFreeOrder": false
  }
}
```

### Locale Currency Resolution

The global `currency` setting is the base and fallback currency. `locale_currency_bindings` binds locales to target currencies and rates. The rate convention is `1 base currency = rate target currency`; with base `USD`, `{ "currency": "CNY", "rate": 7.2 }` converts `10 USD` to `72 CNY`.

Resolution tries the full locale (`zh-cn`), then the language (`zh`), and finally the base currency at rate `1`. Checkout stores the locale, base amount, target currency, rate, and converted amount in `orders.metaData.currencySnapshot`, so later rate changes never alter existing orders.

`orders.amount` and `orders.currency` always store the converted amount and currency actually charged by the payment gateway. Internal accounting uses the locked `currencySnapshot.baseAmount` and `currencySnapshot.baseCurrency` instead. Subscription value, fulfillment/integration transactions, promotion commissions, and agent sales tiers therefore remain in one base currency even when buyers pay in different currencies. Legacy orders without a snapshot fall back to their original order amount and currency.

Payment plugins may declare `currency` (or compatible `sourceCurrency` / `priceCurrency`) in `configJson` or local `config.json`. A declared currency must match the order currency. Legacy plugins without a declaration remain currency-agnostic.

### Initiating Payment

`POST /api/payments/initiate` accepts `orderId`, `methodCode`, and an optional `locale`. The caller must have access to the order. Before executing the payment creation script, APay checks that the method is active, allows the resolved storefront language (`supportedLocales`; empty means unrestricted), and supports the order's locked currency. A language mismatch returns `{ code: 1, message: "Payment method is not available in current language" }` without creating a payment. Refunded and cancelled orders cannot initiate another payment.

`POST /api/payments/info` accepts `orderId` and an optional `locale` under the same order-access policy. Its `data.methods` entries contain only `code`, `name`, `iconUrl`, rendered `content`, and `recommendedByGeo` (used by the checkout UI to highlight geo-recommended gateways). Provider configuration objects and credentials are server-only; payment HTML template substitution uses a shared public-field allowlist, so credential keys such as `key`, `api_key`, `apiKey`, `checkoutSecret`, `vendorAuthCode`, `merchantControl`, and `hmacKey` are never interpolated into payment HTML.

---

## Payment Callback Sandbox Mechanism (Webhook Engine)

APayShop features an original **Dynamic Payment Routing and Webhook Engine**.

In order to avoid hardcoding the messy signature verification codes of dozens of payment gateways (such as Stripe, PayPal, Coinbase, WeChat Pay, etc.) in the main project, APayShop implements a Serverless-style callback mechanism:

1. The pure text `callback.js` code corresponding to the gateway is stored in the `payment_methods` database table.
2. When a third-party gateway sends a Webhook to our `/api/webhooks/[order_id]`.
3. The system extracts the `order_id` and queries the payment channel used by the order.
4. It fetches the corresponding `callback.js` and executes it with an `AsyncFunction` wrapper. These scripts are trusted administrator code, not an isolated security sandbox.

The callback payload includes `order: { id, amount, currency, tradeNo }` read from the stored order, alongside `urlOrderId`, `body`, `rawBody`, `query`, and `headers`. These order facts are not taken from the incoming callback body. Plugins that query the gateway must bind the remote transaction to these facts and verify its amount and currency; subscription activation alone is not proof of collected funds.

### Plugin Development Specification

If you need to write a new payment plugin yourself, your `callback.js` must return an object that complies with the following specifications so that the main system can help you update the order status and trigger automatic fulfillment:

```javascript
// Example of the required return object structure for callback.js:
return {
  isSignValid: true, // Whether the signature verification passed
  orderId: "ORD_123456", // Local order ID
  tradeNo: "ch_123abc", // Third-party gateway transaction number
  status: "paid", // paid, pending, failed, refunded, or cancelled
};
```

This design allows you to modify payment logic at any time through the web editor in the backend, achieving true hot-swapping of payment gateways!

Every callback, including retries for paid orders, must pass signature verification and return the same order ID as the URL. A verified `refunded` notification can update an already-paid order and invoke commission cancellation, subscription revocation, and top-up refund handling. Cancelling an unpaid renewal does not revoke its current subscription. Late failure notifications cannot overwrite paid, refunded, or cancelled orders, and cancellation cannot replace a refunded status. Payment retries use the shared idempotent payment handler and return the plugin's acknowledgement (`responseBody`, default `success`).

### Paid Order Event for Integrations

After the first successful fulfillment, APay emits one `order.paid` event through its existing event rules. The payload contains the order `id`, payment `amount` and `currency`, base-currency `accountingAmount` and `accountingCurrency`, trusted order `metaData`, and a `product` snapshot with its `type` and `metaData`. Consumers should use the accounting amount or the server-calculated `metaData.recharge_amount` for wallet credits; the payment amount may be in another currency. APay does not add a provider-specific transaction to this event. The receiving integration maps the order facts to its own ledger and deduplicates by order ID.

## Complete a Pending Free Order

`POST /api/orders/complete-free` accepts `{ "orderId": "ORDER_ID" }`. This core endpoint is available without the Minimal theme and uses the same order access policy as the payment page: an owner or guest payment-link holder may complete a free order; a signed-in user cannot complete another user's order. Normal session, delegated-session and email-verification gates still apply.

Only a finite amount of exactly zero and `payStatus: pending` can be claimed. Positive or negative amounts, cancelled, refunded and other unpaid states return 400; inaccessible or missing orders return 403 or 404. Concurrent or repeated requests do not repeat fulfillment or payment events. Already-paid free orders return `{ "code": 0, "data": { "id": "ORDER_ID", "isFreeOrder": true, "alreadyPaid": true } }`.

Ordinary APay orders use core fulfillment and `order.paid`; relay orders use relay fulfillment and their existing notification channel. A configured `notifyUrl` never falls back to a second channel after failure. No response includes delivery contents or customer details.

If fulfillment throws after the payment claim, the endpoint returns 503 and preserves the paid state. Administrators must inspect delivery before retrying; changing the payment back to pending could repeat external effects. New zero-price checkout already completes payment during order creation; this endpoint primarily repairs historical pending free orders.

## Administrator Top-up Record Management

The Orders → Top-ups panel supports page selection and single-record actions in the detail dialog. `GET /api/admin/topups` accepts `archive=current|archived|all` (default `current`), along with the existing `status`, `search`, `page` and `pageSize` filters. Both this list and `GET /api/admin/topups/{id}` return `archivedAt`, `archivedBy`, `archiveReason`, `productType` and server-calculated `managementActions`.

`POST /api/admin/topups/manage` requires an administrator session or administrator token with `orders:edit` permission:

```json
{ "action": "archive", "ids": [12, 13], "reason": "Verified payment and entitlement delivery against the original records" }
```

- `ids`: 1–50 positive integer record IDs; duplicates are processed once. `reason` is required, trimmed and limited to 500 characters.
- `close`: closes and archives an unpaid ledger record without cancelling the linked order or a gateway transaction. Paid, refunded, in-flight and inconsistent payment records cannot be closed. A later real payment can reopen a closed top-up and settle using its original idempotency key.
- `archive`: hides a checked `credited`, `refunded`, `closed` or `review_required` record while preserving its financial status and error evidence. Historical pending records for fulfilled non-topup products can also be archived. Pending real top-ups, in-flight credits/refunds and unresolved refund shortfalls cannot be archived.
- `restore`: restores visibility only; it does not reopen payment, change the financial state or credit money.

The response is `{ "code": 0, "data": { "results": [{ "id": 12, "orderId": "…", "outcome": "updated" }] } }`. Per-record outcomes are `updated`, `unchanged`, `skipped` or `failed`; skipped/failed records include a reason (`not_found`, `not_allowed`, `changed`, `failed`). State changes detected during an action are skipped instead of overwritten. The request's actor, action, reason and results enter the operation audit trail, including restore reasons and partial failures.

Archival is persisted server-side, so other administrator clients can reuse these APIs. Archived historical non-topup records leave the automatic retry queue; closed real top-ups remain eligible when a later payment is confirmed. New refunds restore visibility atomically; already-settled callback replays preserve intentional archival. No API in this workflow physically deletes ledger rows or changes wallet balances.

Deployment requires additive core migrations SQLite `0043_topup_archival`, PostgreSQL `0045_topup_archival`, MySQL `0039_topup_archival` before the new APIs serve traffic. They add nullable columns and leave historical data untouched. Regressions run with `node scripts/check-topup-ledger.mjs` against temporary SQLite fixtures. Roll back application code while retaining added columns; an application rollback after management actions needs the new handler's `closed`-state late-payment recovery, or operators must restore affected unpaid ledger rows to their previous status before allowing old settlement code to run. Restore visibility remains available in the new application.
