本頁讓串接人員依方向找到認證、資料、成功結果與例外;不是新的產品 authority,也不是可聯調或部署證明。 僅使用合成資料與 placeholders。{{baseUrl}} 是經操作者確認的產品服務網址,不是本文件站;{{agentCallbackUrl}} 是 Agent 目前設定的 HTTPS 接收網址。本頁沒有 Try-it-out、產品 mutation、第三方送出功能或前端 credential 持久狀態。
固定核對來源:HEAD 258cdc395abf2e34ab7a0b8fedbaaab14f4094f2 的 native source;文件工作區含使用者核准保留的前端入口及 57-table 投影,不沿用舊驗收結論。SQL prerequisite:無,這次不改後端、API、policy、grants、readiness、SQL 或 activation。
串接方向 · 協定與credential · Deposit v1 · SPAY2 相容建單 · Deposit v2 · Withdrawal 目標 · LINE 通知 · Callback · 完整流程 · 缺口與實作方案 · 離線簽章範例 · 技術參考
串接方向
| 誰呼叫誰 | 要解決的問題 | 成功後發生甚麼 | 不負責甚麼 |
|---|---|---|---|
| OGP/外部系統 → Spay | 建立/查詢 Agent-origin Deposit 與 Withdrawal | 合法認證與 payload 才建立 formal order;查詢只看 own Agent | 不提交銀行 evidence,不由 caller 指定 Agent/Currency/餘額 |
| LINE Bank Notification Provider → Spay | 提交入款聲明:Agent credential → HOUSE、Supplier credential → Supply Channel | immutable evidence 先提交,再獨立 matching;ACK 不等於訂單已完成 | 不是 LINE Messaging Bot;不呼叫 LINE 官方 Messaging API、不建立 Agent order、不接收 order callback |
| Spay → OGP | 已提交的 terminal outcome 通知 | immutable event 的 at-least-once delivery;OGP 去重後回 exact ACK | 不等待 ACK 才提交金融結果,不讓 retry 重新結算 |
LINE target 只用於 Deposit 入款:Agent credential → HOUSE、Supplier credential → Supply Channel,同一路由依 credential 所屬分流(ADR-0445);下文 receiver exact-first、fuzzy flags 與 HOUSE matching 細節只適用 Agent credential。Withdrawal 只經 Payment Account/CH 聲明及 BO 最後確認,不把 Legacy LINE OUT/HOUSE 自動付款搬入 SPay4。
Exact route inventory
| 方向/協定 | Method | Exact path/目的地 | 完整 URL 範例 | 接線與啟用界線 |
|---|---|---|---|---|
| OGP → Spay,native v1 | POST | /v1/agentApi/depositOrder/assign | {{baseUrl}}/v1/agentApi/depositOrder/assign | source handler 存在;runtime/部署待核對 |
| OGP → Spay,native v1 | GET | /v1/agentApi/depositOrder/{agentOrderId} | {{baseUrl}}/v1/agentApi/depositOrder/OGP-D-001 | query 的目前狀態,不是首次 response |
| OGP → Spay,SPAY2 相容 | POST | /public/agentOrder | {{baseUrl}}/public/agentOrder | 建 AGENT_ACCOUNT 單(ADR-0485);Signature header 放 {{ogpApiSecret}} 原文,不是 HMAC;見 SPAY2 相容建單 |
| 外部系統 → Spay,v2 | POST | /v2/external/deposit-orders | {{baseUrl}}/v2/external/deposit-orders | 既有另一套 wire,不是 v1 alias;spay4.external-deposit.enabled 預設關閉、上線時 gateway 亦擋(#458) |
| 外部系統 → Spay,v2 | GET | /v2/external/deposit-orders/{clientOrderId} | {{baseUrl}}/v2/external/deposit-orders/EXT-D-001 | own Agent 的目前 projection;與 POST 同一開關,預設關閉 |
| OGP → Spay,Withdrawal native v1 | POST | /v1/agentApi/withdrawalOrder | {{baseUrl}}/v1/agentApi/withdrawalOrder | source handler 存在(Withdrawal 專用 HMAC filter);runtime/部署待核對;不得改打 Legacy 或 Deposit |
| OGP → Spay,Withdrawal native v1 | GET | /v1/agentApi/withdrawalOrder/{agentOrderId} | {{baseUrl}}/v1/agentApi/withdrawalOrder/OGP-W-001 | query 的目前狀態,不是首次 response |
| OGP → Spay,Withdrawal native v1 | GET | /v1/agentApi/withdrawalOrder/byIdentity/{encodedAgentOrderId} | {{baseUrl}}/v1/agentApi/withdrawalOrder/byIdentity/T0dQLVctMDAx | 原 identity 的 UTF-8 Base64url 無 padding(ADR-0407);同一本人 latest 投影,舊 GET 不 redirect/fallback |
| OGP → Spay,House Card 同步 v1 | PUT | /v1/agentApi/houseCard | {{baseUrl}}/v1/agentApi/houseCard | 以 body agentCardId 冪等新增或修改 OGP 管理的卡;不刪除、不帶 version(ADR-0429) |
| OGP → Spay,House Card 同步 v1 | GET | /v1/agentApi/houseCard | {{baseUrl}}/v1/agentApi/houseCard | 回 credential Agent 全部 OGP 管理的卡(含 INACTIVE),不分頁、不篩選 |
| LINE provider → Spay,source-bound | POST | /v2/external/transactions | {{baseUrl}}/v2/external/transactions | LINE source credential(Agent 或 Supplier+Currency,#511),不是 BO Bearer;不經 External v2 filter,舊 internal 路徑與 /v2/external/house-card-transactions/ 皆無 alias(#458、#506) |
| Spay → OGP,callback | POST | agent.callback_url | {{agentCallbackUrl}} | destination 無固定接收端 path;source 預設 callback trigger 開啟,部署環境是否開啟以環境 read-back 為準 |
來源:Deposit、Withdrawal、Native callback。本頁不新增 alias。
協定與credential
ADR-0387 → ADR-0395 只取代 target ciphertext 的持久化限制 → ADR-0396 只取代 BO/Supply principal 的 shared credential persistence。Agent OGP/LINE 的 current integration boundary 保留:metadata 在 credential_reference,唯一 current secret 在 credential_secret;不 import/read/fallback/dual-store Legacy material。
OGP request 與 callback 共用每 Agent DEFAULT scope 的 current apiKey/apiSecret,一起原子輪替、無 retiring slot/overlap;LINE 則綁定該 Agent 與 provider source 的穩定 scope。BO password、TOTP、JWT 不能代替任一 integration credential。不得將 secrets/signatures/raw payload 放入 log、Audit、CSV、URL、seed、文件或前端 persistent state。範例的 {{ogpApiSecret}}/{{lineApiSecret}} 只在呼叫者受控服務端使用。
| 協定 | Headers/codec | 時間與nonce | 簽章資料與path | query/body 邊界 |
|---|---|---|---|---|
| SPAY-HMAC-V1,native Deposit/House Card | X-Api-Key: {{ogpApiKey}}、X-Timestamp、X-Nonce、X-Signature: {{v1SignatureHex}};SHA256 hex,source 接受大小寫 hex,建議 lowercase | epoch seconds,1..10 位 ASCII digits,inclusive ±300 秒;lowercase UUID v4,每 request 新值 | METHOD\nRAW_PATH\nTIMESTAMP\nNONCE\nRAW_BODY;不含 SPAY-HMAC-V1 字面 prefix;不 decode/normalize raw path | 所有 query(含空 query)拒絕;GET body 完全空;POST/PUT JSON/UTF-8或未指定charset;1 MiB、strict UTF-8 |
| External Deposit v2 | 同名四 headers,但 X-Signature: {{v2SignatureBase64}} 是 Base64,不是 hex | epoch seconds、±300 秒、lowercase UUID v4 | 相同五段 raw bytes framing;不加 v2 prefix;不 normalize path | POST 有 query 拒絕;source GET filter 未拒絕 query/body(不表示有query功能),串接固定送空 query/body;不把 v1 Content-Type/UTF-8 filter gate 套入 v2,建議 JSON/UTF-8;body 驗 1 MiB |
| HOUSE ingress,source-bound | 同名四 headers;X-Api-Key: {{lineApiKey}}、X-Signature: {{lineSignatureHex}};SHA256 hex | epoch seconds、±300 秒、lowercase UUID v4 | 固定 POST+exact ingress path;五段 framing 不加協定prefix;raw body bytes 不 decode 後重編碼驗簽 | query 一律拒絕;filter 不額外檢查 Content-Type,但核定 adapter 要合法 UTF-8/JSON/1 MiB;建議 application/json |
| SPAY-CALLBACK-V1 | 完整 X-Spay-* 見 Callback;SHA256 lowercase hex | epoch seconds、nonce UUID v4;event UUID v7、callbackId UUID v4 | SPAY-CALLBACK-V1\nPOST\nNORMALIZED_RAW_PATH\nTIMESTAMP\nNONCE\nEVENT_ID\nRAW_BODY | destination 不允許 query;URL normalize 後實際 HTTP encoded path,空 path /;raw persisted bytes,不能重新 serialize |
前三類驗簽成功後才以 (credentialReferenceId, nonce) 於 native DB 的獨立短交易 claim;300 秒 replay window 不是可以重用 nonce 的許可。產品提交失敗也可能已消耗 nonce;每 transport retry 換 timestamp/nonce/signature,保留業務 identity 與相同 canonical payload。這不是 Legacy Redis replay/rate-limit contract;本頁不自行制定 ingress rate limit、client timeout 或重試次數。
Callback receiver 必須先驗 raw bytes HMAC/header event identity,再以 immutable eventId 去重。receiver 的 timestamp skew、nonce retention 及 key 配置 rollout 尚無本 native contract 明示數值,需兩端確認,不擅自套 inbound ±300 秒。輪替影響下一 attempt 的 current key,不改 immutable event,也不保證在途舊簽章被接受。
來源:上述協定由固定 source filters/authentication 與 callback contract 核對。四協定的 vectors 只驗合成 bytes,不表示 DB nonce/provider runtime 通過。
Deposit v1
Request 與欄位
POST 無 path parameters/query;GET 只有 exact agentOrderId path、無 query/body。GET path segment 以 UTF-8 percent-encode(簽實際 encoded path),identity 不 trim/case-fold/NFC。所有 calls 都帶 v1 四 headers;POST 另帶 Content-Type: application/json。
POST {{baseUrl}}/v1/agentApi/depositOrder/assign
Content-Type: application/json
X-Api-Key: {{ogpApiKey}}
X-Timestamp: {{epochSeconds}}
X-Nonce: {{newUuidV4}}
X-Signature: {{v1SignatureHex}}
{
"agentOrderId": "OGP-D-001",
"amount": "100.00",
"payerBankCode": "KBANK",
"payerAccount": "0012345678",
"payerName": "合成付款人",
"idempotencyKey": "OGP-D-001-create"
}
| 欄位 | 型別/必填/限制 | 拒絕與處理 |
|---|---|---|
| agentOrderId | string,required,≤100 Unicode code points;共用 service 另驗≤100 UTF-16 units | exact identity,不 trim;拒 control、非法 UTF-8、edge whitespace、/、backslash、?、#;建議 ASCII |
| idempotencyKey | string,required,≤160 Unicode code points | exact、不 trim/case-fold/NFC;同樣拒 path/control/edge whitespace |
| amount | JSON number 或 string(ADR-0489),required,正數 plain decimal,0..10 小數位,input precision≤30,且 lossless DECIMAL(30,10)/≤20 整數位 | 不接受 exponent、sign、前置零、逗號、前後空白、rounding、clamping;"100.00"、100.00、100 皆合法 |
| payerBankCode | string,required,≤50 code points,service 另驗≤50 UTF-16 units | 只去 Unicode edge whitespace;必須為 ACTIVE/Agent mapping/同 Currency Bank,不以 name-only fallback |
| payerAccount | string,required,≤100 code points/service≤100 UTF-16 units | 只去 Unicode edge whitespace,內部空白保留;missing/null/blank/control 拒絕,不填假值 |
| payerName | string,required,≤255 code points/service≤255 UTF-16 units | 同上;保留大小寫/Unicode,不從 credential 補 payer |
| preferredPaymentChannelCode | optional string/null;核定串接省略或 null | Native 不使用 channel;non-empty 拒絕。source parser 的空字串會通過但不保存,不能把它當 selectable channel |
| agentCardId | optional string/null,[A-Za-z0-9_-]{1,64},case-sensitive(ADR-0456) | 只在 credential Agent 的 OGP 同步 HOUSE 卡內解析並直接指派;省略/null 走 CH+Supply Channel 派單池(不含 HOUSE)。不存在(含他 Agent、BO 建立的卡)400/40005,不可承接 409/40054,皆不建單、不 fallback;有值時納入 idempotency fingerprint |
strict object-only、unknown/duplicate keys/wrong-type/trailing JSON 都拒絕;request 不接受 Agent、Currency、owner、callback URL、quota、client verified/balance。Order payer 三項必填,不受 LINE nullable evidence 例外影響。
成功、首次 replay 與 latest query
HTTP 200,ResponseVo 包裝如下。未指派也可能成功建立 formal PENDING_REVIEW;不能套 Legacy 417 failed-request-log-only 的 assignment failure。POST 建立的新單 orderNo 為 server 32-hex,不是 Legacy DEP 序號;GET 查到從 Legacy 匯入的單時回傳原號(DEP 加 15 位數字,可帶 S2 前綴,#972)。
{
"code": 2000,
"message": "",
"data": {
"orderNo": "00000000000000000000000000000001",
"agentOrderId": "OGP-D-001",
"orderStatus": "ASSIGNED",
"amount": "100",
"actualAmount": null,
"currencyCode": "THB",
"expireTime": "2026-10-07T10:45:00Z",
"requestedPaymentChannelCode": null,
"assignedPaymentChannelCode": null,
"paymentChannel": null,
"paymentAccount": {
"bankCode": "KBANK",
"bankName": "合成銀行",
"accountNumber": "0099001122",
"accountName": "合成收款戶",
"ownership": "HOUSE"
},
"failureCategory": null,
"failureCode": null,
"failureReason": null
}
}
| Response 欄位 | 型別與意思 |
|---|---|
| orderNo/agentOrderId | string;server opaque identity/caller exact identity |
| orderStatus | string;native SETTLED→COMPLETED;ASSIGNED/PENDING_REVIEW/EXPIRED/REJECTED 等以 target lifecycle 為準 |
| amount/actualAmount | canonical decimal string/nullable decimal string;去尾零,沒有確認實付時 actualAmount=null |
| currencyCode | 建單時 Agent Currency code snapshot string |
| expireTime | UTC offset timestamp/null;目前 attempt 的 immutable deadline,未指派 null |
| requestedPaymentChannelCode/assignedPaymentChannelCode/paymentChannel | Native 全部固定 null,不填 Legacy channel |
| paymentAccount | object/null;目前 attempt 的不可變收款指示;bankCode/bankName/accountNumber/accountName strings,ownership=HOUSE 或 CARDHOLDER |
| failureCategory/failureCode/failureReason | nullable strings;不根據內部 remark 猜 failure。source failureCode 投影 reviewReasonCode,其他未有公開 metadata 時 null |
首次 create-response replay:claim、formal order、assignment/reserve/Audit 與 encrypted 首次 snapshot 同交易提交;先重新驗 current Agent authority 才 replay。相同 Agent/DEPOSIT 的 exact order identity、key 與 canonical payload 不重派,不再 reserve,回第一次安全 POST 結果,即使目前已重派/完成。query 的目前狀態:GET 不讀 create snapshot,回現在 order/current attempt/actual;不可用重送 POST 當 polling。
GET {{baseUrl}}/v1/agentApi/depositOrder/OGP-D-001
X-Api-Key: {{ogpApiKey}}
X-Timestamp: {{epochSeconds}}
X-Nonce: {{newUuidV4}}
X-Signature: {{v1QuerySignatureHex}}
GET 成功仍為同一 envelope/上述全部欄位;無 current attempt 時 account/deadline=null。身份 scope 為 server-derived Agent/Currency;不同 Agent 同字串不能讀他人單,查不到回404。v1 與 v2 claim 不可交叉重用;同 key 異 payload/異 order 或同 order 換 key 衝突,不以換 identity 掩蓋未知結果。輸入金額的尾零經 canonical policy 正規化,不保證字面 JSON 完全相同才 replay;呼叫端最安全做法是保存首次 raw body 原樣重送,再重新簽章。
來源:Deposit contract 與技術參考的 v1 parser/service/VO。只核對 source,沒有產品 HTTP runtime 驗證。
SPAY2 相容建單
POST /public/agentOrder 沿用 SPAY2 的路徑與欄位,建立不經卡片、由 Agent 自有帳戶收款的 AGENT_ACCOUNT 入款單(ADR-0485、Deposit 契約 §3.3)。與 /v1/agentApi/** 共用同一組 EXTERNAL_ORDER_API 憑證與同 Agent 的單號空間。
POST {{baseUrl}}/public/agentOrder
Content-Type: application/json;charset=UTF-8
Signature: {{ogpApiSecret}}
{
"recordId": "OGP-D-002",
"type": "DEPOSIT",
"fromBankCode": "KBANK",
"fromAccount": "0012345678",
"fromAccountName": "合成付款人",
"amount": 1000
}
- 處理順序:
spay.order.cutover.enabled為 true 時一律 HTTP 410、code40037(不驗證、不建單)→Signature缺漏、查無、不符或憑證/Agent 非 ACTIVE 回 HTTP 417、code40002 → body 欄位。 - 欄位:
type只收DEPOSIT;recordId(≤100)、fromAccount(≤100)、fromAccountName(≤255)、amount必填;amount收 JSON number 或純數字字串,須為正數,number 不接受科學記號(例1e5);fromBankCode(≤50)與toBankCode/toAccount/toAccountName可省略,to*不使用、不儲存;未知欄位忽略。不合法回 HTTP 400、code40005。 - 銀行:
fromBankCode找得到 ACTIVE 銀行時存代碼與名稱、幣別取該銀行幣別;找不到照建單,只存原值、銀行名稱為 null、幣別用 Agent 預設幣別。 - 冪等:同 Agent 同
recordId且金額數值、fromBankCode、fromAccount、fromAccountName相同回成功、不再建單;內容不同或單號已被 v1 接口使用回 HTTP 409、code40046。 - 成功回
{"code":2000,"message":"","data":{}};錯誤同為{code,message,data}。建單後 v1 查詢回同一單,paymentAccount為 null。 - 期限:
spay.deposit.agent-account.deadline.seconds(缺值 1800 秒);到期訂單轉PENDING_REVIEW、不發 callback。 - 風險:沒有 timestamp/nonce,截獲的請求可被重送,只靠
recordId冪等擋重複建單;Signature外洩即須整組輪替(ADR-0485 已接受)。
Deposit v2
此入口已存在,與 v1 分開:Base64 signature、JSON numeric amount、clientOrderId、raw success object,不新增 alias。POST body 無 query/path parameters;GET 只有 path identity。headers 同名但務必使用 v2 Base64,建議 JSON/UTF-8。
POST {{baseUrl}}/v2/external/deposit-orders
Content-Type: application/json
X-Api-Key: {{ogpApiKey}}
X-Timestamp: {{epochSeconds}}
X-Nonce: {{newUuidV4}}
X-Signature: {{v2SignatureBase64}}
{
"clientOrderId": "EXT-D-001",
"amount": 100.00,
"payerBankCode": "KBANK",
"payerAccount": "0012345678",
"payerName": "合成付款人"
}
| 欄位 | 型別/限制 |
|---|---|
| clientOrderId | required exact string,非 blank、無 ISO control、≤100 UTF-16 units;不 trim |
| amount | required JSON number 或 string(ADR-0489),plain decimal(0 或不以 0 開頭的整數,可帶小數);正數、lossless DECIMAL(30,10),≤20 整數位/10 有效小數位;不接受 exponent、sign、逗號、前後空白、rounding |
| payerBankCode | nullable string,trim 後≤50 UTF-16 units;與 name 至少一項非空;提供 code 就必須合法 ACTIVE/同 Currency/Agent Bank,不因 code 錯誤退 name |
| payerBankName | nullable string,trim 後≤255 UTF-16 units;可 name-only;不可把這個較舊 v2 規則套到 v1 |
| payerAccount | required string;service 移除所有 Unicode whitespace,結果非空且≤100 UTF-16 units |
| payerName | required string,舊 String.trim 後非空且≤255 UTF-16 units,不等於 v1 Unicode edge policy |
strict object-only、unknown/duplicate/trailing/wrong-type 拒絕。無獨立 idempotencyKey;identity 是 Agent/DEPOSIT/exact clientOrderId,fingerprint 綁 canonical amount、bank code/name、payer account/name。同值重送不重建,但 v2 POST 回目前 projection,沒有 v1 encrypted 首次 response replay 保證。
HTTP200 raw response(無 code/message/data 包裝):
{
"clientOrderId": "EXT-D-001",
"status": "ASSIGNED",
"amount": 100,
"currencyId": 1,
"receivingAccount": "0099001122",
"receivingAccountName": "合成收款戶",
"receivingBankName": "合成銀行",
"deadline": "2026-10-07T10:45:00Z"
}
八欄固定:clientOrderId/status strings,amount JSON number(不要轉 binary floating-point 金融值),currencyId server-derived numeric identity;後四欄 string,可 null;deadline 為 ISO-8601 UTC 帶 Z(ADR-0409)。只有 ASSIGNED 才回收款資訊/deadline;其他狀態均 null,不提供 v1 actualAmount。小數秒依 ISO_INSTANT 以 3/6/9 位分組,0 秒時省略;例為秒整點。
GET {{baseUrl}}/v2/external/deposit-orders/EXT-D-001
X-Api-Key: {{ogpApiKey}}
X-Timestamp: {{epochSeconds}}
X-Nonce: {{newUuidV4}}
X-Signature: {{v2QuerySignatureBase64}}
GET 與 POST 的同一 raw projection;沒有可用 query 功能,送空 body/query。遇 timeout 保留 clientOrderId/payload,先同 Agent GET 補償。來源:技術參考的 v2 controller/parser/service/VO;未核對 deployment,不沿用 Legacy OGP response。
Withdrawal 目標
Native v1 ingress 已有 source(#213 實作、#214 整合驗收): AgentWithdrawalV1Controller 三條 route 由專用 WithdrawalV1HmacFilter 驗 raw bytes HMAC,與 Deposit 的 v1 filter 分開,不能互換 credential 流程。Source presence 只證明 handler/guard 存在,不證明目前部署已啟用;舊 worktree/接受報告不背書目前部署。
POST {{baseUrl}}/v1/agentApi/withdrawalOrder;GET {{baseUrl}}/v1/agentApi/withdrawalOrder/OGP-W-001 或 {{baseUrl}}/v1/agentApi/withdrawalOrder/byIdentity/{Base64url(agentOrderId)}。使用 v1 四 headers(hex/epoch seconds/new UUID v4),POST JSON、GET 無 body、三者皆無 query;query/body 不合法先回 400/40005,再判 token/認證 401/40000,不存在或跨 Agent 404/40029(Withdrawal contract)。
{
"agentOrderId": "OGP-W-001",
"amount": "1000.00",
"receiverBankCode": "SCB",
"receiverAccount": "0055566677",
"receiverName": "合成收款人",
"preferredPaymentChannelCode": null,
"idempotencyKey": "OGP-W-001-create"
}
| 欄位 | 核定目標型別/限制 |
|---|---|
| agentOrderId/idempotencyKey | required case-sensitive exact string,≤100 Unicode code points,不 trim/control;不是 Deposit 160 key 上限;strict unknown/duplicate/wrong-type 拒絕 |
| amount | required v1 positive decimal,JSON number 或 string 皆可(ADR-0489),0..10小數位、precision≤30、lossless DECIMAL(30,10);不接受 exponent/sign/前置零/逗號/前後空白/rounding;錯誤回 422 |
| receiverBankCode | required exact string≤50 code points;由 credential Agent/Currency/ACTIVE Bank scope 解析名稱,client 不帶 receiverBankName |
| receiverAccount | required string;Unicode edge trim 後 ASCII alphanumeric≤100 code points |
| receiverName | required string;Unicode edge trim 後非空≤255 code points |
| preferredPaymentChannelCode | omitted/null=完整合格池;非空須 active allocated/同 Currency 內唯一 native Gateway code;不是 Legacy Payment Channel priority。預設 Gateway 的 code 是 Supplier loginId,不是字面 DEFAULT;帶 DEFAULT 回 HTTP 422、code 40024 |
目標首次 POST 保存 encrypted immutable response,GET 回最新 projection;相同 Agent/order type/identity/payload 去重、異 payload 409,先 fresh authority 再 replay;exact errors/preferred code 拒絕 mapping 必須在 #213 golden/HTTP 驗證閉合,未有 native 實作的欄位與 code 不偽造實際結果。
HTTP200 envelope code=2000,message="",data={...};data 為 AgentWithdrawalV1Response 13 欄:orderNo、agentOrderId、orderStatus、amount、actualAmount、currencyCode、receiverBankCode、receiverBankName、遮罩 receiverAccount/receiverName、failureCategory/failureCode/failureReason。server orderNo 是32-hex(GET 查到從 Legacy 匯入的單時為原號 (S2)?WDR 加 15 位數字,#972);actualAmount nullable canonical decimal string;不暴露 payout account 或 DB ID。以下是合成 response 範例(欄位依 source VO,未對部署環境實測):
{
"code": 2000,
"message": "",
"data": {
"orderNo": "00000000000000000000000000000002",
"agentOrderId": "OGP-W-001",
"orderStatus": "ASSIGNED",
"amount": "1000",
"actualAmount": null,
"currencyCode": "THB",
"receiverBankCode": "SCB",
"receiverBankName": "合成銀行",
"receiverAccount": "****6677",
"receiverName": "合***",
"failureCategory": null,
"failureCode": null,
"failureReason": null
}
}
無 pool 預期 formal PENDING_REVIEW,不走 Deposit Legacy 417。CH 單次 committed proof/actual 只是付款聲明;BO 才是唯一成功 authority。SETTLED→COMPLETED、ROUTING_FAILED→PENDING_REVIEW、REJECTED_NO_TRANSFER→REJECTED;ACCEPTED→PROCESSING、PROOF_SUBMITTED→PENDING_VERIFICATION 的 ingress mapping 仍須目標 golden核對。不要搬入 Legacy UNASSIGNED auto release 或 HOUSE OUT。
BO target settle 可缺省 actual 沿用選定已存申報,或提供正數 final actual;requested 1000/declared900/final1100,雙比較不同必填 reason,原 EVIDENCE 不覆寫,沒有獨立改額 API。source 的 settle 已允許省略 actual(explicit null 拒絕),equality guard 已移除,差額改為必填 reason;部署環境的實際行為以環境 read-back 為準。詳見 Withdrawal contract 及 缺口方案。
OGP與外部系統錯誤矩陣
本表「實際」以 native Deposit 為主;Withdrawal v1 另列專屬情境,其餘 code 以 Withdrawal contract 為準。Legacy OGP 的422/417/Redis503/429不自動適用 native。
| 情境 | 實際回應/結果 | 是否可重試 | identity/簽章如何處理 | 如何查詢補償 | 何時需人工 | 禁止動作 |
|---|---|---|---|---|---|---|
| missing/wrong key/signature/codec、過期 timestamp、nonce replay、transport gate 拒絕 | native filter 401,{"code":40000,"message":"no authentication"};無 data 欄位 | 修認證後可,次數未核定 | 新 timestamp/nonce/signature;業務 identity 不變 | 認證恢復後 own-Agent GET | current key/Agent設定無法確認 | 用 Bearer/LINE key;重用 nonce;hex當Base64 |
| service 期間 Agent inactive/Currency binding失效 | 401/40001 NO_PERMISSION | 修 owner 後才可 | current OGP pair,保留 identity | own-Agent query | owner/credential race 持續 | client 指定 Agent/Currency |
| unknown/duplicate/wrong type、missing payer、非法金額 | 400/40005;MVC malformed 同安全 envelope,非回顯 raw | 修正後才可;若已 claim 不可更改 canonical payload | nonce 已可能消耗;先釐清業務提交 | 同 identity GET,查無才核對修正 | 結果不明或已提交 | rounding、補假 payer、以 message 分支 |
| exact create 重送 | v1 200/2000 首次 snapshot;v2 200 raw 目前 projection;無第二份effects | 可安全重送同 canonical identity/payload | 業務 identity 不變,每次重新簽 | GET最新狀態 | snapshot缺失/tamper需查核 | POST polling、以首次 ASSIGNED 判目前仍可付款 |
| same v1 key跨 order、同 order換 key/v1↔v2 claim | 409/40045 IDEMPOTENCY_KEY_CONFLICT 或409/40046 AGENT_ORDER_CONFLICT;按實際 identity guard | 不盲重送 | 修 caller identity 管理,不更換單號掩蓋 | own GET 核對原單 | caller mapping錯誤 | 製造第二筆經濟交易 |
| v2同 clientOrderId異payload | 409/40003 DATA_ALREADY_EXISTS,安全訊息 EXTERNAL_ORDER_REQUEST_CONFLICT | 不可同 identity改payload | 保留原請求核對 | GET | canonical payload不一致 | overwrite claim |
| unknown order/跨 Agent query | 404/40002 DATA_NOT_EXISTS;不洩漏別人資料 | 先核對 identity/Agent | 用正確 own key,不借他人 key | 同 scope GET | 身份關聯無法釐清 | 404推定其他Agent沒有該單 |
| 無可用assignment | native建 formal PENDING_REVIEW,v1 account/deadline=null,v2收款四欄null;無 reserve/terminal callback | 不重建以求再派 | 原 identity retained | GET+Admin never-assigned處理 | allocation/Bank/Gateway/session/資金/HOUSE quota 無候選 | 套Legacy417、新單洗assignment、expiry自動release |
| 連線逾時/回應遺失/結果不明/500 | 可能已提交;500/5000安全error,不回 infrastructure detail | 先GET,再同identity/payload;caller timeout/backoff未核定 | 保存原raw bytes,新nonce/signature | GET成功表示formal order存在;404不是可立即換identity的充分證據 | 持續未知、DB/crypto不可用或snapshot缺失 | timeout視為未提交、無限重試、換單號重複入款 |
| unique/optimistic persistence競爭 | generic409/40007或40051;僅按實際response處理 | 先query,不猜runtime policy | same identity,新nonce | GET | race/invariant未收斂 | 把技術failure當無候選成功 |
| nonce DB/crypto依賴不可用 | 未捕捉 infrastructure故障可能安全500;沒有已核定Redis503重試教學 | 配置恢復後再query/重試 | 不略過nonce/驗簽 | own query | operator診斷 | fail-open、unsigned、Legacy fallback |
| Withdrawal v1 帶 query/GET 帶 body、byIdentity token 畸形 | Withdrawal filter 先回 400/40005,token/認證失敗 401/40000;不存在/跨 Agent 404/40029 | 修正 request 後可 | 業務 identity 不變,新 nonce/signature;byIdentity 只用 canonical Base64url 無 padding | 同 identity 以 GET 或 byIdentity 查本人 latest | 編碼後仍查無或結果不明 | 改打 Legacy/Deposit route、percent-decode 或 normalize identity |
重要 service error 範例(message 僅診斷,data 可能[]或欄位資訊,不以它判結果):
{"code":40045,"message":"idempotency key conflict","data":[]}
來源:native web.ErrorResponseWriter(HMAC 變體)、ApiExceptionHandler、ExternalDepositOrderServiceImpl;HTTP400/409與 target contract口徑有 wire 差異時,這裡標 固定source,不改 authority 或宣稱已接受新的產品政策。
LINE 通知
Target wire與認證
只有核定 LINE_WEBHOOK / LINE_VENDOR / LINE_VENDOR source type/vendor/profile。Active credential 綁唯一 Agent/Currency/source;writer提交前重讀binding。
Supplier credential 也使用此路由(#511):同一 POST /v2/external/transactions、同一 headers 與簽章 framing。API key 在 Agent(credential_secret)與 Supplier(supplier_credential_secret)兩表各查一次,依所屬分流:Agent 走下述 HOUSE 流程;Supplier 寫入 supply_channel_transaction,在 Supplier+Currency+receiver Bank 範圍先以完整帳號精確比對、再依 Global 收款帳號模糊規則解析 supply_channel_id(不讀 Agent override;不存在或命中兩張以上為 null 並保留證據)。證據 commit 後另開交易自動匹配(#512):唯一匹配 current Supply Channel attempt(同 Channel、requested 等於入款金額、付款帳號比對規則與自動配對時間窗讀候選 Order 所屬 Agent 的設定)即自動結算並消耗該卡 counter 實際金額;無候選依 1/3/5 分鐘重試,用完仍未匹配寫 SUPERADMIN bo_alert;歧義或遲到入款(Order 已 EXPIRED)只留證據進 review,不改 Order;同一 provider transaction 重送回原 transactionNo,內容不同 409。兩表皆命中同一 key 回 401(log authFailure=CREDENTIAL_AMBIGUOUS credentialScope=AGENT,SUPPLIER,不含 key);nonce 以 credential_scope(AGENT/SUPPLIER)區分,兩表同 reference id 的同一 nonce 各自可用一次。Supplier 時間以 Supplier business offset 解析;receiver Bank 在 credential Currency 內以 exact provider code 判唯一(無 Agent Bank mapping),零/多筆 400。信任等級比照 HOUSE LINE_VENDOR(ADR-0415)。未知 adapter 或多adapter 503 fail closed,不使用 LINE_VENDOR_A/B、test profiles、Legacy device credential作production alias。HMAC 證明 sender,不宣稱銀行獨立驗真;本票信任已認證上游,保留上游遭入侵可偽造通知的風險。
POST {{baseUrl}}/v2/external/transactions
Content-Type: application/json
X-Api-Key: {{lineApiKey}}
X-Timestamp: {{epochSeconds}}
X-Nonce: {{newUuidV4}}
X-Signature: {{lineSignatureHex}}
下列 synthetic payload 的 msg_content 必須為 JSON 字串,不是 nested object;送出時使用此 outer body 的實際 bytes簽章,不簽inner object:
{
"app_type": "LINE",
"account_id": "synthetic-provider-account",
"message_id": "LINE-D-001",
"timestamp": "2026-10-07T10:30:00Z",
"msg_content": "{\"bank\":\"KBANK\",\"type\":\"IN\",\"transferInAccount\":\"0099001122\",\"transferOutAccount\":\"0012345678\",\"transferInAmount\":\"100.00\",\"transferInDate\":\"2026-10-07T10:30:00Z\"}"
}
| 欄位/層級 | 型別、限制、authority |
|---|---|
| msg_content/outer | required JSON string;duplicate/trailing/malformed/known field wrong type拒絕,outer/inner unknown metadata沿parser忽略,不把Deposit strict unknown教學套入 |
| message_id/outer | required string,trim-to-nonempty後exact providerTransactionId,≤160 code points,無control;不case-fold/NFC |
| app_type/account_id/timestamp/outer | optional strings,只作metadata,不提供Agent/source/交易時間authority;optional id為integral number,不代替message_id |
| bank/inner | required provider銀行識別string;沿trim-to-nonempty;映射native provider_bank_code+principal Agent mapping+Currency,完整分頁判唯一;不display/native-code fallback |
| type/inner | required string,trim/ignore-case後只能IN;OUT拒絕,不寫Deposit |
| transferInAccount/inner | required receiver string,trim後≤100 raw code points;masked保留原文。只有核定full syntax容許內部tab formatting,其餘control拒絕 |
| transferOutAccount/inner | nullable string,trim後null可保存;非null≤100 code points、無control;不是Order payer optional |
| transferInAmount/inner | required string,移除逗號後BigDecimal正數、lossless DECIMAL(30,10),≤20整數位/10有效小數位;不round/clamp,不採fee或balance-after |
| transferInDate/inner | required交易時間string,解析後UTC、不得future、最多微秒;outer timestamp不能代替 |
| availableBalance及其他metadata/inner | optional string;availableBalance非空會驗數字,但不參與金融authority;remark/sender等不進一般response/log/Audit/CSV |
時間fallback依序:短年 Buddhist d/M/yy H:mm → Gregorian d/M/uuuu H:mm/@H:mm → Thai Buddhist d MMM. yyyy H:mm(可帶 น.)→ ISO zoned → yyyy-MM-dd HH:mm:ss。local分支只用native Agent immutable business UTC offset,missing/invalid fail closed;GSB provider local當地23:00起減一天,ISO zoned early return不減日。短年Buddhist秒歸零、extra tokens忽略行為承續,不宣稱全部strict秒精度。
接收、matching與回應
- raw bytes驗簽/timestamp/nonce → 精确adapter解析/Bank mapping;不信任client verified旗標。
- evidence writer先獨立commit:namespace
(Agent, sourceId, providerTransactionId)、canonical hash、首次encrypted raw immutable、opaque transactionNo。同canonical replay不追加/更新raw;異receiver/payer/amount/time/profile等409 conflict;null→payer也不得覆寫。 - receiver exact-first:full account移除ASCII space/tab/hyphen/underscore、Locale.ROOT uppercase、保留leading zero與X,
[A-Z0-9]{1,100}。exact唯一先選,多exact即歧義且不fuzzy,零exact才唯一 fuzzy;完整 own-Agent/Currency/Bank/HOUSE遍歷,不first-match/300 cap、不以live order遮蔽歷史generation歧義。 - fuzzy flags每次讀ACTIVE Agent override(存在null也disabled,不fallback)→無ACTIVE Agent才ACTIVE Global;只有完整小寫true啟用。
match.rule.aftersuffix、match.rule.before.after前尾數字段、match.rule.long最長連續數字段contains,以OR比對,不加score/priority/最短長度。payer與receiver共用同組predicates。 - 非空payer+amount/scope/assignment/live/history候選必須唯一。最後root locks後重驗Config、receiver/payer、state/version/deadline及金融invariants;deadline
[assignedTime,deadlineTime),鎖等待跨deadline也不成功。可能已有歷史入款時不能只看新live候選。 - 成功HOUSE match同交易更新reservation/counter/Order/attempt/operation/Audit/唯一terminal intent,不寫Payment Account ledger;zero/ambiguity/null payer保存evidence,不猜卡不amount-only自動結算。已commit evidence不因matching exception/金融rollback丟失。
HTTP200只表示service返回的安全ACK,沒有matched/orderStatus欄位;matcher可能成功或留下未配對、歧義、review。匹配出錯時HTTP可能500,但evidence已提交,不能以500推定未收通知。
{"code":2000,"message":"","data":{"transactionNo":"HC-00000000-0000-4000-8000-000000000001"}}
transactionNo opaque string,不含DB ID或raw帳號。新資料帶來源前綴:Agent credential(HOUSE)為 HC-<uuid>、Supplier credential(Supply Channel)為 SC-<uuid>(#513);前綴只供 BO 區分來源,廠商仍須視整串為 opaque string、原樣保存與比對,不得解析或自行組合。#513 前已發出的舊值不回填前綴,重送同 message_id/hash 仍取得原值。provider重送同message_id/hash可取得同tracking identity;每request新nonce/signature。zero-candidate 僅在 committed attempt 後1/3/5分鐘recovery;不是所有失敗通用retry。nullable payer不進auto recovery batch,避免飢餓;人工處理與狀態詳見BO工作台。
LINE錯誤矩陣
| 情境 | 實際回應/結果 | 是否可重試 | identity/簽章如何處理 | 如何查詢補償 | 何時需人工 | 禁止動作 |
|---|---|---|---|---|---|---|
| 認證失敗/過期timestamp/nonce replay/錯key scope | filter401/40000,無data;無evidence | 修認證後可,次數未核定 | samemessage_id/body,新LINE nonce/timestamp/hex | provider保留送出記錄,BO核對tracking | binding/currentpair不明 | OGP key/Bearer/Legacydevice替代 |
| writer前source失效/owner不符 | 401/40000或403/40001;不授新admission | 修owner/source才可 | 原message identity不更改 | BO scoped HOUSE transaction核對 | credential/source lifecycle | client account_id改Agent |
| 未知/多adapter | 503/40044 DEPENDENCY_UNAVAILABLE,未保存新fact | 正確adapter可用後 | 不改vendor/profile試繞過;新nonce | BO查是否既存duplicate | adapter owner | fall open/套LINE_VENDOR_A/B |
| outer/inner malformed/duplicate/wrong type/OUT/Bank零或多映射/時間解析失敗/金額無法解析或超出整數20位、小數10位(parser統一轉換) | 400/40017 MSG_PARSE_ERROR | 修資料前先釐清是否已有identity | canonical變更若已保存則不可覆寫 | 原message_id/BOtracking核對 | provider parser/mapping/time | 回顯raw/native-code或name fallback |
| 長度/UTF8/control/future/秒以下精度非法 | 400/40005;無合法新evidence | 合法修正需先確認是否commit | 保留sourceidentity,新簽章 | BO安全projection | provider修正、不可改舊fact | rounding、amount-only、換id洗重複 |
| samecanonical duplicate | 同transactionNo,raw/hash不變,matching仍獨立guard | 可同identity安全重送 | 新nonce;不得新增message_id | BO核對immutablefact與Order;Order由OGPquery | 長期未配對 | 更新首次raw、重新credit/callback |
| sameidentity異canonical/null→payer | 409/40049 TRANSACTION_MATCH_CONFLICT,原fact保留 | 不可overwrite | 原id不可改payload補全 | BO比對安全hash/tracking | provider修正流程另核定 | 改message_id躲conflict、覆寫payer |
| receiver零/多exact/多fuzzy、payer歧義/nullable payer | 合法evidence保存;可能200但不結算、留未配對/review | 重送不會使猜測合法;effectiveconfig改變仍重驗 | immutablefacts不改 | BO page/detail、OGP orderquery | 歧義或unknownpayer需manual | first-match、300cap、masked改完整帳號 |
| matching exception/金融依賴不可用/timeout結果不明 | evidence可能已commit;500或連線中斷不是未接收證明 | sameidentity/hash重送+查核 | 新nonce/signature,不重建economicidentity | BO查transactionNo/safeprojection、OGPquery | 持續錯誤、counter/reservation invariant | 刪evidence、partialcredit、略過Audit |
| late/HOUSE EXPIRED/terminal | 去重evidence保留,不reopen/不重結算;HOUSE到期與EXPIRED同交易釋放原quota(ADR-0405) | 只查核,不重試金融成功 | evidenceidentity不變 | BO 人工異常處理 | late/雙入款/terminal後入款 | CH expiry 自動 release、退款 writer、terminal 改寫 |
人工入口只使用來源證實的 /bo/v2/houseCardTransactions scoped reads/manual match。Admin/Prefix own-AgentHOUSE;需要相應VIEW/UPDATE、target binding、current guards及reason,不以HTTP接收ACK授權人工結算。manual可處理原contract允許的payer/amount mismatch,但不是解除deadline/terminal/scope規則。沒有對外source query/改fact API,本頁不虛構。
來源:Deposit LINE scoped contract、ADR-0415 HOUSE、技術參考的parser/writer。HMAC可信上游與銀行獨立provenance分開,provider/release證據未取得。
Callback
Destination、headers與payload
Spay呼叫 POST {{agentCallbackUrl}},唯一current destination是agent.callback_url;不是預設 /ogp/callback,不從request/credential/lease snapshot/LegacypendingURL取目的地。每attempt讀ACTIVE Agent currentURL/currentkey一致projection。
目的地須public HTTPS,可合法custom port;拒絕userinfo、fragment、query、nonpublicIPv4/IPv6。DNS A/AAAA任一非public即UNSAFE_TARGET;每次重新lookup與pinning、不redirect/proxy/automaticnetworkretry,TLS certificate/hostname/SNI保留。這些是transport guards,不是endpoint allowlist。
POST {{agentCallbackUrl}}
Content-Type: application/json
Accept-Encoding: identity
X-Spay-Key-Id: {{ogpApiKey}}
X-Spay-Callback-Id: {{newCallbackUuidV4}}
X-Spay-Event-Id: {{immutableEventUuidV7}}
X-Spay-Event-Type: DEPOSIT_COMPLETED
X-Spay-Timestamp: {{epochSeconds}}
X-Spay-Nonce: {{newUuidV4}}
X-Spay-Signature: {{callbackSignatureHex}}
| Header | 意義/型別 |
|---|---|
| X-Spay-Key-Id | current OGP apiKey 公開識別string,receiver識別currentpair |
| X-Spay-Callback-Id | 此delivery attempt UUID v4,不是去重businesskey |
| X-Spay-Event-Id | 原immutable event UUID v7,與payload eventId一致 |
| X-Spay-Event-Type | payload eventType;native Deposit COMPLETED/EXPIRED/REJECTED/CANCELLED;Withdrawal COMPLETED/REJECTED |
| X-Spay-Timestamp/X-Spay-Nonce | epoch seconds string/此attempt UUID v4 |
| X-Spay-Signature | lowercase hex HMAC-SHA256 |
canonical格式必須每段LF,沒有結尾額外換行,最後直接接rawbody:
SPAY-CALLBACK-V1\nPOST\nNORMALIZED_RAW_PATH\nTIMESTAMP\nNONCE\nEVENT_ID\nRAW_BODY
NORMALIZED_RAW_PATH=URLnormalize後HTTPclient實際encodedpath,不含scheme/host/query;空path /。dot segments/encoded dots/percentencoding/Unicode由clientnormalization決定,不直接對字面配置URL簽。receiver須用實際wirepath/rawbody,不自行decode/rewrite。
合成Depositpayload(顯示pretty JSON只為閱讀,不代表實際persistedbytes格式):
{
"eventId": "019fa1f0-9a10-7c4b-8a91-1234567890ab",
"eventType": "DEPOSIT_COMPLETED",
"occurredAt": "2026-10-07T10:31:00Z",
"orderType": "DEPOSIT",
"orderNo": "00000000000000000000000000000001",
"agentOrderId": "OGP-D-001",
"orderStatus": "COMPLETED",
"amount": "100",
"actualAmount": "100",
"currency": "THB",
"failureCategory": null,
"failureCode": null,
"failureReason": null
}
合成Withdrawal producer範例(source 預設 callback trigger 開啟,部署環境是否開啟以環境 read-back 為準;不是三方驗收):
{
"eventId": "019fa1f0-9a10-7c4b-8a91-1234567890ac",
"eventType": "WITHDRAWAL_COMPLETED",
"occurredAt": "2026-10-07T10:35:00Z",
"orderType": "WITHDRAWAL",
"orderNo": "00000000000000000000000000000002",
"agentOrderId": "OGP-W-001",
"orderStatus": "COMPLETED",
"amount": "1000",
"actualAmount": "900",
"currency": "THB",
"failureCategory": null,
"failureCode": null,
"failureReason": null
}
兩方向payload相同13欄:eventId/eventType/occurredAt/orderType/orderNo/agentOrderId/orderStatus/currency都是strings(occurredAt UTC ISO);amount正數decimalstring,actualAmount成功為positive string,非成功終態(Deposit REJECTED/EXPIRED/CANCELLED、Withdrawal REJECTED)一律為字串"0"、不送null(#1012;建單與查詢接口的actualAmount仍以null表示未確定);failure三欄nullable安全strings,source目前不猜metadata且為null。不含DBID、Supply identity、receiver/payerPII、proof、remark、payout account/bankName。native WITHDRAWAL_COMPLETED 不可默改為Legacy WITHDRAWAL_SUCCESS;release前兩端須核對事件enum。Native差額terminal仍送callback,不套Legacy mismatch query-only。
Terminal commit、claim與ACK
- 金融終態/reservation/Ledger(如適用)/operation/Audit/唯一terminal intent同交易;任何持久化失敗全rollback,不能先送callback。CHreview不建terminal;BO-originWithdrawal為NOT_APPLICABLE。
- immutable event 保存event identity/type/occurredAt/payload;delivery attempt/claim是送同一event的嘗試,不是新金融事件。
- 小交易Order-first→outbox claim,DB refresh已persisted wire snapshot;commit後在交易外HTTP。每claim換callbackId/nonce/timestamp/currentURL/currentkey,eventId及payload不變。
- 首送與retry都使用 persisted wire snapshot,只一次UTF8encoding;可唯讀核eventID/type,不得parse後重新serialize。DB JSON roundtrip可能改whitespace/keyorder,pre-storecompactbytes不是wireauthority。
- finalize短交易驗lease/version/generation,拒stale結果;transport失敗不rollback已commit金融終態。nativeoutbox是PENDING/PROCESSING/RETRY/SENT/DEAD,不沿LegacySENDING/RETRYING狀態。
OGP必須在成功處理 或已成功去重duplicate 後回以下兩個rawbytes;body沒有LF:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8
OK
ACK必須HTTP 2xx且raw body精確大寫OK,不trim、不parseJSON、不依Content-Type。204 空 body、空 body、大小寫不同與前後空白、ok、 OK、OK 、OK\n、JSON "OK"、{"result":"OK"}全是invalidACK;非2xx即使OK也失敗。停用transparentgzip、Accept-Encoding identity,避免解壓結果當rawACK。receiver需transactional event去重與本地businessupdate一起commit,再ACK,避免「先ACK後丟工作」。本地worker流程是receiver端實作建議,不新增Spay產品API。
Native五次 committed claims;retryable失敗後由各次finalize/recover server時間加 1/5/30/60分鐘,不是Legacy相對首次0/1/5/30。lease60秒不續租,send整體20秒(含lookup/signing/DNS/TLS/response),recovery每分鐘UTC第0秒batch50。Claim/Auditrollback不消耗committedattempt;missingtransport可recover expiredlease但不新claim。scheduler於Deposit或Withdrawal任一readiness ready即註冊,且只discover/claim/recover已ready方向的outbox,未ready方向的列維持原狀(#375)。source 預設 spay4.scheduler.triggers.native-callback-dispatch.enabled=true,Deposit/Withdrawal workspace 在 catalog 皆為 ready,兩方向預設皆派送;部署環境是否開啟以環境 read-back 為準。
Callback錯誤矩陣
| 情境 | 實際回應/結果 | 是否可重試 | identity/簽章如何處理 | 如何查詢補償 | 何時需人工 | 禁止動作 |
|---|---|---|---|---|---|---|
| 成功/duplicate已處理 | 2xx+rawexactOK → SENT | 無需;後到duplicate仍有效ACK | eventId去重,不以callbackId去重 | OGPquery最新order | event內容同id矛盾需查核 | 每attempt重複入帳 |
| receiver認證失敗 | receiver401等其他4xx → permanentHTTP_REJECTED/DEAD | sender不自動retry | 核currentpair/path/rawbody/rotation,不改event | OGPquery,兩端核keyrollout | currentpair不同步 | 保存signature/secret、unsigned、retiringfallback |
| 空body/204/JSON/大小寫/空白/3xx | INVALID_ACK,retryable | nativebudget內 | 同event/persistedbody,新nonce/signature | OGPquery+本地eventreceipt | receiver ACK 修正/重試耗盡 | 2xx-only成功、trimJSON、跟redirect |
| 408/425/429/5xx | HTTP_RETRYABLE | 五次claims內按nativebackoff | newattempt、event不變;不套LegacyRetry-After政策 | query | retryexhaustion/receiver依賴 | 修改terminal/財務rollback |
| DNS/networkfailure | NETWORK_FAILURE;freshkey缺失時credentialpermanent優先;無HTTP | 可用key且暫時網路問題才retry | currentURL/currentkey每attemptfresh | query | DNS長期異常 | systemresolverfallback、略publicIPguard |
| overall20秒timeout/取消 | NETWORK_TIMEOUT或取消結果;取消後不發HTTP | retryable結果按budget;stale結果不finalize | event不變,新claimgeneration | query,receiver同eventdedup | lease/recovery卡住 | 每階段重置deadline、cancel後另送 |
| unsafeURL/IP/rebinding/nonHTTPS/query | UNSAFE_TARGET permanent/DEAD;knownunsafe優先credential缺失 | 不自動 | 改current安全destination需另authorized流程 | query/運維安全診斷 | destinationowner | redirect/proxy、允private、把documentationsIP當public |
| missing/inactive/invalidcurrentcredential、URL或Currency缺失 | CREDENTIAL_UNAVAILABLE或intentCALLBACK_*_UNAVAILABLE/DEAD,不unsigned | 不自動 | 另授權修current設定,不重建event | query | operator與Agentowner | leaseURL/Legacymaterialfallback |
| HTTP結果不明/workercrash/expiredlease | PROCESSING→recovery RETRY/DEAD;stale finalize拒絕 | nexteligibility內claim | 同event/persistedbytes,newnonce/callbackId | query+OGPeventreceipt | stalelease持續 | 續租、同claim強送、重建event |
| fifthretryablefailure | DEAD/ATTEMPTS_EXHAUSTED;終態財務不變 | 無automaticretry;Superadmin可經#455人工補送 | immutableevent保留 | OGPquery補償 | 兩端運維查核後以#455補送 | 降attemptcount(#455人工補送為唯一授權例外)、直接DB修狀態、Native套LegacymanualSend |
人工補送界線
POST /agentCallback/manualSend 是LegacyBO入口:terminal AgentAPI-originOrder、可見scope及對應列表UPDATE、orderNo/reason、既有SENT/DEADimmutableevent、busy event拒絕;它不是native API,不用它補送native32-hex單。Native DEAD 的人工補送由 #455 的 BO API POST /bo/v2/agentCallbackOutbox/{id}/manualResend 承接(只限 Superadmin、只接受 DEAD、reason 必填並寫 audit),契約見 Native callback contract;它把 attempt 歸零、沿用同一 immutable event,是下表「禁止降attemptcount」唯一的授權例外,其餘直接修改 outbox 仍禁止。補送前仍可先用 query 補償。
來源:Native callback contract、Withdrawal target。#218有固定component與隔離DB→HTTPSpacket,只及自身producer/transport;本頁未重跑它們,tested inputs/現行fingerprints適用性仍須獨立runtime gate核對。
完整流程
Deposit端到端
角色:OGP建單/展示付款指示,Spay認證/routing/金融authority,LINEprovider通知HOUSE入款,BO處理review,OGP接callback或query。前提:ACTIVEAgent/Currency/currentOGPpair、allocation/Bank/HOUSEquota或CHsession/Account/Gatewayrange、deadlineconfig、sourcebinding+exactLINEadapter、OGPreceiverexactACK。credential/storage/App/runtimeactivation各自有gate。
| 步驟 | 成功結果 | 失敗/重複分支與依賴 |
|---|---|---|
| 1 OGP v1 POST/v2 POST | HMAC→claim→formalorder與routing同transaction;ASSIGNED或PENDING_REVIEW | 認證/strictbody/claimconflict先拒;無候選保留review;timeout先query,sameidentityreplay |
| 2 OGP顯示指示並付款 | 讀account/amount/deadline;query取目前assignment | 首次create snapshot不是latest;review不自判expired;不付到舊帳號/未指派 |
| 3 HOUSE:LINE POST通知 | 認證source→Bank解析→evidence先commit | nullpayer/masked歧義只保存,不amount-only;sameID/hashduplicate、不overwrite;未知adapterclosed |
| 4 matching/CH可信receipt | HOUSE唯一receiver/payer/amount且freshdeadline→SETTLED;CH需verifiedsession/evidence | matcherrollback不丟evidence;CH HTTP 預設開啟(spay4.cardholder.native-enabled=true,部署環境是否開啟以環境 read-back 為準),不借HOUSE背書 |
| 5 BO review/到期 | 合法CHapprove正actual/close reason;HOUSE到期EXPIRED並同交易釋放原quota(ADR-0405),保留owner | CHexpiryreview保留占用不terminal;重派同Supplier原子新reserve舊release;late/雙入款不雙credit/refund |
| 6 terminal intent同金融commit | COMPLETED/REJECTED/HOUSEEXPIRED唯一event | terminal後不得改event/帳務;缺callback設定DEAD不阻金融 |
| 7 Spay callback→OGP ACK | persistedbytes+currentkey/path驗簽、OGPeventdedup→exactOK | retry/recovery/耗盡後走 query;source 預設 callback trigger 開啟(部署環境是否開啟以環境 read-back 為準),不宣稱本次三方實跑 |
成功預期:HOUSEreserve/counter正確收斂(無PaymentAccountLedger),或CH credit/ledger/requestedrelease/actualconsume原子;OGP一次businessupdate。已驗證結果:本次只有文件/合成signing/browser,不是上述金融/providerE2E。
Withdrawal端到端
角色:OGP建單目標、SpayAgentingress/routing、CH付款聲明、BO最後成功與disposition、OGPcallback/query。LINE不參與SPay4Withdrawal出款authority。前提:#213nativeingress與#214同sourcefullmatrix已結案;productionstorage/auth與activation另案。
| 步驟 | 預期結果 | 卡點/例外/依賴 |
|---|---|---|
| 1 OGP POST/GET | verifiedAgent/Currency、exactclaim、encryptedfirstresponse/latestGET、nativeGatewaypreference | route/專用HMAC filter已有source(#213);部署啟用與runtime待核對 |
| 2 routing/BO-origin maker-checker | Agent-origin不走BOapproval;BO-originpending無reserve/callback,另account核准 | Admin create/self-approve 僅 spay4.dev.self-approval(dev/local);無candidate保留review;指定Account失效不得fallback;current實作/fixture適用性待核對 |
| 3 admission/CHaccept | EXTERNAL_POOL PaymentAccount-only,requestedbalance reserve、原日counter/fairness | noHOUSE;Freeze/session/Bank/Gateway/owner/availablebalance重驗;lockedfunding不足不partialreserve |
| 4 CH一次proof/actual | committed付款聲明;CHconfirm非financialterminal | 現行來源缺最新CH單次/BOfinalauthorityconsumer;storageVERIFIED不是銀行驗真 |
| 5 BO選定evidence settle | omittedactual用declared,providedfinalactual正數;與requested/declared任一不同mandatoryreason | source 已允許省略 actual、無 equality guard(部署環境是否開啟以環境 read-back 為準);不足資金/Auditfailure全rollback,原evidence保留 |
| 6 expiry/disposition/redispatch | 未accept/proofASSIGNED到期review保留RESERVED;AdminexplicitNOT_TRANSFERRED才close/redispatch | timeout/缺proof不能推未付;新reserve舊release同transaction;成功重派後新舊付款evidence規則按target,舊attempt新evidence拒且不保存、外部人工處理 |
| 7 BO唯一terminal+callback | uniqueWITHDRAWAL_DEBIT/Order/Ledger/counter/Audit/Agentintent同commit;BO-originNOT_APPLICABLE | final900或1100都可依合法BO裁決;callbacknativeWITHDRAWAL_COMPLETED、不query-only;source 預設 callback trigger 開啟(部署環境是否開啟以環境 read-back 為準),未宣稱三方已完成 |
成功預期:requested1000/actual900釋放requested1000而debit900;actual1100debit1100、餘額覆蓋其他remainingreserved;不得將多attempt金額合計,不改已terminal actual/Ledger。已驗證結果仍缺同來源整合+runtime,不以文件tests代替。
Postman 與本機流程證據
| 用途 | 位置 | 界線 |
|---|---|---|
| OGP Agent API v1 與 LINE 入款通知 HMAC collection(#626) | repository OGP collection、LINE collection;匯入與簽章說明見 repository docs/spay4/postman/README.md「HMAC collections」段與下列夥伴文件站 | 只保存變數名稱與空值;LINE collection 分 Agent 與 Supplier 兩組憑證 |
| 夥伴下載與 callback 接收端範例(#628) | OGP 對接文件 Postman、OGP callback 接收端範例、LINE 入款通知對接文件 Postman | 夥伴站只附 dev/release 空白 environment;接收端範例是實作參考,不是 SPay 提供的服務 |
| 本機跨端流程 A–E(#629) | 報告 A、B、C、D、E;執行方式見 repository docs/spay4/postman/README.md「本機跨端流程(Newman)」段 | 本機 Newman 串接;callback 只驗到已 commit 的 outbox 列,不實際送出 callback 與 FCM,不升「已驗證」 |
真實環境聯測仍待辦:OGP、LINE 廠商與 callback 接收端的 DEV/UAT 聯測待 #465;Cardholder App 切換 SPay4 edge 的真機回報待 #606。
缺口與實作方案
功能進度只引用 各模組兩維進度 的 site-progress.json 規格/後端;本頁不新增百分比/另一套狀態。以下是方案與預期結果,尚未驗證,本次不補後端。
Withdrawal ingress與目前source落差
問題情境: native route/verifier已由#213接線、#214完成同source整合驗收;BOsettle 的 optional final actual 已在 source 落地(actual 可省略、無 equality guard);剩餘落差是CH單次付款聲明接線未完成(本段未於#469重驗)。
為甚麼有問題: Legacyroute與nativeclaim/Currency/owner/金融authority不同;primitive存在與舊worktreePASS不能證明目前部署,照舊流程可能CH直接terminal或錯誤拒合法BO改額。
解決方案: #213由nativeAgentcontroller/parser/authentication owner實作canonicalPOST/GET,輸入verifiedAgent+strictv1DTO、輸出firstencryptedPOSTsnapshot/currentGETVO;重用Agent-ownedcredential與nativeclaim服務,不複製Deposit欄位上限。claim/order/routing/Audit/firstsnapshot同交易,HMACnonce獨立短交易,無外部IO持鎖;並行sameidentity鎖currentwinner,異payload409,technicalfailure全rollback。先整合經owner核准的#211authority到固定candidate,補CHone-successful-submission/freshauthorityreplay/BOevidence/finalactual,不覆寫rawEVIDENCE。#212補maker-checker、候選preview後freshguard、rollback/race矩陣;#214同source跑HTTP→disposableMySQL→financial/consumer/golden/privacy完整驗證。activation前需要operatorreadiness、真auth/storage、App/前端及route啟用授權;不能為文件通過改catalog/grants。
解決後結果: 預期OGP一次建單、duplicate不重派,GET最新finalactual;CH聲明不debit、BO唯一成功。ingress已有#214同source整合結果;部署runtime未驗證,部署環境是否開啟以環境 read-back 為準。
LINEprovider與identity保障
問題情境: signature合法但receiver/payermasked或unknown;provider不同messageID/sourcenamespace可能對同經濟交易重複通知;切換profile不應改舊fact。
為甚麼有問題: HMAC只認sender;任何first-match/amount-only都可能錯結算,上游遭入侵可提交合法假通知。distinctsyntheticsource不是production lifecycle驗證。
解決方案: providerowner保障message_id穩定與source切換重接策略,不改現有canonicalfacts。ingresssourcebinding/exactadapter→immutablewritertransaction→獨立 matching transaction;matching最後locks重讀Config/scoped完整receiver/payer/歷史唯一性;zero候選才既有1/3/5recovery,nullpayer留BOmanual且不自動batch。測試rawUTF8/outerinner/時間fallback/Bankambiguity/>300traversal/exact多候選/nullpayer/duplicateconflict/rollback/deadline;另以實providerfixture核對time/ID/secret-safe接收,但實際送出須另授權。不得新增銀行provenanceAPI或放寬unknownadapter。
解決後結果: 預期合法上游事實可追溯、 ambiguity不結算、retry不重credit;上游經濟交易ID與bank-independent風險仍需外部保證,本次未取得provider acceptance。
Callback receiver、manual recovery與bytes
問題情境: 金融已commit但receiverinvalidACK/keyrotation不同步/fiveclaims exhausted;新manual-send未核定,DBJSON可能正規化bytes。
為甚麼有問題: retry不是新event;parse再serialize會破壞rawHMAC,先ACK後businesscommit會丟結果;直接改outbox或走Legacymanual不具nativeauthority。
解決方案: OGPreceiverowner輸入rawPOST/headers、先currentpair驗簽→immutableevent去重/businessupdate同本地transaction→精確rawOK。Spaynativeproducer同金融transactionpersistintent,dispatchclaim/finalize短交易、HTTPtransaction外,persistedbytes跨retry不重建,lease/CAS拒stale;同source獨立MySQLJSONroundtrip→實際HTTPSbytesgate核first/retry/currentURL/currentkey/unsafe不送,不能只用本頁vectors。Native人工recovery先另核定API/角色scope/terminalstate/busy/exhaustion限制與Audit/appendattempt規則,再以publicseam negative測試;未核定前OGPquery+運維核對,不擅造route/backoff或改attemptcount。receiver成功與duplicateACKruntime證據、scheduler/readiness與operatorrelease各自閉合才activation。
解決後結果: 預期重送同event只改delivery投影、financialterminal不rollback;manual能力與實receiver/DB→wire證據須獨立交付,文件tests不算runtime驗收。
離線簽章範例
服務端Node.js標準庫示例,只算合成公開test-only vectors,不發HTTP、不連DB、不讀runtimecredential。實務使用呼叫者安全secret管理與原始file/bufferbytes,禁止放進browserlocalStorage。固定timestamp/nonce不是可直接送產品的request;body也不是合法完整業務request,是專測Unicode/rawbytes的合成fixture。
下列四個expected由離線Python hmac/SHA256獨立核對;LF、無BOM、無尾端LF。callback的normalizedpath已固定為encodedpath,這不是URLnormalizer或MySQLgate測試。
// SPAY4_OFFLINE_SIGNING_VECTORS:公開人工fixture,絕非runtime secret。
import { createHmac } from 'node:crypto';
import assert from 'node:assert/strict';
const testOnlyKey = 'spay4-public-test-only';
const rawBody = Buffer.from('{"amount":"100.00","note":"合成資料"}', 'utf8');
const timestamp = '1785168000';
const nonce = '123e4567-e89b-42d3-a456-426614174000';
const eventId = '019fa1f0-9a10-7c4b-8a91-1234567890ab';
const hmac = (prefix, codec, body = rawBody) => createHmac('sha256', testOnlyKey)
.update(Buffer.from(prefix, 'utf8')).update(body).digest(codec);
const v1 = `POST\n/v1/agentApi/depositOrder/assign\n${timestamp}\n${nonce}\n`;
const v2 = `POST\n/v2/external/deposit-orders\n${timestamp}\n${nonce}\n`;
const house = `POST\n/v2/external/transactions\n${timestamp}\n${nonce}\n`;
const callback = `SPAY-CALLBACK-V1\nPOST\n/notify/%E5%90%88%E6%88%90\n${timestamp}\n${nonce}\n${eventId}\n`;
assert.equal(hmac(v1, 'hex'), '515e0a64c5e66f46c2a214fd38366408cb203fe1fdbad8d49356cc2d72f940c0');
assert.equal(hmac(v2, 'base64'), 'sPthRm0VXm+y9F/bSIb2Q9KRNgQilIsg1a94O80lIVo=');
assert.equal(hmac(house, 'hex'), 'bd25eaee16afea15cbe577222f34bdf611f7287d17ff893d18ef5f2e445676fe');
assert.equal(hmac(callback, 'hex'), 'bb91ba93476e4c21d4f341dbd34a9c0d91f6952b1ac92730ce4afd60ad6629f7');
assert.notEqual(hmac(callback, 'hex', Buffer.concat([rawBody, Buffer.from('\n')])), hmac(callback, 'hex'));
assert.notEqual(hmac(callback, 'hex', Buffer.from(JSON.stringify(JSON.parse(rawBody), null, 2))), hmac(callback, 'hex'));
console.log('4 synthetic raw-byte vectors passed; not a runtime/DB gate');
v1/v2/HOUSE request的rawprefix沒有protocol-name首行,callback才有SPAY-CALLBACK-V1+eventId;換codec不代表更換credentialscope。實際成功request/response字段見各方向章節,不把合成vectors的note欄送到strictparser。
技術參考
版本與相容性隔離
| 舊入口/來源 | 本頁使用方式 | 不可沿用的部分 |
|---|---|---|
/agentNotification/webhook、/public/webhook/line | 最小相容性對照:不可當成 SPay4 alias | Legacydevice credential/sourceprofile、first-match/OUT付款 |
| OGP API既有文件/three-party Postman | 僅核對v1外形及§9outwardsigning/ACK;native例子因requiredpayer/nullchannel/32-hex/currentkey/nativeeventtype改為本指南synthetic | Legacyoptionalpayer、417failedlog、Redisguard、fourattempts、query-only差額、WITHDRAWAL_SUCCESS、receiverPIIcallback |
/agentCallback/manualSend | 只作Legacy對照,不是native API | Legacy權限與status不得憑名稱變native補送能力 |
| LINE_VENDOR_A/B/test profile | 非核定productionadapter;只提拒絕界線 | 不以舊profile/大ADR編號/class存在推定新authority |
舊版 /public/webhook/line 對 SPay4 新路徑 POST /v2/external/transactions 的逐項參數對照(#506;供 Operator 在 #465 聯測前通知 LINE 廠商):
| 項目 | 舊版 /public/webhook/line | SPay4 POST /v2/external/transactions |
|---|---|---|
| Body 欄位 | 六欄(LineWebhookRequestVo) | 同六欄(LineVendorWebhook) |
| Header | X-Api-Key、X-Timestamp、X-Signature | 同三個,新增必填 X-Nonce |
| 時間戳 | 毫秒,容許 ±5 分鐘(ExternalApiAccessFilter) | epoch 秒 |
| Nonce | 無 | 必填 UUID v4,防重放 |
| 簽章 | hex HMAC-SHA256(timestamp + body) | hex HMAC-SHA256(METHOD\npath\ntimestamp\nnonce\n + raw body)(HmacSha256Support),path 為新路徑 |
| Credential | device account | LINE_WEBHOOK credential(新 key/secret) |
現有 BO Postman collection 仍獨立、僅手動逐筆,未重排;原three-partycollection位於repository docs/archive/legacy/postman/ogp-line-three-party.postman_collection.json,屬Legacy驗證資產,不直接送native。原範例經核對不能照搬的原因已列上表;本頁新增的是指南內syntheticnative範例,不改BOcollection。OGP/LINE 的 HMAC collection 與本機流程證據見 Postman 與本機流程證據。完整歷史不進新頁/Reader搜尋。
現行authority與固定驗證界線
- Deposit target:ADR-0397/0398與Freeze overlay;HOUSE scoped規則依ADR-0415明示partial supersession,nullable只限核定LINE入站,不改Orderpayer/CH/manual/absence。
- Withdrawal target:ADR-0403(Withdrawal)核定BOfinalactual/disposition/CH單次聲明;不與HOUSE的ADR-0415混用。
- Native callback:沿OGP§9wire,不沿Legacydeliverylifecycle;#218已記component/isolatedDB→HTTPS固定packet,本頁沒重跑也沒把它當三方provider證據。
- Overview Freeze contract:凍結保留可信款項/evidence/obligation,先unfreeze再confirm;unfreeze不是settlement。
- 各模組、完整需求流程:規格/後端兩維共用site-progress.json,不新增狀態模型。
Source presence只證明handler/guard已存在,不證明deployed/ready。#218歷史packet的testedHEAD是57efcd6b72fe8ba3a766441cdd7f783789eb2f06,NativeCallbackTransportImplTest component 與 NativeCallbackPersistenceHttpIntegrationTest兩案例及相關financialfixtures各有scope;同producer/dependencies指紋覆蓋才可引用,不因文檔HEAD不同一律作廢,也不以舊PASS背書新的inputs。本次未讀回新DB、未重跑Java/provider/receiver,DB JSON roundtrip/實際wirebytes仍是獨立runtime gate。
Source追溯(只讀固定HEAD)
- v1 controller、v1 request VO、v1 VO、shared Deposit service:firstsnapshot/latestquery、strict型別與exactclaim。
- v2 controller、v2 request VO、v2 VO:numericamount/rawresponse。
- HMAC service、v1 filter、v2 filter、HOUSE filter:四協定transport/codec不混用;Withdrawalv1由Withdrawal filter獨立處理(Withdrawal controller)。
- LINE adapter、LINE parser、evidence writer、ingress coordinator:immutablecommit先於matching。
- native outbox、Deposit producer、Withdrawal producer、scheduler:immutableevent/五claims/backoff/closedgate。
公開副本會停用內網/Java/SQL/站外local來源連結;必要串接資訊已完整列在本頁,不依賴被移除來源才能使用。沒有真實key/token/secret或交易payload。文件與browser成功只代表展示/生成驗證,不取代#219合併後正式驗收或產品activation。