完整示例与工具
以下工具和代码示例可在 HTML 页面内展开查看完整内容并复制。
| 工具 | 用途 |
|---|---|
| OpenAPI | 机器可读接口定义 |
| Postman Collection | 接口请求与签名示例 |
| staging 环境模板 | 测试环境变量模板 |
| Node.js 示例 | 代收创建、查询和余额查询 |
| PHP 示例 | 代收创建、查询和余额查询 |
| Node.js Notify 示例 / PHP Notify 示例 | 通知验签与去重 |
代码示例#
请求示例适用于 Node.js 18+ 或 PHP 8.2+(HTTP 调用需要 curl 扩展)。通知示例依赖同语言的请求示例,将两者保存在同一目录。
Node.js 请求示例 · merchant-api-node.mjs
#!/usr/bin/env node
import { createHmac, randomUUID } from 'node:crypto';
import { request as httpRequest } from 'node:http';
import { request as httpsRequest } from 'node:https';
import { pathToFileURL } from 'node:url';
export const FIXTURE = {
secret: 'test_secret_123',
parameters: {
api_key: 'test_key',
merchant_id: 'merchant_1001',
nonce: 'nonce_001',
platform_order_no: 'P202608120001',
timestamp: '1786502400'
},
canonical: 'api_key=test_key&merchant_id=merchant_1001&nonce=nonce_001&platform_order_no=P202608120001×tamp=1786502400',
signature: '03b28189b1d613de76f444db1ffb834daefd609e2eee65d4871b34db8818bd73'
};
export function canonicalString(parameters) {
return Object.keys(parameters)
.filter((key) => key !== 'sign' && String(parameters[key]) !== '')
.sort()
.map((key) => `${key}=${String(parameters[key])}`)
.join('&');
}
export function paymentSign(parameters, secret) {
return createHmac('sha256', secret)
.update(canonicalString(parameters), 'utf8')
.digest('hex');
}
function requireObject(value, label) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function requireString(value, label) {
if (typeof value !== 'string' || value === '') {
throw new Error(`${label} must be a non-empty string`);
}
}
export function validateSuccessPayload(action, payload) {
requireObject(payload, `${action} response`);
if (!Number.isInteger(payload.code)) {
throw new Error(`${action} response.code must be an integer`);
}
if (payload.code !== 0) {
requireString(payload.message_key, `${action} response.message_key`);
requireString(payload.default_message, `${action} response.default_message`);
requireString(payload.message, `${action} response.message`);
if (payload.data !== null) throw new Error(`${action} error response.data must be null`);
requireString(payload.request_id, `${action} response.request_id`);
const requestID = typeof payload.request_id === 'string' ? payload.request_id : 'missing';
throw new Error(`${action} failed: code=${String(payload.code)} message=${String(payload.message)} request_id=${requestID}`);
}
requireString(payload.message, `${action} response.message`);
requireString(payload.request_id, `${action} response.request_id`);
requireObject(payload.data, `${action} response.data`);
if (action === 'create' || action === 'query') {
for (const field of ['checkout_mode', 'platform_order_no', 'merchant_order_no', 'amount', 'currency', 'status']) {
requireString(payload.data[field], `${action} response.data.${field}`);
}
if (payload.data.checkout_mode === 'direct') {
for (const field of ['channel_code', 'fee_amount', 'net_amount']) {
requireString(payload.data[field], `${action} response.data.${field}`);
}
} else if (payload.data.checkout_mode === 'cashier') {
if (!['awaiting_payment_method', 'selecting', 'submitted', 'expired'].includes(payload.data.status)) {
throw new Error(`${action} response.data.status must be a cashier session status`);
}
requireString(payload.data.expired_at, `${action} response.data.expired_at`);
if (action === 'create') requireString(payload.data.payment_url, `${action} response.data.payment_url`);
} else {
throw new Error(`${action} response.data.checkout_mode must be direct or cashier`);
}
} else if (action === 'balance') {
if (!Array.isArray(payload.data.balances)) {
throw new Error('balance response.data.balances must be an array');
}
for (const [index, item] of payload.data.balances.entries()) {
requireObject(item, `balance response.data.balances[${index}]`);
for (const field of ['currency', 'available_amount', 'frozen_amount', 'pending_settlement_amount']) {
requireString(item[field], `balance response.data.balances[${index}].${field}`);
}
}
} else {
throw new Error(`unsupported response action: ${action}`);
}
return payload;
}
function fixture() {
const canonical = canonicalString(FIXTURE.parameters);
const signature = paymentSign(FIXTURE.parameters, FIXTURE.secret);
const valid = canonical === FIXTURE.canonical && signature === FIXTURE.signature;
console.log(JSON.stringify({ canonical, signature, valid }, null, 2));
if (!valid) process.exitCode = 1;
}
function required(name) {
const value = process.env[name]?.trim();
if (!value) throw new Error(`${name} is required`);
return value;
}
function optional(name) {
return process.env[name]?.trim() || '';
}
function commonParameters() {
return {
api_key: required('FOUR_PARTY_API_KEY'),
merchant_id: required('FOUR_PARTY_MERCHANT_ID'),
timestamp: String(Math.floor(Date.now() / 1000)),
nonce: randomUUID().replaceAll('-', '')
};
}
function requestFor(action, overrides = {}) {
const common = commonParameters();
switch (action) {
case 'create':
return {
path: '/api/v1/pay/create',
body: {
...common,
merchant_order_no: overrides.merchantOrderNo || optional('FOUR_PARTY_MERCHANT_ORDER_NO') || `DEMO_${Date.now()}`,
amount: required('FOUR_PARTY_AMOUNT'),
currency: required('FOUR_PARTY_CURRENCY'),
channel_code: optional('FOUR_PARTY_CHANNEL_CODE'),
customer_id: optional('FOUR_PARTY_CUSTOMER_ID'),
customer_name: optional('FOUR_PARTY_CUSTOMER_NAME'),
customer_email: optional('FOUR_PARTY_CUSTOMER_EMAIL'),
customer_phone: optional('FOUR_PARTY_CUSTOMER_PHONE'),
payer_bank_code: optional('FOUR_PARTY_PAYER_BANK_CODE'),
payer_bank_account_owner: optional('FOUR_PARTY_PAYER_BANK_ACCOUNT_OWNER'),
payer_bank_account_number: optional('FOUR_PARTY_PAYER_BANK_ACCOUNT_NUMBER'),
payer_username: optional('FOUR_PARTY_PAYER_USERNAME'),
notify_url: optional('FOUR_PARTY_NOTIFY_URL'),
return_url: optional('FOUR_PARTY_RETURN_URL')
}
};
case 'query': {
const platformOrderNo = overrides.platformOrderNo || optional('FOUR_PARTY_PLATFORM_ORDER_NO');
const merchantOrderNo = overrides.merchantOrderNo || optional('FOUR_PARTY_MERCHANT_ORDER_NO');
if (!platformOrderNo && !merchantOrderNo) {
throw new Error('FOUR_PARTY_PLATFORM_ORDER_NO or FOUR_PARTY_MERCHANT_ORDER_NO is required');
}
return {
path: '/api/v1/pay/query',
body: {
...common,
platform_order_no: platformOrderNo,
merchant_order_no: merchantOrderNo
}
};
}
case 'balance':
return {
path: '/api/v1/balance/query',
body: { ...common, currency: optional('FOUR_PARTY_CURRENCY') }
};
default:
throw new Error('action must be fixture, create, query, balance, or smoke');
}
}
function baseURL() {
const parsed = new URL(required('FOUR_PARTY_BASE_URL'));
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) {
throw new Error('FOUR_PARTY_BASE_URL must be an HTTP(S) URL without credentials');
}
return parsed.toString().replace(/\/$/, '');
}
export function developmentRequestHost(base, rawOverride) {
const override = String(rawOverride || '').trim();
if (!override) return '';
const target = new URL(base);
const targetHost = target.hostname.toLowerCase();
const loopbackTarget = targetHost === 'localhost' || targetHost === '127.0.0.1' || targetHost === '::1';
if (!loopbackTarget) {
throw new Error('FOUR_PARTY_REQUEST_HOST is allowed only when FOUR_PARTY_BASE_URL uses a loopback host');
}
if (override.includes('://') || /[/\\@?#\s]/.test(override)) {
throw new Error('FOUR_PARTY_REQUEST_HOST must be a host[:port] value without scheme, path, credentials, query, or fragment');
}
const parsed = new URL(`http://${override}`);
if (!parsed.hostname || parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash) {
throw new Error('FOUR_PARTY_REQUEST_HOST must be a valid host[:port] value');
}
return parsed.host;
}
function sendWithDevelopmentHost(prepared, signal) {
const target = new URL(prepared.url);
const request = target.protocol === 'https:' ? httpsRequest : httpRequest;
const body = JSON.stringify(prepared.body);
return new Promise((resolve, reject) => {
const outgoing = request(target, {
method: prepared.method,
headers: { ...prepared.headers, 'content-length': Buffer.byteLength(body) }
}, (incoming) => {
const chunks = [];
let size = 0;
incoming.on('data', (chunk) => {
size += chunk.length;
if (size > 1024 * 1024) {
outgoing.destroy(new Error('response exceeds 1 MiB'));
return;
}
chunks.push(chunk);
});
incoming.on('end', () => resolve({
status: incoming.statusCode || 0,
text: async () => Buffer.concat(chunks).toString('utf8')
}));
});
outgoing.on('error', reject);
signal.addEventListener('abort', () => outgoing.destroy(new Error('request timed out')), { once: true });
outgoing.end(body);
});
}
export function isSafeSmokeHost(host) {
const normalized = String(host).toLowerCase().replace(/^\[|\]$/g, '');
if (normalized === 'localhost' || normalized === '127.0.0.1' || normalized === '::1' || normalized.endsWith('.local')) {
return true;
}
return normalized.split('.').some((label) => /^(?:stage|staging)(?:-|$)|-(?:stage|staging)$/.test(label));
}
export function assertSafeSmokeTarget(url) {
const host = new URL(url).hostname;
const safe = isSafeSmokeHost(host);
if (!safe && optional('FOUR_PARTY_ALLOW_NON_STAGING_HOST') !== 'I_UNDERSTAND') {
throw new Error('smoke refuses a non-staging host; set FOUR_PARTY_ALLOW_NON_STAGING_HOST=I_UNDERSTAND only after verifying the target');
}
}
async function send(action, overrides = {}, options = {}) {
const request = requestFor(action, overrides);
const secret = required('FOUR_PARTY_API_SECRET');
const body = { ...request.body };
body.sign = paymentSign(body, secret);
const targetBaseURL = baseURL();
const requestHost = developmentRequestHost(targetBaseURL, optional('FOUR_PARTY_REQUEST_HOST'));
const prepared = {
method: 'POST',
url: targetBaseURL + request.path,
headers: {
'content-type': 'application/json',
'x-request-id': `merchant_${randomUUID().replaceAll('-', '')}`,
...(requestHost ? { host: requestHost } : {})
},
body
};
if (options.dryRun) {
console.log(JSON.stringify({ ...prepared, canonical: canonicalString(body) }, null, 2));
return null;
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
try {
const response = requestHost
? await sendWithDevelopmentHost(prepared, controller.signal)
: await fetch(prepared.url, {
method: prepared.method,
headers: prepared.headers,
body: JSON.stringify(prepared.body),
signal: controller.signal,
redirect: 'error'
});
const responseText = await response.text();
let payload;
try {
payload = JSON.parse(responseText);
} catch {
throw new Error(`${action} returned non-JSON response: HTTP ${response.status}`);
}
validateSuccessPayload(action, payload);
if (!options.quiet) console.log(JSON.stringify(payload, null, 2));
return payload;
} finally {
clearTimeout(timeout);
}
}
async function smoke() {
if (optional('FOUR_PARTY_SMOKE_CONFIRM') !== 'RUN_STAGING_MERCHANT_SMOKE') {
throw new Error('FOUR_PARTY_SMOKE_CONFIRM=RUN_STAGING_MERCHANT_SMOKE is required because smoke creates a real staging order');
}
const url = baseURL();
assertSafeSmokeTarget(url);
const merchantOrderNo = optional('FOUR_PARTY_MERCHANT_ORDER_NO') || `SMOKE_${Date.now()}`;
const created = await send('create', { merchantOrderNo }, { quiet: true });
const duplicate = await send('create', { merchantOrderNo }, { quiet: true });
if (duplicate.data.platform_order_no !== created.data.platform_order_no) {
throw new Error('duplicate create returned a different platform_order_no');
}
const queried = await send('query', {
platformOrderNo: created.data.platform_order_no,
merchantOrderNo
}, { quiet: true });
if (queried.data.platform_order_no !== created.data.platform_order_no || queried.data.merchant_order_no !== merchantOrderNo) {
throw new Error('query response does not match the created order');
}
const balances = await send('balance', {}, { quiet: true });
console.log(JSON.stringify({
valid: true,
base_url: url,
merchant_order_no: merchantOrderNo,
platform_order_no: created.data.platform_order_no,
create_status: created.data.status,
query_status: queried.data.status,
balance_currencies: balances.data.balances.map((item) => item.currency),
checks: ['create', 'duplicate_create', 'query', 'balance']
}, null, 2));
}
async function main() {
const action = process.argv[2] || 'fixture';
if (action === 'fixture') {
fixture();
} else if (action === 'smoke') {
await smoke();
} else {
await send(action, {}, { dryRun: process.argv.includes('--dry-run') });
}
}
const isMain = Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
PHP 请求示例 · merchant-api-php.php
<?php
declare(strict_types=1);
namespace FourParty\Example;
use RuntimeException;
const MAX_RESPONSE_BYTES = 1048576;
function fixtureData(): array
{
return [
'secret' => 'test_secret_123',
'parameters' => [
'api_key' => 'test_key',
'merchant_id' => 'merchant_1001',
'nonce' => 'nonce_001',
'platform_order_no' => 'P202608120001',
'timestamp' => '1786502400',
],
'canonical' => 'api_key=test_key&merchant_id=merchant_1001&nonce=nonce_001&platform_order_no=P202608120001×tamp=1786502400',
'signature' => '03b28189b1d613de76f444db1ffb834daefd609e2eee65d4871b34db8818bd73',
];
}
function scalarString(mixed $value): string
{
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
if (!is_scalar($value)) {
throw new RuntimeException('signed values must be scalar');
}
return (string) $value;
}
function canonicalString(array $parameters): string
{
unset($parameters['sign']);
$parameters = array_filter(
$parameters,
static fn (mixed $value): bool => scalarString($value) !== ''
);
ksort($parameters, SORT_STRING);
$parts = [];
foreach ($parameters as $key => $value) {
$parts[] = $key . '=' . scalarString($value);
}
return implode('&', $parts);
}
function paymentSign(array $parameters, string $secret): string
{
if ($secret === '') {
throw new RuntimeException('API Secret must not be empty');
}
return hash_hmac('sha256', canonicalString($parameters), $secret);
}
function requiredEnv(string $name): string
{
$value = trim((string) getenv($name));
if ($value === '') {
throw new RuntimeException($name . ' is required');
}
return $value;
}
function optionalEnv(string $name): string
{
return trim((string) getenv($name));
}
function randomNonce(string $prefix = ''): string
{
return $prefix . bin2hex(random_bytes(16));
}
function baseUrl(): string
{
$value = rtrim(requiredEnv('FOUR_PARTY_BASE_URL'), '/');
$parts = parse_url($value);
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])) {
throw new RuntimeException('FOUR_PARTY_BASE_URL must be a valid HTTP(S) URL');
}
if (!in_array(strtolower((string) $parts['scheme']), ['http', 'https'], true)) {
throw new RuntimeException('FOUR_PARTY_BASE_URL must use HTTP or HTTPS');
}
if (isset($parts['user']) || isset($parts['pass'])) {
throw new RuntimeException('FOUR_PARTY_BASE_URL must not contain credentials');
}
return $value;
}
function developmentRequestHost(string $baseUrl, string $override): string
{
if ($override === '') {
return '';
}
$targetHost = strtolower((string) parse_url($baseUrl, PHP_URL_HOST));
if (!in_array($targetHost, ['localhost', '127.0.0.1', '::1'], true)) {
throw new RuntimeException('FOUR_PARTY_REQUEST_HOST is allowed only for a loopback Base URL');
}
if (preg_match('/^[A-Za-z0-9.\-\[\]:]+$/D', $override) !== 1) {
throw new RuntimeException('FOUR_PARTY_REQUEST_HOST must be a host[:port] value');
}
$parsedOverride = parse_url('http://' . $override);
if (!is_array($parsedOverride) || !isset($parsedOverride['host']) || isset(
$parsedOverride['user'],
$parsedOverride['pass'],
$parsedOverride['path'],
$parsedOverride['query'],
$parsedOverride['fragment']
)) {
throw new RuntimeException('FOUR_PARTY_REQUEST_HOST must be a host[:port] value');
}
return $override;
}
function commonParameters(): array
{
return [
'api_key' => requiredEnv('FOUR_PARTY_API_KEY'),
'merchant_id' => requiredEnv('FOUR_PARTY_MERCHANT_ID'),
'timestamp' => (string) time(),
'nonce' => randomNonce(),
];
}
function requestDefinition(string $action, array $overrides = []): array
{
$common = commonParameters();
if ($action === 'create') {
return [
'path' => '/api/v1/pay/create',
'body' => array_merge($common, [
'merchant_order_no' => $overrides['merchant_order_no'] ?? optionalEnv('FOUR_PARTY_MERCHANT_ORDER_NO') ?: 'DEMO_' . time() . '_' . bin2hex(random_bytes(4)),
'amount' => requiredEnv('FOUR_PARTY_AMOUNT'),
'currency' => requiredEnv('FOUR_PARTY_CURRENCY'),
'channel_code' => optionalEnv('FOUR_PARTY_CHANNEL_CODE'),
'customer_id' => optionalEnv('FOUR_PARTY_CUSTOMER_ID'),
'customer_name' => optionalEnv('FOUR_PARTY_CUSTOMER_NAME'),
'customer_email' => optionalEnv('FOUR_PARTY_CUSTOMER_EMAIL'),
'customer_phone' => optionalEnv('FOUR_PARTY_CUSTOMER_PHONE'),
'payer_bank_code' => optionalEnv('FOUR_PARTY_PAYER_BANK_CODE'),
'payer_bank_account_owner' => optionalEnv('FOUR_PARTY_PAYER_BANK_ACCOUNT_OWNER'),
'payer_bank_account_number' => optionalEnv('FOUR_PARTY_PAYER_BANK_ACCOUNT_NUMBER'),
'payer_username' => optionalEnv('FOUR_PARTY_PAYER_USERNAME'),
'notify_url' => optionalEnv('FOUR_PARTY_NOTIFY_URL'),
'return_url' => optionalEnv('FOUR_PARTY_RETURN_URL'),
]),
];
}
if ($action === 'query') {
$platformOrderNo = (string) ($overrides['platform_order_no'] ?? optionalEnv('FOUR_PARTY_PLATFORM_ORDER_NO'));
$merchantOrderNo = (string) ($overrides['merchant_order_no'] ?? optionalEnv('FOUR_PARTY_MERCHANT_ORDER_NO'));
if ($platformOrderNo === '' && $merchantOrderNo === '') {
throw new RuntimeException('FOUR_PARTY_PLATFORM_ORDER_NO or FOUR_PARTY_MERCHANT_ORDER_NO is required');
}
return [
'path' => '/api/v1/pay/query',
'body' => array_merge($common, [
'platform_order_no' => $platformOrderNo,
'merchant_order_no' => $merchantOrderNo,
]),
];
}
if ($action === 'balance') {
return [
'path' => '/api/v1/balance/query',
'body' => array_merge($common, ['currency' => optionalEnv('FOUR_PARTY_CURRENCY')]),
];
}
throw new RuntimeException('action must be fixture, create, query, balance, or smoke');
}
function prepareRequest(string $action, array $overrides = []): array
{
$definition = requestDefinition($action, $overrides);
$body = $definition['body'];
$body['sign'] = paymentSign($body, requiredEnv('FOUR_PARTY_API_SECRET'));
$base = baseUrl();
return [
'method' => 'POST',
'url' => $base . $definition['path'],
'headers' => [
'Content-Type: application/json',
'X-Request-ID: merchant_' . randomNonce(),
],
'request_host' => developmentRequestHost($base, optionalEnv('FOUR_PARTY_REQUEST_HOST')),
'body' => $body,
'canonical' => canonicalString($body),
];
}
function requireStringField(array $value, string $field, string $label): void
{
if (!array_key_exists($field, $value) || !is_string($value[$field]) || $value[$field] === '') {
throw new RuntimeException($label . '.' . $field . ' must be a non-empty string');
}
}
function validateResponse(string $action, mixed $payload): array
{
if (!is_array($payload) || array_is_list($payload)) {
throw new RuntimeException($action . ' response must be a JSON object');
}
if (!isset($payload['code']) || !is_int($payload['code'])) {
throw new RuntimeException($action . ' response.code must be an integer');
}
requireStringField($payload, 'message', $action . ' response');
requireStringField($payload, 'request_id', $action . ' response');
if ($payload['code'] !== 0) {
requireStringField($payload, 'message_key', $action . ' response');
requireStringField($payload, 'default_message', $action . ' response');
if (($payload['data'] ?? null) !== null) {
throw new RuntimeException($action . ' error response.data must be null');
}
throw new RuntimeException(sprintf('%s failed: code=%d message=%s request_id=%s', $action, $payload['code'], $payload['message'], $payload['request_id']));
}
if (!isset($payload['data']) || !is_array($payload['data']) || array_is_list($payload['data'])) {
throw new RuntimeException($action . ' response.data must be an object');
}
if (in_array($action, ['create', 'query'], true)) {
foreach (['checkout_mode', 'platform_order_no', 'merchant_order_no', 'amount', 'currency', 'status'] as $field) {
requireStringField($payload['data'], $field, $action . ' response.data');
}
if ($payload['data']['checkout_mode'] === 'direct') {
foreach (['channel_code', 'fee_amount', 'net_amount'] as $field) {
requireStringField($payload['data'], $field, $action . ' response.data');
}
} elseif ($payload['data']['checkout_mode'] === 'cashier') {
if (!in_array($payload['data']['status'], ['awaiting_payment_method', 'selecting', 'submitted', 'expired'], true)) {
throw new RuntimeException($action . ' response.data.status must be a cashier session status');
}
requireStringField($payload['data'], 'expired_at', $action . ' response.data');
if ($action === 'create') {
requireStringField($payload['data'], 'payment_url', $action . ' response.data');
}
} else {
throw new RuntimeException($action . ' response.data.checkout_mode must be direct or cashier');
}
} elseif ($action === 'balance') {
if (!isset($payload['data']['balances']) || !is_array($payload['data']['balances'])) {
throw new RuntimeException('balance response.data.balances must be an array');
}
}
return $payload;
}
function sendRequest(string $action, array $overrides = [], bool $dryRun = false): ?array
{
$prepared = prepareRequest($action, $overrides);
if ($dryRun) {
echo json_encode($prepared, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
return null;
}
if (!extension_loaded('curl')) {
throw new RuntimeException('PHP curl extension is required');
}
$body = json_encode($prepared['body'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
$headers = $prepared['headers'];
if ($prepared['request_host'] !== '') {
$headers[] = 'Host: ' . $prepared['request_host'];
}
$responseBody = '';
$curl = curl_init($prepared['url']);
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $body,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$responseBody): int {
if (strlen($responseBody) + strlen($chunk) > MAX_RESPONSE_BYTES) {
return 0;
}
$responseBody .= $chunk;
return strlen($chunk);
},
]);
$ok = curl_exec($curl);
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($ok === false) {
throw new RuntimeException('request failed: ' . ($error !== '' ? $error : 'response exceeds 1 MiB'));
}
if ($status < 200 || $status >= 300) {
throw new RuntimeException('HTTP request failed with status ' . $status);
}
return validateResponse($action, json_decode($responseBody, true, 64, JSON_THROW_ON_ERROR));
}
function isSafeSmokeHost(string $host): bool
{
$normalized = strtolower(trim($host, '[]'));
if (in_array($normalized, ['localhost', '127.0.0.1', '::1'], true) || str_ends_with($normalized, '.local')) {
return true;
}
foreach (explode('.', $normalized) as $label) {
if (preg_match('/^(?:stage|staging)(?:-|$)|-(?:stage|staging)$/D', $label) === 1) {
return true;
}
}
return false;
}
function requireSmokeConfirmation(): void
{
if (optionalEnv('FOUR_PARTY_SMOKE_CONFIRM') !== 'RUN_STAGING_MERCHANT_SMOKE') {
throw new RuntimeException('FOUR_PARTY_SMOKE_CONFIRM=RUN_STAGING_MERCHANT_SMOKE is required because smoke creates a real staging order');
}
}
function assertSafeSmokeTarget(string $url): void
{
$host = strtolower((string) parse_url($url, PHP_URL_HOST));
$safe = isSafeSmokeHost($host);
if (!$safe && optionalEnv('FOUR_PARTY_ALLOW_NON_STAGING_HOST') !== 'I_UNDERSTAND') {
throw new RuntimeException('smoke refuses a non-staging host');
}
}
function runSmoke(): array
{
requireSmokeConfirmation();
assertSafeSmokeTarget(baseUrl());
$merchantOrderNo = optionalEnv('FOUR_PARTY_MERCHANT_ORDER_NO') ?: 'SMOKE_' . time() . '_' . bin2hex(random_bytes(4));
$created = sendRequest('create', ['merchant_order_no' => $merchantOrderNo]);
$repeated = sendRequest('create', ['merchant_order_no' => $merchantOrderNo]);
if ($created['data']['platform_order_no'] !== $repeated['data']['platform_order_no']) {
throw new RuntimeException('repeated create returned a different platform_order_no');
}
$queried = sendRequest('query', [
'platform_order_no' => $created['data']['platform_order_no'],
'merchant_order_no' => $merchantOrderNo,
]);
if ($queried['data']['platform_order_no'] !== $created['data']['platform_order_no']
|| $queried['data']['merchant_order_no'] !== $merchantOrderNo) {
throw new RuntimeException('query response does not match the created order');
}
$balance = sendRequest('balance');
return [
'merchant_order_no' => $merchantOrderNo,
'platform_order_no' => $created['data']['platform_order_no'],
'create_status' => $created['data']['status'],
'query_status' => $queried['data']['status'],
'balance_currencies' => count($balance['data']['balances']),
'valid' => true,
];
}
function main(array $arguments): int
{
try {
$action = $arguments[1] ?? 'fixture';
if ($action === 'fixture') {
$fixture = fixtureData();
$canonical = canonicalString($fixture['parameters']);
$signature = paymentSign($fixture['parameters'], $fixture['secret']);
$valid = hash_equals($fixture['canonical'], $canonical) && hash_equals($fixture['signature'], $signature);
echo json_encode(compact('canonical', 'signature', 'valid'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
return $valid ? 0 : 1;
}
if ($action === 'smoke') {
echo json_encode(runSmoke(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
return 0;
}
$result = sendRequest($action, [], in_array('--dry-run', $arguments, true));
if ($result !== null) {
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
}
return 0;
} catch (\Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
return 1;
}
}
if (realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
exit(main($argv ?? []));
}
Node.js 通知接收示例 · merchant-notify-node.mjs
#!/usr/bin/env node
import { timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
import { pathToFileURL } from 'node:url';
import { canonicalString, paymentSign } from './merchant-api-node.mjs';
const MAX_BODY_BYTES = 64 * 1024;
const DEFAULT_ALLOWED_SKEW_SECONDS = 300;
export const NOTIFY_FIXTURE = {
secret: 'test_secret_123',
payload: {
event_type: 'payin.succeeded',
platform_order_no: 'P202608120001',
merchant_order_no: 'M202608120001',
channel_order_no: 'C202608120001',
channel_code: 'test_myr',
amount: '10.00',
fee_amount: '0.15',
net_amount: '9.85',
paid_amount: '10.00',
currency: 'MYR',
status: 'paid',
completed_at: '2026-08-12T08:00:00Z',
paid_at: '2026-08-12T08:00:00Z',
timestamp: 1786502400,
nonce: 'notify_nonce_001',
secret_version: 7,
sign: '7163e75692b8cbf6b82ef92e9a3c6bf4e8d6c26db7867a016ce2f3036f87f30d'
}
};
function required(name) {
const value = process.env[name]?.trim();
if (!value) throw new Error(`${name} is required`);
return value;
}
function optional(name) {
return process.env[name]?.trim() || '';
}
function requireObject(value, label) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function requireString(value, label, allowEmpty = false) {
if (typeof value !== 'string' || (!allowEmpty && value === '')) {
throw new Error(`${label} must be ${allowEmpty ? 'a string' : 'a non-empty string'}`);
}
}
function requirePositiveInteger(value, label) {
if (!Number.isSafeInteger(value) || value < 1) {
throw new Error(`${label} must be a positive integer`);
}
}
function requireTimestamp(value, label) {
if (!Number.isSafeInteger(value) || value < 0) {
throw new Error(`${label} must be a non-negative Unix-second integer`);
}
}
function requireDateTime(value, label) {
requireString(value, label);
if (!Number.isFinite(Date.parse(value))) {
throw new Error(`${label} must be an RFC 3339 date-time`);
}
}
function requireFlatScalars(payload) {
for (const [name, value] of Object.entries(payload)) {
if (value === null || !['string', 'number', 'boolean'].includes(typeof value)) {
throw new Error(`notify.${name} must be a scalar value`);
}
}
}
function secureHexEqual(expectedHex, providedHex) {
if (!/^[0-9a-f]{64}$/.test(providedHex)) return false;
const expected = Buffer.from(expectedHex, 'hex');
const provided = Buffer.from(providedHex, 'hex');
return expected.length === provided.length && timingSafeEqual(expected, provided);
}
export function verifyNotifyPayload(payload, secret, options = {}) {
requireObject(payload, 'notify payload');
requireString(secret, 'API Secret');
requireFlatScalars(payload);
for (const field of [
'event_type',
'platform_order_no',
'merchant_order_no',
'amount',
'currency',
'status',
'nonce',
'sign'
]) {
requireString(payload[field], `notify.${field}`);
}
const cashierExpiry = ['cashier.payin.expired', 'cashier.payout.expired'].includes(payload.event_type);
const payInTerminal = ['payin.succeeded', 'payin.failed', 'payin.expired'].includes(payload.event_type);
if (!cashierExpiry) {
requireString(payload.channel_code, 'notify.channel_code');
requireString(payload.channel_order_no, 'notify.channel_order_no', true);
}
requireDateTime(payload.completed_at, 'notify.completed_at');
requireTimestamp(payload.timestamp, 'notify.timestamp');
requirePositiveInteger(payload.secret_version, 'notify.secret_version');
if (payInTerminal) {
requireString(payload.fee_amount, 'notify.fee_amount');
requireString(payload.net_amount, 'notify.net_amount');
}
if (cashierExpiry && payload.status === 'expired') {
if (payload.checkout_mode !== 'cashier' || !['cashier_channel_not_selected', 'cashier_submission_timeout'].includes(payload.reason_code)) {
throw new Error('cashier expiry notify requires checkout_mode=cashier and a supported reason_code');
}
if ('expiry_revision' in payload && (typeof payload.expiry_revision !== 'string' || !/^[1-9][0-9]*$/.test(payload.expiry_revision))) {
throw new Error('cashier expiry notify requires a positive string expiry_revision when present');
}
requireDateTime(payload.expired_at, 'notify.expired_at');
if (payload.expired_at !== payload.completed_at) throw new Error('notify.expired_at must equal notify.completed_at');
for (const field of ['channel_code', 'channel_order_no', 'fee_amount', 'net_amount', 'frozen_amount', 'paid_amount', 'paid_at', 'status_revision', 'correction']) {
if (field in payload) throw new Error(`cashier expiry notify must not contain ${field}`);
}
} else if (payload.event_type === 'payin.succeeded' && payload.status === 'paid') {
requireString(payload.paid_amount, 'notify.paid_amount');
requireDateTime(payload.paid_at, 'notify.paid_at');
} else if (payload.event_type === 'payin.failed' && payload.status === 'failed') {
if ('paid_amount' in payload || 'paid_at' in payload) {
throw new Error('failed notify must not contain paid_amount or paid_at');
}
} else if (payload.event_type === 'payin.expired' && payload.status === 'expired') {
requireString(payload.reason_code, 'notify.reason_code');
if (payload.reason_code !== 'order_timeout') {
throw new Error('notify.reason_code must be order_timeout');
}
requireDateTime(payload.expired_at, 'notify.expired_at');
if (payload.expired_at !== payload.completed_at) {
throw new Error('notify.expired_at must equal notify.completed_at');
}
if ('paid_amount' in payload || 'paid_at' in payload) {
throw new Error('expired notify must not contain paid_amount or paid_at');
}
} else if (
(payload.event_type === 'payout.succeeded' && payload.status === 'success') ||
(payload.event_type === 'payout.failed' && payload.status === 'failed')
) {
requireString(payload.fee_amount, 'notify.fee_amount');
requireString(payload.net_amount, 'notify.net_amount');
if ('paid_amount' in payload || 'paid_at' in payload) {
throw new Error('payout notify must not contain paid_amount or paid_at');
}
} else {
throw new Error('notify event_type and status do not form a supported terminal state');
}
const corrected = 'status_revision' in payload || 'correction' in payload;
if (corrected && (typeof payload.status_revision !== 'string' || !/^[1-9][0-9]*$/.test(payload.status_revision) || payload.correction !== 'true')) {
throw new Error('correction notify requires a positive string status_revision and correction="true"');
}
if (options.expectedSecretVersion !== undefined && payload.secret_version !== options.expectedSecretVersion) {
throw new Error('notify.secret_version does not match the configured API Secret version');
}
const allowedSkewSeconds = options.allowedSkewSeconds ?? DEFAULT_ALLOWED_SKEW_SECONDS;
if (!Number.isSafeInteger(allowedSkewSeconds) || allowedSkewSeconds < 0) {
throw new Error('allowedSkewSeconds must be a non-negative integer');
}
const nowSeconds = options.nowSeconds ?? Math.floor(Date.now() / 1000);
requireTimestamp(nowSeconds, 'nowSeconds');
if (Math.abs(nowSeconds - payload.timestamp) > allowedSkewSeconds) {
throw new Error('notify.timestamp is outside the allowed clock-skew window');
}
const expectedSign = paymentSign(payload, secret);
if (!secureHexEqual(expectedSign, payload.sign)) {
throw new Error('notify.sign is invalid');
}
return {
canonical: canonicalString(payload),
eventKey: `${payload.event_type}:${payload.platform_order_no}${cashierExpiry ? `:${payload.expiry_revision ?? '0'}` : corrected ? `:${payload.status_revision}` : ''}`,
nonceKey: `${payload.secret_version}:${payload.nonce}`
};
}
export function createNotifyProcessor(options) {
requireObject(options, 'processor options');
requireString(options.secret, 'API Secret');
const acceptedEvents = new Set();
const acceptedNonces = new Map();
const pendingEvents = new Map();
const pendingNonces = new Map();
const onFirstAccept = options.onFirstAccept || (() => undefined);
return async function processNotify(payload) {
const verified = verifyNotifyPayload(payload, options.secret, {
allowedSkewSeconds: options.allowedSkewSeconds,
expectedSecretVersion: options.expectedSecretVersion,
nowSeconds: options.nowSeconds?.()
});
const previousCanonical = acceptedNonces.get(verified.nonceKey) ?? pendingNonces.get(verified.nonceKey);
if (previousCanonical !== undefined && previousCanonical !== verified.canonical) {
throw new Error('notify nonce was reused with a different signed payload');
}
if (previousCanonical !== undefined || acceptedEvents.has(verified.eventKey) || pendingEvents.has(verified.eventKey)) {
const pending = pendingEvents.get(verified.eventKey);
if (pending) await pending;
acceptedNonces.set(verified.nonceKey, verified.canonical);
return { duplicate: true, ...verified };
}
// Production handling must atomically compare the highest order revision
// before applying a correction; session expiry must never book funds.
const acceptance = Promise.resolve().then(() => onFirstAccept(payload, verified));
pendingEvents.set(verified.eventKey, acceptance);
pendingNonces.set(verified.nonceKey, verified.canonical);
try {
await acceptance;
acceptedEvents.add(verified.eventKey);
acceptedNonces.set(verified.nonceKey, verified.canonical);
return { duplicate: false, ...verified };
} finally {
pendingEvents.delete(verified.eventKey);
pendingNonces.delete(verified.nonceKey);
}
};
}
async function readBody(request) {
const chunks = [];
let size = 0;
for await (const chunk of request) {
size += chunk.length;
if (size > MAX_BODY_BYTES) throw new Error('notify request body exceeds 64 KiB');
chunks.push(chunk);
}
if (size === 0) throw new Error('notify request body is empty');
return Buffer.concat(chunks).toString('utf8');
}
function fixture() {
const result = verifyNotifyPayload(NOTIFY_FIXTURE.payload, NOTIFY_FIXTURE.secret, {
nowSeconds: NOTIFY_FIXTURE.payload.timestamp,
expectedSecretVersion: NOTIFY_FIXTURE.payload.secret_version
});
console.log(JSON.stringify({
canonical: result.canonical,
signature: NOTIFY_FIXTURE.payload.sign,
valid: true
}, null, 2));
}
async function serve() {
const host = optional('FOUR_PARTY_NOTIFY_BIND_HOST') || '127.0.0.1';
if (!['127.0.0.1', '::1', 'localhost'].includes(host) && optional('FOUR_PARTY_NOTIFY_ALLOW_PUBLIC_BIND') !== 'I_UNDERSTAND_DEMO_ONLY') {
throw new Error('receiver refuses a non-loopback bind; this sample is not a production server');
}
const rawPort = optional('FOUR_PARTY_NOTIFY_PORT') || '8787';
const port = Number(rawPort);
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
throw new Error('FOUR_PARTY_NOTIFY_PORT must be an integer from 1 to 65535');
}
const expectedVersionRaw = optional('FOUR_PARTY_NOTIFY_SECRET_VERSION');
const expectedSecretVersion = expectedVersionRaw === '' ? undefined : Number(expectedVersionRaw);
if (expectedSecretVersion !== undefined) requirePositiveInteger(expectedSecretVersion, 'FOUR_PARTY_NOTIFY_SECRET_VERSION');
const processNotify = createNotifyProcessor({
secret: required('FOUR_PARTY_API_SECRET'),
expectedSecretVersion,
nowSeconds: () => Math.floor(Date.now() / 1000),
onFirstAccept: (payload) => {
console.log(`accepted platform_order_no=${payload.platform_order_no} status=${payload.status}`);
}
});
const server = createServer(async (request, response) => {
try {
if (request.method !== 'POST' || request.url !== '/notify') {
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
response.end('NOT FOUND');
return;
}
if (!String(request.headers['content-type'] || '').toLowerCase().startsWith('application/json')) {
throw new Error('Content-Type must be application/json');
}
const payload = JSON.parse(await readBody(request));
const result = await processNotify(payload);
console.log(`notify_result=${result.duplicate ? 'duplicate' : 'accepted'} event_key=${result.eventKey}`);
response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
response.end('SUCCESS');
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
response.end('FAIL');
}
});
server.listen(port, host, () => {
console.log(`Merchant Notify demo receiver listening on http://${host}:${port}/notify`);
console.log('Demo only: replace the in-memory nonce/event stores and business callback before production use.');
});
}
async function main() {
const action = process.argv[2] || 'fixture';
if (action === 'fixture') {
fixture();
} else if (action === 'serve') {
await serve();
} else {
throw new Error('action must be fixture or serve');
}
}
const isMain = Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
PHP 通知接收示例 · merchant-notify-php.php
<?php
declare(strict_types=1);
namespace FourParty\Example;
use RuntimeException;
require_once __DIR__ . '/merchant-api-php.php';
const MAX_NOTIFY_BODY_BYTES = 65536;
const DEFAULT_NOTIFY_SKEW_SECONDS = 300;
function notifyFixture(): array
{
return [
'secret' => 'test_secret_123',
'payload' => [
'event_type' => 'payin.succeeded',
'platform_order_no' => 'P202608120001',
'merchant_order_no' => 'M202608120001',
'channel_order_no' => 'C202608120001',
'channel_code' => 'test_myr',
'amount' => '10.00',
'fee_amount' => '0.15',
'net_amount' => '9.85',
'paid_amount' => '10.00',
'currency' => 'MYR',
'status' => 'paid',
'completed_at' => '2026-08-12T08:00:00Z',
'paid_at' => '2026-08-12T08:00:00Z',
'timestamp' => 1786502400,
'nonce' => 'notify_nonce_001',
'secret_version' => 7,
'sign' => '7163e75692b8cbf6b82ef92e9a3c6bf4e8d6c26db7867a016ce2f3036f87f30d',
],
];
}
function requireNotifyString(array $payload, string $field, bool $allowEmpty = false): string
{
if (!array_key_exists($field, $payload) || !is_string($payload[$field]) || (!$allowEmpty && $payload[$field] === '')) {
throw new RuntimeException('notify.' . $field . ' must be ' . ($allowEmpty ? 'a string' : 'a non-empty string'));
}
return $payload[$field];
}
function requireNotifyTimestamp(array $payload, string $field): int
{
if (!array_key_exists($field, $payload) || !is_int($payload[$field]) || $payload[$field] < 0) {
throw new RuntimeException('notify.' . $field . ' must be a non-negative Unix-second integer');
}
return $payload[$field];
}
function requireNotifyDateTime(array $payload, string $field): string
{
$value = requireNotifyString($payload, $field);
// Go emits RFC3339Nano; normalize fractional seconds for PHP's parser.
if (preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/D', $value) !== 1) {
throw new RuntimeException('notify.' . $field . ' must be an RFC 3339 date-time');
}
$normalized = preg_replace_callback('/\.(\d{1,9})/', static fn (array $match): string => '.' . str_pad(substr($match[1], 0, 6), 6, '0'), $value);
$format = str_contains($normalized, '.') ? 'Y-m-d\TH:i:s.uP' : \DateTimeInterface::RFC3339;
$parsed = \DateTimeImmutable::createFromFormat($format, $normalized);
$errors = \DateTimeImmutable::getLastErrors();
if ($parsed === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0))) {
throw new RuntimeException('notify.' . $field . ' must be an RFC 3339 date-time');
}
return $value;
}
function verifyNotifyPayload(array $payload, string $secret, array $options = []): array
{
if ($secret === '') {
throw new RuntimeException('API Secret must not be empty');
}
if (array_is_list($payload)) {
throw new RuntimeException('notify payload must be a JSON object');
}
foreach ($payload as $field => $value) {
if ($value === null || (!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value))) {
throw new RuntimeException('notify.' . $field . ' must be a scalar value');
}
}
foreach (['event_type', 'platform_order_no', 'merchant_order_no', 'amount', 'currency', 'status', 'nonce', 'sign'] as $field) {
requireNotifyString($payload, $field);
}
$cashierExpiry = in_array($payload['event_type'], ['cashier.payin.expired', 'cashier.payout.expired'], true);
$payInTerminal = in_array($payload['event_type'], ['payin.succeeded', 'payin.failed', 'payin.expired'], true);
if (!$cashierExpiry) {
requireNotifyString($payload, 'channel_code');
requireNotifyString($payload, 'channel_order_no', true);
}
requireNotifyDateTime($payload, 'completed_at');
$timestamp = requireNotifyTimestamp($payload, 'timestamp');
if (!isset($payload['secret_version']) || !is_int($payload['secret_version']) || $payload['secret_version'] < 1) {
throw new RuntimeException('notify.secret_version must be a positive integer');
}
if ($payInTerminal) {
requireNotifyString($payload, 'fee_amount');
requireNotifyString($payload, 'net_amount');
}
if ($cashierExpiry && $payload['status'] === 'expired') {
if (($payload['checkout_mode'] ?? null) !== 'cashier' || !in_array($payload['reason_code'] ?? null, ['cashier_channel_not_selected', 'cashier_submission_timeout'], true)) {
throw new RuntimeException('cashier expiry notify requires checkout_mode=cashier and a supported reason_code');
}
if (array_key_exists('expiry_revision', $payload) && (!is_string($payload['expiry_revision']) || preg_match('/^[1-9][0-9]*$/D', $payload['expiry_revision']) !== 1)) {
throw new RuntimeException('cashier expiry notify requires a positive string expiry_revision when present');
}
if (requireNotifyDateTime($payload, 'expired_at') !== $payload['completed_at']) {
throw new RuntimeException('notify.expired_at must equal notify.completed_at');
}
foreach (['channel_code', 'channel_order_no', 'fee_amount', 'net_amount', 'frozen_amount', 'paid_amount', 'paid_at', 'status_revision', 'correction'] as $field) {
if (array_key_exists($field, $payload)) throw new RuntimeException('cashier expiry notify must not contain ' . $field);
}
} elseif ($payload['event_type'] === 'payin.succeeded' && $payload['status'] === 'paid') {
requireNotifyString($payload, 'paid_amount');
requireNotifyDateTime($payload, 'paid_at');
} elseif ($payload['event_type'] === 'payin.failed' && $payload['status'] === 'failed') {
if (array_key_exists('paid_amount', $payload) || array_key_exists('paid_at', $payload)) {
throw new RuntimeException('failed notify must not contain paid_amount or paid_at');
}
} elseif ($payload['event_type'] === 'payin.expired' && $payload['status'] === 'expired') {
requireNotifyString($payload, 'reason_code');
if ($payload['reason_code'] !== 'order_timeout') {
throw new RuntimeException('notify.reason_code must be order_timeout');
}
requireNotifyDateTime($payload, 'expired_at');
if ($payload['expired_at'] !== $payload['completed_at']) {
throw new RuntimeException('notify.expired_at must equal notify.completed_at');
}
if (array_key_exists('paid_amount', $payload) || array_key_exists('paid_at', $payload)) {
throw new RuntimeException('expired notify must not contain paid_amount or paid_at');
}
} elseif (
($payload['event_type'] === 'payout.succeeded' && $payload['status'] === 'success')
|| ($payload['event_type'] === 'payout.failed' && $payload['status'] === 'failed')
) {
requireNotifyString($payload, 'fee_amount');
requireNotifyString($payload, 'net_amount');
if (array_key_exists('paid_amount', $payload) || array_key_exists('paid_at', $payload)) {
throw new RuntimeException('payout notify must not contain paid_amount or paid_at');
}
} else {
throw new RuntimeException('notify event_type and status do not form a supported terminal state');
}
$corrected = array_key_exists('status_revision', $payload) || array_key_exists('correction', $payload);
if ($corrected && (!is_string($payload['status_revision'] ?? null) || preg_match('/^[1-9][0-9]*$/D', $payload['status_revision']) !== 1 || ($payload['correction'] ?? null) !== 'true')) {
throw new RuntimeException('correction notify requires a positive string status_revision and correction="true"');
}
if (isset($options['expected_secret_version']) && $payload['secret_version'] !== $options['expected_secret_version']) {
throw new RuntimeException('notify.secret_version does not match the configured API Secret version');
}
$allowedSkew = $options['allowed_skew_seconds'] ?? DEFAULT_NOTIFY_SKEW_SECONDS;
$now = $options['now_seconds'] ?? time();
if (!is_int($allowedSkew) || $allowedSkew < 0 || !is_int($now) || $now < 0) {
throw new RuntimeException('notify time validation options are invalid');
}
if (abs($now - $timestamp) > $allowedSkew) {
throw new RuntimeException('notify.timestamp is outside the allowed clock-skew window');
}
$provided = $payload['sign'];
if (preg_match('/^[0-9a-f]{64}$/', $provided) !== 1 || !hash_equals(paymentSign($payload, $secret), $provided)) {
throw new RuntimeException('notify.sign is invalid');
}
return [
'canonical' => canonicalString($payload),
'event_key' => $payload['event_type'] . ':' . $payload['platform_order_no'] . ($cashierExpiry ? ':' . ($payload['expiry_revision'] ?? '0') : ($corrected ? ':' . $payload['status_revision'] : '')),
'nonce_key' => $payload['secret_version'] . ':' . $payload['nonce'],
];
}
function processNotifyIdempotently(array $payload, string $secret, string $stateFile, array $options = []): array
{
$verified = verifyNotifyPayload($payload, $secret, $options);
$directory = dirname($stateFile);
if (!is_dir($directory)) {
throw new RuntimeException('notify state directory does not exist');
}
$handle = fopen($stateFile, 'c+');
if ($handle === false) {
throw new RuntimeException('cannot open notify state file');
}
try {
if (!flock($handle, LOCK_EX)) {
throw new RuntimeException('cannot lock notify state file');
}
rewind($handle);
$raw = stream_get_contents($handle);
$state = $raw === '' ? ['events' => [], 'nonces' => []] : json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($state) || !isset($state['events'], $state['nonces']) || !is_array($state['events']) || !is_array($state['nonces'])) {
throw new RuntimeException('notify state file is invalid');
}
$existingCanonical = $state['nonces'][$verified['nonce_key']] ?? null;
if ($existingCanonical !== null && !hash_equals((string) $existingCanonical, $verified['canonical'])) {
throw new RuntimeException('notify nonce was reused with a different signed payload');
}
$duplicate = $existingCanonical !== null || isset($state['events'][$verified['event_key']]);
if (!$duplicate) {
// Production must atomically compare the highest order revision
// before applying corrections; session expiry must never book funds.
$state['events'][$verified['event_key']] = gmdate('c');
}
$state['nonces'][$verified['nonce_key']] = $verified['canonical'];
rewind($handle);
if (!ftruncate($handle, 0) || fwrite($handle, json_encode($state, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)) === false || !fflush($handle)) {
throw new RuntimeException('cannot persist notify idempotency state');
}
return ['duplicate' => $duplicate] + $verified;
} finally {
flock($handle, LOCK_UN);
fclose($handle);
}
}
function notifyStateFile(): string
{
$configured = optionalEnv('FOUR_PARTY_NOTIFY_STATE_FILE');
return $configured !== '' ? $configured : sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'four-party-notify-example-state.json';
}
function handleNotifyHttpRequest(): void
{
header('Content-Type: text/plain; charset=utf-8');
try {
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
header('Allow: POST');
echo 'FAIL';
return;
}
$contentType = strtolower(trim(explode(';', (string) ($_SERVER['CONTENT_TYPE'] ?? ''))[0]));
if ($contentType !== 'application/json') {
throw new RuntimeException('Content-Type must be application/json');
}
$body = file_get_contents('php://input', false, null, 0, MAX_NOTIFY_BODY_BYTES + 1);
if ($body === false || $body === '' || strlen($body) > MAX_NOTIFY_BODY_BYTES) {
throw new RuntimeException('notify body must be between 1 byte and 64 KiB');
}
$payload = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($payload) || array_is_list($payload)) {
throw new RuntimeException('notify payload must be a JSON object');
}
$version = filter_var(requiredEnv('FOUR_PARTY_NOTIFY_SECRET_VERSION'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($version === false) {
throw new RuntimeException('FOUR_PARTY_NOTIFY_SECRET_VERSION must be a positive integer');
}
processNotifyIdempotently($payload, requiredEnv('FOUR_PARTY_API_SECRET'), notifyStateFile(), [
'expected_secret_version' => $version,
'allowed_skew_seconds' => DEFAULT_NOTIFY_SKEW_SECONDS,
]);
http_response_code(200);
echo 'SUCCESS';
} catch (\Throwable $error) {
error_log('four-party notify rejected: ' . $error->getMessage());
http_response_code(400);
echo 'FAIL';
}
}
function notifyMain(array $arguments): int
{
try {
$action = $arguments[1] ?? 'fixture';
if ($action !== 'fixture') {
throw new RuntimeException('action must be fixture; use php -S for the receiver');
}
$fixture = notifyFixture();
$result = verifyNotifyPayload($fixture['payload'], $fixture['secret'], [
'now_seconds' => $fixture['payload']['timestamp'],
'expected_secret_version' => $fixture['payload']['secret_version'],
]);
echo json_encode([
'canonical' => $result['canonical'],
'signature' => $fixture['payload']['sign'],
'valid' => true,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
return 0;
} catch (\Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
return 1;
}
}
if (realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
if (PHP_SAPI === 'cli-server') {
handleNotifyHttpRequest();
} else {
exit(notifyMain($argv ?? []));
}
}
OpenAPI 与 Postman#
展开后可查看和复制完整 JSON 内容。
OpenAPI 3.1 · 完整内容
{
"openapi": "3.1.0",
"jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema",
"info": {
"title": "四方支付收银台 API",
"version": "1.5.0",
"description": "通过收银台创建代收或代付会话,查询订单、余额与可用币种、银行/电子钱包及支付网络/方式,接收交易通知。代收、代付均使用自由匹配 Key(merchant_global),一个 Key 可获授权多个支付类型和交易币种;每笔请求仍使用单一 currency,由用户在收银台确认通道。",
"x-documentation-revision": "2026-10-16-r20"
},
"servers": [
{
"url": "https://{apiHost}",
"description": "使用平台为当前环境提供的 Merchant API Host。",
"variables": {
"apiHost": {
"default": "api.example.com",
"description": "由平台提供;测试与生产环境使用不同 Host 和凭证。"
}
}
}
],
"tags": [
{
"name": "PayIn",
"description": "代收订单"
},
{
"name": "Payout",
"description": "代付订单"
},
{
"name": "Balance",
"description": "商户余额"
},
{
"name": "Options",
"description": "可用币种与银行选项"
}
],
"paths": {
"/api/v1/currency/options": {
"post": {
"tags": [
"Options"
],
"operationId": "queryPublicCurrencyOptions",
"summary": "查询平台币种目录",
"description": "使用有效 api_key,无需签名。返回平台币种目录。",
"x-sdk-signing-required": false,
"x-authentication": "merchant-api-key-only",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PublicCurrencyOptionsRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/PublicCurrencyOptionsResponse"
}
}
}
},
"/api/v1/bank/options": {
"post": {
"tags": [
"Options"
],
"operationId": "queryPublicBankOptions",
"summary": "查询平台银行与支付代码目录",
"description": "使用有效 api_key,无需签名;currency 必填。返回平台银行与支付代码,包含 kind;USDT 返回空 options。",
"x-sdk-signing-required": false,
"x-authentication": "merchant-api-key-only",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PublicBankOptionsRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/PublicBankOptionsResponse"
}
}
}
},
"/api/v1/pay/create": {
"post": {
"tags": [
"PayIn"
],
"operationId": "createPayIn",
"summary": "创建代收收银台会话",
"description": "使用 payin 自由匹配 Key(merchant_global),不绑定特定通道。merchant_order_no 必须在商户侧唯一,重复提交保持原始业务字段一致。创建返回收银台会话;客户与付款人资料可预填,由用户确认通道并补齐资料后提交正式订单。 收银台模式保存新会话或返回 payment_url 前,预检同商户、environment、currency、payment_type 的有效通道绑定、金额限额、完整有效费率及银行/支付方式映射;其他无匹配通道情形返回 30001 error.channel_unavailable,已传银行/支付方式不匹配返回既有对应错误。预检可读取 Provider 银行列表,但不调用创建交易、不提前冻结。未生成正式订单的创建重试重新预检,已有正式订单沿用原幂等查询;用户确认和正式建单仍重新校验。Deposit 不检查商户余额。 自由匹配(merchant_global 且未指定 channel_code)创建被拒绝时,金额低于当前商户、环境、币种和支付类型的有效绑定通道配置 min_amount 最小值返回 40002 error.amount_below_min,高于 max_amount 最大值返回 40003 error.amount_above_max;message 显示币种及对应金额,例如 amount below minimum (MYR 10.00) 或 amount above maximum (MYR 2000.00)。有通道未配置某侧边界时该侧不限。仅汇总通道配置,不合并 API Key/商户绑定限额,区间内仍须通过原有校验;固定 Key、指定通道、余额不足、内部错误及已有正式订单保持原行为。default_message、响应字段和 HTTP 200 合同不变。 通道处于 maintenance 时不接新单;未生成正式订单的收银台会话不能选择维护通道,仍可选择其他满足条件的 active 通道。维护前已生成的正式订单继续使用原通道,尚未提交的订单仍可按原幂等和有效期规则继续提交,不重复建单或冻结。因通道维护拒绝新单可返回 30002 error.channel_maintenance(default_message 为 channel maintenance);自由匹配排除维护通道,无合格候选时沿用对应校验错误。",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PayCreateRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/PayCreateResponse"
}
}
}
},
"/api/v1/pay/query": {
"post": {
"tags": [
"PayIn"
],
"operationId": "queryPayIn",
"summary": "查询代收订单",
"description": "platform_order_no 与 merchant_order_no 至少提供一个,同时提供时须指向同一订单或会话。优先返回正式订单;尚未生成正式订单时返回 checkout_mode=cashier 的会话状态和过期时间,不返回创建时的 payment_url、正式通道或费用。 通道 maintenance 本身不阻断已有订单的本地状态查询,也不会将订单改为失败;仍执行原签名、权限和订单归属校验。",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PayQueryRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/PayQueryResponse"
}
}
}
},
"/api/v1/payout/create": {
"post": {
"tags": [
"Payout"
],
"operationId": "createPayout",
"summary": "创建代付收银台会话",
"description": "使用 payout 自由匹配 Key(merchant_global),不绑定特定通道。四个收款字段独立可选,支持部分预填;已传字段不可修改,用户选定通道后只补齐缺失必填项。创建成功后将 payment_url 交给用户,由用户确认通道和收款资料;code=0 不表示收款人已到账。 收银台模式允许全部省略收款资料,创建响应返回 payment_url,不返回银行列表;用户进入收银台并选择付款方式后选择银行、补齐缺失资料,再确认提交。 收银台模式保存新会话或返回 payment_url 前,预检同商户、environment、currency、payment_type 的有效通道绑定、金额限额、完整有效费率及银行/支付方式映射;其他无匹配通道情形返回 30001 error.channel_unavailable,已传银行/支付方式不匹配返回既有对应错误。预检可读取 Provider 银行列表,但不调用创建交易、不提前冻结。未生成正式订单的创建重试重新预检,已有正式订单沿用原幂等查询;用户确认和正式建单仍重新校验。Withdraw 可用余额须覆盖同商户、环境、币种的 amount + merchant_fee;不足或缺少余额记录返回 40001 error.insufficient_balance,不创建新会话或返回链接。指定 channel_code 时仅按该通道预检。 自由匹配(merchant_global 且未指定 channel_code)创建被拒绝时,金额低于当前商户、环境、币种和支付类型的有效绑定通道配置 min_amount 最小值返回 40002 error.amount_below_min,高于 max_amount 最大值返回 40003 error.amount_above_max;message 显示币种及对应金额,例如 amount below minimum (MYR 10.00) 或 amount above maximum (MYR 2000.00)。有通道未配置某侧边界时该侧不限。仅汇总通道配置,不合并 API Key/商户绑定限额,区间内仍须通过原有校验;固定 Key、指定通道、余额不足、内部错误及已有正式订单保持原行为。default_message、响应字段和 HTTP 200 合同不变。 通道处于 maintenance 时不接新单;未生成正式订单的收银台会话不能选择维护通道,仍可选择其他满足条件的 active 通道。维护前已生成的正式订单继续使用原通道,尚未提交的订单仍可按原幂等和有效期规则继续提交,不重复建单或冻结。因通道维护拒绝新单可返回 30002 error.channel_maintenance(default_message 为 channel maintenance);自由匹配排除维护通道,无合格候选时沿用对应校验错误。",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PayoutCreateRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/PayoutResponse"
}
}
}
},
"/api/v1/payout/query": {
"post": {
"tags": [
"Payout"
],
"operationId": "queryPayout",
"summary": "查询代付订单",
"description": "platform_order_no 与 merchant_order_no 至少提供一个;同时提供时必须指向同一订单。 通道 maintenance 本身不阻断已有订单查询;sync_provider=true 时,processing 订单仍可尝试同步最新状态,超时或未知结果保持原状态和冻结。仍执行原签名、权限和订单归属校验。",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PayoutQueryRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/PayoutResponse"
}
}
}
},
"/api/v1/balance/query": {
"post": {
"tags": [
"Balance"
],
"operationId": "queryMerchantBalance",
"summary": "查询商户余额",
"description": "currency 省略时返回当前商户可查询的全部币种余额。 通道 maintenance 本身不影响商户余额查询;仍执行原签名、权限和环境隔离校验。",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/BalanceQueryRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/BalanceResponse"
}
}
}
},
"/api/v1/channel/options": {
"post": {
"tags": [
"Options"
],
"operationId": "queryChannelOptions",
"summary": "查询通道币种、支付方式与银行选项",
"description": "固定 Key 保持 data.options;自由匹配 Key 支持 currency、payin_bank、payout_bank、payment_method,银行/钱包按授权和有效通道能力合并去重返回 data.options,不返回所属通道或 channels;payment_method 的 channels 分组包含通道名称、支付方向、支付方式和该通道已验证映射的银行。银行及支付方式查询必填授权 currency,可按 payment_type 和 channel_code 筛选。payin_bank/payout_bank 使用对应创建权限;currency/payment_method 使用 query_balance。四国银行、钱包、支付方式仅返回平台 code/name,不返回 provider_code。无可信银行来源时 banks 为空数组;单通道 API 失败不回退文档。查询不创建订单、不选择路由,不保证具体金额和费率可交易。银行列表查询与收款资料预填无关,不需要 bank_code、account_no、account_name 或 recipient_email;未传这些资料不会导致列表为空。 全局查询逐通道保留正常结果;全部匹配通道失败或指定通道失败返回 30001,不借用其他通道结果。 仅返回当前可用于新单的 active 通道选项,排除 maintenance 通道。指定维护通道不借用其他通道结果;已有正式订单的处理与查询不依赖此选项列表。",
"parameters": [
{
"$ref": "#/components/parameters/XRequestID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ChannelOptionsRequest"
}
}
}
},
"responses": {
"200": {
"$ref": "#/components/responses/ChannelOptionsResponse"
}
}
}
}
},
"webhooks": {
"payInNotify": {
"post": {
"operationId": "receiveMerchantNotify",
"summary": "接收代收或代付终态通知",
"description": "平台向订单的 notify_url 发送。商户必须验签并幂等处理;成功后返回 HTTP 2xx 和纯文本 SUCCESS。",
"parameters": [
{
"$ref": "#/components/parameters/NotifyRequestID"
},
{
"$ref": "#/components/parameters/NotifyTraceID"
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/MerchantNotify"
}
}
}
},
"responses": {
"200": {
"description": "通知已成功处理",
"content": {
"text/plain": {
"schema": {
"type": "string",
"const": "SUCCESS"
}
}
}
}
}
}
}
},
"components": {
"parameters": {
"XRequestID": {
"name": "X-Request-ID",
"in": "header",
"required": false,
"description": "可选请求关联 ID;平台会在响应中返回最终 request_id。",
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"pattern": "^[A-Za-z0-9._:-]+$"
}
},
"NotifyRequestID": {
"name": "X-Request-ID",
"in": "header",
"required": true,
"description": "通知请求关联 ID,用于排查。",
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 64
}
},
"NotifyTraceID": {
"name": "X-Trace-ID",
"in": "header",
"required": true,
"description": "通知链路关联 ID,用于排查。",
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 64
}
}
},
"responses": {
"PublicCurrencyOptionsResponse": {
"description": "HTTP 返回 200;根据响应体 code 判断结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/PublicCurrencyOptionsSuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
},
"PublicBankOptionsResponse": {
"description": "HTTP 返回 200;根据响应体 code 判断结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/PublicBankOptionsSuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
},
"PayCreateResponse": {
"description": "HTTP 通常返回 200;必须根据响应体 code 判断业务结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/PayCreateSuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
},
"PayQueryResponse": {
"description": "HTTP 通常返回 200;必须根据响应体 code 判断业务结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/PayQuerySuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
},
"PayoutResponse": {
"description": "HTTP 通常返回 200;必须根据响应体 code 判断业务结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/PayoutSuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
},
"BalanceResponse": {
"description": "HTTP 通常返回 200;必须根据响应体 code 判断业务结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/BalanceSuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
},
"ChannelOptionsResponse": {
"description": "HTTP 通常返回 200;必须根据响应体 code 判断业务结果。",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/ChannelOptionsSuccess"
},
{
"$ref": "#/components/schemas/ErrorEnvelope"
}
]
}
}
}
}
},
"schemas": {
"PublicCatalogTokenRequest": {
"type": "object",
"maxProperties": 64,
"propertyNames": {
"maxLength": 8192
},
"required": [
"api_key"
],
"properties": {
"api_key": {
"type": "string",
"minLength": 1,
"maxLength": 128,
"description": "当前环境有效 Merchant API Key。"
}
}
},
"PublicCurrencyOptionsRequest": {
"example": {
"api_key": "<API_KEY>"
},
"allOf": [
{
"$ref": "#/components/schemas/PublicCatalogTokenRequest"
}
]
},
"PublicBankOptionsRequest": {
"example": {
"api_key": "<API_KEY>",
"currency": "MYR"
},
"allOf": [
{
"$ref": "#/components/schemas/PublicCatalogTokenRequest"
},
{
"type": "object",
"required": [
"currency"
],
"properties": {
"currency": {
"type": "string",
"enum": [
"IDR",
"MYR",
"SGD",
"THB",
"USDT"
],
"description": "平台币种目录中的大写代码。"
}
}
}
]
},
"PublicCurrencyOption": {
"type": "object",
"required": [
"code",
"name"
],
"additionalProperties": false,
"properties": {
"code": {
"type": "string",
"enum": [
"IDR",
"MYR",
"SGD",
"THB",
"USDT"
]
},
"name": {
"type": "string"
}
}
},
"PublicBankOption": {
"type": "object",
"required": [
"currency",
"code",
"name",
"kind"
],
"additionalProperties": false,
"properties": {
"currency": {
"type": "string",
"enum": [
"IDR",
"MYR",
"SGD",
"THB",
"USDT"
]
},
"code": {
"type": "string"
},
"name": {
"type": "string"
},
"kind": {
"type": "string",
"enum": [
"bank",
"ewallet",
"payment_scheme",
"payment_method"
]
}
}
},
"PublicCurrencyOptionsData": {
"type": "object",
"required": [
"options"
],
"properties": {
"options": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PublicCurrencyOption"
}
}
}
},
"PublicBankOptionsData": {
"type": "object",
"required": [
"options"
],
"properties": {
"options": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PublicBankOption"
}
}
}
},
"PublicCurrencyOptionsSuccess": {
"example": {
"code": 0,
"message": "OK",
"data": {
"options": [
{
"code": "IDR",
"name": "IDR"
},
{
"code": "MYR",
"name": "MYR"
},
{
"code": "SGD",
"name": "SGD"
},
{
"code": "THB",
"name": "THB"
},
{
"code": "USDT",
"name": "USDT"
}
]
},
"request_id": "req_example_currency"
},
"type": "object",
"required": [
"code",
"message",
"data",
"request_id"
],
"properties": {
"code": {
"type": "integer",
"const": 0
},
"message": {
"type": "string",
"const": "OK"
},
"data": {
"$ref": "#/components/schemas/PublicCurrencyOptionsData"
},
"request_id": {
"type": "string",
"minLength": 1
}
}
},
"PublicBankOptionsSuccess": {
"example": {
"code": 0,
"message": "OK",
"data": {
"options": [
{
"currency": "MYR",
"code": "MBB",
"name": "Maybank",
"kind": "bank"
},
{
"currency": "MYR",
"code": "TNG",
"name": "Touch 'n Go eWallet",
"kind": "ewallet"
}
]
},
"request_id": "req_example_bank"
},
"type": "object",
"required": [
"code",
"message",
"data",
"request_id"
],
"properties": {
"code": {
"type": "integer",
"const": 0
},
"message": {
"type": "string",
"const": "OK"
},
"data": {
"$ref": "#/components/schemas/PublicBankOptionsData"
},
"request_id": {
"type": "string",
"minLength": 1
}
}
},
"SignedRequest": {
"type": "object",
"maxProperties": 64,
"propertyNames": {
"maxLength": 8192
},
"required": [
"api_key",
"merchant_id",
"timestamp",
"nonce",
"sign"
],
"properties": {
"api_key": {
"type": "string",
"minLength": 1,
"description": "平台为当前环境提供的 Merchant API Key。"
},
"merchant_id": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"description": "API Key 绑定的 Merchant Code。"
},
"timestamp": {
"oneOf": [
{
"type": "string",
"pattern": "^[0-9]+$"
},
{
"type": "integer",
"minimum": 0
}
],
"description": "Unix 秒时间戳;建议使用 JSON 字符串。"
},
"nonce": {
"type": "string",
"minLength": 1,
"description": "每次请求生成的新随机串。"
},
"sign": {
"type": "string",
"pattern": "^[0-9a-f]{64}$",
"description": "小写 HMAC-SHA256 签名。"
}
}
},
"PayCreateRequest": {
"allOf": [
{
"$ref": "#/components/schemas/SignedRequest"
},
{
"type": "object",
"required": [
"merchant_order_no",
"amount",
"currency"
],
"properties": {
"merchant_order_no": {
"type": "string",
"minLength": 1,
"maxLength": 128,
"pattern": "^[\\x20-\\x7E]+$"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"channel_code": {
"type": "string",
"minLength": 1,
"description": "可省略;传入时将收银台可选范围限定为该通道,仍须满足当前商户、币种、支付类型和限额要求"
},
"customer_id": {
"type": "string",
"maxLength": 191,
"description": "客户标识型代收通道必填;最长 191 字符。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"customer_name": {
"type": "string",
"maxLength": 191,
"description": "需要客户资料的代收通道必填;最长 191 字符,参与签名与幂等校验。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"customer_email": {
"type": "string",
"format": "email",
"maxLength": 254,
"description": "需要客户资料的代收通道必填;合法邮箱,最长 254 字符。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"customer_phone": {
"type": "string",
"maxLength": 191,
"description": "需要客户资料的代收通道必填;最长 191 字符。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"payer_bank_code": {
"type": "string",
"maxLength": 191,
"description": "MYR/SGD/THB/IDR 使用平台支付代码,与 currency 组成身份;可选择已验证银行、支付网络或方式。需要付款银行资料的通道仍只支持 DBS、UOB、OCBC。通过 channel/options 查询有效选项。参与签名及幂等指纹,收银台在正式提交前匹配和校验。"
},
"payer_bank_account_owner": {
"type": "string",
"maxLength": 191,
"description": "需要付款账户资料的代收通道必填;最长 191 字符。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"payer_bank_account_number": {
"type": "string",
"maxLength": 191,
"description": "需要付款账户资料的代收通道必填;最长 191 字符。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"payer_username": {
"type": "string",
"maxLength": 191,
"description": "可选付款人用户名;最长 191 字符。可选填用于预填,用户可在确认前编辑或补齐,条件必填项在正式提交前校验。"
},
"notify_url": {
"type": "string",
"format": "uri",
"maxLength": 2048,
"pattern": "^https?://",
"description": "异步通知地址;生产环境必须使用 HTTPS。"
},
"return_url": {
"type": "string",
"format": "uri",
"maxLength": 2048,
"pattern": "^https?://",
"description": "本次订单的浏览器返回地址,须为绝对 HTTP/HTTPS URL,最长 2048 字节;生产环境建议 HTTPS。收银台未传时可使用商户默认地址(如有)。浏览器返回不能作为支付成功依据。"
}
}
}
]
},
"PayQueryRequest": {
"allOf": [
{
"$ref": "#/components/schemas/SignedRequest"
},
{
"type": "object",
"properties": {
"platform_order_no": {
"type": "string",
"minLength": 1,
"maxLength": 64
},
"merchant_order_no": {
"type": "string",
"minLength": 1,
"maxLength": 128
}
},
"anyOf": [
{
"required": [
"platform_order_no"
]
},
{
"required": [
"merchant_order_no"
]
}
]
}
]
},
"PayoutCreateRequest": {
"allOf": [
{
"$ref": "#/components/schemas/SignedRequest"
},
{
"type": "object",
"required": [
"merchant_order_no",
"amount",
"currency"
],
"properties": {
"merchant_order_no": {
"type": "string",
"minLength": 1,
"maxLength": 128,
"pattern": "^[\\x20-\\x7E]+$"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"channel_code": {
"type": "string",
"minLength": 1,
"description": "可省略;传入时将收银台可选范围限定为该通道,仍须满足当前商户、币种、支付类型和限额要求"
},
"bank_code": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"description": "MYR/SGD/THB/IDR 使用平台银行或电子钱包代码,与 currency 组成身份,不提交上游原始代码。可独立预填,并据此匹配收银台通道。 收银台模式未预填时,由用户在银行列表中选择;未传 bank_code 不会关闭银行列表读取。"
},
"account_no": {
"type": "string",
"minLength": 1,
"maxLength": 128
},
"account_name": {
"type": "string",
"minLength": 1,
"maxLength": 128
},
"recipient_email": {
"type": "string",
"format": "email",
"maxLength": 254,
"description": "各收款字段独立可选,支持部分预填;缺失必填项按所选通道在确认前补齐,已传字段不可修改。邮箱仅要求邮箱的通道补填,提供时须格式合法。"
},
"notify_url": {
"type": "string",
"format": "uri",
"maxLength": 2048,
"pattern": "^https?://",
"description": "异步通知地址;省略时使用商户默认通知地址,生产环境必须使用 HTTPS。"
},
"return_url": {
"type": "string",
"format": "uri",
"maxLength": 2048,
"description": "代付收银台手动返回地址;必须为绝对 HTTP(S) URL,不含用户凭证,最长 2048 字节。非空字段参与签名与会话幂等校验。未传或为空时无返回地址,不使用商户默认地址。返回不能作为代付成功依据。",
"pattern": "^https?://"
}
}
}
]
},
"PayoutQueryRequest": {
"allOf": [
{
"$ref": "#/components/schemas/SignedRequest"
},
{
"type": "object",
"properties": {
"platform_order_no": {
"type": "string",
"minLength": 1,
"maxLength": 64
},
"merchant_order_no": {
"type": "string",
"minLength": 1,
"maxLength": 128
},
"sync_provider": {
"type": "boolean",
"default": false,
"description": "仅对 processing 订单尝试获取最新支付状态;该字段参与签名。"
}
},
"anyOf": [
{
"required": [
"platform_order_no"
]
},
{
"required": [
"merchant_order_no"
]
}
]
}
]
},
"BalanceQueryRequest": {
"allOf": [
{
"$ref": "#/components/schemas/SignedRequest"
},
{
"type": "object",
"properties": {
"currency": {
"$ref": "#/components/schemas/Currency"
}
}
}
]
},
"Money": {
"type": "string",
"pattern": "^(?:0|[1-9][0-9]*)(?:\\.[0-9]{1,8})?$",
"description": "十进制定点金额字符串;不得使用 float 或科学计数法。"
},
"Currency": {
"type": "string",
"pattern": "^[A-Z0-9]{3,8}$",
"examples": [
"MYR",
"SGD",
"USDT"
]
},
"PayInStatus": {
"type": "string",
"enum": [
"created",
"pending",
"paid",
"failed",
"expired",
"closed",
"manual_review"
]
},
"CheckoutMode": {
"type": "string",
"enum": [
"direct",
"cashier"
]
},
"CashierStatus": {
"type": "string",
"enum": [
"awaiting_payment_method",
"selecting",
"submitted",
"expired"
]
},
"PayoutStatus": {
"type": "string",
"enum": [
"reviewing",
"processing",
"success",
"failed",
"cancelled"
]
},
"PayoutAuditStatus": {
"type": "string",
"enum": [
"pending",
"approved",
"rejected"
]
},
"PayCreateData": {
"type": "object",
"required": [
"checkout_mode",
"platform_order_no",
"merchant_order_no",
"amount",
"requested_amount",
"currency",
"status"
],
"properties": {
"checkout_mode": {
"$ref": "#/components/schemas/CheckoutMode"
},
"platform_order_no": {
"type": "string"
},
"merchant_order_no": {
"type": "string"
},
"channel_order_no": {
"type": "string"
},
"channel_code": {
"type": "string"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"requested_amount": {
"$ref": "#/components/schemas/Money",
"description": "商户创建订单时提交的原始金额;当支付服务确认了不同的实际应付金额时,amount 为实际应付金额,否则两者相同。"
},
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "扣除订单锁定商户手续费后的金额,即 amount - fee_amount。"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"status": {
"oneOf": [
{
"$ref": "#/components/schemas/PayInStatus"
},
{
"$ref": "#/components/schemas/CashierStatus"
}
]
},
"payment_url": {
"type": "string",
"format": "uri",
"description": "不透明跳转地址,不得修改或跨订单复用。"
},
"qr_string": {
"type": "string"
},
"qr_image": {
"type": "string"
},
"crypto_address": {
"type": "string"
},
"expired_at": {
"type": "string",
"format": "date-time",
"description": "本次代收订单的支付截止时间,调用方应按 RFC 3339 时间处理。"
}
}
},
"PayQueryData": {
"type": "object",
"required": [
"checkout_mode",
"platform_order_no",
"merchant_order_no",
"amount",
"currency",
"status"
],
"properties": {
"checkout_mode": {
"$ref": "#/components/schemas/CheckoutMode"
},
"platform_order_no": {
"type": "string"
},
"merchant_order_no": {
"type": "string"
},
"channel_order_no": {
"type": "string"
},
"channel_code": {
"type": "string"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"paid_amount": {
"$ref": "#/components/schemas/Money"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"status": {
"oneOf": [
{
"$ref": "#/components/schemas/PayInStatus"
},
{
"$ref": "#/components/schemas/CashierStatus"
}
]
},
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "扣除订单锁定商户手续费后的金额,即 amount - fee_amount。"
},
"paid_at": {
"type": "string",
"format": "date-time"
},
"expired_at": {
"type": "string",
"format": "date-time"
}
}
},
"PayoutReceiver": {
"type": "object",
"required": [
"type",
"bank_code",
"account_mask",
"account_name_masked",
"recipient_email_masked",
"payload_format"
],
"properties": {
"type": {
"type": "string",
"const": "bank"
},
"bank_code": {
"type": "string"
},
"account_mask": {
"type": "string"
},
"account_name_masked": {
"type": "string"
},
"recipient_email_masked": {
"type": "string"
},
"payload_format": {
"type": "string"
}
}
},
"PayoutData": {
"type": "object",
"required": [
"checkout_mode",
"platform_order_no",
"merchant_order_no",
"amount",
"currency",
"status"
],
"properties": {
"checkout_mode": {
"$ref": "#/components/schemas/CheckoutMode"
},
"platform_order_no": {
"type": "string"
},
"merchant_order_no": {
"type": "string"
},
"channel_order_no": {
"type": "string"
},
"channel_code": {
"type": "string"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"status": {
"oneOf": [
{
"$ref": "#/components/schemas/PayoutStatus"
},
{
"$ref": "#/components/schemas/CashierStatus"
}
]
},
"audit_status": {
"$ref": "#/components/schemas/PayoutAuditStatus"
},
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "订单总扣款,即 amount + fee_amount;与 frozen_amount 相同。成功时实际扣除,失败时解冻。"
},
"frozen_amount": {
"$ref": "#/components/schemas/Money"
},
"receiver": {
"$ref": "#/components/schemas/PayoutReceiver"
},
"payment_url": {
"type": "string",
"format": "uri"
},
"completed_at": {
"type": "string",
"format": "date-time"
},
"created_at": {
"type": "string",
"format": "date-time"
},
"expired_at": {
"type": "string",
"format": "date-time"
}
}
},
"BalanceItem": {
"type": "object",
"required": [
"currency",
"available_amount",
"frozen_amount",
"pending_settlement_amount"
],
"properties": {
"currency": {
"$ref": "#/components/schemas/Currency"
},
"available_amount": {
"$ref": "#/components/schemas/Money"
},
"frozen_amount": {
"$ref": "#/components/schemas/Money"
},
"pending_settlement_amount": {
"$ref": "#/components/schemas/Money",
"description": "同环境、商户与币种的代收待到账净额,包含 pending/processing/dead;credited/cancelled 不计入。订单 paid 与 Notify 不代表延迟资金已可用。"
}
}
},
"BalanceData": {
"type": "object",
"required": [
"balances"
],
"properties": {
"balances": {
"type": "array",
"items": {
"$ref": "#/components/schemas/BalanceItem"
}
}
}
},
"ChannelOption": {
"type": "object",
"required": [
"code",
"name",
"enabled"
],
"properties": {
"code": {
"type": "string",
"minLength": 1
},
"provider_code": {
"type": "string"
},
"name": {
"type": "string",
"minLength": 1
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"payment_method": {
"type": "string"
},
"enabled": {
"type": "boolean"
},
"min_amount": {
"$ref": "#/components/schemas/Money"
},
"max_amount": {
"$ref": "#/components/schemas/Money"
}
}
},
"ChannelOptionsData": {
"type": "object",
"required": [
"options"
],
"properties": {
"options": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ChannelOption"
},
"description": "币种查询及固定 Key 返回标准选项。自由匹配银行/钱包查询按 currency + code 合并去重,不返回所属通道;channel_code 可限制范围。未指定通道时省略通道金额限额,实际金额由创建或确认校验。payment_method 指定 channel_code 时返回该通道选项,同时仍可读取 channels 分组。"
},
"channels": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ChannelOptionsChannel"
},
"description": "仅自由匹配 payment_method 查询按通道分组;每组包含通道名称、支付方向、支付方式和已验证映射的银行。银行/钱包、固定 Key 和币种查询不返回此字段。"
},
"min_amount": {
"type": "string",
"description": "固定 Key 查询,或全局 Key 银行/支付方式查询指定 channel_code 时,返回对应通道配置的单笔最小金额,按查询币种精度返回十进制字符串;未配置时省略。仅展示通道限额,实际交易仍执行既有校验。",
"example": "10.00"
},
"max_amount": {
"type": "string",
"description": "固定 Key 查询,或全局 Key 银行/支付方式查询指定 channel_code 时,返回对应通道配置的单笔最大金额,按查询币种精度返回十进制字符串;未配置时省略。仅展示通道限额,实际交易仍执行既有校验。",
"example": "5000.00"
}
}
},
"SuccessEnvelope": {
"type": "object",
"required": [
"code",
"message",
"request_id"
],
"properties": {
"code": {
"type": "integer",
"const": 0
},
"message": {
"type": "string",
"const": "OK"
},
"request_id": {
"type": "string",
"minLength": 1
}
}
},
"PayCreateSuccess": {
"example": {
"code": 0,
"message": "OK",
"data": {
"checkout_mode": "cashier",
"platform_order_no": "P202609160001",
"merchant_order_no": "PAY202609160001",
"amount": "100.00",
"requested_amount": "100.00",
"currency": "MYR",
"status": "awaiting_payment_method",
"payment_url": "https://cashier.example.com/#/cashier/<opaque-token>",
"expired_at": "2026-09-16T15:30:00Z"
},
"request_id": "req_01JEXAMPLE"
},
"allOf": [
{
"$ref": "#/components/schemas/SuccessEnvelope"
},
{
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$ref": "#/components/schemas/PayCreateData"
}
}
}
]
},
"PayQuerySuccess": {
"allOf": [
{
"$ref": "#/components/schemas/SuccessEnvelope"
},
{
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$ref": "#/components/schemas/PayQueryData"
}
}
}
]
},
"PayoutSuccess": {
"example": {
"code": 0,
"message": "OK",
"data": {
"checkout_mode": "cashier",
"platform_order_no": "W202609160001",
"merchant_order_no": "OUT202609160001",
"amount": "50.00",
"currency": "MYR",
"status": "awaiting_payment_method",
"payment_url": "https://cashier.example.com/#/cashier/<opaque-token>",
"expired_at": "2026-09-16T15:30:00Z"
},
"request_id": "req_01JEXAMPLE"
},
"allOf": [
{
"$ref": "#/components/schemas/SuccessEnvelope"
},
{
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$ref": "#/components/schemas/PayoutData"
}
}
}
]
},
"BalanceSuccess": {
"allOf": [
{
"$ref": "#/components/schemas/SuccessEnvelope"
},
{
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$ref": "#/components/schemas/BalanceData"
}
}
}
]
},
"ChannelOptionsSuccess": {
"allOf": [
{
"$ref": "#/components/schemas/SuccessEnvelope"
},
{
"type": "object",
"required": [
"data"
],
"properties": {
"data": {
"$ref": "#/components/schemas/ChannelOptionsData"
}
}
}
],
"example": {
"code": 0,
"message": "OK",
"data": {
"options": [
{
"code": "MBB",
"name": "Maybank",
"currency": "MYR",
"enabled": true
}
]
},
"request_id": "req_example_channel_options"
}
},
"ErrorCode": {
"type": "integer",
"enum": [
10001,
10002,
10003,
10004,
10005,
10006,
10007,
10008,
10009,
10010,
10011,
10012,
10013,
10014,
10015,
10016,
20001,
20002,
30001,
30002,
30007,
30008,
40001,
40002,
40003,
40004,
50002,
50003,
50006,
50007,
50008,
50009,
90000,
90001
]
},
"ErrorEnvelope": {
"type": "object",
"required": [
"code",
"message_key",
"default_message",
"message",
"data",
"request_id"
],
"properties": {
"code": {
"$ref": "#/components/schemas/ErrorCode"
},
"message_key": {
"type": "string",
"pattern": "^error\\.[a-z0-9_]+$"
},
"default_message": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string",
"minLength": 1
},
"data": {
"type": "null"
},
"request_id": {
"type": "string",
"minLength": 1
}
}
},
"MerchantNotify": {
"oneOf": [
{
"$ref": "#/components/schemas/PayInSucceededNotify"
},
{
"$ref": "#/components/schemas/PayInFailedNotify"
},
{
"$ref": "#/components/schemas/PayInExpiredNotify"
},
{
"$ref": "#/components/schemas/PayoutSucceededNotify"
},
{
"$ref": "#/components/schemas/PayoutFailedNotify"
},
{
"$ref": "#/components/schemas/CashierPayInExpiredNotify"
},
{
"$ref": "#/components/schemas/CashierPayoutExpiredNotify"
}
],
"discriminator": {
"propertyName": "event_type",
"mapping": {
"payin.succeeded": "#/components/schemas/PayInSucceededNotify",
"payin.failed": "#/components/schemas/PayInFailedNotify",
"payin.expired": "#/components/schemas/PayInExpiredNotify",
"payout.succeeded": "#/components/schemas/PayoutSucceededNotify",
"payout.failed": "#/components/schemas/PayoutFailedNotify",
"cashier.payin.expired": "#/components/schemas/CashierPayInExpiredNotify",
"cashier.payout.expired": "#/components/schemas/CashierPayoutExpiredNotify"
}
}
},
"PayInNotifyBase": {
"type": "object",
"required": [
"platform_order_no",
"merchant_order_no",
"channel_order_no",
"channel_code",
"amount",
"currency",
"completed_at",
"timestamp",
"nonce",
"secret_version",
"sign"
],
"properties": {
"platform_order_no": {
"type": "string"
},
"merchant_order_no": {
"type": "string"
},
"channel_order_no": {
"type": "string"
},
"channel_code": {
"type": "string"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"completed_at": {
"type": "string",
"format": "date-time"
},
"timestamp": {
"type": "integer",
"minimum": 0
},
"nonce": {
"type": "string",
"minLength": 1
},
"secret_version": {
"type": "integer",
"minimum": 1
},
"sign": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
}
}
},
"PayInSucceededNotify": {
"allOf": [
{
"$ref": "#/components/schemas/PayInNotifyBase"
},
{
"type": "object",
"required": [
"event_type",
"status",
"fee_amount",
"net_amount",
"paid_amount",
"paid_at"
],
"properties": {
"event_type": {
"type": "string",
"const": "payin.succeeded"
},
"status": {
"type": "string",
"const": "paid"
},
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "扣除订单锁定商户手续费后的金额,即 amount - fee_amount。"
},
"paid_amount": {
"$ref": "#/components/schemas/Money"
},
"paid_at": {
"type": "string",
"format": "date-time"
},
"status_revision": {
"type": "string",
"pattern": "^[1-9][0-9]*$",
"description": "正式订单状态更正版本;与 correction 同时出现,参与签名。商户在事务内保存最高版本,避免旧通知覆盖。"
},
"correction": {
"type": "string",
"const": "true",
"description": "正式订单状态更正标识;与 status_revision 同时出现,参与签名。"
}
},
"dependentRequired": {
"status_revision": [
"correction"
],
"correction": [
"status_revision"
]
}
}
]
},
"PayInFailedNotify": {
"allOf": [
{
"$ref": "#/components/schemas/PayInNotifyBase"
},
{
"type": "object",
"required": [
"event_type",
"status",
"fee_amount",
"net_amount"
],
"properties": {
"event_type": {
"type": "string",
"const": "payin.failed"
},
"status": {
"type": "string",
"const": "failed"
},
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "扣除订单锁定商户手续费后的金额,即 amount - fee_amount。"
},
"status_revision": {
"type": "string",
"pattern": "^[1-9][0-9]*$",
"description": "正式订单状态更正版本;与 correction 同时出现,参与签名。商户在事务内保存最高版本,避免旧通知覆盖。"
},
"correction": {
"type": "string",
"const": "true",
"description": "正式订单状态更正标识;与 status_revision 同时出现,参与签名。"
}
},
"not": {
"anyOf": [
{
"required": [
"paid_amount"
]
},
{
"required": [
"paid_at"
]
}
]
},
"dependentRequired": {
"status_revision": [
"correction"
],
"correction": [
"status_revision"
]
}
}
]
},
"PayInExpiredNotify": {
"allOf": [
{
"$ref": "#/components/schemas/PayInNotifyBase"
},
{
"type": "object",
"required": [
"event_type",
"status",
"fee_amount",
"net_amount",
"reason_code",
"expired_at"
],
"properties": {
"event_type": {
"type": "string",
"const": "payin.expired"
},
"status": {
"type": "string",
"const": "expired"
},
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "扣除订单锁定商户手续费后的金额,即 amount - fee_amount。"
},
"reason_code": {
"type": "string",
"const": "order_timeout"
},
"expired_at": {
"type": "string",
"format": "date-time"
},
"status_revision": {
"type": "string",
"pattern": "^[1-9][0-9]*$",
"description": "正式订单状态更正版本;与 correction 同时出现,参与签名。商户在事务内保存最高版本,避免旧通知覆盖。"
},
"correction": {
"type": "string",
"const": "true",
"description": "正式订单状态更正标识;与 status_revision 同时出现,参与签名。"
}
},
"not": {
"anyOf": [
{
"required": [
"paid_amount"
]
},
{
"required": [
"paid_at"
]
}
]
},
"dependentRequired": {
"status_revision": [
"correction"
],
"correction": [
"status_revision"
]
}
}
]
},
"PayoutNotifyBase": {
"allOf": [
{
"$ref": "#/components/schemas/PayInNotifyBase"
},
{
"type": "object",
"required": [
"fee_amount",
"net_amount"
],
"properties": {
"fee_amount": {
"$ref": "#/components/schemas/Money"
},
"net_amount": {
"$ref": "#/components/schemas/Money",
"description": "订单总扣款,即 amount + fee_amount;成功时实际扣除,失败时表示已解冻的原订单总额。"
}
}
}
]
},
"PayoutSucceededNotify": {
"allOf": [
{
"$ref": "#/components/schemas/PayoutNotifyBase"
},
{
"type": "object",
"required": [
"event_type",
"status",
"fee_amount",
"net_amount"
],
"properties": {
"event_type": {
"type": "string",
"const": "payout.succeeded"
},
"status": {
"type": "string",
"const": "success"
},
"status_revision": {
"type": "string",
"pattern": "^[1-9][0-9]*$",
"description": "正式订单状态更正版本;与 correction 同时出现,参与签名。商户在事务内保存最高版本,避免旧通知覆盖。"
},
"correction": {
"type": "string",
"const": "true",
"description": "正式订单状态更正标识;与 status_revision 同时出现,参与签名。"
}
},
"not": {
"anyOf": [
{
"required": [
"paid_amount"
]
},
{
"required": [
"paid_at"
]
}
]
},
"dependentRequired": {
"status_revision": [
"correction"
],
"correction": [
"status_revision"
]
}
}
]
},
"PayoutFailedNotify": {
"allOf": [
{
"$ref": "#/components/schemas/PayoutNotifyBase"
},
{
"type": "object",
"required": [
"event_type",
"status",
"fee_amount",
"net_amount"
],
"properties": {
"event_type": {
"type": "string",
"const": "payout.failed"
},
"status": {
"type": "string",
"const": "failed"
},
"status_revision": {
"type": "string",
"pattern": "^[1-9][0-9]*$",
"description": "正式订单状态更正版本;与 correction 同时出现,参与签名。商户在事务内保存最高版本,避免旧通知覆盖。"
},
"correction": {
"type": "string",
"const": "true",
"description": "正式订单状态更正标识;与 status_revision 同时出现,参与签名。"
}
},
"not": {
"anyOf": [
{
"required": [
"paid_amount"
]
},
{
"required": [
"paid_at"
]
}
]
},
"dependentRequired": {
"status_revision": [
"correction"
],
"correction": [
"status_revision"
]
}
}
]
},
"CashierExpiredNotifyBase": {
"type": "object",
"required": [
"platform_order_no",
"merchant_order_no",
"amount",
"currency",
"completed_at",
"timestamp",
"nonce",
"secret_version",
"sign",
"checkout_mode",
"status",
"reason_code",
"expired_at"
],
"properties": {
"platform_order_no": {
"type": "string"
},
"merchant_order_no": {
"type": "string"
},
"amount": {
"$ref": "#/components/schemas/Money"
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"completed_at": {
"type": "string",
"format": "date-time"
},
"timestamp": {
"type": "integer",
"minimum": 0
},
"nonce": {
"type": "string",
"minLength": 1
},
"secret_version": {
"type": "integer",
"minimum": 1
},
"sign": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"checkout_mode": {
"type": "string",
"const": "cashier"
},
"status": {
"type": "string",
"const": "expired"
},
"reason_code": {
"type": "string",
"enum": [
"cashier_channel_not_selected",
"cashier_submission_timeout"
],
"description": "会话过期原因:未选通道或提交超时。"
},
"expiry_revision": {
"type": "string",
"pattern": "^[1-9][0-9]*$",
"description": "可选的过期通知版本,参与签名;缺省按版本 0 处理。按 event_type + platform_order_no + expiry_revision 幂等处理,不同版本不能作为重复通知忽略。"
},
"expired_at": {
"type": "string",
"format": "date-time",
"description": "会话截止时间,与 completed_at 相同。"
}
},
"not": {
"anyOf": [
{
"required": [
"channel_code"
]
},
{
"required": [
"channel_order_no"
]
},
{
"required": [
"fee_amount"
]
},
{
"required": [
"frozen_amount"
]
},
{
"required": [
"paid_amount"
]
},
{
"required": [
"paid_at"
]
},
{
"required": [
"status_revision"
]
},
{
"required": [
"correction"
]
}
]
}
},
"CashierPayInExpiredNotify": {
"description": "尚未生成正式订单的代收收银台会话过期,包括未选通道和提交超时;通知验签及 SUCCESS 应答规则与正式订单相同。",
"allOf": [
{
"$ref": "#/components/schemas/CashierExpiredNotifyBase"
},
{
"type": "object",
"required": [
"event_type"
],
"properties": {
"event_type": {
"type": "string",
"const": "cashier.payin.expired"
}
}
}
]
},
"CashierPayoutExpiredNotify": {
"description": "未确认通道的收银台会话过期,尚未创建正式订单;通知验签及 SUCCESS 应答规则与正式订单相同。",
"allOf": [
{
"$ref": "#/components/schemas/CashierExpiredNotifyBase"
},
{
"type": "object",
"required": [
"event_type"
],
"properties": {
"event_type": {
"type": "string",
"const": "cashier.payout.expired"
}
}
}
]
},
"ChannelOptionsRequest": {
"allOf": [
{
"$ref": "#/components/schemas/SignedRequest"
},
{
"type": "object",
"required": [
"option_type"
],
"properties": {
"channel_code": {
"type": "string",
"minLength": 1,
"description": "可省略;传入时限定当前商户在同一环境中已启用的一个有效通道。"
},
"currency": {
"$ref": "#/components/schemas/Currency",
"description": "银行查询必填一个已授权币种;币种查询可省略,传入时只查询该币种。"
},
"option_type": {
"type": "string",
"enum": [
"currency",
"payin_bank",
"payout_bank",
"payment_method"
]
},
"payment_type": {
"type": "string",
"enum": [
"payin",
"payout"
],
"description": "币种查询可按 payin/payout 筛选,省略取已授权类型的并集。银行类型由 option_type 决定,传入时须一致。"
}
},
"allOf": [
{
"if": {
"properties": {
"option_type": {
"enum": [
"payin_bank",
"payout_bank",
"payment_method"
]
}
},
"required": [
"option_type"
]
},
"then": {
"required": [
"currency"
]
}
}
]
}
],
"example": {
"api_key": "<API_KEY>",
"merchant_id": "merchant_1001",
"option_type": "payout_bank",
"currency": "MYR",
"timestamp": "1789731000",
"nonce": "options_bank_001",
"sign": "<64位小写HMAC-SHA256>"
},
"examples": [
{
"api_key": "<API_KEY>",
"merchant_id": "merchant_1001",
"option_type": "currency",
"payment_type": "payout",
"timestamp": "1789731000",
"nonce": "options_currency_001",
"sign": "<64位小写HMAC-SHA256>"
},
{
"api_key": "<API_KEY>",
"merchant_id": "merchant_1001",
"option_type": "payout_bank",
"currency": "MYR",
"timestamp": "1789731000",
"nonce": "options_bank_001",
"sign": "<64位小写HMAC-SHA256>"
}
]
},
"ChannelOptionsChannel": {
"type": "object",
"required": [
"channel_code",
"name",
"payment_type",
"currency",
"options",
"banks"
],
"properties": {
"channel_code": {
"type": "string",
"minLength": 1
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 191,
"description": "与 Cashier 一致的通道显示名称。"
},
"payment_type": {
"type": "string",
"enum": [
"payin",
"payout"
]
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"options": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ChannelOption"
}
},
"banks": {
"type": "array",
"description": "该通道、币种和支付方向下已启用且有准确平台映射的银行或电子钱包;无可信来源时为空数组。",
"items": {
"$ref": "#/components/schemas/ChannelOption"
}
},
"min_amount": {
"type": "string",
"description": "对应通道配置的单笔最小金额,按查询币种精度返回十进制字符串;未配置时省略。仅展示通道限额,实际交易仍执行既有校验。",
"example": "10.00"
},
"max_amount": {
"type": "string",
"description": "对应通道配置的单笔最大金额,按查询币种精度返回十进制字符串;未配置时省略。仅展示通道限额,实际交易仍执行既有校验。",
"example": "5000.00"
}
}
}
}
},
"x-merchant-signature": {
"algorithm": "HMAC-SHA256",
"canonicalization": [
"Remove sign.",
"Remove fields whose value is the empty string.",
"Sort field names ascending by ASCII.",
"Join original scalar values as key=value with & and no URL encoding.",
"Use the API Secret as HMAC key and output lowercase hexadecimal."
],
"timestampUnit": "Unix seconds",
"typicalClockSkewSeconds": 300,
"note": "Generate a new timestamp, nonce and sign immediately before each request."
},
"x-request-limits": {
"maxBodyBytes": 65536,
"maxParameterCount": 64,
"maxParameterNameBytes": 8192,
"maxScalarValueBytes": 8192
}
}
Postman Collection · 完整内容
{
"info": {
"_postman_id": "b0d53355-7b27-4cd0-9576-c0788ad5985f",
"name": "4Fang Cashier API v1.5.0",
"description": "Cashier API requests for PayIn, Payout, order queries, and balance query. Use a separate merchant_global key for each payment type and currency. Keys are not bound to a channel; an optional channel_code limits the Cashier selection. Fill credentials locally. Save payment_url from creation, let the user confirm the payment channel, and verify the result through queries or signed notifications. Payout receiver fields must be all provided or all omitted. Browser return does not confirm a successful transaction.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"auth": {
"type": "noauth"
},
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"const requireEnvironment = (name) => {",
" const value = pm.environment.get(name);",
" if (typeof value !== 'string' || value === '') throw new Error(`${name} is required in the active Postman environment`);",
" return value;",
"};",
"",
"const baseUrl = requireEnvironment('base_url');",
"const parsedBaseUrl = new URL(baseUrl);",
"if (!['http:', 'https:'].includes(parsedBaseUrl.protocol) || parsedBaseUrl.username || parsedBaseUrl.password || parsedBaseUrl.search || parsedBaseUrl.hash) {",
" throw new Error('base_url must be an HTTP(S) URL without credentials, query, or fragment');",
"}",
"",
"const requestHost = String(pm.environment.get('request_host') || '').trim();",
"if (requestHost) {",
" const loopback = ['localhost', '127.0.0.1', '::1'].includes(parsedBaseUrl.hostname.toLowerCase());",
" if (!loopback) throw new Error('request_host is allowed only when base_url uses loopback');",
" if (requestHost.includes('://') || /[\\/\\\\@?#\\s]/.test(requestHost)) throw new Error('request_host must be host[:port] only');",
" const parsedHost = new URL(`http://${requestHost}`);",
" if (!parsedHost.hostname || parsedHost.username || parsedHost.password || parsedHost.pathname !== '/' || parsedHost.search || parsedHost.hash) throw new Error('request_host is invalid');",
" pm.request.headers.upsert({ key: 'Host', value: parsedHost.host });",
"}",
"",
"pm.variables.set('timestamp', String(Math.floor(Date.now() / 1000)));",
"pm.variables.set('nonce', pm.variables.replaceIn('{{$guid}}').replace(/-/g, ''));",
"pm.variables.set('request_id', `postman_${pm.variables.replaceIn('{{$guid}}').replace(/-/g, '')}`);",
"if ((pm.info.requestName === 'Create PayIn' || pm.info.requestName === 'Create Payout') && !String(pm.environment.get('merchant_order_no') || '').trim()) {",
" pm.variables.set('merchant_order_no', `${pm.info.requestName === 'Create Payout' ? 'PAYOUT' : 'PAYIN'}_POSTMAN_${Date.now()}`);",
"}",
"",
"if (!pm.request.body || pm.request.body.mode !== 'raw') throw new Error('signed request body must use raw JSON');",
"const renderedBody = pm.variables.replaceIn(pm.request.body.raw);",
"let parameters;",
"try { parameters = JSON.parse(renderedBody); } catch (error) { throw new Error(`request body is not valid JSON: ${error.message}`); }",
"if (!parameters || typeof parameters !== 'object' || Array.isArray(parameters)) throw new Error('request body must be a JSON object');",
"for (const [key, value] of Object.entries(parameters)) {",
" if (value === null || (typeof value === 'object')) throw new Error(`${key} must be a scalar value`);",
"}",
"if ((pm.info.requestName === 'Query PayIn' || pm.info.requestName === 'Query Payout') && !String(parameters.platform_order_no || '') && !String(parameters.merchant_order_no || '')) {",
" throw new Error(`platform_order_no or merchant_order_no is required for ${pm.info.requestName}`);",
"}",
"",
"const canonical = Object.keys(parameters)",
" .filter((key) => key !== 'sign' && String(parameters[key]) !== '')",
" .sort()",
" .map((key) => `${key}=${String(parameters[key])}`)",
" .join('&');",
"const cryptoLibrary = typeof CryptoJS !== 'undefined' ? CryptoJS : pm.require('npm:crypto-js@4.2.0');",
"const signature = cryptoLibrary.HmacSHA256(canonical, requireEnvironment('api_secret')).toString(cryptoLibrary.enc.Hex);",
"pm.variables.set('sign', signature);",
"pm.variables.set('canonical_string', canonical);"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"pm.test('HTTP status is 200', () => pm.response.to.have.status(200));",
"let payload;",
"pm.test('response is valid JSON', () => { payload = pm.response.json(); pm.expect(payload).to.be.an('object'); });",
"if (!payload) return;",
"pm.test('response has stable envelope fields', () => {",
" pm.expect(payload.code).to.be.a('number');",
" pm.expect(payload.request_id).to.be.a('string').and.not.empty;",
" pm.expect(payload.message).to.be.a('string').and.not.empty;",
"});",
"if (payload.code !== 0) {",
" pm.test('business error is fail-closed', () => {",
" pm.expect(payload.message_key).to.be.a('string').and.not.empty;",
" pm.expect(payload.default_message).to.be.a('string').and.not.empty;",
" pm.expect(payload.data).to.equal(null);",
" });",
" pm.test('business response code is zero', () => pm.expect(payload.code, `${payload.message_key}: ${payload.message}`).to.equal(0));",
" return;",
"}",
"pm.test('success response contains data object', () => pm.expect(payload.data).to.be.an('object'));",
"if (['Create PayIn', 'Query PayIn', 'Create Payout', 'Query Payout'].includes(pm.info.requestName)) {",
" pm.test('order response exposes required public fields', () => {",
" for (const field of ['checkout_mode', 'platform_order_no', 'merchant_order_no', 'amount', 'currency', 'status']) {",
" pm.expect(payload.data[field], field).to.be.a('string').and.not.empty;",
" }",
" pm.expect(payload.data.amount).to.match(/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/);",
" pm.expect(payload.data.checkout_mode).to.be.oneOf(['direct', 'cashier']);",
" if (payload.data.checkout_mode === 'cashier') {",
" pm.expect(payload.data.status).to.be.oneOf(['awaiting_payment_method', 'selecting', 'submitted', 'expired']);",
" pm.expect(payload.data.expired_at).to.be.a('string').and.not.empty;",
" if (pm.info.requestName.startsWith('Create ')) pm.expect(payload.data.payment_url).to.be.a('string').and.not.empty;",
" } else {",
" const directFields = ['channel_code', 'fee_amount', 'net_amount'];",
" for (const field of directFields) pm.expect(payload.data[field], field).to.be.a('string').and.not.empty;",
" pm.expect(payload.data.fee_amount).to.match(/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/);",
" pm.expect(payload.data.net_amount).to.match(/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/);",
" }",
" });",
" if (pm.info.requestName === 'Create PayIn' || pm.info.requestName === 'Create Payout') {",
" pm.environment.set('platform_order_no', payload.data.platform_order_no);",
" pm.environment.set('merchant_order_no', payload.data.merchant_order_no);",
" }",
"}",
"if (pm.info.requestName === 'Query Balance') {",
" pm.test('balance response uses decimal strings', () => {",
" pm.expect(payload.data.balances).to.be.an('array');",
" for (const balance of payload.data.balances) {",
" for (const field of ['currency', 'available_amount', 'frozen_amount', 'pending_settlement_amount']) pm.expect(balance[field], field).to.be.a('string').and.not.empty;",
" for (const field of ['available_amount', 'frozen_amount', 'pending_settlement_amount']) pm.expect(balance[field]).to.match(/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?$/);",
" }",
" });",
"}"
]
}
}
],
"item": [
{
"name": "Create PayIn",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "X-Request-ID",
"value": "{{request_id}}"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"api_key\": \"{{api_key}}\",\n \"merchant_id\": \"{{merchant_id}}\",\n \"merchant_order_no\": \"{{merchant_order_no}}\",\n \"amount\": \"{{amount}}\",\n \"currency\": \"{{currency}}\",\n \"channel_code\": \"{{channel_code}}\",\n \"customer_id\": \"{{customer_id}}\",\n \"customer_name\": \"{{customer_name}}\",\n \"customer_email\": \"{{customer_email}}\",\n \"customer_phone\": \"{{customer_phone}}\",\n \"payer_bank_code\": \"{{payer_bank_code}}\",\n \"payer_bank_account_owner\": \"{{payer_bank_account_owner}}\",\n \"payer_bank_account_number\": \"{{payer_bank_account_number}}\",\n \"payer_username\": \"{{payer_username}}\",\n \"notify_url\": \"{{notify_url}}\",\n \"return_url\": \"{{return_url}}\",\n \"timestamp\": \"{{timestamp}}\",\n \"nonce\": \"{{nonce}}\",\n \"sign\": \"{{sign}}\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/v1/pay/create",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"pay",
"create"
]
},
"description": "Create a PayIn Cashier session. Customer and payer fields are optional prefill; channel-specific required fields are completed in the Cashier."
}
},
{
"name": "Query PayIn",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "X-Request-ID",
"value": "{{request_id}}"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"api_key\": \"{{api_key}}\",\n \"merchant_id\": \"{{merchant_id}}\",\n \"platform_order_no\": \"{{platform_order_no}}\",\n \"merchant_order_no\": \"{{merchant_order_no}}\",\n \"timestamp\": \"{{timestamp}}\",\n \"nonce\": \"{{nonce}}\",\n \"sign\": \"{{sign}}\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/v1/pay/query",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"pay",
"query"
]
},
"description": "Queries the order created by the same API Key. At least one order number must be present. The collection fills both after a successful Create PayIn call."
}
},
{
"name": "Create Payout",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "X-Request-ID",
"value": "{{request_id}}"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"api_key\": \"{{api_key}}\",\n \"merchant_id\": \"{{merchant_id}}\",\n \"merchant_order_no\": \"{{merchant_order_no}}\",\n \"amount\": \"{{amount}}\",\n \"currency\": \"{{currency}}\",\n \"channel_code\": \"{{channel_code}}\",\n \"bank_code\": \"{{bank_code}}\",\n \"account_no\": \"{{account_no}}\",\n \"account_name\": \"{{account_name}}\",\n \"recipient_email\": \"{{recipient_email}}\",\n \"notify_url\": \"{{notify_url}}\",\n \"timestamp\": \"{{timestamp}}\",\n \"nonce\": \"{{nonce}}\",\n \"sign\": \"{{sign}}\",\n \"return_url\": \"{{return_url}}\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/v1/payout/create",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"payout",
"create"
]
},
"description": "Create a Payout Cashier session using a payout merchant_global key. Provide all four receiver fields or omit all four. return_url is optional; without it no browser return address is configured."
}
},
{
"name": "Query Payout",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "X-Request-ID",
"value": "{{request_id}}"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"api_key\": \"{{api_key}}\",\n \"merchant_id\": \"{{merchant_id}}\",\n \"platform_order_no\": \"{{platform_order_no}}\",\n \"merchant_order_no\": \"{{merchant_order_no}}\",\n \"sync_provider\": {{sync_provider}},\n \"timestamp\": \"{{timestamp}}\",\n \"nonce\": \"{{nonce}}\",\n \"sign\": \"{{sign}}\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/v1/payout/query",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"payout",
"query"
]
},
"description": "Queries a Cashier session or formal order created by the same payout API Key. Set sync_provider=true to refresh a processing order. Timeout or unknown results remain processing."
}
},
{
"name": "Query Balance",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "X-Request-ID",
"value": "{{request_id}}"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"api_key\": \"{{api_key}}\",\n \"merchant_id\": \"{{merchant_id}}\",\n \"currency\": \"{{currency}}\",\n \"timestamp\": \"{{timestamp}}\",\n \"nonce\": \"{{nonce}}\",\n \"sign\": \"{{sign}}\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/v1/balance/query",
"host": [
"{{base_url}}"
],
"path": [
"api",
"v1",
"balance",
"query"
]
},
"description": "Queries Merchant balances. currency may be left empty and is then excluded from the signature."
}
}
]
}
staging 环境模板 · 完整内容
{
"id": "c85d27e6-c7d3-40f4-b490-c6fb9a73fe18",
"name": "4Fang Public Merchant API - Staging",
"values": [
{
"key": "base_url",
"value": "https://staging-api.example.com",
"type": "default",
"enabled": true
},
{
"key": "request_host",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "api_key",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "api_secret",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "merchant_id",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "amount",
"value": "100.00",
"type": "default",
"enabled": true
},
{
"key": "currency",
"value": "MYR",
"type": "default",
"enabled": true
},
{
"key": "channel_code",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "customer_id",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "customer_name",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "customer_email",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "customer_phone",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "payer_bank_code",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "payer_bank_account_owner",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "payer_bank_account_number",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "payer_username",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "notify_url",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "return_url",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "bank_code",
"value": "MBB",
"type": "default",
"enabled": true
},
{
"key": "option_type",
"value": "payout_bank",
"type": "default",
"enabled": true
},
{
"key": "account_no",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "account_name",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "recipient_email",
"value": "",
"type": "secret",
"enabled": true
},
{
"key": "merchant_order_no",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "platform_order_no",
"value": "",
"type": "default",
"enabled": true
},
{
"key": "sync_provider",
"value": "false",
"type": "default",
"enabled": true
}
],
"_postman_variable_scope": "environment",
"_postman_exported_at": "2026-09-16T00:00:00.000Z",
"_postman_exported_using": "Codex"
}