# PA API Integration Guide (SSBO V1)


PG `iconUrl` is optional and contains the HTTPS URL of the current default PG icon, maintained by PA operations. Requests require an application public key and current PA product codes; merchant-level key fallback and historical product aliases are no longer supported.

For merchant and SSBO developers integrating deposits, withdrawals, and transaction notifications from their servers. API base path: `/unipay/pa/v1`. Document date: 2026-11-14. V1 exposes confirmed terminal outcomes only; unconfirmed outcomes omit status. Available capabilities depend on the selected environment, account authorization, and current channel options.

PA submits transactions to payment gateways (PGs), queries their status, and notifies integrators. Integrators maintain their own business orders, user interface, event deduplication, and accounting. Create, query and synchronization responses omit `status` entirely while the outcome is unconfirmed; they do not return null, an empty string or an intermediate state. Once confirmed, only `SUCCEEDED` or `FAILED` is returned. Both callback modes send confirmed terminal outcomes only. Integrators must support an absent `status`; coordinate PA and consumer versions before deployment.

> A merchant's service countries and domains are descriptive profile information maintained by operations. They do not automatically change API authorization, PG payment services, or notification URLs. Query the available methods and provide a valid HTTPS Webhook URL.

Management dashboards, payment-method reports, and separate rebate permissions do not add SSBO endpoints or change the eleven business endpoints below. Management roles and API application scopes are separate. Dashboard totals do not replace individual order queries or notification signature verification; post business entries according to the final transaction status.

## Preparation and integration flow

For first-time integration, follow this sequence and consult the endpoint and field reference as needed:

1. Confirm the environment base path, merchant/application identity, scopes, egress IP and the two public-key roles using the preparation table below.
2. **Deploy the receiver before selecting the callback protocol.** New merchants default to [field signatures](#field-signature-mode-fields_rsa_v1), with a plain-text `SUCCESS` acknowledgment. The Java Demo HTTP receiver requires [standard events](#standard-event-mode-raw_body_v1), raw-byte verification and a JSON acknowledgment.
3. Query merchant capabilities and select the country, currency and precision. Query methods and candidate fields with the actual amount, then the relevant unified banks when needed. Persist your local order number, idempotency key and business facts before creating an order.
4. Submit an agreed test order, verify the response and order facts, display its payment medium and query the original order. Deduplicate notifications. Keep an unconfirmed original order without creating a replacement; see [integration acceptance](#java-example-and-integration-acceptance).

Obtain or confirm the following with PA. Except for the explicitly listed project domains below, merchant IDs, application IDs, payment methods, and channel options are placeholders.

| Information | Purpose |
|---|---|
| Test/production API gateway | Confirm the complete `baseUrl`, including any reverse-proxy prefix, against the onboarding information |
| `mchNo` and `appId` | Merchant and its API application identity |
| Your RSA public key | Register with PA so PA can verify your requests |
| Your RSA private key | Keep exclusively on your server; sign outgoing requests |
| PA platform public key | Verify its source, then use it to verify responses and Webhooks |
| API scopes, source IP allowlist, and rate limits | Enable the required scopes below and register your server's egress IP |
| Country, currency, payment methods, routes, and channels | PA enables these; query available options at runtime |
| HTTPS Webhook URL | Request `notifyUrl` takes precedence; omission or null uses an enabled default for the owning application |

Public key self-service is enabled by default for new and existing merchants; explicit operator disables are preserved. Merchant super administrators have dedicated key management permission by default; other roles require an explicit grant. When self-service is enabled, an authorized user can upload an RSA SPKI PUBLIC KEY PEM of at least 2048 bits under **API integration settings**, using their own authenticator code. Keep the private key on your server. The new key takes effect immediately; an existing application key may remain valid for a selected 0–10080 minute grace period, default 60. Initial application key registration does not retain the merchant-level fallback key. Disabling self-service does not revoke existing keys. Only operations can restore a revoked application. Merchant key changes do not change the platform key used to verify PA responses and Webhooks.

Send requests from your server. Never embed private keys in a browser, app package, or frontend source. Keep test and production configurations, keys, and order records separate. `clientIp` is the end user's IP; it does not replace the server source IP allowlist.

The API source IP allowlist controls integrator → PA requests. Operations separately configure PG → PA callback source allowlists by PG and environment. PA → integrator Webhooks use the destination saved on the order. Your order server and Webhook receiver can be different; receiving a Webhook does not require adding the receiver’s IP to the API request allowlist.

PA configures PG API credentials on the merchant's PG accounts. SSBO does not submit these credentials in transactions, and they are separate from the RSA keys above. PA operations must configure and enable accounts, map payment methods, activate applicable fee rules, and approve and publish merchant services. An API application or saved PG credentials alone are insufficient. Deposit and withdrawal permissions are separate.

PA operations maintain the global PG switch under Payment configuration → PG channel management, and merchant accounts under Merchant channel accounts. A loaded PG, a selectable management option, or an enabled account does not replace a current `/payment-methods` query. Disabling a PG prevents new transactions; continue querying existing orders and processing notifications. Do not create a replacement order merely because its channel disappears. SSBO submits neither PG switches nor credentials nor a merchant entity type.

Deposit flow: persist a local business order → query methods and amount rules → create a deposit → display the returned payment medium → receive notifications/query the order → confirm the final state and complete your business processing.

Withdrawal flow: persist a local order → query countries/currencies and withdrawal methods → query unified banks for the amount, method, and channel → collect recipient and dynamic fields → create a withdrawal → receive notifications/query the order → confirm the final state. If creation times out, retain and query the original order.

### Where to obtain options and field values

Paths below are relative to the selected environment's `baseUrl`; queries also require signatures. Use current responses for your merchant, rather than full management dictionaries or the illustrative values in this guide.

| Selection or field | Source | How to use it |
|---|---|---|
| Country, currency, precision, and trade direction | `/merchant-capabilities`: `data.countries[].countryCode`, `currencies[].currency/decimalPlaces/tradeTypes` | Use `countries[]` for fiat and `cryptoAssets[]` for digital assets. Convert amounts using the returned precision; crypto networks come from `/payment-methods` |
| Deposit/withdrawal method | `/payment-methods` with `tradeType=DEPOSIT/WITHDRAWAL` respectively | Select an item with `available=true` from `data.methods[]`; submit its `code` as `paymentMethod`/`payoutMethod` |
| Display groups | `/payment-methods`: `data.groups[]` | Display the group and its `options[]`; submit the option code, never the group code |
| Channel and icon | Query `/payment-methods` with the actual `amount`; use the selected method's `channels[]` | Submit `channelOptionId` to designate a channel; `name/iconUrl` are for display. Follow `channelSelection`: automatic routing, player selection for deposits, or merchant operator selection for withdrawals |
| Amount ranges and fixed denominations | Selected method/channel rules in `/payment-methods`; deposits also have `/deposit/options` | Apply `amountRanges` or `denominations` according to `ruleType`; designated channels impose their own limits. Do not bridge gaps between ranges |
| Deposit bank | `/deposits/banks` with country, currency, `paymentMethod`, actual `amount`, `bankRole=PAYER/TARGET`, and optional channel | Submit the returned ID in `payer.bankId` for PAYER or top-level `targetBankId` for TARGET. PA maps provider values |
| Withdrawal recipient bank | `/withdrawals/banks` with the same country, currency and `payoutMethod`. Omit amount to choose a bank first; requery with actual `amount` to validate. Include `channelOptionId` if selected | Display `data.banks[].name`; submit the returned `bankId` string as `recipient.bankId`. Its `code` is a PA code, not a legacy PG `bankCode` |
| Required fields and request locations | `/payment-methods`: `requiredFields`, top-level `data.fieldDefinitions[]`, and channel `fieldDefinitions[]` | Match logical `code` to `requestPath`. A catalog does not make every field required; use the selected channel's requirements |
| Finite account/document types and other choices | Selected method's `channels[].fieldDefinitions[]` with `inputType=select` | Submit the selected `options[].value` string at `requestPath`; display its `label`. Choices belong to that channel: do not combine incompatible channels. The top-level catalog does not enumerate channel-specific choices |
| Names, accounts, phone, email, document ID, IFSC, and other actual details | Payer/recipient, validated by the integrator | Populate `payer`, `recipient`, or `paymentMethodFields` according to `requestPath`; these are not demo values obtained from a PA dictionary |
| Payer bank, target bank/wallet, wallet type, and other PG-specific values | Returned `select/options` when present; otherwise PA-confirmed integration information for that channel | Deposit banks are available from `/deposits/banks`; wallet fields remain channel-specific. `/withdrawals/banks` covers withdrawal banks only; non-bank wallet `providerCode` and `paynowType` still use current channel options |
| `mchNo/appId`, scopes, keys, notification URL | PA onboarding details, your server configuration, and enabled application notification defaults | Do not infer these from transaction options. Generate and persist your own business order number, idempotency key, and user ID |

Resolve dependencies in this order: environment → country/currency and direction → amount → method → designated channel, if any → bank/finite field choices. When an upstream condition changes, clear invalid selections and query again. Refresh labels when the language changes; never infer codes from names. Empty `countries`, `methods`, or `banks` means no match for that request. Stop that selection flow and ask PA to check authorization, enabled configuration, and mappings; do not use another merchant's or PG's list.

Queries reserve no quota and do not guarantee balance or execution. Refreshing selections prepares new orders. Once a creation request has been sent, retain its original parameters, order number, and idempotency key and query it first; do not retry an unknown-result order with newly selected values.

### Domains, endpoints, and callback URLs

The project is configured under `tktkpay.com`. These addresses have been checked against the project's Nginx configuration. Configuration alone does not prove deployment or acceptance; confirm the environment, certificate, and endpoint version during onboarding.

| Purpose | Address or requirement |
|---|---|
| Merchant portal | `https://tktkpay.com/merchant/` |
| API documentation | `https://tktkpay.com/docs/pa/`; English edition: `https://tktkpay.com/docs/pa/en/` |
| SSBO API `baseUrl` | `https://api.tktkpay.com/unipay/pa/v1` |
| Complete payment-method query URL | `https://api.tktkpay.com/unipay/pa/v1/payment-methods` |
| PG → PA callback base URL | `https://api.tktkpay.com/unipay/pa/v1/pg/callback`; configured by a PA administrator |
| PA → SSBO notification `notifyUrl` | Your HTTPS endpoint, for example `https://merchant.example/pa/webhook`; this is a placeholder, not a fixed endpoint on PA's domain |
| Browser `returnUrl` | Your order result page, separate from the server notification endpoint |

External API requests use the dedicated `api` subdomain and the full `/unipay/pa/v1` path. Do not add `/api` or duplicate the base path. The management and merchant UIs continue to use `/api` on the main domain. Confirm the base URL, application, keys, and Webhook registration separately for test and production. Do not infer the environment from the hostname. Call HTTPS directly without relying on redirects.

Select the PG environment through the base path. This is separate from deployment-level server or database isolation:

| Base path | PG environment | Allowed operations |
|---|---|---|
| `/unipay/pa/v1` or `/unipay/pa/v1/production` | PRODUCTION (default) | All eleven business endpoints |
| `/unipay/pa/v1/sandbox` | SANDBOX | All eleven business endpoints |
| `/unipay/pa/v1/all` | All environments | Complete merchant support, merchant capabilities, methods/channels, deposit amount options, unified banks, deposit queries, withdrawal queries |

`all` rejects deposit creation, withdrawal creation, and `/trades/sync` with `1001`. Environment path values are case-sensitive: use lowercase `production`, `sandbox`, or `all`. Invalid values return `1001`. Example: `https://api.tktkpay.com/unipay/pa/v1/sandbox/payment-methods`.

New orders retain their creation environment. Automatic routing, explicit channel selection, recovery, and later channel switching respect that snapshot. A channel from another environment returns `3006`; no available account in the selected environment returns `3001`. Reusing an idempotency key in another environment returns `2001`; the uniqueness boundary for merchant order numbers does not change. Query and synchronize using the creation environment; a mismatch returns `4001`. Use `all` only for cross-environment reads.

Historical orders without an environment snapshot retain NULL and their existing query/recovery behavior; the new path filter does not apply to them. Do not infer historical facts from an account's currently editable environment. PG account gateways, credentials, and callback settings remain independently configured. After changing the selected environment, refresh countries, currencies, and channels. Never use an environment change or a new order number to retry an unknown transaction.

`SANDBOX` is a PA account classification and does not guarantee a separate PG test system. When an adapter declares a production gateway but no sandbox gateway, it uses the production address as the sandbox default. An explicitly declared sandbox gateway takes precedence. PA must verify the actual gateway, credentials, and permitted testing scope; `/sandbox` alone does not guarantee that no real transaction can occur.

RSA signatures cover the JSON body, not the URL path. HTTPS protects the path; pin and validate the intended `baseUrl` and prevent intermediary path rewriting. The legacy `environment` field on the three discovery/option queries is deprecated: omit it and use the path. If supplied, it remains part of the signature and must match the path, or PA returns `1001`. Older clients that selected SANDBOX/ALL in the body must use the corresponding base path.

The notification directions are independent:

```text
PG → PA callback → PA verifies and updates the transaction
PA → SSBO notifyUrl → SSBO verifies and updates its business order
Payer's browser → returnUrl → display a result, then confirm the status on the server
```

Deploy a publicly reachable HTTPS Webhook receiver. An explicit `notifyUrl` in a deposit/withdrawal create request takes precedence and need not match a backend default. Omission or null uses an enabled default belonging to the application; withdrawals use their separate default when present, otherwise the deposit default. If neither source provides a URL, PA returns `1001` with “notifyUrl: 缺少回调地址，请传 notifyUrl 或配置后台默认地址” (provide notifyUrl or configure a backend default). An explicit empty string or invalid URL also returns `1001` without fallback. Implement verification, deduplication, and acknowledgment for the selected mode as described below. Do not use a LAN IP, localhost, management page, or PG payment page.

An authorized PA administrator maintains the PG callback base URL under System management → Platform configuration → PG public callback URL, with secondary verification. Technical staff manage the public domain, HTTPS, and reverse proxy. New requests use the saved URL dynamically; PA generates account and deposit/withdrawal suffixes. Old callback endpoints must remain available for historical orders. Merchants and SSBO do not submit this configuration. Do not enter your own `notifyUrl` in a PG merchant portal. Opening a payment page, registering a callback URL, or returning through the browser does not prove payment or callback acceptance.

Management fee and rebate configuration does not change SSBO endpoints, signatures, or amount units. Rules saved directly by an authorized operator or approved through draft review must also be within their effective period. Visibility or APPROVED status alone does not prove a usable transaction fee policy. For `FEE_POLICY_UNAVAILABLE`, ask PA to check the merchant, PG, transaction direction, method, and effective/expiry times. Do not bypass the error by repeatedly creating orders. Current fee rules are not configured separately by currency; fee amounts use the order's currency and minor unit.

### Obtain the PA platform public key

The version with separate login and payment keys provides this key-distribution endpoint, independently of the eleven signed business endpoints below:

```http
GET https://api.tktkpay.com/unipay/pa/v1/public-key
```

Example call (no business signature required):

```bash
curl --fail-with-body --proto '=https' \
  'https://api.tktkpay.com/unipay/pa/v1/public-key'
```

No login, merchant number, application ID or request signature is required. A successful response is HTTP 200 with JSON `code=0` and `data` containing the RSA public key as a `BEGIN PUBLIC KEY` PEM string. The response includes `Cache-Control: no-store`. Example:

```json
{
  "code": 0,
  "data": "-----BEGIN PUBLIC KEY-----\n<REPLACE_WITH_PA_PUBLIC_KEY_BASE64>\n-----END PUBLIC KEY-----",
  "message": "success"
}
```

This is the complete key-distribution response; the PEM content is a placeholder. It uses `message`, rather than the business endpoints' `msg`, and has no reqId/resTime/retryable/sign.

Fetch and retain the key only after confirming the gateway domain and its HTTPS certificate. For initial onboarding, PA administrators can supply the key and confirm its fingerprint through an established channel. For deployments not yet upgraded, ask PA administrators to confirm and provide the current payment-signing public key. Public-key access does not grant business API permissions.

Merchants in the same PA deployment share its verification key. The `production`, `sandbox` and `all` base-path aliases also support `/public-key`; they select PG business scope and do not select different platform keys. Separate deployments or payment-key rotation may use different keys. Each merchant must generate an independent request key pair and retain its private key on its own server.

`/api/token/public-key` distributes the backend login-password encryption key. After key separation, it must not be used to verify payment responses or Webhooks. Update trusted payment keys through PA's confirmed rotation procedure. Never automatically fetch and trust a replacement key after a signature failure, or skip verification. After verification, also match the merchant, request/order, amount and currency, and handle duplicate events using event IDs and sequences.

## Common protocol and signatures

All eleven signed business endpoints use `POST`, `Content-Type: application/json`, and UTF-8 JSON. Append the endpoint path to the confirmed `baseUrl`. Authentication uses the RSA signature in JSON; no merchant portal login cookie is required.

Amounts are exact positive integers in the currency's smallest unit for both fiat and crypto, without Java `long` capacity limits. THB `10000` means THB 100.00; use the precision returned by capabilities for other currencies. Contract revision `1.1.0` retains `/v1` and accepts JSON integers or plain decimal integer strings. Business API responses keep numeric amounts within JavaScript's safe integer range and use strings for larger amounts. Submit large amounts as strings and use arbitrary precision integers or exact decimals; never use binary floating point, fractional minor units or scientific notation. `RAW_BODY_V1` callbacks retain exact JSON integers and raw-byte signatures; read large numeric values with a lossless parser. Integer inputs have a 1000-digit parsing budget; PG capabilities, merchant grants and configured limits still apply.

### Currency codes

`Currency` is a fiat or digital-asset code actually returned by `/merchant-capabilities` for the required direction, matching `^[A-Z][A-Z0-9]{1,15}$`. Fiat codes usually follow ISO 4217; do not restrict every currency to three letters or treat a syntactically valid code as enabled. Digital-asset orders use the asset amount directly, without fiat conversion. Read its precision from `decimalPlaces` just as for fiat currencies.

### Amount units and conversion responsibilities

Fiat markets and global digital assets have separate capability lists. Currency codes contain 2–16 uppercase letters or digits, starting with a letter; use only codes and precision returned by merchant capabilities. Crypto orders use the asset amount directly, without converting MYR or other fiat currencies. For example, with USDT `decimalPlaces=6`, send `amount=1250000` for 1.25 USDT. Asset precision is immutable. Select the configured payment method/channel for the intended network; do not infer a network from the currency symbol.

CCPayment initially supports order deposits and network payouts, confirmed through authenticated original-order queries. TETH deposits and withdrawals on Sepolia have been verified, including receipt in the destination wallet. The connector confirms transactions through authenticated queries. Provider callback parsing, other networks, and production funds acceptance remain pending. Use `recipient.account` for the payout address and `paymentMethodFields.memo` for a memo/tag when required by discovery; recipient name remains required, while digital asset withdrawals may omit country. Partial, excess, late or risky payments do not automatically count as an exact successful deposit. Query the original order after unknown acceptance; never resend a payout.

Merchants request authorization by asset, payment method and direction. A grant covers the account’s current and future eligible platform networks. Account eligibility, direction, network availability and limits still apply. Query `/payment-methods` with the actual amount; select from the chosen channel's `fieldDefinitions` entry with `code=network`, then send the selected option value as `paymentMethodFields.network`, for example `{"network":"TRX"}`, on both deposits and withdrawals. Each `amountRules[]` entry retains its network-specific amount and field requirements. Recheck after changing currency, network, direction or amount. Crypto orders require an explicit authorized network; missing, disabled, unauthorized or amount-incompatible choices are rejected without switching networks. The choice is included in the order snapshot and idempotency comparison. Keep the original order when submission is unknown. Withdrawal addresses and memos must match the selected network. Fiat hosted checkout does not use this field.


Explicitly enabled CCPayment fiat collection accounts accept the original fiat order amount and return a hosted checkout URL. Customers select merchant-enabled coins and networks there; SSBO callers do not supply a payment asset or network. Order amounts, limits, fees, query results and merchant success notifications retain the original fiat unit. These collection accounts expose no fiat asset balance or payouts. Query unknown submissions by their original order ID; never recreate them.

First query `/merchant-capabilities` and take `countries[].currencies[].decimalPlaces` for fiat, or `cryptoAssets[].decimalPlaces` for a digital asset, as `n`. It defines PA's minor-unit precision, not the number of decimal places to send in JSON. Business API fields `amount`, `minAmount`, `maxAmount`, and amount ranges all use this unit.

```text
Integer amount sent to PA = actual currency amount × 10^n
Actual currency amount for display = PA integer amount ÷ 10^n
```

| `decimalPlaces` | Actual currency amount | JSON field sent to PA |
|---|---|---|
| `0` | `100` | `"amount": 100` |
| `2` | `10.25` | `"amount": 1025` |
| `3` | `10.125` | `"amount": 10125` |

These examples illustrate conversion only; use the precision returned for the selected fiat currency or digital asset. For example, when THB returns `decimalPlaces=2`, send `1025` for THB 10.25. Do not multiply every currency by `100`. Use exact decimal or integer arithmetic. A converted order amount must be an exact positive integer; reject excess precision or configured-limit violations without silently rounding. If your system already stores minor-unit integers at the same precision, use them directly to avoid converting twice.

- **The integrator handles “actual business amount ↔ PA minor-unit integer”**: convert, validate, and display using the returned `decimalPlaces`.
- **PA handles “PA minor-unit integer ↔ third-party PG protocol amount”**: PA's adapters convert major/minor units and fixed decimal formats for PG order creation, queries, and callbacks according to each PG's protocol. Integrators do not need another multiplication/division by `100` for different PGs.

`decimalPlaces` does not mean every PG channel accepts arbitrary fractional amounts; follow the amount restrictions returned for the payment method. Process Webhook amount types and formats according to the notification protocol in this guide. `FIELDS_RSA_V1` uses fixed decimal text, so do not apply the business API's integer JSON format to it.

The nine amount-bearing business endpoints (amount options, payment methods, deposit/withdrawal banks, deposit/withdrawal creation and queries, and trade synchronization) return `data.decimalPlaces` for all amounts, ranges, denominations, and steps within that `data`. For example, `{"amount":1000,"currency":"THB","decimalPlaces":2}` means THB 10.00; `amount` remains an integer in minor units. Verify the response before using this precision for display; continue converting creation requests with precision from merchant capabilities. Older servers may omit the field: use only previously verified country/currency precision, or retain the original minor-unit value if unknown. Do not assume division by 100. The added field participates in the existing whole-response signature; the algorithm and request signature are unchanged.

### Common request fields

Include these fields at the same JSON level as each endpoint's business fields.

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `mchNo` | string | Yes | PA-assigned merchant number; maximum 32 characters |
| `appId` | string | Yes | Unique API application assigned to the merchant; must belong to it; maximum 32 |
| `reqId` | string | Yes | HTTP request identifier; generate a fresh value per request for correlation and diagnostics; maximum 64 |
| `nonceStr` | string | Yes | Fresh random value per transmission; a 32-character UUID without hyphens is recommended; maximum 32 |
| `reqTime` | string | Yes | ISO 8601 with timezone and second precision: `yyyy-MM-dd'T'HH:mm:ssXXX`, for example `2026-09-25T02:00:00Z`; no fractional milliseconds |
| `clientIp` | string | No; channel-dependent for creation | IP of the end user initiating the transaction; maximum 64. Nonblank values must be valid IPv4 or IPv6. Captured on first creation and not overwritten by idempotent replays; see usage and required conditions below |
| `sign` | string | Yes | unipay RSA signature described below; maximum 1024 |

Request-time validation and nonce retention are controlled by PA security configuration. When enabled without a valid configured duration, the fallback is 300 seconds; confirm actual values with PA. Synchronize server clocks. Each merchant has one application; every calling instance must generate non-repeating nonces across that application.

### End-user IP usage and validation

The integrator submits `clientIp` as a single end-user IP in the request. It is retained with the order and passed to the PG according to the channel protocol. Do not send an allowlist range, CIDR or multiple IPs. The API server egress IP allowlist controls request-source authorization separately; changing `clientIp` does not change that check.

The common API accepts a string of up to 64 characters and validates nonblank values as IPv4 or IPv6. Each PG may restrict supported IP types or impose further requirements. The field is optional at the common level; for order creation, inspect both method and channel `requiredFields` returned by `/payment-methods`. A nonblank value is required when `clientIp` is listed. When optional, omit it or send null; an empty string does not satisfy a required field.

If the integrator cannot obtain the actual end-user IP, use an available channel that does not require it, or confirm an acceptable arrangement for a channel that does. Do not assume a merchant server IP or allowlisted IP may substitute for the end-user IP. Passing format validation does not establish compliance with the PG's end-user IP requirement.

### Signing requests and verifying responses

Use `SHA256withRSA` (RSASSA-PKCS1-v1_5) and standard Base64, not Base64URL. RSA keys of at least 2048 bits are recommended. The Java example accepts PKCS#8 private key PEM (`BEGIN PRIVATE KEY`) and X.509 SubjectPublicKeyInfo public key PEM (`BEGIN PUBLIC KEY`).

1. Recursively flatten JSON. Use dotted object paths such as `payer.name` and indexed array paths such as `data.methods[0].code`.
2. Exclude root-level `sign` and all null values. Include empty strings, `false`, and `0`. Empty objects/arrays have no leaf entries.
3. Sort complete field paths in ascending lexicographic order. Join as `key=value&key=value` with no trailing `&`. Use decoded string contents, without JSON quotes, URL encoding, or additional trimming.
4. Sign the UTF-8 bytes with RSA-SHA256 and put the standard Base64 result in `sign`. Do not change fields afterward.

Flattening example only:

```json
{"payer":{"name":"Alice"},"amount":10000,"memo":"","enabled":false,"unused":null,"sign":"OMITTED"}
```

Canonical signing input:

```text
amount=10000&enabled=false&memo=&payer.name=Alice
```

`memo` and `enabled` above illustrate the algorithm; they are not business request fields. Use the agreed dynamic field names; do not invent names containing dots or brackets.

Verify responses using the same flattening rules and the **PA platform public key**. Include every leaf under `data`, including unfamiliar optional fields. After verification, check `reqId` correlation, order numbers, amount, currency, and business `code`. Your own public key cannot verify PA responses.

Non-200 HTTP responses, missing signatures, invalid JSON, failed verification, or mismatched correlation do not establish transaction success or definitive failure. After a creation request has been sent, treat these as an unknown outcome. Proxy error pages may not be PA business responses.

<a id="ten-business-endpoints"></a>

## Business endpoints

Paths below are relative to the selected environment's base path (default `/unipay/pa/v1`). Every endpoint requires common fields and a valid signature.

| Operation | POST path | Scope |
|---|---|---|
| Discover complete merchant support | `/merchant-support` | `deposit:options` |
| Discover merchant countries and currencies | `/merchant-capabilities` | `deposit:options` |
| Query payment methods | `/payment-methods` | `deposit:options`, including withdrawal method queries |
| Query unified deposit banks | `/deposits/banks` | `deposit:options` |
| Query unified withdrawal banks | `/withdrawals/banks` | `deposit:options` |
| Query deposit amount options | `/deposit/options` | `deposit:options` |
| Create a deposit | `/deposits` | `deposit:create` |
| Query a deposit | `/deposits/query` | `deposit:query` |
| Create a withdrawal | `/withdrawals` | `withdrawal:create` |
| Query a withdrawal | `/withdrawals/query` | `withdrawal:query` |
| Synchronize a transaction | `/trades/sync` | `trade:sync` |

Each endpoint section includes a complete JSON response with common fields and `data`. Arrays contain representative illustrative items; nested objects are not replaced by ellipses. Match `reqId` to the current request. Example signatures and business values cannot be used for live integration. Optional fields depend on the case: success does not require reasonCode/failureCode, and absent payment media need not be filled with paymentMedium=null. Also handle the [complete error examples](#complete-error-response-examples).

### Bank selection and mapping strategies

Display `banks[].name` and submit only the selected PA `bankId` string. Do not substitute a name, the unified `code`, or a raw PG code for that ID. Select a bank once per role: PAYER uses `payer.bankId`, TARGET uses `targetBankId`, and RECIPIENT uses `recipient.bankId`. PA supplies the PG bank code, name, and other mapped bank fields for that role. Merchants do not maintain separate bank tables for each PG; other required names, account details, and identity information still come from the integrator.

PA maintains one bank catalog, a separate PG bank catalog and explicit mappings between configured records by PG, currency and deposit/withdrawal. The mapping is shared across merchants and payment methods within that PG. Merchant groups and default-group fallback have been retired. A missing mapping or a disabled PA bank, PG bank or mapping is unavailable; old group/account bank codes are not used as a fallback. Account authorization, environment, product rules and bank limits still apply.

Merchants may set display aliases in Payment services → Bank display aliases. Only that merchant's `banks[].name` changes; `bankId` remains stable and is the only unified-bank input accepted for orders. Empty aliases restore the PA localized name. Alias updates do not affect bank availability or existing order fingerprints/snapshots. After an unknown creation result, query the original order and retain its parameters, order number and idempotency key.

### Unified deposit banks: POST /deposits/banks

Use the existing signed request and `deposit:options` scope. Required: `countryCode`, `currency`, `paymentMethod`, positive integer minor-unit `amount` and `bankRole` (`PAYER` for the payer bank, `TARGET` for the target receiving bank). Optional: `channelOptionId`, `locale`. Path environments work as for withdrawal bank queries.

```json
{"countryCode":"TH","currency":"THB","paymentMethod":"bank_transfer","bankRole":"PAYER","amount":10000,"locale":"en-US"}
```

The response `data` includes the selection dimensions and `banks[]`. Bank IDs, localized names and anonymous channels have the same shape as withdrawal banks, without PG codes or account IDs. Submit the actual returned string ID as `payer.bankId` for PAYER, or top-level `targetBankId` for TARGET. PA maps provider values and captures the exact attempt snapshot before dispatch.

Bank inputs accept PA IDs only: `payer.bankId`, top-level `targetBankId`, and `recipient.bankId`. Raw `payer.bankCode`, `recipient.bankCode`, `bankCodeScheme`, and bank code/name/branch fields or internal selectors in `paymentMethodFields` are rejected even without an ID. Both deposit roles may be selected when one actual channel supports both; other payer and non-bank dynamic fields remain required as declared.

PA maintains one bank identity directory with separate mapping strategies for deposit and withdrawal roles. An empty result means no matching verified bank. Do not fall back to withdrawal banks. Query again after selection changes and query the original order after an unknown creation result.

Complete successful response example (HTTP 200; placeholder signature):

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-deposit-banks-001",
  "resTime": "2026-09-10T02:00:01Z",
  "data": {
    "countryCode": "TH",
    "currency": "THB",
    "decimalPlaces": 2,
    "paymentMethod": "bank_transfer",
    "bankRole": "PAYER",
    "amount": 10000,
    "banks": [
      {
        "bankId": "1234567890123456789",
        "code": "EXAMPLE_BANK",
        "name": "Example bank",
        "channels": [
          {
            "channelOptionId": "REPLACE_CHANNEL_OPTION_ID",
            "name": "Channel 1",
            "ruleType": "RANGE",
            "minAmount": 10000,
            "maxAmount": 50000,
            "denominations": []
          }
        ]
      }
    ]
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### Unified withdrawal banks: POST /withdrawals/banks

SS uses the same PA bank IDs as other merchants. The optional response `banks[].ssCode` is reference data only and cannot be submitted instead of a PA ID. Legacy SS code markers and direct PG bank codes are rejected.

Supply `countryCode`, `currency` and `payoutMethod`. `amount` is optional and must be a positive integer in minor units when supplied; optional `channelOptionId` and `locale` narrow the result. Reuse common signing and the `deposit:options` scope. Production, sandbox and ALL query paths are supported. Business payload example, before adding signed common fields:

```json
{"countryCode":"TH","currency":"THB","payoutMethod":"bank_transfer","amount":10000,"locale":"en-US"}
```

Both input orders are supported. With an amount, return banks matching that amount. To choose a bank first, omit `amount` and preview authorized banks with valid environment/mapping scope and their channel amount rules. The response omits `amount` or returns null; this preview does not confirm availability for an order. After entering or changing an amount, query again with the actual amount and confirm that the selected `bankId` still exists and any designated channel remains in that bank's `channels[]`. Block an unsupported selection without silently changing the bank or designated channel. Withdrawal creation still requires the actual amount and rechecks the bank, channel, limits and balance.

Response `data` contains those selection dimensions and `banks[]`. Each bank has a stable string `bankId`, PA bank `code`, localized `name`, and anonymous `channels[]` whose amount rules intersect the bank limits. No match returns an empty array, without exposing provider bank codes or account IDs. Availability may change before execution.

Complete successful response example (HTTP 200; placeholder signature):

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-banks-001",
  "resTime": "2026-09-10T02:00:01Z",
  "data": {
    "countryCode": "TH",
    "currency": "THB", "decimalPlaces": 2,
    "payoutMethod": "bank_transfer",
    "amount": 10000,
    "banks": [
      {
        "bankId": "1234567890123456789",
        "code": "EXAMPLE_BANK",
        "name": "Example bank",
        "channels": [
          {
            "channelOptionId": "REPLACE_CHANNEL_OPTION_ID",
            "name": "Channel 1",
            "ruleType": "RANGE",
            "minAmount": 10000,
            "maxAmount": 50000,
            "denominations": []
          }
        ]
      }
    ]
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

Use `name` as the bank selector label and the `bankId` string as its submitted value. If the channel is selected first, include it in the bank query. If a bank is selected first, a designated channel must appear both in that bank's `channels[]` and in the current method's channel list. A `channelOptionId` is not a bank ID.

Create withdrawals using only the actual returned `recipient.bankId`. Legacy bank codes, SS markers and raw PG bank fields are rejected. Query again when country, currency, amount, method, channel or environment changes; bank identity participates in idempotency checks.

PA operators maintain a unified bank directory, PG bank directories and explicit mappings by PG, currency and deposit/withdrawal usage, shared across merchants and payment methods within the PG. No merchant bank groups or legacy-code fallback apply. Existing bank-specific limits still narrow eligibility. SS/SPB merchants do not maintain every PG's bank table. PA filters bank and amount eligibility before existing routing rules, revalidates before dispatch and freezes the exact PG bank values. An unsupported designated channel returns `3006`; no automatic candidate returns `3001`. Keep the original order after an unknown result and never repeat a payout blindly.

### Merchant capability discovery: POST /merchant-capabilities

Only common signed fields are required; do not preselect a country or currency. `countries[]` contains fiat markets; `cryptoAssets[]` independently contains each authorized digital asset with `currency`, `decimalPlaces` and `tradeTypes`, without a country. Treat an absent `cryptoAssets` on older deployments as an empty list. The base path determines the environment. Use the same base path for capabilities, payment methods, and amount options. Complete successful response example (HTTP 200; placeholder signature):

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-capabilities-001",
  "resTime": "2026-09-10T02:00:01Z",
  "data": {
    "countries": [
      {
        "countryCode": "TH",
        "name": "Thailand",
        "currencies": [
          {
            "currency": "THB",
            "decimalPlaces": 2,
            "tradeTypes": [
              "DEPOSIT",
              "WITHDRAWAL"
            ]
          }
        ]
      }
    ],
    "cryptoAssets": []
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

Countries contain fiat markets, sorted by code; digital assets are returned independently in `cryptoAssets[]`. An empty list means no eligible grant for that category. An absent `cryptoAssets` on older deployments is treated as empty; PA does not fall back to every platform configuration. `decimalPlaces` is the minor-unit precision (0–18); see [Amount units and conversion responsibilities](#amount-units-and-conversion-responsibilities) for formulas, examples, and each party's responsibilities.

Results depend on enabled merchant payment-service authorization, enabled PG accounts in the selected environment, enabled country/currency definitions, merchant method switches, and account mappings. The response does not disclose accounts, credentials, or PG details. It does not check balances, live quotas, temporary circuit breakers, or a particular amount; discovery is not a promise that an order will be accepted.

Create orders under the same base path. A supplied `channelOptionId` must belong to that environment; otherwise PA routes within the same environment. Selecting a path neither changes the database nor rewrites account gateways or credentials.

Integration sequence: discover capabilities → select the fiat country/currency or digital asset for the trade direction → query `/payment-methods` with the amount → select a method (and let the appropriate role select a channel in designated mode) → create the order. Refresh after configuration changes. Historical order queries and notifications do not depend on the current capability list.

### Complete merchant configuration support: POST /merchant-support

Use this endpoint to synchronize configuration instead of enumerating the legacy discovery endpoints. Omitting `keys` retains a full read with common signed fields and optional `locale`; no country, currency, direction or amount is required. Supply the `keys` array described below for country/currency blocks. Both modes use the existing `deposit:options` scope and follow the `production`, `sandbox`, and read-only `all` path rules.

`data` contains `version`, `environment`, and `markets[]`. Each market has `countryCode`, `name`, `currency`, `decimalPlaces`, and `directions[]`; digital assets have `countryCode=null`. Each direction's `paymentMethods` reuses the complete `/payment-methods` structure: `tradeType`, methods, display groups, anonymous channels, ranges/denominations, every `amountRules[].restrictions`, and the rule-specific `requiredFields/fieldDefinitions`. All restrictions within a rule must hold; one alternative rule may be selected. Preserve gaps between ranges.

Each direction's `banks[]` groups a bank directory by `paymentMethod` and `bankRole`: `PAYER/TARGET` for deposits and `RECIPIENT` for withdrawals. Its nested `banks[]` uses the existing unified withdrawal-bank structure, including `bankId/code/name/ssCode`, anonymous `channels[]`, and complete amount rules intersected with bank limits. An empty list means no configured support for that role; bank selection is not mandatory for every product. Digital assets have no national bank directory. Existing selector paths, channel-selection roles, and dynamic field rules still apply. Field-catalog coverage matches the existing contract; PG-specific length, pattern, and identity checks outside that catalog remain creation-time validations. Amounts use minor units; values outside the JavaScript safe-integer range are decimal strings.

Compare the `sha256:` content `version` only for the same merchant and path environment. It covers configured display languages and is independent of the requested display language. Refresh after configuration, grants, or effective PG versions change; [support change notifications](/docs/pa/support-notifications.md) can prompt a refresh. No support returns `markets=[]`, never a platform-wide fallback. Data is assembled in one database snapshot without a long cross-request cache. PG accounts, credentials, balances, and remaining quotas are excluded.

Clients may filter the returned rules locally and call the creation endpoint directly; creation does not require a token from an earlier amount query. Configured support does not promise real-time quota, balance, channel health, or successful payment. Creation still validates current conditions. Legacy discovery endpoints remain compatible for optional current checks; `all` cannot create transactions.

#### Batch synchronization by country and currency

The same endpoint accepts an optional `keys` array. This example shows business fields only; the common identity, timestamp, replay-protection and signature fields remain required. Sign the original key order, including any duplicates:

```json
{"keys":["TH/THB","MY/MYR","_/USDT"],"locale":"en-US"}
```

A key has exactly two segments: country/currency. Countries use two uppercase letters. Countryless assets retain `countryCode=null` and use keys such as `_/USDT`. Currency codes follow the existing `Currency` rule: 2–16 uppercase letters or digits, starting with a letter. Do not append directions, banks, fields, channels, merchants or environments. Send 1–100 entries per request; results are deduplicated and sorted by key. The path still selects `production`, `sandbox` or `all`, and the signed identity selects the merchant.

With `keys`, `data` contains the current `environment` and `parts[]`; it omits the legacy full `version/markets`. Each part contains:

| Field | Meaning |
| --- | --- |
| `key` | The requested country/currency identity |
| `version` | This key's content hash in the selected environment, covering public display languages; independent of requested locale, unordered, and not a full-snapshot version |
| `deleted` | When true, no support block currently exists; remove this key's old local content |
| `data` | The complete current block, or explicit `null` for deletion |

A block contains `countryCode/name/currency/decimalPlaces`, a unified `banks[]` dictionary and `directions[]`. Deposit, withdrawal, methods, channels, amount constraints and field requirements belong to this one key. A missing direction means it is no longer supported; do not preserve its old data. `directions[].paymentMethods` retains methods, presentation groups and full rule structures.

Each dictionary bank appears once with `bankId/code/name/ssCode`. Method `channels[].bankSupport[]` groups supported bank references by `bankRole`. Its `banks[]` entries reference `bankId` and retain `ruleType/minAmount/maxAmount/denominations/amountRules`. Several channels may reference the same bank with different limits. Keep those limits on the relationships, not on the dictionary. Evaluate full rules rather than aggregate bounds alone. An empty support list neither permits arbitrary banks nor makes a bank mandatory for every product. Field catalogs and rule-specific field requirements remain inside the block's method/channel structures.

Every valid key receives a result. Nonexistent, unauthorized and revoked scopes all return `deleted=true,data=null`, without exposing another merchant's configuration. Malformed keys, empty arrays or excessive entries fail the whole batch with `1001`. Database/configuration failures fail the batch and never become deletion results; preserve local data on failure.

Batch several changed keys in one request. For more than 100 entries, fetch successive batches without truncating the notification's change list or treating one batch as a complete support manifest. After signature verification and whole-batch success, replace each block completely and apply explicit deletions; leave unrequested keys unchanged. One request reads one database snapshot. Partition client caches by merchant identity, environment and display language; serialize synchronization within each partition and merge newly arriving keys into the next batch. Fetch the new language's content when switching locale even if its version is unchanged. Duplicate/out-of-order notifications trigger reads of current state, not rollback to an event's old hash. An environment-specific key can change while the notification's ALL version stays the same, so version equality alone is not a reason to ignore changed keys.

Omitting `keys` preserves the existing full `version/environment/markets[]`, signature and version semantics. Partial reads constrain market/account/catalog SQL before assembly; they do not assemble the full response and trim it. Shared method/field definitions and required PG/currency dictionaries remain dependencies. Creation still validates current configuration and runtime conditions.

**Notification verification and full synchronization.** Automatic, manual and legacy-baseline recovery `support.changed` notifications all use `RAW_BODY_V1`. With the confirmed PA platform public key, verify `webhook-signature: v1-rsa,<Base64>` using `SHA256withRSA` over UTF-8 `webhook-id + "." + webhook-timestamp + "."` followed by the original body bytes; never parse and reserialize before verification. The signature covers `changedKeys/fullSync/mchNo` and every business-body field. Also validate the timestamp window, header/body event-ID consistency and merchant ownership. Retries retain the event ID and business body while refreshing the timestamp and signature; verify first, then deduplicate by event ID. A missing notification URL suppresses notifications; the manual action uses the separately saved URL. See the [notification contract](/docs/pa/support-notifications.md). Neither events, keys nor event IDs replace signed API identity, replay checks, Scope, IP policy or rate limits. Verify synchronization response signatures too.

`fullSync=true` is a notification flag, not a new read-request parameter. Manual notifications and first key-baseline recovery use it. Never delete cached blocks using an event's potentially old key list as the current manifest. Prefer one full read without `keys` in the current environment. After signature verification, normalize that single response locally, then replace the cache and remove blocks outside that current manifest:

1. Derive each market key as `(countryCode ?? "_") + "/" + currency`; retain all direction, method, field, group and amount-rule data.
2. Collect `directions[].banks[].banks[]`, deduplicate by string `bankId`, and retain only `bankId/code/name/ssCode` in the dictionary. Conflicting identities fail synchronization rather than silently overwriting data.
3. For channels in both `paymentMethods.methods[]` and `groups[].options[]`, locate original bank-channel entries by payment-method code, `bankRole` and `channelOptionId`. Copy their effective amount rules unchanged to channel `bankSupport`, referencing the shared dictionary by `bankId`. This is a pure local conversion, requiring no further server read. Do not invent per-key server hashes; the full version may be stored separately for tracing, and changed keys still require fresh reads.

Clients without local conversion can read the current full `markets[]` manifest and then fetch its keys in successive batches for the new block representation. Replace the full cache and remove out-of-list blocks only after every batch succeeds. Separate HTTP requests are not one globally atomic snapshot. Queue notifications arriving during synchronization for a subsequent fresh-state pass.


### 1. Query payment methods: POST /payment-methods

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `environment` | string | No | Deprecated; omit it. If PRODUCTION/SANDBOX/ALL is supplied, it must match the path and participate in signing |
| `countryCode` | string | Conditional | Keep the existing country rules for fiat; digital assets may omit it and never use it for authorization or routing |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `tradeType` | string | Yes | DEPOSIT / WITHDRAWAL |
| `locale` | string | No | Display language, for example en-US or zh-CN; maximum 16 |
| `amount` | Amount | No | Optional. Omit for scoped methods, channel configuration, amount rules and required fields; this does not confirm transaction availability. Supply to filter channels by amount and quota. Withdrawal balance is checked live before execution. |

Success `data` is `PaymentMethods`. `methods[]` contains display codes/names, availability, amount rules, dynamic required fields, routing modes, and anonymous channel options. Use this same endpoint with `tradeType=WITHDRAWAL` for withdrawals.

`methods[]` only includes enabled payment methods with an enabled merchant authorization and enabled account matching the merchant, requested country, currency, trade direction, and path environment, subject to the method's own currency restrictions. Matching methods remain present with `available=false` when a PG is disabled, quota is exhausted, or the merchant method switch is off. With no matching configuration, `methods=[]`; there is no fallback to the platform-wide catalog. `all` combines account environments while preserving every other scope filter. The amount still filters channel options and `groups[]`; an unsuitable amount alone does not remove a matching entry from `methods[]`.

For withdrawals, `available=true` means authorization, account, method, environment, amount rules, and quotas allow selection; it does not guarantee funds or successful payout. Discovery does not call the PG or use cached balances to cap amounts or hide options. After creating a withdrawal, PA queries the PG balance live before execution routing. Failed queries or insufficient funds prevent payout dispatch. Scheduled balance sync serves dashboards and alerts; enabling it is not a prerequisite for discovery or withdrawal submission.

`groups[]` contains presentation groups already resolved for this merchant, trade direction, country, currency, and amount; render them in returned order. `methods[]` remains for compatibility. Custom groups without available members are omitted. Available ungrouped methods appear as standalone default groups. Query with the actual amount to filter gaps and unsupported denominations; omitting it provides only an overview.

Each group contains `code`, `name`, and `options[]`; options have the same structure as `methods[]`. Group names fall back from the requested locale to English, Chinese, then another configured language. For example, grouping `qr` and `wallet` under “Electronic payments” returns a group with those two options. **A group code is display-only and must never be submitted as `paymentMethod`.** Submit the selected option's code. Each option retains its own amount rules, fields, and route; grouping does not merge routing across methods.

`channelSelection` indicates who chooses the channel: `AUTOMATIC` means PA selects it; `PLAYER` means the player selects a non-rotating deposit channel; `OPERATOR` means a merchant operator selects a non-rotating withdrawal channel. Do not ask a player to select a withdrawal channel. The merchant system passes the operator's selected current anonymous option with its withdrawal request. Presentation grouping does not create a merchant approval queue. An explicitly selected channel does not automatically fail over after failure; signing, validation, and unknown-outcome protection remain unchanged.

Omit `amount` to list payment methods and channel configuration, amount rules and required fields for the merchant, country, currency, direction and environment. Channel `amountRules[]` preserves each rule’s fields and finite choices; top-level channel fields summarize them and may not all be required for a given amount. `amountRanges[]` preserves gaps; legacy min/max describes only the first range. This metadata does not confirm transaction availability. Automatic routing includes hidden channels for field discovery; `cashierVisible=false` prevents a deposit channel from being offered for explicit selection. Caller-designated deposit lists still exclude hidden channels. Query again with the actual amount for available channels. In `CALLER_DESIGNATED` mode, creation requires a `channelOptionId` selected from that amount-specific response. Creation revalidates availability; a query reserves neither quota nor a channel.

Each channel's `iconUrl` is the HTTPS URL of its PG's current default icon. Accounts using the same PG share the icon. An unset or deleted icon is explicitly `null`; treat omission by older servers the same way and display your own placeholder. `groups[].options[].channels[]` and `methods[].channels[]` are consistent. The image may identify the PG brand but does not expose PG codes, accounts, or credentials. Refresh from the latest query: replacement changes the URL, and removed asset URLs return 404. Image loading failures should display a placeholder without changing transaction behavior. The image endpoint requires neither private keys nor management sessions. Non-null URLs participate in the existing response signature; null values follow the existing exclusion rule.

- Do not proceed using an option with `available=false`.
- For `RANGE`, validate against one of the individual `amountRanges[]`. Do not merge separated intervals. Legacy `minAmount/maxAmount` in deposit options describe only the first interval; absent `maxAmount` means no upper limit.
- `FIXED_DENOMINATIONS` accepts only amounts listed in `denominations[]`.
- Method, deposit-option and bank-channel responses include `amountRules[]`. Alternatives are ORed; within each alternative, the base range/denominations AND every `restrictions[]` entry must hold. Channel rules also retain their field requirements. `MIXED` requires evaluating these alternatives instead of the top-level envelope. Different PGs may use different rules for the same payment product.
- `integerOnly` uses the returned `decimalPlaces` from the country/currency directory. `step` is a positive minor-unit integer string; the amount must be a multiple starting at zero. `suffixDigits` is 1–6. `MINOR_UNIT` examines the minor-unit integer; `INTEGER_PART` first truncates the fractional currency amount. An empty `allowedSuffixes` adds no whitelist; `forbiddenSuffixes` still applies. Leading zeroes follow the configured digit count. Use exact integer arithmetic.
- PG and merchant-account restrictions intersect. Clearing an account restriction retains PG requirements. Queries preserve gaps, steps and suffix constraints, and creation revalidates the same rules.
- A selected channel's own amount rules and `requiredFields` also apply.
- `methods[].requiredFields` contains common method fields, not every PG difference. Even in `PRIORITY` mode, query with the actual amount and inspect `channels[].requiredFields`. An empty method-level `requiredFields` list does not mean no payer information is required. For example, VCPay fixed-denomination deposits require `payerName`, `payerAccount`, and `targetBankId`, mapped to `payer.name`, `payer.account`, and top-level `targetBankId`. If channels require different fields, specify the returned `channelOptionId` to select the channel matching the collected data.
- `channelOptionId` is an anonymous PA option, not a real PG name, code, or account. An explicit option is honored regardless of routing mode. Without one, the configured route applies; designated mode returns `3005` when it is missing.

#### Finite choices and display language

`channels[].fieldDefinitions` provides channel-specific choices. For `inputType=select`, `options[]` contains string `value` and localized `label`. Display the label and submit the value at requestPath. PA validates before creation and excludes incompatible automatic routes. Do not union incompatible channel choices; use their intersection or a selected channel. Legacy services without choices retain their existing contract.

The merchant has separate interface and API display defaults. `apiDefaultLanguage` controls the fallback for missing channel-name translations; changing the interface default does not change API names or the merchant-support version. Existing merchants retain their previous API fallback; new merchants default to `en-US`.

Language precedence: signed body `locale`, `Accept-Language`, then `en-US`. `locale` must be a valid language tag, up to 16 characters; the header accepts language ranges and q wtens, up to 512 characters. Invalid input returns `1001`. An explicit body locale takes precedence over the header. Missing translations fall back to English. `label` is additive; `name/nameEn` remain compatible. Language never changes values, requirements or routing. SUPEFINA choices: `accountType` uses `"10"` for CLABE and `"20"` for bank cards; `documentType` uses `"10"` for RFC and `"20"` for CURP. The Mexico purpose-of-funds subset remains unconfirmed and is not exposed as choices.

Complete successful response example (HTTP 200; placeholder signature): This deposit example uses designated routing. groups[].options[] retains complete method/channel objects; the top-level catalog shows one representative field. Creating a deposit from this result requires payer.name and the selected channelOptionId. For withdrawals, tradeType is WITHDRAWAL and designated channelSelection is OPERATOR; read finite choices from the actual channel fieldDefinitions[].options.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-methods-001",
  "resTime": "2026-09-25T02:00:01Z",
  "data": {
    "currency": "THB", "decimalPlaces": 2,
    "tradeType": "DEPOSIT",
    "methods": [
      {
        "code": "REPLACE_METHOD_CODE",
        "name": "Example payment method",
        "available": true,
        "ruleType": "RANGE",
        "minAmount": 10000,
        "maxAmount": 50000,
        "amountRanges": [
          {
            "minAmount": 10000,
            "maxAmount": 50000
          }
        ],
        "denominations": [],
        "requiredFields": [],
        "routeMode": "CALLER_DESIGNATED",
        "channelSelection": "PLAYER",
        "channels": [
          {
            "channelOptionId": "REPLACE_CHANNEL_OPTION_ID",
            "name": "Channel 1",
            "iconUrl": null,
            "displayOrder": 1,
            "ruleType": "RANGE",
            "minAmount": 10000,
            "maxAmount": 50000,
            "denominations": [],
            "requiredFields": [
              "payerName"
            ],
            "fieldDefinitions": []
          }
        ]
      }
    ],
    "groups": [
      {
        "code": "method:REPLACE_METHOD_CODE",
        "name": "Example payment method",
        "options": [
          {
            "code": "REPLACE_METHOD_CODE",
            "name": "Example payment method",
            "available": true,
            "ruleType": "RANGE",
            "minAmount": 10000,
            "maxAmount": 50000,
            "amountRanges": [
              {
                "minAmount": 10000,
                "maxAmount": 50000
              }
            ],
            "denominations": [],
            "requiredFields": [],
            "routeMode": "CALLER_DESIGNATED",
            "channelSelection": "PLAYER",
            "channels": [
              {
                "channelOptionId": "REPLACE_CHANNEL_OPTION_ID",
                "name": "Channel 1",
                "iconUrl": null,
                "displayOrder": 1,
                "ruleType": "RANGE",
                "minAmount": 10000,
                "maxAmount": 50000,
                "denominations": [],
                "requiredFields": [
                  "payerName"
                ],
                "fieldDefinitions": []
              }
            ]
          }
        ]
      }
    ],
    "fieldDefinitions": [
      {
        "code": "payerName",
        "name": "付款人姓名",
        "nameEn": "Payer name",
        "requestPath": "payer.name",
        "inputType": "text",
        "configurable": true,
        "label": "Payer name",
        "options": []
      }
    ]
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### 2. Query deposit amount options: POST /deposit/options

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `environment` | string | No | Deprecated; omit it. If supplied, it must match the path and participate in signing |
| `countryCode` | string | Conditional | Keep the existing country rules for fiat; digital assets may omit it and never use it for authorization or routing |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `paymentMethod` | string | Yes | `methods[].code` from payment-methods; maximum 64 |

Success `data` is `DepositOptions` for displaying current amount rules for a deposit method. This endpoint neither creates an order nor handles withdrawals. Apply the interval, denomination, and availability rules above.

Complete successful response example (HTTP 200; placeholder signature): Range boundaries are inclusive; 50001–99999 is unavailable. Fixed denominations use ruleType=FIXED_DENOMINATIONS and the returned denominations instead; do not mix amount rules from the two modes.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-options-001",
  "resTime": "2026-09-10T02:00:01Z",
  "data": {
    "available": true,
    "currency": "THB", "decimalPlaces": 2,
    "paymentMethod": "REPLACE_METHOD_CODE",
    "minAmount": 10000,
    "maxAmount": 50000,
    "amountRanges": [
      {
        "minAmount": 10000,
        "maxAmount": 50000
      },
      {
        "minAmount": 100000,
        "maxAmount": 200000
      }
    ],
    "ruleType": "RANGE",
    "denominations": [],
    "retryable": false
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### 3. Create a deposit: POST /deposits

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `countryCode` | string | Conditional | Keep the existing country rules for fiat; digital assets may omit it and never use it for authorization or routing |
| `merchantOrderNo` | string | Yes | Your business order number; keep it unchanged after creation; maximum 64 |
| `idempotencyKey` | string | Yes | Key for this business creation operation; retain it on retries; maximum 64 |
| `amount` | Amount | Yes | Integer minor units; minimum 1 |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `paymentMethod` | string | Yes | `methods[].code` from payment-methods; maximum 64 |
| `channelOptionId` | string | No | Current channel option from payment-methods; PA revalidates it regardless of route mode. Without it, configured routing applies; caller-designated mode returns 3005; maximum 40 |
| `playerId` | string | Yes | Your user identifier; maximum 64 |
| `payer` | Payer | No | Populate required payer data; bank selection may use unified `payer.bankId` |
| `targetBankId` | string | No | PA ID from the TARGET bank query; required when the actual PG product requires a target bank |
| `paymentMethodFields` | PaymentMethodFields | No | Dynamic fields from method/channel requirements; at most 32 entries |
| `notifyUrl` | string or null | No | Valid HTTPS notification URL, maximum 500; request takes precedence, omission/null uses the backend default, and neither source being set rejects creation |
| `extend` | string | No | Optional, maximum 1024; preserved and signed in requests/Webhooks and compared for idempotency; never change it on replay |
| `returnUrl` | string | Per channel | Browser return URL; required for RapidPay FPX deposits. For other channels, follow the required fields returned for the actual amount. A redirect does not prove payment success; maximum 500 |
| `clientIp` | string | Per channel | Single end-user IP; maximum 64. Nonblank values must be valid IPv4 or IPv6; see [usage and validation](#end-user-ip-usage-and-validation) |

Success `data` is `Trade`. Save `orderNo` and display the medium selected by `paymentMedium.type`. `code=0` means the API call succeeded; only transaction `status=SUCCEEDED` represents transaction success.

Complete request structure: replace every `REPLACE_` value, time, and random identifier, and use methods/fields returned by discovery. The placeholder signature is invalid.

```json
{
  "mchNo": "REPLACE_MCH_NO",
  "appId": "REPLACE_APP_ID",
  "reqId": "req-deposit-001",
  "nonceStr": "0123456789abcdef0123456789abcdef",
  "reqTime": "2026-09-10T02:00:00Z",
  "merchantOrderNo": "deposit-20260910-001",
  "idempotencyKey": "deposit-key-20260910-001",
  "amount": 10000,
  "countryCode": "TH",
  "currency": "THB",
  "paymentMethod": "REPLACE_METHOD_CODE",
  "playerId": "player-001",
  "notifyUrl": "https://merchant.example/pa/webhook",
  "sign": "REPLACE_WITH_COMPUTED_SIGNATURE"
}
```

Add `channelOptionId`, `payer`, `clientIp`, and `paymentMethodFields` as required by the channel before signing.

Complete successful response example (HTTP 200; placeholder signature): The create call succeeded; the transaction remains in progress. Preserve the complete payment URL and expiry.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-deposit-001",
  "resTime": "2026-09-10T02:00:01Z",
  "data": {
    "orderNo": "PA_DEPOSIT_EXAMPLE_001",
    "merchantOrderNo": "deposit-20260910-001",
    "tradeType": "DEPOSIT",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "paymentMedium": {
      "type": "REDIRECT_URL",
      "redirectUrl": "https://cashier.example/order/example",
      "expiresAt": "2026-09-10T02:15:00Z"
    },
    "retryable": false,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:00:01Z"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### 4. Query a deposit: POST /deposits/query

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `merchantOrderNo` | string | Yes | Your original business order number; maximum 64 |

Success `data` is `Trade`. Query PA's stored state by merchant order number, not PA `orderNo`. Use it for unknown creation outcomes, polling, and notification recovery.

Complete successful response example (HTTP 200; placeholder signature): The original deposit has succeeded in this example. Match local order facts and process idempotently; do not reopen the payment URL to pay again.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-deposit-query-001",
  "resTime": "2026-09-10T02:05:00Z",
  "data": {
    "orderNo": "PA_DEPOSIT_EXAMPLE_001",
    "merchantOrderNo": "deposit-20260910-001",
    "tradeType": "DEPOSIT",
    "status": "SUCCEEDED",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "paymentMedium": {
      "type": "REDIRECT_URL",
      "redirectUrl": "https://cashier.example/order/example",
      "expiresAt": "2026-09-10T02:15:00Z"
    },
    "retryable": false,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:05:00Z"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### 5. Create a withdrawal: POST /withdrawals

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `merchantOrderNo` | string | Yes | Your business order number; keep it unchanged after creation; maximum 64 |
| `idempotencyKey` | string | Yes | Key for this creation operation; retain it on retries; maximum 64 |
| `amount` | Amount | Yes | Integer minor units; minimum 1 |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `payoutMethod` | string | Yes | `methods[].code` from a WITHDRAWAL query; maximum 64 |
| `channelOptionId` | string | No | Current option from payment-methods, revalidated regardless of route mode. Omission uses configured routing; caller-designated mode returns 3005; maximum 40 |
| `recipient` | Recipient | Yes | Withdrawal recipient; see the structure and dynamic requirements below |
| `paymentMethodFields` | PaymentMethodFields | No | Dynamic fields from method/channel requirements; at most 32 entries |
| `notifyUrl` | string or null | No | Valid HTTPS notification URL, maximum 500; request takes precedence, omission/null uses the backend default, and neither source being set rejects creation |
| `extend` | string | No | Optional, maximum 1024; preserved and signed in requests/Webhooks and compared for idempotency; never change it on replay |

Success `data` is `Trade`. Fiat withdrawals require `recipient.countryCode`; digital asset withdrawals may omit it. The method field is `payoutMethod`, not the deposit field `paymentMethod`. Use strings for account numbers and phone numbers to preserve leading zeros.

Replace the details, time, and random identifiers, then compute the signature:

```json
{
  "mchNo": "REPLACE_MCH_NO",
  "appId": "REPLACE_APP_ID",
  "reqId": "req-withdrawal-001",
  "nonceStr": "1123456789abcdef0123456789abcdef",
  "reqTime": "2026-09-10T02:00:00Z",
  "merchantOrderNo": "withdrawal-20260910-001",
  "idempotencyKey": "withdrawal-key-20260910-001",
  "amount": 10000,
  "currency": "THB",
  "payoutMethod": "REPLACE_METHOD_CODE",
  "recipient": {
    "name": "REPLACE_RECIPIENT_NAME",
    "account": "REPLACE_RECIPIENT_ACCOUNT",
    "countryCode": "TH",
    "bankId": "1234567890123456789"
  },
  "notifyUrl": "https://merchant.example/pa/webhook",
  "sign": "REPLACE_WITH_COMPUTED_SIGNATURE"
}
```

The bank ID above only illustrates the format. Replace it with the recipient's selection from the current `/withdrawals/banks` response. PA supplies mapped bank values; merchants must not submit raw bank codes, names or branches. Bank selection is required only when the actual PG product requires it. A required bank ID or valid mapping missing at execution is rejected before dispatch; continue providing required recipient and non-bank fields.

Complete successful response example (HTTP 200; placeholder signature): The call succeeded, but the payout is still processing and does not establish receipt. No payment page is needed, so paymentMedium is absent.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-withdrawal-001",
  "resTime": "2026-09-10T02:00:01Z",
  "data": {
    "orderNo": "PA_WITHDRAWAL_EXAMPLE_001",
    "merchantOrderNo": "withdrawal-20260910-001",
    "tradeType": "WITHDRAWAL",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "retryable": false,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:00:01Z"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### 6. Query a withdrawal: POST /withdrawals/query

Send the common fields plus `merchantOrderNo`, defined as for deposit queries. Success `data` is `Trade`. Use the withdrawal query path.

Complete successful response example (HTTP 200; placeholder signature): The original payout has succeeded in this example. A successful query can also return other statuses; use the actual order state.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-withdrawal-query-001",
  "resTime": "2026-09-10T02:05:00Z",
  "data": {
    "orderNo": "PA_WITHDRAWAL_EXAMPLE_001",
    "merchantOrderNo": "withdrawal-20260910-001",
    "tradeType": "WITHDRAWAL",
    "status": "SUCCEEDED",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:05:00Z"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

Another complete response: the query call succeeds (code=0), but the original payout has failed (data.status=FAILED) and may include failureCode:

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-withdrawal-failed-query-001",
  "resTime": "2026-09-10T02:05:00Z",
  "data": {
    "orderNo": "PA_WITHDRAWAL_FAILED_EXAMPLE_001",
    "merchantOrderNo": "withdrawal-failed-example-001",
    "tradeType": "WITHDRAWAL",
    "status": "FAILED",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:05:00Z",
    "failureCode": "CHANNEL_EXECUTION_FAILED"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### 7. Synchronize a transaction: POST /trades/sync

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `tradeType` | string | Yes | DEPOSIT / WITHDRAWAL |
| `merchantOrderNo` | string | Yes | Your original business order number; maximum 64 |

Success `data` is `Trade`. Unlike an ordinary query of PA's stored record, synchronization attempts to obtain channel transaction state and may update the PA order and trigger a notification. It requires `trade:sync`. It does not guarantee an immediate final state; avoid frequent calls without intervals.

A query business body is `{"merchantOrderNo":"deposit-20260910-001"}`; a synchronization body is `{"tradeType":"DEPOSIT","merchantOrderNo":"deposit-20260910-001"}`. Add all common fields, generate fresh nonce/time metadata, and sign both requests.

Complete successful response example (HTTP 200; placeholder signature): This example synchronizes an original WITHDRAWAL and still has no final state. Deposit synchronization returns tradeType=DEPOSIT and may include paymentMedium.

```json
{
  "code": 0,
  "msg": "SUCCESS",
  "retryable": false,
  "reqId": "req-sync-001",
  "resTime": "2026-09-10T02:03:00Z",
  "data": {
    "orderNo": "PA_WITHDRAWAL_EXAMPLE_001",
    "merchantOrderNo": "withdrawal-20260910-001",
    "tradeType": "WITHDRAWAL",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:03:00Z"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

### Code for each endpoint (Python 3)

These examples use the Python 3 standard library and the OpenSSL command on your server. Save the common functions in a local script and add only the snippets needed for your operation; do not run all creation/synchronization snippets as a read-only demo. Set `PA_BASE_URL`, `PA_MCH_NO`, `PA_APP_ID`, `PA_PRIVATE_KEY_FILE`, and `PA_PLATFORM_KEY_FILE`. The last two are server-side PEM paths: your PKCS#8 private key and the verified PA SPKI public key. `PA_BASE_URL` includes the confirmed `/unipay/pa/v1`, `/production`, or `/sandbox` path; creation/synchronization cannot use `/all`.

The shared function generates fresh nonce, second-precision time, and signature, rejects redirects, then verifies the response signature and reqId before using data. It handles JSON integers under the current contract, avoiding floating-point amounts.

```python
import base64
import json
import os
import subprocess
import tempfile
import uuid
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener

BASE_URL = os.environ["PA_BASE_URL"].rstrip("/")
MCH_NO = os.environ["PA_MCH_NO"]
APP_ID = os.environ["PA_APP_ID"]
PRIVATE_KEY = os.environ["PA_PRIVATE_KEY_FILE"]
PLATFORM_KEY = os.environ["PA_PLATFORM_KEY_FILE"]
url = urlsplit(BASE_URL)
if url.scheme != "https" or not url.hostname or url.query or url.fragment or url.username:
    raise ValueError("Use the confirmed HTTPS API base URL")


def canonical(body):
    fields = {}

    def flatten(value, path=""):
        if value is None:
            return
        if isinstance(value, dict):
            for key, item in value.items():
                if not path and key == "sign":
                    continue
                flatten(item, f"{path}.{key}" if path else key)
        elif isinstance(value, list):
            for index, item in enumerate(value):
                flatten(item, f"{path}[{index}]")
        elif isinstance(value, (str, bool, int)):
            fields[path] = str(value).lower() if isinstance(value, bool) else str(value)
        else:
            raise ValueError("Expected JSON strings, booleans, or integers")

    flatten(body)
    return "&".join(f"{key}={fields[key]}" for key in sorted(fields)).encode("utf-8")


def sign_request(body):
    result = subprocess.run(
        ["openssl", "dgst", "-sha256", "-sign", PRIVATE_KEY],
        input=canonical(body), capture_output=True, check=True,
    )
    return base64.b64encode(result.stdout).decode("ascii")


def verify_response(body, req_id):
    signature = base64.b64decode(body["sign"], validate=True)
    with tempfile.TemporaryDirectory() as directory:
        signature_file = Path(directory) / "response.sig"
        signature_file.write_bytes(signature)
        result = subprocess.run(
            ["openssl", "dgst", "-sha256", "-verify", PLATFORM_KEY,
             "-signature", str(signature_file)],
            input=canonical(body), capture_output=True,
        )
    if result.returncode != 0 or body.get("reqId") != req_id:
        raise ValueError("Invalid PA signature or request association")


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class PaBusinessError(Exception):
    def __init__(self, response):
        self.response = response
        super().__init__(f"PA code={response['code']}, reqId={response['reqId']}")


opener = build_opener(NoRedirect())


def call(path, business):
    if BASE_URL.endswith("/all") and path in ("/deposits", "/withdrawals", "/trades/sync"):
        raise ValueError("Choose the order's production or sandbox path for writes")
    body = {**business, "mchNo": MCH_NO, "appId": APP_ID,
            "reqId": uuid.uuid4().hex, "nonceStr": uuid.uuid4().hex,
            "reqTime": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")}
    body["sign"] = sign_request(body)
    request = Request(BASE_URL + path, method="POST",
                      headers={"Content-Type": "application/json"},
                      data=json.dumps(body, ensure_ascii=False, allow_nan=False).encode("utf-8"))
    with opener.open(request, timeout=15) as http:
        if http.status != 200:
            raise ValueError("Unexpected HTTP status; query the original order")
        response = json.loads(http.read().decode("utf-8"))
    verify_response(response, body["reqId"])
    data = response.get("data")
    if isinstance(data, dict) and "merchantOrderNo" in business:
        trade_type = ("DEPOSIT" if path.startswith("/deposits") else
                      "WITHDRAWAL" if path.startswith("/withdrawals") else business["tradeType"])
        expected = {key: business[key] for key in ("merchantOrderNo", "amount", "currency") if key in business}
        expected["tradeType"] = trade_type
        if any(data.get(key) != value for key, value in expected.items()):
            raise ValueError("Order facts do not match the request")
    if response["code"] != 0:
        raise PaBusinessError(response)
    if data is None:
        raise ValueError("Missing response data")
    return data
```

`call` returns verified successful `data`; code=0 does not establish payment success: inspect `status`. Nonzero business codes raise `PaBusinessError`, retaining the complete verified response as `exception.response`, including retryable/reasonCode/data. Follow the error-handling section and check any existing order facts. HTTP, timeout, JSON, and signature errors propagate without automatic retries; once creation was sent, query the original order as an unknown result. For queries/synchronization, also compare amount/currency with your persisted original order and reuse idempotent business accounting.

The transaction snippets use `.get("status")` because status is optional. `None` means unconfirmed: retain and query the original order without converting it to failure.

#### Query merchant capabilities：POST /merchant-capabilities

No country/currency input is required. Select a country/currency supporting your direction and use its precision. Later examples assume TH/THB and 10000 minor units have been confirmed; they are not enabled for every merchant.

```python
capabilities = call("/merchant-capabilities", {})
for country in capabilities["countries"]:
    print(country["countryCode"], country["currencies"])
```

#### Query deposit and withdrawal methods：POST /payment-methods

Query each direction separately. Replace placeholders with the actual method codes selected by your user/business; do not automatically choose the first item. Later examples reuse these selected method objects.

```python
deposit_methods = call("/payment-methods", {
    "countryCode": "TH", "currency": "THB", "tradeType": "DEPOSIT",
    "amount": 10000, "locale": "en-US",
})
withdrawal_methods = call("/payment-methods", {
    "countryCode": "TH", "currency": "THB", "tradeType": "WITHDRAWAL",
    "amount": 10000, "locale": "en-US",
})
deposit_method = next(m for m in deposit_methods["methods"]
                      if m["available"] and m["code"] == "REPLACE_DEPOSIT_METHOD_CODE")
withdrawal_method = next(m for m in withdrawal_methods["methods"]
                         if m["available"] and m["code"] == "REPLACE_PAYOUT_METHOD_CODE")
```

#### Query deposit amount options：POST /deposit/options

These are method-level rules; a designated channel must also accept the amount according to payment-methods.

```python
deposit_options = call("/deposit/options", {
    "countryCode": "TH", "currency": "THB", "paymentMethod": deposit_method["code"],
})
print(deposit_options)
```

#### Query unified deposit banks: POST /deposits/banks

Query only for a payer or target bank required by the actual candidate. Use `bankRole=PAYER` or `TARGET`. A designated channel must use the same current ID in discovery and creation. Replace the selected bank placeholder with an actual value returned by this query.

```python
deposit_bank_query = {
    "countryCode": "TH", "currency": "THB", "paymentMethod": deposit_method["code"],
    "amount": 10000, "bankRole": "PAYER", "locale": "en-US",
}
if deposit_method.get("channelSelection") == "PLAYER":
    deposit_bank_query["channelOptionId"] = "REPLACE_CURRENT_DEPOSIT_CHANNEL_ID"
deposit_banks = call("/deposits/banks", deposit_bank_query)
if not deposit_banks["banks"]:
    raise ValueError("No matching deposit bank")
deposit_bank = next(b for b in deposit_banks["banks"]
                    if b["bankId"] == "REPLACE_SELECTED_BANK_ID")
```

Put a PAYER selection in creation `payer.bankId`. For a TARGET bank, query with `bankRole=TARGET` and put the selection in top-level `targetBankId`. If both roles are needed, query each and ensure one candidate supports both. Carry any designated `channelOptionId` into creation unchanged.

#### Query unified withdrawal banks：POST /withdrawals/banks

For operator-designated routing, replace the placeholder with a current channel ID for this method. Select a bank from this response; stop when empty. Automatic routing omits channelOptionId.

```python
withdrawal_channel_id = None
if withdrawal_method.get("channelSelection") == "OPERATOR":
    withdrawal_channel_id = "REPLACE_CURRENT_WITHDRAWAL_CHANNEL_ID"
bank_query = {"countryCode": "TH", "currency": "THB",
              "payoutMethod": withdrawal_method["code"], "amount": 10000, "locale": "en-US"}
if withdrawal_channel_id is not None:
    bank_query["channelOptionId"] = withdrawal_channel_id
bank_result = call("/withdrawals/banks", bank_query)
if not bank_result["banks"]:
    raise ValueError("No matching withdrawal bank")
bank = next(b for b in bank_result["banks"] if b["bankId"] == "REPLACE_SELECTED_BANK_ID")
```

#### Create a deposit：POST /deposits

Persist the business order number, idempotency key, and complete business parameters before sending. Populate payer, clientIp, and paymentMethodFields according to requiredFields. In PLAYER mode, the player selects a current channel.

```python
deposit_body = {
    "merchantOrderNo": "REPLACE_PERSISTED_DEPOSIT_ORDER_NO",
    "idempotencyKey": "REPLACE_PERSISTED_DEPOSIT_IDEMPOTENCY_KEY",
    "countryCode": "TH", "currency": "THB", "amount": 10000,
    "paymentMethod": deposit_method["code"], "playerId": "REPLACE_PLAYER_ID",
    "notifyUrl": "https://merchant.example/pa/webhook",
}
if deposit_method.get("channelSelection") == "PLAYER":
    deposit_body["channelOptionId"] = "REPLACE_CURRENT_DEPOSIT_CHANNEL_ID"
# Add all required payer/clientIp/paymentMethodFields before saving and signing.
deposit = call("/deposits", deposit_body)
print(deposit["orderNo"], deposit.get("status"), deposit.get("paymentMedium"))
```

#### Query a deposit：POST /deposits/query

Use the original merchant order number saved locally. This reads PA's stored state. Also compare amount, currency, and other facts with your local original order.

```python
deposit = call("/deposits/query", {
    "merchantOrderNo": "REPLACE_PERSISTED_DEPOSIT_ORDER_NO",
})
print(deposit.get("status"))
```

#### Create a withdrawal：POST /withdrawals

Use the bankId selected above and the same amount, method, country, and channel as the bank query. Populate required phone, IFSC, finite choices, and other details, then persist the complete business parameters before sending.

```python
withdrawal_body = {
    "merchantOrderNo": "REPLACE_PERSISTED_WITHDRAWAL_ORDER_NO",
    "idempotencyKey": "REPLACE_PERSISTED_WITHDRAWAL_IDEMPOTENCY_KEY",
    "currency": "THB", "amount": 10000, "payoutMethod": withdrawal_method["code"],
    "recipient": {"name": "REPLACE_RECIPIENT_NAME", "account": "REPLACE_RECIPIENT_ACCOUNT",
                  "countryCode": "TH", "bankId": bank["bankId"]},
    "notifyUrl": "https://merchant.example/pa/webhook",
}
if withdrawal_channel_id is not None:
    withdrawal_body["channelOptionId"] = withdrawal_channel_id
# Add required recipient/clientIp/paymentMethodFields; never combine bankId with bankCode/bankName/bankBranch.
withdrawal = call("/withdrawals", withdrawal_body)
print(withdrawal["orderNo"], withdrawal.get("status"))
```

#### Query a withdrawal：POST /withdrawals/query

After a creation timeout or missing notification, query the original withdrawal. Do not resubmit with a new order number; compare amount/currency with the local original order.

```python
withdrawal = call("/withdrawals/query", {
    "merchantOrderNo": "REPLACE_PERSISTED_WITHDRAWAL_ORDER_NO",
})
print(withdrawal.get("status"))
```

#### Synchronize a transaction：POST /trades/sync

This may update an order and trigger notifications. Use the creation environment, original merchant order number, and correct direction. For deposits, use DEPOSIT and the original deposit order number.

```python
trade = call("/trades/sync", {
    "tradeType": "WITHDRAWAL", "merchantOrderNo": "REPLACE_PERSISTED_WITHDRAWAL_ORDER_NO",
})
print(trade.get("status"))
```

### Requests and responses by endpoint

Merge each business body below with the common fields into **one top-level object**. Do not wrap it in `data` or `request`. The Java CLI adds common fields and signs, so its input files contain only business fields. Direct HTTP requests require the complete signed object.

| POST path | Example business body or reference | Complete response example |
|---|---|---|
| `/merchant-support` | `{}` | [Complete configuration support](#complete-merchant-configuration-support-post-merchant-support) |
| `/merchant-capabilities` | `{}` | [Merchant capability discovery section](#merchant-capability-discovery-post-merchant-capabilities) |
| `/payment-methods` | `{"countryCode":"TH","currency":"THB","tradeType":"DEPOSIT","amount":10000,"locale":"en-US"}` | [Query payment methods section, including methods/groups/fieldDefinitions](#1-query-payment-methods-post-payment-methods) |
| `/deposits/banks` | `{"countryCode":"TH","currency":"THB","paymentMethod":"REPLACE_METHOD_CODE","bankRole":"PAYER","amount":10000}` | [Unified deposit bank section](#unified-deposit-banks-post-depositsbanks) |
| `/withdrawals/banks` | `{"countryCode":"TH","currency":"THB","payoutMethod":"REPLACE_METHOD_CODE","amount":10000,"locale":"en-US"}` | [Unified withdrawal bank section](#unified-withdrawal-banks-post-withdrawalsbanks) |
| `/deposit/options` | `{"countryCode":"TH","currency":"THB","paymentMethod":"REPLACE_METHOD_CODE"}` | [Deposit amount options section](#2-query-deposit-amount-options-post-depositoptions) |
| `/deposits` | Complete request in the deposit creation section | [Create deposit section](#3-create-a-deposit-post-deposits) |
| `/deposits/query` | `{"merchantOrderNo":"deposit-20260910-001"}` | [Query deposit section](#4-query-a-deposit-post-depositsquery) |
| `/withdrawals` | Complete request in the withdrawal creation section | [Create withdrawal section](#5-create-a-withdrawal-post-withdrawals) |
| `/withdrawals/query` | `{"merchantOrderNo":"withdrawal-20260910-001"}` | [Query withdrawal section](#6-query-a-withdrawal-post-withdrawalsquery) |
| `/trades/sync` | `{"tradeType":"WITHDRAWAL","merchantOrderNo":"withdrawal-20260910-001"}` | [Synchronization section (WITHDRAWAL example)](#7-synchronize-a-transaction-post-tradessync) |

Complete payment-method HTTP JSON:

```json
{
  "mchNo": "REPLACE_MCH_NO",
  "appId": "REPLACE_APP_ID",
  "reqId": "req-methods-001",
  "nonceStr": "2123456789abcdef0123456789abcdef",
  "reqTime": "2026-09-25T02:00:00Z",
  "countryCode": "TH",
  "currency": "THB",
  "tradeType": "DEPOSIT",
  "amount": 10000,
  "locale": "en-US",
  "sign": "REPLACE_WITH_COMPUTED_SIGNATURE"
}
```

## Responses, transaction states, and payment display

The response envelope contains `code`, `msg`, `retryable`, `reqId`, `resTime`, and `sign`, with business content in `data`. Errors may omit `data`. Optional `reasonCode` distinguishes access-policy rejection and rate limiting. If absent or unknown, handle the original `code` and `retryable`; signature verification must still cover all received fields.

### Complete error response examples

Business errors normally still use signed JSON with HTTP 200; checking HTTP status alone is insufficient. Nonstandard responses such as proxy error pages leave the result unknown. These formats apply to the relevant business endpoints. Access rejection/rate limiting may additionally include reasonCode; see the complete rejection example later.

When request field constraints or manual business-parameter checks fail, `code=1001`, `retryable=false`, and `msg` identifies each field path and reason. Nested fields use dotted paths; multiple errors are sorted by path and separated by `; `, for example `amount: 金额不可小于一个最小货币单位; payer.email: 付款人邮箱格式不正确`. Rejected values, internal exceptions and raw PG diagnostics are not returned. Continue handling other business or access rejections by `code` and `reasonCode`; never parse or match `msg` text for business decisions.

Automatic routing also validates the unified field mappings for each PG. If every otherwise eligible candidate has invalid or missing information, PA reports one candidate's specific fields, such as `returnUrl: 必填`, instead of only `NO_AVAILABLE_ROUTE`; it does not combine all PG requirements. New requests are rejected before order creation, without reserving the merchant order number or idempotency key. Retries of historical orders that were never submitted to a PG also report specific fields. Accepted or unknown-result orders retain the existing recovery rules.

For example, a legacy bank field is rejected as follows:

```json
{
  "code": 1001,
  "data": null,
  "msg": "payer.bankCode: 请使用PA统一银行bankId",
  "retryable": false,
  "reqId": "req-invalid-bank-001",
  "resTime": "2026-10-19T09:28:13Z",
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

Remove `payer.bankCode` and put the string ID returned by the bank query in `payer.bankId`. Refresh the request timestamp, request ID and nonce, then sign again. Field constraints run before request signature verification; manual parameter checks run at the relevant business entry point and report the condition that actually failed. The corrected request must still pass subsequent checks. Verify the complete response signature as usual.

Manual checks cover the following inputs. Their messages come from the actual rejection branch; a `1001` never by itself identifies a bank-field error. Only checks that have actually run and failed are described. Multiple failures from the same check are returned together; correcting them can still expose a later failure:

| Field or location | Check represented by the reason |
|---|---|
| `path.environment`, `environment` | Invalid environment path, writing through `all`, or a body/path environment mismatch |
| `countryCode`, `recipient.countryCode`, `currency` | Missing/unavailable fiat country or mismatched fiat currency; unsupported digital asset or missing/disabled/unauthorized network |
| `locale`, `headers.Accept-Language` | Invalid language tag/range list or length |
| `notifyUrl` | Missing request and default URLs, or the effective URL is not valid HTTPS |
| `payer.bankId`, `recipient.bankId`, `targetBankId`, legacy bank fields | Invalid ID format/range or prohibited raw bank values/internal selectors |
| `payer.*`, `recipient.*`, `paymentMethodFields.*` | Actual required fields, wrong types, explicitly rejected blank strings, missing dependent fields or unsupported finite choices |
| `paymentMethodFields.payerBirthDate` | A real calendar date in `YYYY-MM-DD` format; PA never fills or guesses it |
| `amount`, `extend` and order scalar fields | Actual requiredness, positive-integer, format or length constraint |

For example, `paymentMethodFields.documentId: 必须为文本` reports a type error; an absent required field reports `必填` instead. If automatic routing cannot find one channel supporting the supplied finite-choice combination, `msg` names the participating fields and reports the combination mismatch; it does not claim that every value is individually invalid. A designated-channel mapping check likewise names the relevant `channelOptionId`, `amount` and payment-method fields without guessing which individual value is wrong.

A failed manual check stops subsequent order creation or PG dispatch in that call. Query the original order first if it already exists or an earlier creation result is unknown. Authorization, source allowlists, idempotency conflicts, unavailable routes, fee configuration and internal errors retain their existing business codes and disclosure boundaries; raw internal exceptions or account configuration are never returned as parameter diagnostics.

An order query can return no data when the order is not found (4001 does not prove that a timed-out creation can never persist):

```json
{
  "code": 4001,
  "msg": "ORDER_NOT_FOUND",
  "retryable": false,
  "reqId": "req-query-missing-001",
  "resTime": "2026-09-10T02:05:00Z",
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

When synchronization is incomplete but returns original order facts, handle nonzero `code` and optional `data.status` separately. The unconfirmed example omits status:

```json
{
  "code": 5001,
  "msg": "SYSTEM_BUSY",
  "retryable": true,
  "reqId": "req-sync-busy-001",
  "resTime": "2026-09-10T02:03:01Z",
  "data": {
    "orderNo": "PA_WITHDRAWAL_EXAMPLE_001",
    "merchantOrderNo": "withdrawal-20260910-001",
    "tradeType": "WITHDRAWAL",
    "amount": 10000,
    "currency": "THB", "decimalPlaces": 2,
    "createdAt": "2026-09-10T02:00:00Z",
    "updatedAt": "2026-09-10T02:03:00Z"
  },
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

This outcome remains uncertain: do not mark the payout failed or resubmit under a new order number. retryable=true does not permit changing business parameters. The states below apply to Trade returned by creation, queries, and synchronization.

### Transaction states and payment display

| State | Meaning | Integrator action |
|---|---|---|
| `status` absent | Outcome not yet confirmed | Retain the original order and idempotency key, query/synchronize and follow the review process; do not record success, infer failure or resubmit the same transaction under a new number |
| `SUCCEEDED` | Final success | Verify transaction facts and apply your success processing idempotently |
| `FAILED` | Final failure | Handle confirmed failure idempotently; do not replay the same final order with altered parameters as a new transaction |

PA retains `PENDING`, `PROCESSING`, `IN_DOUBT`, inquiry, recovery and manual review internally. `code=0` means the API request was processed successfully, not that payment succeeded. Creating a PG order or obtaining payment details is not payment success; unknown outcomes remain unresolved rather than becoming failures. Creation responses, queries, and notifications can race. Older facts must not overwrite newer state; isolate conflicting final states for review.

| `paymentMedium.type` | Field | Display behavior |
|---|---|---|
| `REDIRECT_URL` | `redirectUrl` | Open the provider cashier or PA hosted QR payment page |
| `QR_CONTENT` | `qrContent` | Generate a QR code from the exact content |
| `QR_IMAGE_URL` | `qrImageUrl` | Display the QR image |
| `BANK_ACCOUNT` | `bankAccount` | Display the receiving account details for this order |
| `TOKEN` | `token` | Use only in the agreed client payment flow for that method. Without instructions, contact PA; do not guess or treat the token as evidence of payment |

If present, provide `cashierAccessCode` with the cashier URL to this order's payer, and show validity based on `expiresAt`. Keep access codes, tokens, and cashier URLs out of shared logs. A browser return, page message, or displayed QR code cannot replace a server-verified transaction state.

PA preserves a complete payment-page URL supplied by the provider. If the provider returns only raw QR content or a QR image, PA returns `REDIRECT_URL` with the hosted payment page in `redirectUrl`. Integrators open that URL without rendering provider QR fields or building their own page. The page shows the amount, currency, payment method, order references and receiving details actually supplied by the provider. Payment state follows PA's verified server-side result.

When the provider supplies an expiry, the hosted link uses that deadline and displays a countdown. Without a provider expiry, PA uses a default expiry of 5 minutes, returns the actual `expiresAt`, and displays a countdown. Authorized operators can change the platform configuration `payment.hosted-qr`, using a positive integer `defaultTtlSeconds` (default `300` seconds); changes apply only to newly issued links. Refreshing or reopening resumes the same order and deadline without extending access or creating a new provider order. Legacy links without a stored expiry expire 5 minutes after their original creation. Page expiry does not mark the transaction as failed; the provider determines whether its payment details remain usable.

Use the actual `paymentMedium`, not a hardcoded provider name. For compatibility responses, encode `QR_CONTENT` unchanged rather than opening it as a URL, and display `QR_IMAGE_URL` as the original image. Preserve the complete `REDIRECT_URL` and its parameters; do not replace it with a provider API root, old order URL, or constructed path.

If a link is expired, check `expiresAt` if supplied and the original order state. Provider-hosted pages retain the provider's validity rules, and an expired page does not establish transaction failure. Apply unknown-outcome handling to creation/query timeouts; do not automatically create a new merchant order number. Use a new business order number for a separate new transaction without overwriting the original evidence.

### PG-specific constraints and exception handling

SSBO field limits do not replace PG-specific limits. SulifuPay limits playerId and payer name to 50 characters, bank code to 16, and return URL to 200. Its PG notification URL is configured by PA; that PG limit is not the limit for the integrator Webhook field. Credentials and gateways are maintained per merchant PG account, not supplied per transaction.

SulifuPay checks both the original order amount and requested payment amount; paying a different amount is currently unsupported. If amounts differ, payment details are incomplete, or an outcome is unknown, retain the PA order number and query/synchronize it; ask operations to inspect the PG attempt. Do not alter the amount or resend with a new idempotency key. A retained PG order number does not prove payment.

Use `paymentMedium` to distinguish redirects, QR images, and bank accounts; not every method returns a link. Record 403 responses, expired sessions, or incomplete human verification separately from payment success. Internal PG diagnostics help operations and do not become new SSBO top-level business codes. Continue checking signatures, business codes, and transaction state.

### Pay247 withdrawals awaiting approval

When Pay247 requires secondary approval, SSBO continues querying the unified order state and does not call PG confirm/reject APIs. An authorized merchant user approves in the PA merchant portal under Withdrawal records → Details, with secondary verification. Approval alone does not establish withdrawal success; PA queries and Webhooks determine the final result. Do not recreate the withdrawal under a new order number while approval is pending. This management/internal connector capability adds no public SSBO endpoint and changes neither signatures nor states.

<a id="webhook-notifications"></a>

## Transaction webhook notifications

Merchants select the rule under **API integration settings**. New merchants default to `FIELDS_RSA_V1`, the final-state field protocol with `SUCCESS` acknowledgment below; existing choices are preserved. `RAW_BODY_V1` uses raw-body signatures and JSON acknowledgment containing `eventId`. Both are signed by PA and verified with the **PA platform public key**. The merchant public key registered with PA verifies API requests.

Match the backend options to this guide by name and protocol value rather than their position in the list.

| Callback rule (same label as UI) | `webhook-signature` format | Signing input | Successful acknowledgment (HTTP 200 for both) |
|---|---|---|---|
| Standard event callbacks (RAW_BODY_V1) | `v1-rsa,<Base64 signature>` | `webhook-id.webhook-timestamp.raw HTTP request body` | JSON: `{"code":0,"message":"OK","eventId":"received event ID"}` |
| Field signatures for final states (FIELDS_RSA_V1) | `v1-fields-rsa,<Base64 signature>`, matching body `sign` | The 13 fields below in fixed order with RFC 3986 encoding | Exactly `SUCCESS`, without quotes, spaces or newline |

Both transaction-notification modes notify only confirmed `SUCCEEDED`/`FAILED` results and use the PA platform public key with `SHA256withRSA`. The prefix and comma identify the protocol and are excluded from the Base64 signature. Use the signing input and acknowledgment for the selected mode.

Queued events and subsequent retries use the current application rule after a switch. An already claimed attempt keeps its rule through signing and acknowledgment validation. Prepare the receiver before switching and briefly support both rules. Switching preserves event IDs, failure counts and internal payloads; it neither resends delivered events nor requeues dead letters. Historical events without verified currency precision need PA review; precision is never guessed or rounded.

Deposit and withdrawal defaults may be different, shared, or both empty when each request supplies `notifyUrl`. Both protocols resolve and save the destination when the order is first created; notifications and retries always use that saved URL. Backend default changes affect new orders only. An idempotent replay omitting the URL retains the original destination; changing it for the same idempotency key returns a conflict. Protocol changes do not reset failed attempts or automatically resend delivered/dead events. The following raw-body signature and JSON acknowledgment sections apply to the UI option **Standard event callbacks (RAW_BODY_V1)**.

### Simulated deposit and withdrawal integration

This feature is available only on PA test deployments. In **Merchant Management → Merchant Workbench → Merchant Profile**, an authorized operator can enable **Merchant debugging**. While enabled, all new deposits and withdrawals for that merchant are simulated and no orders are sent to a PG. The switch applies to the default, `production`, and `sandbox` paths. The `all` path remains read-only. Use the existing app, business request, signature, and idempotency key. There is no client-side simulation parameter.

Simulated orders retain the entry environment and validate the payment method, direction, currency and common required fields. No PG account or PG-specific parameters are required. They produce no PG attempts, fees, or commissions and are excluded from real-transaction totals, reports, withdrawal risk counts and order CSV exports.

Until a result is confirmed, the API omits `status`. An operator with the separate simulated deposit or withdrawal permission selects **Simulate success** or **Simulate failure** in the relevant order details. PA saves the terminal result and sends the configured transaction notification under the existing signature, acknowledgment, retry and dead-letter rules. Order queries and `/trades/sync` read the same result without contacting a PG. Repeating the same result does not create another terminal event. PA rejects a conflicting result. Use a new merchant order number and idempotency key for each independent test scenario.

Merchant debugging is off by default. Only authorized PA operators can change the audited switch. Turning it off restores the normal PG flow for new orders. Existing simulated orders stay simulated during replay and recovery, and real orders cannot be completed through simulation. PG sandbox, end-to-end and funds acceptance require separate evidence.

### Callback signature test

In the merchant portal, use **API integration settings → Test callback signature** to send one `POST application/json` to the current merchant's **saved, enabled default URL**. Select deposit or withdrawal; withdrawal falls back to the deposit URL when no separate URL is saved. PA uses the saved callback rule and the same PA platform private key as normal callbacks. The URL, merchant, order and body cannot be customized. Unsaved edits are ignored. Callback management permission is required; no configuration update or authenticator code is needed. This is a merchant portal operation, not an SSBO transaction API.

The payload format is fixed; only merchant identity, direction, unique test identifiers, current time and signatures are generated for the request. Both modes contain the current `mchNo`, `eventId=evt_test_<unique-id>`, `merchantOrderNo` and `orderNo=TEST_<unique-id>`, selected `tradeType` (`DEPOSIT` or `WITHDRAWAL`), `sequence=1`, `status=FAILED`, `currency=USD`, and `extend=PA_WEBHOOK_SIGNATURE_TEST`. USD and zero amounts are fixed signature samples, not evidence of currency authorization or any transaction.

| Mode | Fixed test payload and verification | Required acknowledgement |
|---|---|---|
| `RAW_BODY_V1` | Also includes `eventVersion=v1`, `eventType=webhook.test`, `test=true`, integer `amount=0`, and current UTC `occurredAt`; verify the raw bytes and headers as usual | HTTP 200, JSON `{"code":0,"message":"OK","eventId":"received test event ID"}` |
| `FIELDS_RSA_V1` | Also includes `callbackMode=FIELDS_RSA_V1`, string `amount="0.00"`, integer `requestAmount=0`, `decimalPlaces=2`, `signV2`, current UTC `finishTime`, `failReason=PA_WEBHOOK_SIGNATURE_TEST`, and `sign`; verify `sign` in the original 13-field order and `signV2` with the amount extension | HTTP 200 and exactly the plain text `SUCCESS`, without quotes, whitespace or newline |

Headers follow the selected protocol: `webhook-id`, `webhook-timestamp`, `webhook-signature`, and `webhook-attempt=1`. First verify with the PA platform public key, then identify the signed `extend` marker and only acknowledge the test. **Do not look up real orders, post funds, or trigger payment or withdrawal.** The raw-mode `webhook.test` event is reserved for this manual test and is separate from real transaction events.

Tests create no orders or normal delivery events, change no transaction state, and enter no retry or dead-letter queue. The production transport restrictions apply: public HTTPS, DNS checks, no redirects, a 30-second deadline, and a 64 KiB ACK limit. The result dialog distinguishes HTTP status from strict ACK validation and displays the response as text, limited to 4096 characters. On timeout or missing results, check receiver logs; PA does not retry automatically. A correct ACK only confirms the receiver response; it does not prove that the receiver performed verification or validate real orders or funds.

### Standard event mode: RAW_BODY_V1

PA sends `POST application/json` to the destination saved on the order, using at-least-once delivery. Notifications may be duplicated, arrive out of order, or precede the creation response. Persist your local order before sending a creation request.

New trade events created after the upgrade add integer `decimalPlaces` (0–18) to the original body, using the event's stored currency precision. Retries and manual replays retain the stored body and never read current configuration. `amount` remains an integer in minor units; display it as `amount ÷ 10^decimalPlaces`. The existing raw-byte signature covers this field, with no new signature field or algorithm. Historical events may omit it and retain their original body and signature handling; use only verified precision from the original order, without guessing.

### Headers and signature verification

| HTTP header | Content |
|---|---|
| `webhook-id` | Event ID; must equal body.eventId |
| `webhook-timestamp` | Delivery time as Unix seconds, not milliseconds |
| `webhook-attempt` | Delivery attempt, 1–10 |
| `webhook-signature` | `v1-rsa,<Base64 signature>`; if multiple space-separated signatures are present, match a valid entry using a verified public key |

Signing input is this byte concatenation:

```text
UTF8(webhook-id + "." + webhook-timestamp + ".") + raw HTTP request body bytes
```

Verify with the PA platform public key and RSA-SHA256. **Do not parse and reserialize JSON before verifying.** Whitespace, field order, and newlines affect the bytes. Preserve the original body first. Header names are case-insensitive. V1 events use `eventVersion=v1`; the signature prefix remains `v1-rsa,`.

Validate delivery time against current time; a maximum 300-second difference is recommended and used by the Java example. Also validate merchant, event ID/type, order numbers, direction, amount, and currency. Use the header's delivery timestamp for the window, not business `occurredAt`, because retries may concern older events.

Example event:

```json
{
  "eventId": "evt-example-001",
  "eventVersion": "v1",
  "eventType": "deposit.succeeded",
  "occurredAt": "2026-09-10T02:01:00Z",
  "mchNo": "REPLACE_MCH_NO",
  "orderNo": "PA_EXAMPLE_001",
  "merchantOrderNo": "deposit-20260910-001",
  "sequence": 3,
  "status": "SUCCEEDED",
  "amount": 10000,
  "currency": "THB",
  "decimalPlaces": 2
}
```

Event types are limited to `deposit.succeeded`, `deposit.failed`, `withdrawal.succeeded` and `withdrawal.failed`. The original internal sequence is retained; omitted intermediate events and observations can cause gaps.

### Persistence and acknowledgment

1. Verify the signature, event identity, and order facts.
2. In one business database transaction, persist event deduplication, update the order, and post business entries, or reliably enqueue subsequent processing.
3. After the transaction commits, return **HTTP 200** and the JSON below. Return the same acknowledgment for an already processed duplicate with matching facts.

```json
{"code":0,"message":"OK","eventId":"evt-example-001"}
```

`code` must be numeric `0`, `message` must be exactly `OK`, and `eventId` must match the received event. HTTP `204`, plain text `success`, string `"0"`, or `msg` instead of `message` is not a valid acknowledgment.

Deduplicate by `eventId` and use per-order `sequence` to prevent state regression. Isolate conflicting duplicate facts, different facts at the same sequence, or mismatched amounts/orders; do not acknowledge them as successful. A valid older event may be recorded as ignored and acknowledged without overwriting newer state. Failed verification or database transactions must not receive a successful acknowledgment.

### Standard event callback verification example (Node.js)

For the UI option `RAW_BODY_V1`. Save as `raw-webhook.mjs` and use Node.js 22 or later; only the built-in `node:crypto` module is required. Supply the **original Buffer**, headers with lowercase names, and the verified PA platform public key PEM. Capture raw bytes before JSON middleware parses the body. This example uses a 300-second delivery window.

```javascript
import { constants, verify } from 'node:crypto';

export function verifyRawCallback(rawBody, headers, platformPublicKey,
  nowSeconds = Math.floor(Date.now() / 1000)) {
  if (!Buffer.isBuffer(rawBody)) throw new Error('Expected the original body Buffer');
  const eventId = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  if (typeof eventId !== 'string' || !eventId || !/^[0-9]+$/.test(timestamp ?? '')) {
    throw new Error('Missing or invalid webhook headers');
  }
  const seconds = Number(timestamp);
  if (!Number.isSafeInteger(seconds) || Math.abs(nowSeconds - seconds) > 300) {
    throw new Error('Webhook timestamp is outside the allowed window');
  }
  const signedBytes = Buffer.concat([
    Buffer.from(`${eventId}.${timestamp}.`, 'utf8'), rawBody,
  ]);
  const valid = String(headers['webhook-signature'] ?? '').split(' ').some((entry) => {
    if (!entry.startsWith('v1-rsa,')) return false;
    const signature = entry.slice('v1-rsa,'.length);
    return verify('sha256', signedBytes, {
      key: platformPublicKey, padding: constants.RSA_PKCS1_PADDING,
    }, Buffer.from(signature, 'base64'));
  });
  if (!valid) throw new Error('Invalid webhook signature');
  const body = JSON.parse(rawBody.toString('utf8'), (name, value, context) => {
    if (name !== 'amount') return value;
    if (!/^[0-9]+$/.test(context.source)) throw new Error('Expected integer minor-unit amount');
    return BigInt(text);
  });
  if (Object.hasOwn(body, 'decimalPlaces') &&
      (!Number.isInteger(body.decimalPlaces) || body.decimalPlaces < 0 || body.decimalPlaces > 18)) {
    throw new Error('Invalid currency precision');
  }
  if (body.eventId !== eventId) throw new Error('Webhook event ID mismatch');
  return body;
}
```

Call `verifyRawCallback(rawBody, headers, platformPublicKey)` to obtain the verified event. Then validate merchant, order, amount and currency, persist reliably and handle idempotency before returning the JSON acknowledgment `{"code":0,"message":"OK","eventId":body.eventId}`. Return a non-200 status on an exception; do not acknowledge success.

### Payment amount mismatch handling

PA retains authenticated paid-amount evidence and reviews mismatches internally. Neither callback mode sends `deposit.amount_mismatch` or other unconfirmed results. A terminal notification is sent only after success or failure is confirmed; late observations do not regress an existing terminal result.

### Field signature mode: FIELDS_RSA_V1

This is the UI option **Field signatures for final states (FIELDS_RSA_V1)**.

Use POST, `application/json`, UTF-8. Only confirmed `SUCCEEDED` and `FAILED` results are notified. A timeout or cancellation becomes failure only after payment or payout is confirmed unsuccessful. Intermediate states and amount mismatches remain internal. Historical pending deliveries, retries and manual replays follow the same rule; switching callback modes never exposes intermediate states. A local timeout does not authorize a new payout.

The signed fields, in this exact order, are:

```text
callbackMode,mchNo,eventId,merchantOrderNo,orderNo,tradeType,sequence,status,amount,currency,finishTime,failReason,extend
```

All fields are strings except `sequence`, a positive integer rendered as decimal digits without leading zeros. `callbackMode` is `FIELDS_RSA_V1`; `tradeType` is `DEPOSIT` or `WITHDRAWAL`; `status` is `SUCCEEDED` or `FAILED`. Both order IDs match the original create request/response. Event IDs are stable across retries. Sequences increase per order and may skip values because intermediate states are not delivered. `finishTime` is the event completion time in UTC, `yyyy-MM-dd'T'HH:mm:ss'Z'`, without fractions. `failReason` is the recorded failure reason or failure code, otherwise empty; success uses an empty string. `extend` returns the original optional string, including spaces and Unicode; absent/null becomes an empty string. `sign` holds the standard Base64 signature and is excluded from signing.

Amount metadata is added without changing the original 13-field order or `sign`:

| Field | Type and meaning |
|---|---|
| `requestAmount` | Exact positive integer or decimal integer string: the original order amount in minor units, before division by `10^n` |
| `decimalPlaces` | Integer 0–18: the stored precision used to convert this event's `amount`; retries and replays do not read current configuration |
| `signV2` | Standard Base64 extension signature covering the original 13 fields and both amount fields |

For 10 THB at precision 2:

```json
{"amount":"10.00","requestAmount":1000,"decimalPlaces":2}
```

The exact equation is `amount × 10^decimalPlaces = requestAmount`. Keep `amount` as fixed decimal text; do not divide it again. Compare `requestAmount` directly with the original minor-unit request. Preserve all integer digits: large responses use strings; parse historical numeric JSON losslessly before any unsafe conversion to `Number`.

The legacy `sign` and `webhook-signature: v1-fields-rsa,<sign>` still cover only the original 13 fields. For `signV2`, append `&requestAmount=<decimal integer>&decimalPlaces=<decimal integer>` to that canonical string, with no leading zeros. Use the same platform key, RSA-SHA256 algorithm and RFC 3986 encoding. Neither signature field participates in either canonical string.

New field callbacks and signature-test probes send all three extension fields. Existing consumers may ignore them and continue validating `sign`. Before using metadata, new consumers must verify `signV2` and the amount equation. If any extension field is present, all three must be present; failure must never fall back to the legacy signature. During rollout, only messages missing all three may use legacy verification, without inventing missing values. After cutover, require the extension to prevent downgrade by removal of all three fields. `RAW_BODY_V1` keeps its minor-unit integer `amount` and raw-body signature.

`amount` uses the event's currency precision, from 0 to 18 digits: `"100"`, `"100.00"`, or `"100.00000000"`, for example. It is not always two decimals and is not a minor-unit integer. API creation/query amounts remain minor-unit integers. Success contains the confirmed amount equal to the order; failure contains the original order amount and does not establish that money was transferred. Underpayment, overpayment, currency conflicts and uncertain results require review and produce no successful callback. Use exact decimal arithmetic and verify both order IDs, direction, currency and amount after signature verification.

Use **RSASSA-PKCS1-v1_5 with SHA-256**, Java `SHA256withRSA`, standard Base64, RSA at least 2048 bits, X.509 SPKI public PEM. Do not use RSA-PSS or Base64URL. The key is used by RSA and is not appended to the canonical string.

For each value, percent-encode its UTF-8 bytes under RFC 3986: retain only `A-Z a-z 0-9 - . _ ~`, encode other bytes as uppercase `%HH`, and use `%20` for spaces, never `+`. Join the fixed fields as `name=encodedValue` separated by `&`, with no trailing separator, newline or BOM. Empty fields participate. Do not trim, normalize Unicode, or encode twice. JSON contains the original values; parse it before constructing the canonical string.

Download the [complete signature test vectors](/docs/pa/signature-test-vectors.json) for request/response signing and deposit/withdrawal success/failure examples, with canonical strings, final signatures, and public test keys. The example `extend` value is `903759 & 张三`, yielding `&failReason=&extend=903759%20%26%20%E5%BC%A0%E4%B8%89` at the end of the canonical string. These published keys are for offline tests only and must never be registered or used for transactions. Fixed example timestamps do not pass live freshness checks.

The body carries `sign`; the matching header is `webhook-signature: v1-fields-rsa,<same Base64 signature>`. Timestamp and attempt headers are tracing information and are not signed in this mode. Do not treat them as authenticated freshness evidence. Business fields remain stable across retries in this mode; signatures remain stable while the platform signing key is unchanged. Verify and update the platform public key when PA rotates its signing key. Deduplicate using signed merchant/order/event identity and sequence.

After durable processing, including a duplicate whose facts match, reply **HTTP 200 with exactly seven ASCII bytes `SUCCESS`**, preferably `text/plain; charset=utf-8`. No quotes, whitespace, newline or BOM. Lowercase `success`, `SUCCESS\n`, JSON, HTTP 204 or HTTP 400 fails acknowledgment and triggers retries. Invalid signatures, unknown orders, mismatched amounts, or failed transactions receive non-200 responses.

#### Field callback verification example (Node.js)

For the UI option `FIELDS_RSA_V1`. Save as `fields-webhook.mjs`; use Node.js 22 or later and the PA platform public key PEM. JSON may be parsed first. Preserve string values such as `amount` exactly; do not convert them to numbers and reformat. The original field order includes empty strings. The extension appends the two amount fields; both signatures exclude `sign`, `signV2`, delivery timestamps and attempt counts.

```javascript
import { constants, verify } from 'node:crypto';

const fieldOrder = [
  'callbackMode', 'mchNo', 'eventId', 'merchantOrderNo', 'orderNo',
  'tradeType', 'sequence', 'status', 'amount', 'currency',
  'finishTime', 'failReason', 'extend',
];
function encodeField(value) {
  return encodeURIComponent(value).replace(/[!'()*]/g,
    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
}
// Node.js 22+: preserve exact numeric and string amounts before Number can lose digits.
export function parseFieldsCallback(rawText) {
  return JSON.parse(rawText, (key, value, context) => {
    if (key !== 'requestAmount') return value;
    const text = typeof value === 'string' ? value : context.source;
    if (!/^(0|[1-9][0-9]{0,999})$/.test(text ?? '')) {
      throw new Error('requestAmount must be an exact integer or integer string');
    }
    return BigInt(text);
  });
}
export function verifyFieldsCallback(body, platformPublicKey, requireAmountMetadata = false) {
  if (body.callbackMode !== 'FIELDS_RSA_V1' || typeof body.sign !== 'string') {
    throw new Error('Invalid field callback');
  }
  const canonical = fieldOrder.map((field) => {
    const value = body[field];
    const valid = field === 'sequence'
      ? Number.isSafeInteger(value) && value > 0 && value <= 2147483647
      : typeof value === 'string';
    if (!valid) throw new Error(`Missing or invalid field: ${field}`);
    return `${field}=${encodeField(String(value))}`;
  }).join('&');
  const validSignature = (text, signature) => typeof signature === 'string'
    && verify('sha256', Buffer.from(text, 'utf8'), {
      key: platformPublicKey, padding: constants.RSA_PKCS1_PADDING,
    }, Buffer.from(signature, 'base64'));
  if (!validSignature(canonical, body.sign)) throw new Error('Invalid webhook signature');
  const metadata = ['requestAmount', 'decimalPlaces', 'signV2'];
  const extended = metadata.some((field) => Object.hasOwn(body, field));
  if (!extended) {
    if (requireAmountMetadata) throw new Error('Amount metadata required');
    return body; // Legacy: no authenticated requestAmount or decimalPlaces.
  }
  if (!metadata.every((field) => Object.hasOwn(body, field))) {
    throw new Error('Incomplete amount metadata');
  }
  const value = body.requestAmount;
  const minor = typeof value === 'bigint' ? value
    : Number.isSafeInteger(value) ? BigInt(value) : null;
  const scale = body.decimalPlaces;
  if (minor === null || minor < 0n || minor.toString().length > 1000
      || !Number.isInteger(scale) || scale < 0 || scale > 18) {
    throw new Error('Invalid amount metadata');
  }
  const extendedCanonical = `${canonical}&requestAmount=${minor}&decimalPlaces=${scale}`;
  if (!validSignature(extendedCanonical, body.signV2)) {
    throw new Error('Invalid signV2'); // Never fall back to sign.
  }
  const digits = minor.toString().padStart(scale + 1, '0');
  const expected = scale === 0 ? digits : `${digits.slice(0, -scale)}.${digits.slice(-scale)}`;
  if (body.amount !== expected) throw new Error('Amount conversion mismatch');
  return body;
}
```

Use `parseFieldsCallback` before verification; parsed `requestAmount` is a `BigInt`, while wire JSON may be an integer or a decimal integer string. Pass `true` after cutover to require metadata; use `false` only during legacy migration. An invalid extension is always rejected. The verifier does not perform business posting or ACK. Identify signature-test probes separately and never post their zero amount.


Call `verifyFieldsCallback(parseFieldsCallback(rawBody.toString('utf8')), platformPublicKey, true)`. Body `sign` is already plain Base64; do not add `v1-fields-rsa,`. If reading the signature from the header, remove the prefix and comma and check it matches body `sign`. After verification, validate merchant, order, direction, amount, currency, status and event idempotency facts. Only after reliable processing return HTTP 200 with exactly `SUCCESS`; return a non-200 status on an exception. This example does not implement business posting or automatic acknowledgment.

Store a unique `eventId`, and prevent order state regression by direction and `sequence`. A verified older event may be recorded as ignored and acknowledged. Conflicting duplicates or the same sequence with different facts must be isolated without a successful acknowledgment. Queries and callbacks share order locking/transactions and a unique posting constraint. For missing final notifications, exhausted retries or an API response without `status`, query the original direction with `/deposits/query` or `/withdrawals/query`, and use `/trades/sync` as needed. Preserve the original merchant order ID and idempotency key. Reconcile funds, fees and orders through statements and PA's reconciliation process; a successful query response alone does not prove unverified funds.

### Delivery retries

Both modes allow 30 seconds for the receiver response and do not follow redirects.

PA attempts delivery at most 10 times, including the first immediate attempt. Each subsequent wait after the preceding failed attempt is: 30 seconds, 2 minutes, 5 minutes, 15 minutes, 30 minutes, 1 hour, 3 hours, 6 hours, and 12 hours. Actual timing also depends on scheduling.

After exhaustion, the event remains a dead letter for PA support/operations to handle and manually redeliver. Redelivery does not change transaction state. Continue periodically querying unresolved orders; do not rely solely on callbacks.

## Idempotency, retries, and errors

Management PG account “unpaid order verification” records (PV numbers) are independent of SSBO merchant orders. Their `UNKNOWN` and `FAILED_CONFIRMED` statuses are verification states, not API transaction states. Operations query the original verification order when its result is unknown. A new verification requires confirmed failure/non-acceptance, renewed confirmation, and MFA. Do not apply that management retry workflow to SSBO orders; follow the original-order and original-key rules below.

`reqId` identifies an HTTP request; `nonceStr` protects against replay; `merchantOrderNo` identifies a business order; `idempotencyKey` identifies its creation operation. They are not interchangeable.

Within one merchant/application, order numbers and idempotency keys remain permanently occupied across deposits and withdrawals. Retry a business creation with the same order number, idempotency key, and business fields. Refresh only `reqId`, `nonceStr`, and `reqTime`, then sign again. Do not resend an old signed HTTP body unchanged.

After timeout, disconnection, system busy, or signature verification failure, query the original order and synchronize if needed. Retry original business parameters only when permitted; never use a new number to repeat a payout. Changing the method, recipient details, amount, currency, notification URL, selected channel, or other business parameters is not an idempotent retry. Preserve and query the original order after configuration changes.

`retryable=true` permits a retry with identical business parameters and both business keys. It does not authorize a new transaction or imply failure. Even when `code != 0`, inspect any returned existing-order facts. `4001` alone cannot prove that an earlier timed-out creation will never persist.

| code | Identifier | Action |
|---|---|---|
| 0 | SUCCESS | Inspect data and, for transactions, status |
| 1001 | INVALID_PARAMETER | For field constraints or manual parameter checks, read the field paths and reasons in msg; otherwise check required/dynamic fields, merchant/application relationship, scopes, source IP, request notification URL or backend default, and enabled configuration |
| 1002 | SIGNATURE_INVALID | Check keys, flattening, null handling, and the original timestamp text; sign again |
| 1003 | REPLAY_REJECTED | Check clock and nonce; sign fresh request metadata |
| 2001 | IDEMPOTENCY_CONFLICT | The key is bound to different facts; stop retrying and reconcile local records |
| 2002 | MERCHANT_ORDER_CONFLICT | The order number is occupied; query and reconcile it, without a new number for a repeated payout |
| 3001 | NO_AVAILABLE_ROUTE | Refresh options and ask PA to check route availability |
| 3002 | RISK_REJECTED | Follow the business process for risk rejection |
| 3003 | INSUFFICIENT_BALANCE | Ask PA to check funds in the relevant channel |
| 3004 | FEE_POLICY_UNAVAILABLE | Ask PA to check applicable fee configuration |
| 3005 | CHANNEL_SELECTION_REQUIRED | Select channelOptionId for designated mode before an order has been created |
| 3006 | CHANNEL_OPTION_UNAVAILABLE | Query the original order first; do not blindly retry altered parameters |
| 3007 | CHANNEL_EXECUTION_FAILED | Check the returned transaction state and original order |
| 4001 | ORDER_NOT_FOUND | Check environment, application, order number, and direction; continue investigating unknown creation outcomes |
| 5001 | SYSTEM_BUSY | Includes rate limits/transient errors; back off and query the original order, avoiding rapid retries |

### Optional rejection reasons and handling order

These details do not change the main business code or its `retryable` value. Older deployments may return only the main code. Reasons are returned only after application signature verification and do not disclose scope lists, allowlists, counters, or internal exceptions.

Example error with a placeholder signature. `msg` is display text, not a programmatic discriminator:

```json
{
  "code": 1001,
  "msg": "INVALID_PARAMETER",
  "retryable": false,
  "reasonCode": "SCOPE_DENIED",
  "reqId": "req-methods-001",
  "resTime": "2026-09-25T02:00:01Z",
  "sign": "REPLACE_WITH_PA_SIGNATURE"
}
```

Even without `data`, verify the signature and `reqId` before handling access denial. A failed query after creation timed out does not prove that the original transaction failed.

| reasonCode | Main code | Action |
|---|---|---|
| `SCOPE_DENIED` | 1001 | Ask PA to check endpoint authorization; repeated identical requests cannot obtain permission |
| `SOURCE_IP_DENIED` | 1001 | Check the calling server's actual egress IP and application allowlist; changing clientIp does not change source authorization |
| `RATE_LIMITED` | 5001 | The application/scope exceeded its fixed per-minute window; back off with jitter to avoid synchronized retries |

If rate-limit counting fails, PA returns `5001` without `RATE_LIMITED` and does not execute the business operation. Access denial/rate limiting describes this request only; it does not prove that an earlier request for the same order is absent or failed.

Handling order: verify the signature and correlation → inspect `code` and optional `reasonCode` → check returned transaction facts. For an existing order with no returned `status`, query/synchronize the original; `retryable` does not permit a new order. Retain business parameters and both keys on a retry, and regenerate `reqId`, `nonceStr`, `reqTime`, and the signature. Rate limiting occurs after nonce validation, so do not resend the same signed payload.

Query intervals, timeouts, and rate limits depend on application configuration. The Java example's 15-second overall response deadline is a client default, not a guarantee that PA completes a transaction in that time. For support, provide environment, timezone-qualified time, `reqId`, merchant order number, PA order number, and business error code, with sensitive information redacted.

## Java example and integration acceptance

Obtain the Java integration example from PA. It requires Java 21+ and includes the current V1 business endpoints, including merchant capabilities and unified deposit/withdrawal banks, signing/verification, a Webhook receiver, and persistent deduplication examples. Follow the supplied instructions to configure and run it; start with the offline demo, which requires no account.

The Java receiver currently supports only `RAW_BODY_V1`. Select standard event mode explicitly when using it. New merchants default to field mode, which requires a receiver implementing the field canonicalization and fixed acknowledgment described here.

For real integration, fill in the example configuration `config/config.example.json`; `baseUrl` includes `/unipay/pa/v1`. Keep request templates and keys in a protected private location on your server. Configure HTTPS forwarding for the Webhook receiver, query available methods, then create agreed test orders. CLI creation and synchronization require `--allow-write`.

To transmit a complete JSON request already signed on your server, replace the domain/private file paths as needed:

```bash
curl --request POST 'https://api.tktkpay.com/unipay/pa/v1/payment-methods'   --header 'Content-Type: application/json'   --data-binary @/private/payment-methods.signed.json   --output /private/payment-methods.response.json
```

This curl command only transports data; it neither signs nor verifies. Generate a fresh signature before transmission and verify the saved response before using its data. Do not submit expired example timestamps or placeholder signatures.

During integration, prepare merchant and service authorization through the management UI, then use SSBO to query methods and actual amount options → submit one deposit → verify signature and order correlation → display the real payment page or QR code → query/synchronize the original order. This stage does not include scanning to pay, actual deposits, or payouts. The requester separately accepts real deposits, withdrawals, settlement, and public callbacks after handover.

Triage failures separately: internal validation/parsing errors or requests that never leave PA go to development; actual PG allowlist/authentication/channel/amount rejections go to the requester and PG with redacted correlation evidence. Record human verification, expired links, and cashier display errors separately. Do not assume every PG failure is a credential issue, switch protocols speculatively, or copy unrelated channel fields and resend.

Before completing integration and later funds acceptance, verify:

- Request/response signatures and flattening of Chinese text, empty strings, booleans, and nested arrays; wrong keys and tampered responses are rejected.
- Availability, actual amount intervals, fixed denominations, dynamic fields, and expired channel selections are handled.
- Unpaid test order, current payment medium, and original-order query evidence are retained; later authorized funds tests reconcile deposits, withdrawals, settlement, and callbacks.
- Creation timeouts, duplicate submissions, changed parameters with the same idempotency key, and repeated nonces do not cause duplicate business transactions.
- Invalid, duplicated, reordered, wrong-amount, early-arriving, and lost-ACK Webhooks, plus transaction failures, are handled correctly.
- An absent `status` means the outcome remains unconfirmed; queries compensate for missing notifications; final business processing happens once.
- Test and production settings are separately confirmed; keys and sensitive payment data stay out of frontends and public logs.

The Java example's local-file persistence is for demonstration. Production multi-instance services should use their own database transactions for consistent event deduplication and accounting. Passing the offline demo does not complete real PG integration.

## Field reference

The following objects and response fields are used by the API. Optional fields may be omitted. Dynamic `requiredFields` can make payer, recipient, or method fields mandatory. Accept new optional fields within the same major version, and verify the entire received response.

### Populating dynamic required fields

`requiredFields` contains logical names. Map them below; other method-specific fields belong in `paymentMethodFields` under the exact returned names.

| Logical field | Request location |
|---|---|
| clientIp | Top-level field with the same name (common field for all endpoints) |
| playerId / returnUrl (deposit) | Top-level field with the same name |
| payerName / payerAccount / payerPhone / payerEmail | payer.name / account / phone / email |
| payerBankId / targetBankId / bankId | payer.bankId / top-level targetBankId / recipient.bankId; select from unified bank queries |
| payerBirthDate (deposit) | paymentMethodFields.payerBirthDate |
| beneficiaryName / accountNo | recipient.name / account |
| phone / email / ifsc / countryCode (withdrawal) | Same-named field under recipient |

Do not put structured payer/recipient fields only in `paymentMethodFields` instead of their designated locations; the backend overwrites same-named values with the structured fields.

`fieldDefinitions` supplies display names, input types, and request paths for form generation. It is not a required-field list or a claim that every PG accepts all catalog fields. Use the selected method/channel's `requiredFields`; optional data must also meet that PG's requirements. If an older version omits the catalog, use the mapping above and agreed channel requirements.

To synchronize a complete field list, use `/merchant-support` once. Only the legacy incremental flow queries `/payment-methods` separately for each enabled country, currency, environment and direction. Omit the amount to inspect authorized methods, channels and each `amountRules[]` entry; optionally query current availability with the actual amount; a complete support snapshot also permits local filtering followed directly by creation. Satisfy both the method's common requirements and the selected channel's applicable rule, using `requestPath` for placement. The response identifies anonymous channels and exposes no PG accounts or credentials. `fieldDefinitions` provides names, input types, request paths and supported finite choices; it does not expose every PG-specific length, pattern, identity or account-ownership check. Confirm undocumented channel requirements with PA; a missing catalog restriction does not establish that no restriction exists.

These examples explain mapping only. Always read `channels[].requiredFields` for the actual merchant, direction, currency, and amount.

Bank requiredness follows the actual PG transaction protocol, not a shared product default. `channels[].requiredFields` uses `payerBankId` → `payer.bankId`, `targetBankId` → top-level `targetBankId`, and `bankId` → `recipient.bankId`. ValuePay PromptPay payin has no bank input; its bank payout requires `recipient.bankId`. Historical orders and immutable provider snapshots remain unchanged. Old raw-code creation requests are rejected; query an unknown original result before any retry.

| Scenario | Integrator action |
|---|---|
| DirectPay deposit requires payer email | Populate `payer.email`; do not omit or fabricate it because an older example is empty |
| VCPay fixed-denomination deposit | Map payerName/payerAccount to `payer.name`/`payer.account`; submit the PA ID from a TARGET bank query as top-level `targetBankId` |
| TGCpay deposit | Send top-level `clientIp`. `payer.name`/`payer.account` map to PG real_name/bank_card_number. Submit `payer.bankId`; PA supplies the complete PG bank name from its deposit mapping. Raw bank names and codes are rejected. Follow account requirements and check that the returned payment page has no missing-parameter error |
| ValuePay type UUID / HonorPay deposit type | PA configures the PG method mapping. SSBO uses the returned PA method and channel option; PG credentials and unrelated channel codes are not payment fields |
| Monetix MXN (SPEI deposits) | Optional `paymentMethodFields`: `payerTaxId` (RFC), `payerDocumentId` (CURP) and `payerDocumentType` (the value confirmed by the provider for this project, separate from payout enums). Provide CURP and its type together. Omit all three or leave them blank to keep checkout collection. Values are preserved, limited to 255 characters, never truncated or restricted to digits; semicolons are rejected. A published PG configuration containing these mappings is required. TRY is unaffected. |
| Monetix TRY (bank transfers in Turkey) | Deposit: `payer.account` is the payer's account (an IBAN may be used). Payout: `recipient.account` is the Turkish IBAN (26 characters, spaces allowed) and `recipient.name` the recipient's full name (required). Choose the bank only with `recipient.bankId`; PA maps the 5-digit bank code and checks it against the IBAN. Top-level `clientIp` is required; no identity document or account type. A wrong IBAN check digit or an IBAN from another bank is rejected before anything is sent to the PG (`PG_PREFLIGHT_NOT_SUBMITTED`) |
| Hızlı Havale TRY (bank transfers in Turkey, `bank_transfer`) | Deposit: top-level `playerId` (the PG customer ID) and `payer.name` (the payer's full name) are required. The result is `paymentMedium.type=REDIRECT_URL` to the Hızlı Havale payment page; use the returned `expiresAt` (sessions last 30 minutes). One player has at most one active session at Hızlı Havale: while another order's session is active, this channel does not open the new deposit and returns no link; PA tries another available channel, otherwise the request fails with `CHANNEL_EXECUTION_FAILED`. Payouts are not available through Hızlı Havale yet: PA routes payouts only to channels with a real-time balance check, which this PG does not offer, so a TRY withdrawal is served by another available channel or returns `NO_AVAILABLE_ROUTE`. Once enabled, payouts need `recipient.account` (the Turkish IBAN, 26 characters, spaces allowed) and `recipient.name` (the recipient's full name), both required; `paymentMethodFields.playerId` is optional; no `clientIp`, bank code or identity document; an invalid IBAN is rejected before anything is sent to the PG (`PG_PREFLIGHT_NOT_SUBMITTED`) |
| Fenito TRY (IBAN transfers in Turkey, `bank_transfer`) | Deposit: top-level `playerId` is required by the PA creation API (sent as the Fenito client ID); optionality in the provider protocol does not override the PA requirement; no payer fields are sent. The result is `paymentMedium.type=BANK_ACCOUNT`: `bankAccount` is a JSON string with `receiver_account` (the IBAN to pay, uppercase without spaces), `receiver_name` (the account holder), `receiver_bank_code` (Fenito bank code, may be absent) and `receiver_bank_name` (only when Fenito returns a bank name). Show the payer the IBAN, the holder and the deadline `paymentMedium.expiresAt`; the payer must transfer exactly the order amount (a different amount goes to manual review, never automatic success). When Fenito issues no bank details this channel fails and PA tries another available channel, otherwise the request fails with `CHANNEL_EXECUTION_FAILED`. Payouts are not available through Fenito yet: Fenito's documentation example shows the balance in USDT, and the currency of a TRY store's balance is to be confirmed (Fenito Q4); if it is not TRY, balance sync fails with `BALANCE_CURRENCY_MISMATCH` and a TRY withdrawal has no route through Fenito (`NO_AVAILABLE_ROUTE`; PA never converts currencies); in addition, until Operations add bank codes confirmed by Fenito, every Fenito payout is rejected before anything is sent. Once enabled, payouts need `recipient.account` (the Turkish IBAN, 26 characters, spaces allowed) and `recipient.name` (the recipient's full name), both required, and the bank via `recipient.bankId`; `paymentMethodFields.playerId` is optional. An invalid IBAN or an unconfirmed bank code is rejected before anything is sent to the PG (`PG_PREFLIGHT_NOT_SUBMITTED`) |

When specifying `channelOptionId`, use that option's required fields. If it expires, query again; do not silently switch to a channel with different requirements. `KHUSD` is a documentation category: CapitalPay uses country `KH` and currency `USD`, not currency `KHUSD`. Convert amounts to minor units using the account currency's precision.

### Automatic routing required-field workflow

Automatic routing does not ask the player to choose a PG, but the integration must still inspect candidate-channel requirements. `methods[].requiredFields` contains common method requirements only; an empty list does not remove `channels[].requiredFields`. There is currently no separate field containing a final automatic-routing required-field list, and discovery does not reserve the final channel.

1. **Fix the transaction context.** Call `/payment-methods` under the production or sandbox base path that will be used for creation, with the currency, direction and actual integer minor-unit `amount`. Pass the country for fiat currencies. With MYR precision 2, 10.00 MYR is `1000`. Discovery without an amount previews configuration and does not replace this query.
2. **Read candidates for one method.** Find the selected method in `data.methods[]` or `data.groups[].options[]`; require `available=true`, `channelSelection=AUTOMATIC` and a nonempty amount-specific `channels[]`. Do not merge candidates across methods or discard automatic-routing channels marked `cashierVisible=false`. Stop and check configuration or amount when no candidate is available.
3. **Keep requirements per candidate.** A candidate must satisfy both common method fields and its own fields. If multiple `amountRules[]` are returned, retain rules matching the actual amount and restrictions; alternative rules do not make all mutually exclusive requirements mandatory. Match each logical field `code` to its `requestPath`, preferring the channel definition over the top-level catalog. For example, `payerName` and `payerEmail` map to `payer.name` and `payer.email`. The catalog itself is not a required-field list. Obtain real values from the payer, recipient or merchant configuration, rather than copying examples.
4. **Collect data and retain compatible candidates.** At least one candidate must have all required data and pass field validation for automatic routing to proceed on data requirements. To allow more candidates to participate, collect compatible fields that the business needs. Optional fields are validated when supplied; empty or fabricated values and blindly combining every field do not expand routing safely. Query banks through the unified endpoint for the correct direction and role. A bank, account type, document type and other selected values must all be supported by the same candidate; do not union channel-specific choices or combine individually valid values that no single channel accepts together.
5. **Submit an automatically routed order.** Populate the mapped locations, add the creation endpoint's common required fields, sign the request and omit `channelOptionId`. PA applies the configured route among candidates satisfying the data and other current conditions. Supplying the ID designates a channel instead of letting PA choose automatically. Discovery reserves no quota and guarantees no execution result; withdrawals still refresh balances before execution.
6. **Handle changes and rejection.** While preparing a new order, query again and clear stale selections whenever environment, country, currency, direction, method or amount changes. If every current candidate lacks required data, PA returns `1001` with one candidate's missing fields, such as `payer.email: 必填`; this is not an aggregate of every candidate's requirements. Confirm a pre-creation rejection with no order created before completing the data and signing a new submission. For accepted, unknown or transport-uncertain outcomes, query the original order first; do not change the order number or parameters and resubmit.

The following **hypothetical channels for the same method** illustrate payer-field differences only, not current PG configuration. Common creation fields and all other validation still apply.

| Candidate | `requiredFields` | Request locations |
|---|---|---|
| A | `payerName`, `payerEmail` | `payer.name`, `payer.email` |
| B | `payerName`, `payerPhone` | `payer.name`, `payer.phone` |

| Valid data supplied | Candidates satisfying data requirements |
|---|---|
| Name and email | A; B lacks a phone number |
| Name and phone | B; A lacks an email address |
| Name, email and phone, valid for each candidate | Both may participate; current conditions and routing rules still determine the final choice |
| Name only | Neither; pre-creation `1001` may name email or phone and does not mean both are mandatory |

If the business requires a particular candidate, query again, submit its `channelOptionId` explicitly and collect that channel's fields and choices. This is designated-channel routing.

### Payer

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `name` | string | Per channel | Payer name, used for PG payer details and transaction identification. Optional at the common level; maximum 128. Logical field `payerName`, request path `payer.name`; must be nonblank when required by the channel |
| `account` | string | Per channel | Actual payer account, used for PG payer-account details and transaction identification. Optional at the common level; maximum 128. Logical field `payerAccount`, request path `payer.account`; must be nonblank when required by the channel |
| `phone` | string | No | Maximum length: 32 |
| `email` | string | No | Email format; Maximum length: 254 |

| `bankId` | string | By PG protocol | Actual PA ID from the PAYER bank query; positive int64 decimal string, maximum 19 characters |

Provide the actual payer or account holder's name as required by the payment method. The common API imposes no universal English-only, letter-case or name-pattern rule and performs no universal bank identity or name-to-account ownership verification. Individual PGs may require a specific format or a match to account details. For example, SulifuPay limits payer names to 50 characters, so the common 128-character limit is insufficient for that channel. When local-script or separate first/last names are required, populate the returned fields at `paymentMethodFields.payerNameLocal` or `paymentMethodFields.payerFirstName` / `paymentMethodFields.payerLastName`; do not split or replace `payer.name` yourself.

Send the payer account as a string, preserving leading zeros; do not convert it to a JSON number. The common API imposes no universal digits-only, fixed-length, bank-card checksum or IBAN check. Account type and format depend on the selected channel; for example, a Monetix TRY deposit may use the payer's IBAN. Do not put the PG-assigned destination collection account in `payer.account`, or use it in place of withdrawal `recipient.account`. Omit these two fields when optional; when required, provide actual nonblank values rather than placeholder names or fabricated accounts. Passing format validation does not establish identity or account ownership.

### Recipient

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `name` | string | Yes | Maximum length: 128 |
| `account` | string | Yes | Maximum length: 128 |
| `phone` | string | No | Maximum length: 32 |
| `countryCode` | string | Yes | Two uppercase letters, for example TH |
| `bankId` | string | By PG protocol | PA ID from /withdrawals/banks; positive int64 decimal string, maximum 19 characters |


| `email` | string | No | Email format; maximum 254; required when mandated by the channel |
| `ifsc` | string | No | Maximum length: 32; required when mandated by the selected channel |

### PaymentMethodFields

Dynamic key-value object with at most 32 entries. Use names and values required by the current method/channel; there is no fixed universal field list.

### PaymentMethods

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `tradeType` | string | Yes | DEPOSIT / WITHDRAWAL |
| `methods` | array<PaymentMethodOption> | Yes | Original method list, retained for compatibility |
| `groups` | array<PaymentPresentationGroup> | No | Resolved merchant presentation groups |
| `fieldDefinitions` | array<PaymentFieldDefinition> | No | Logical field catalog for this trade direction; display/mapping metadata, not a replacement for requiredFields |
| `decimalPlaces` | integer | No | Precision for response amounts, 0–18; older services may omit it, never invent it |

### PaymentFieldDefinition

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `code` | string | Yes | Logical name matching the corresponding requiredFields entry |
| `name` | string | Yes | Chinese display name |
| `nameEn` | string | Yes | English display name |
| `requestPath` | string | Yes | Request path, for example payer.name or payer.bankId |
| `inputType` | string | Yes | text / date / email / tel / url / select; input presentation hint |
| `configurable` | boolean | Yes | Whether operations may configure it as an additional required field; does not imply that it is optional or supported by every PG |
| `label` | string | No | Field label in the resolved locale; name/nameEn remain compatible |
| `options` | array<PaymentFieldChoice> | No | Channel-specific finite choices; submit the value string, not the label; the top-level catalog may return an empty array |

Example deposit field definition. The required fields still come from the selected channel's `requiredFields`. The `name` value remains Chinese by contract; English clients can display `nameEn`:

```json
{
  "code": "payerBankId",
  "name": "付款银行名称",
  "nameEn": "Payer bank name",
  "requestPath": "payer.bankId",
  "inputType": "text",
  "configurable": false
}
```

Deposit `playerId` has `configurable=false`: operations cannot edit it as an additional required option, but clients must still send top-level `playerId` for deposit creation. Put `payerBirthDate` in `paymentMethodFields.payerBirthDate`; its input type is `date`.

All merchant fields with `inputType=date` use a `yyyy-MM-dd` string (years 0001–9999), for example `1990-05-21`. Supply a real Gregorian calendar date without a time, time zone or surrounding whitespace. `2024-02-29` is valid; `2025-02-29`, `21/05/1990`, `19900521` and timestamps are invalid. PA validates dates before creating an order or calling a PG and returns `1001 INVALID_PARAMETER` for invalid values. Optional non-null dates follow the same rule; omit an absent optional date or send null, never an empty string. Current method/channel rules still determine whether a field is required. Each PG adapter converts the date to its provider format, so switching PGs or using automatic routing requires no merchant format changes. Date-only values do not undergo time-zone conversion; date-time fields such as `reqTime` retain their existing time-zone contract.

When a channel returns `inputType=select`, override the top-level display metadata for that `code` with the channel definition. For example, `requestPath=paymentMethodFields.accountType` means submitting the selected `options[].value` at that location. Empty `options` does not permit arbitrary input. Ask PA to check missing required choices; do not invent account/document type codes. Automatic routing also requires a single candidate channel to accept the submitted combination of choices.

Example channel-specific choices (`EXAMPLE_VALUE` is illustrative; obtain the actual value from the current channel response):

```json
{
  "code": "accountType",
  "name": "收款账户类型",
  "nameEn": "Recipient account type",
  "requestPath": "paymentMethodFields.accountType",
  "inputType": "select",
  "configurable": true,
  "label": "Recipient account type",
  "options": [{"value": "EXAMPLE_VALUE", "label": "Example account type"}]
}
```

After selecting that example option, the request fragment is `{"paymentMethodFields":{"accountType":"EXAMPLE_VALUE"}}`. Submit the value at the field name/location specified by `requestPath`.

### PaymentFieldChoice

| Field | Type | Required | Description |
|---|---|---|---|
| `value` | string | Yes | Actual accepted value for this channel; preserve the string type and leading zeros |
| `label` | string | Yes | Localized display label; never the submitted value |

### PaymentPresentationGroup

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `code` | string | Yes | Presentation identifier; never submit as paymentMethod |
| `name` | string | Yes | Group name for the current locale |
| `options` | array<PaymentMethodOption> | Yes | Payment options, each retaining its own fields, amounts, and routing |

### PaymentMethodOption

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `code` | string | Yes | Maximum length: 64 |
| `name` | string | Yes |  |
| `available` | boolean | Yes |  |
| `ruleType` | string | Yes | RANGE / FIXED_DENOMINATIONS / MIXED; evaluate amountRules |
| `minAmount` | Amount | No | Integer minor units; Minimum: 1 |
| `maxAmount` | Amount | No | Integer minor units; Minimum: 1 |
| `amountRanges` | array<DepositAmountRange> | No |  |
| `denominations` | array<Amount> | No |  |
| `requiredFields` | array<string> | Yes |  |
| `routeMode` | string | Yes | PRIORITY / ROUND_ROBIN / QUOTA_BALANCED / CALLER_DESIGNATED |
| `channelSelection` | string | No | AUTOMATIC / PLAYER / OPERATOR; designated deposits use PLAYER and designated withdrawals use OPERATOR |
| `channels` | array<ChannelOption> | Yes |  |
| `amountRules` | array<AmountRule> | No | Any one rule may match; all restrictions within it apply. Required to interpret MIXED rules |

### ChannelOption

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `channelOptionId` | string | Yes | Maximum length: 40 |
| `name` | string | Yes | Maximum length: 64 |
| `iconUrl` | string or null | No | Current default PG icon HTTPS URL; explicitly null when absent; older servers may omit it |
| `displayOrder` | integer | Yes | Minimum: 1 |
| `ruleType` | string | Yes | RANGE / FIXED_DENOMINATIONS / MIXED; evaluate amountRules |
| `minAmount` | Amount | No | Integer minor units; Minimum: 1 |
| `maxAmount` | Amount | No | Integer minor units; Minimum: 1 |
| `denominations` | array<Amount> | No |  |
| `requiredFields` | array<string> | Yes |  |
| `fieldDefinitions` | array<PaymentFieldDefinition> | No | Finite choices for this channel; do not merge channels; match code and use requestPath/options |
| `amountRanges` | array<DepositAmountRange> | No | Full union preserving gaps; do not use only the first minAmount/maxAmount |
| `amountRules` | array<ChannelAmountRule> | No | Per-amount rules with requiredFields/fieldDefinitions; amount-specific queries return matching rules |
| `cashierVisible` | boolean | No | Visible to deposit players; absence means true. False still participates in automatic routing and field discovery; hidden options cannot be designated |

### WithdrawalBanks / WithdrawalBank / WithdrawalBankChannel

| Object/field | Type | Description |
|---|---|---|
| `DepositBanks.countryCode/currency/paymentMethod/bankRole/amount` | string / string / string / string / Amount | Deposit query dimensions; banks use the withdrawal bank shape, with IDs submitted according to role |
| `WithdrawalBanks.countryCode/currency/payoutMethod/amount` | string / string / string / Amount | Query dimensions; keep consistent with creation. An amountless preview omits `amount` or returns null |
| `WithdrawalBanks.banks` | array<WithdrawalBank> | Empty array when no match exists |
| `WithdrawalBank.bankId` | string | Stable PA bank ID; submit as recipient.bankId |
| `WithdrawalBank.code/name` | string | Unified PA code/localized name for identification and display |
| `WithdrawalBank.ssCode` | string | Verified original SS code for this country; absent or null when unbound |
| `WithdrawalBank.channels` | array<WithdrawalBankChannel> | Anonymous channels supporting this bank and amount |
| `WithdrawalBankChannel.channelOptionId/name` | string | Channel ID/display name |
| `WithdrawalBankChannel.ruleType` | string | RANGE / FIXED_DENOMINATIONS / MIXED; evaluate amountRules |
| `WithdrawalBankChannel.minAmount/maxAmount` | Amount | Optional; intersected with bank limits |
| `WithdrawalBankChannel.denominations` | array<Amount> | Fixed denominations; may be empty for RANGE |

### DepositOptions

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `available` | boolean | Yes |  |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `paymentMethod` | string | Yes | methods[].code from payment-methods |
| `minAmount` | Amount | No | Lower bound of the first available interval, for compatibility; Minimum: 1 |
| `maxAmount` | Amount | No | Upper bound of the first available interval; null means no upper limit; Minimum: 1 |
| `amountRanges` | array<DepositAmountRange> | No | Currently available continuous intervals; multiple intervals represent coverage gaps |
| `ruleType` | string | No | RANGE / FIXED_DENOMINATIONS / MIXED; evaluate amountRules |
| `denominations` | array<Amount> | No |  |
| `retryable` | boolean | No |  |
| `decimalPlaces` | integer | No | Precision for response amounts, 0–18; older services may omit it, never invent it |
| `amountRules` | array<AmountRule> | No | Any one rule may match; all restrictions within it apply. Required to interpret MIXED rules |

### AmountRule / ChannelAmountRule

`AmountRule` requires `ruleType`, `denominations` and `restrictions`, with optional `minAmount/maxAmount`. `ChannelAmountRule` requires `ruleType`, `denominations`, `amountRanges`, `requiredFields` and `fieldDefinitions`, with optional `minAmount/maxAmount` and `restrictions`. One rule uses only `RANGE` or `FIXED_DENOMINATIONS`; `MIXED` describes an aggregate of different rules. Ranges, denominations and bounds use integer minor units.

Channel rules attach the fields and definitions needed for that amount rule; do not accumulate requirements from incompatible rules. Empty denomination, range or field arrays retain their respective structure. Availability still depends on actual-amount discovery and creation-time validation.

### AmountRestriction

All fields are optional. Apply every returned restriction together using exact integer arithmetic for amounts, steps and suffixes.

| Field | Type | Meaning |
|---|---|---|
| `integerOnly` | boolean | True accepts whole major-unit amounts only |
| `step` | string or null | Positive minor-unit integer text; amount must be a multiple starting at zero |
| `suffixDigits` | integer or null | Suffix length, 1–6 |
| `suffixBasis` | string | MINOR_UNIT uses the minor-unit integer; INTEGER_PART uses the integer part in major units |
| `allowedSuffixes` | array<integer> | Suffix allowlist; an empty list adds no whitelist restriction |
| `forbiddenSuffixes` | array<integer> | Suffix denylist |
| `decimalPlaces` | integer | PA-supplied precision, 0–18; do not override it |

### DepositAmountRange

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `minAmount` | Amount | Yes | Integer minor units; Minimum: 1 |
| `maxAmount` | Amount | No | Integer minor units; Minimum: 1 |

### ResponseBase

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `code` | integer | Yes | 0 / 1001 / 1002 / 1003 / 2001 / 2002 / 3001 / 3002 / 3003 / 3004 / 3005 / 3006 / 3007 / 4001 / 5001 |
| `msg` | string | Yes | Error explanation; field constraint or manual parameter failures include request paths and reasons, separated by semicolons. Never use the text for business decisions |
| `retryable` | boolean | Yes | Whether the same business parameters, merchant order number, and idempotency key may be retried; not a transaction state. Refresh request metadata and signature each time |
| `reasonCode` | string | No | Optional reason: SCOPE_DENIED / SOURCE_IP_DENIED / RATE_LIMITED; handle unknown values using the main code |
| `reqId` | string | Yes | HTTP request identifier; generate a fresh value for each request for correlation and diagnostics |
| `resTime` | string | Yes | PA response time; ISO 8601 with timezone |
| `sign` | string | Yes | Base64-encoded RSA-SHA256 signature |

### Trade

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `orderNo` | string | Yes | Maximum length: 64 |
| `merchantOrderNo` | string | Yes | Your business order number; retain the original after creation; Maximum length: 64 |
| `tradeType` | string | Yes | DEPOSIT / WITHDRAWAL |
| `status` | TradeStatus | No | SUCCEEDED / FAILED only; omitted while the outcome is unconfirmed |
| `amount` | Amount | Yes | Integer minor units; Minimum: 1 |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `paymentMedium` | PaymentMedium | No |  |
| `failureCode` | string | No | Stable business failure code that does not disclose the PG |
| `failureReason` | string | No | Controlled explanation for a confirmed failure or an unconfirmed outcome, such as the allowed amount range. A specific terminal reason takes precedence. Otherwise, the saved first error takes precedence over a later query without a reason. Branch on failureCode and query the original order if its outcome is uncertain |
| `retryable` | boolean | No |  |
| `createdAt` | string | Yes |  |
| `updatedAt` | string | Yes |  |
| `decimalPlaces` | integer | No | Precision for response amounts, 0–18; older services may omit it, never invent it |

### PaymentMedium

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `type` | string | Yes | REDIRECT_URL / QR_CONTENT / QR_IMAGE_URL / BANK_ACCOUNT / TOKEN |
| `redirectUrl` | string | No |  |
| `cashierAccessCode` | string | No | Optional cashier access code for this order; display to its payer when present. Separate from API credentials |
| `qrContent` | string | No |  |
| `qrImageUrl` | string | No |  |
| `bankAccount` | string | No |  |
| `token` | string | No |  |
| `expiresAt` | string | No |  |
| `ticketnara` | object | No | VaultOne gift details: receiverName, receiverMobile, partnerCode, productPageUrl. Display returned values and query the original order before resuming |

When VaultOne returns `ticketnara`, use this order’s details to fund the member’s own virtual account and then select gifting; buying and holding does not complete the gift. Query the original order before resuming; do not reuse stale details or create a replacement order.

### WebhookEvent

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `eventId` | string | Yes | Maximum length: 64 |
| `eventVersion` | string | Yes | Fixed value v1 |
| `eventType` | string | Yes | deposit.succeeded / deposit.failed / withdrawal.succeeded / withdrawal.failed |
| `occurredAt` | string | Yes |  |
| `mchNo` | string | Yes | PA-assigned merchant number; Maximum length: 32 |
| `orderNo` | string | Yes | Maximum length: 64 |
| `merchantOrderNo` | string | Yes | Your business order number; retain the original after creation; Maximum length: 64 |
| `sequence` | integer | Yes | Per-order state-event sequence, increasing from 1; Minimum: 1 |
| `status` | TradeStatus | Yes | SUCCEEDED / FAILED |
| `amount` | Amount | Yes | Integer minor units; Minimum: 1 |
| `currency` | Currency | Yes | Enabled fiat or digital-asset code |
| `decimalPlaces` | integer | No | Saved event precision, 0–18; may be absent in historical events, never invent it |
| `extend` | string | No | Preserved from creation when supplied, maximum 1024; covered by the raw-body signature |
| `failureCode` | string | No | Stable business failure identifier without raw PG errors; do not branch on msg text |

RAW event bodies provide optional `failureCode`, not the query response's `failureReason`. Field-mode `failReason` is defined in its protocol section.

### WebhookAck

| Field | Type | Required | Constraints and description |
|---|---|---|---|
| `code` | integer | Yes | Fixed value 0 |
| `message` | string | Yes | Fixed value OK |
| `eventId` | string | Yes | Maximum length: 64 |

## Management fields and API mapping

Required fields in unified payment-method management use PA V1 logical names as returned by `listPaymentMethods.requiredFields`, not raw PG parameter names. For example, payerName/payerAccount map to `payer.name`/`payer.account`. Send extensions according to the `paymentMethodFields` contract; the adapter converts them into PG requests. Platform configuration cannot remove adapter-mandated fields.

Merchant country/region and service countries are profile information and do not automatically grant payment capabilities. Published services and current `listPaymentMethods` results determine available countries, currencies, methods, and directions. Each merchant has one application, managed in the operations portal under Merchant management → Manage merchant → API integration configuration. The application ID remains an API field even if a management list column is hidden.

### Re-onboarding a revoked application

A merchant continues to have one `appId`. Operations administrators can re-onboard a revoked application using their own MFA and a newly registered RSA public key. The existing `mchNo`, `appId`, and historical orders remain. The former public key no longer verifies new requests. Sign with the new private key and confirm registered HTTPS Webhook, scopes, and source IP allowlist. This does not create a PG account or replace PG credentials. SSBO fields and signing rules stay unchanged.
