本參考文件說明 pain001 v0.0.91 的命令列介面、Python API、REST 微服務與驗證管線。此處列出的每個旗標、端點與行為皆取自實際釋出的程式碼,而非願景。
Pain001 支援 13 種 ISO 20022 電文定義:pain.001.001.03 至 pain.001.001.13(客戶貸記轉帳發動,共十一個版本)以及 pain.008.001.02 / pain.008.001.08(客戶直接扣款發動)。
1. 命令列介面#
pain001 執行檔將功能劃分為多個子命令。僅帶產生旗標執行時會隱含呼叫 generate,因此既有的自動化流程可照常運作。
| 子命令 | 用途 |
|---|---|
generate | 將資料檔轉換為經結構描述驗證的 ISO 20022 XML(預設命令)。 |
validate | 僅驗證輸入資料,不寫出 XML。 |
check <file>... [--scheme] [--format] | Check pain.001 or pain.008 files you already have: the XSD of the message type each file declares, the message definition's cross-element rules, and any scheme profiles, policy or Schematron rulebook you name. |
verify-signature <file>... --cert <PEM> | Verify the XML-DSig signature on each file against the signer's certificate or public key; --trust-embedded-cert checks integrity only (requires the sign extra). |
versions [--format json] | 列出全部 13 種支援的電文定義。 |
inspect <type> [--format json] | 顯示某一報文類型隨附的範本、結構描述、範例資料以及可接受的輸入格式。 |
init <type> [-o FILE] | 為電文類型建立入門 CSV 範本。 |
serve [--host] [--port] [--reload] | 啟動 FastAPI REST 微服務(需安裝 api 額外相依)。 |
mcp | 透過 stdio 啟動核心函式庫內建的 Model Context Protocol 伺服器(需要 mcp 擴充);完整的伺服器以 pain001-mcp 形式發布。 |
plugins list / show / disable | 列出已發現的載入器、驗證器、規則與寫入器外掛,顯示其中一個,或說明如何關閉第三方外掛的探索。 |
face <file> [--face] [--bindings] [-o] [--loss-report] | Project a pain.001 XML file into another standard's JSON shape, with a report of every element not carried. |
upload [<file>] --sftp <url> | Deliver a file atomically to an SFTP server you trust explicitly (requires the upload extra). |
generate 選項
| 旗標 | 說明 |
|---|---|
-t, --xml-message-type <TYPE> | 電文定義,例如 pain.001.001.09。 |
-d, --data <FILE> | 輸入資料:.csv、.json、.jsonl、.db / .sqlite、.parquet,或經 PGP 加密的 .gpg / .asc。 |
-o, --output-dir <DIR> | 存放產生 XML 的目錄。 |
-m, --template <FILE> / -s, --schema <FILE> | 覆寫內建的 Jinja2 範本或 XSD 結構描述。 |
-c, --config <FILE> | 從組態設定檔載入預設值(--profile、--show-config)。 |
--dry-run(別名 --validate-only) | 依 JSON Schema、XSD 與方案規則手冊驗證輸入,但不寫出任何輸出。 |
--scheme <NAME[,NAME]> | 執行一個或多個規則手冊,以逗號分隔。pain001 plugins list 會列出每一個已安裝的規則手冊。 |
--explain / --format json | 搭配 --scheme 使用時,會為每一處違規輸出修正提示,格式為文字或 JSON。 |
--rules <FILE> | Enforce a private YAML CEL policy before generation (requires the rules extra). |
--schematron <PRESET or FILE> | Apply Schematron business rules: the sepa, fednow or cbpr preset, or your own .sch file. |
--decrypt-key <FILE> / --decrypt-passphrase-env <VAR> | Import a GPG private key, and name the variable that holds its passphrase, for .gpg / .asc input (requires the gpg extra). |
--streaming / --chunk-size <N> | 針對大批次的記憶體受控分塊處理(預設每塊 1,000 筆交易;每個分塊各自產生一個 XML 檔案,並重新計算 NbOfTxs 與 CtrlSum)。 |
--emit-metrics | 輸出機器可讀的執行指標,供可觀測性管線使用。 |
--envelop-bah | Wrap generated payment XML into an ISO 20022 Business Application Header (head.001.001.03) and BizData (head.003.001.01) envelope. |
--bah-sender <BIC/ID> | Sender financial institution BIC or organisation identifier for BAH <Fr>. |
--bah-receiver <BIC/ID> | Receiver financial institution BIC or organisation identifier for BAH <To>. |
--bah-msg-id <ID> | Business Message Identifier for BAH <BizMsgIdr> (defaults to generated UUID). |
--xml-sign-key <FILE> | PEM private key (RSA, or EC P-256/P-384) for a W3C XML Digital Signature (XML-DSig); the algorithm follows the key. |
--xml-sign-cert <FILE> | Optional PEM X.509 certificate to embed in XML-DSig <ds:KeyInfo>. |
--xml-sign-alg <ALG> | rsa-sha256, rsa-pss-sha256, ecdsa-sha256 or ecdsa-sha384; by default an RSA key signs rsa-sha256. |
--xml-sign-passphrase-env <VAR> | Environment variable holding the passphrase for --xml-sign-key. |
--list-templates / --show-template <TYPE> | List the bundled templates, or show one template's metadata, and exit. |
結束代碼對 CI 友善:0 表示成功、1 表示驗證失敗、2 表示用法錯誤。
XML signing and verify-signature need the sign extra (pip install "pain001[sign]", which installs cryptography and lxml).
Signatures: pain001 verify-signature
pain001 verify-signature checks the signature on files you received or wrote. Pass the signer's certificate or public key with --cert; that is the trust anchor. --trust-embedded-cert verifies with each file's own certificate instead, which proves the file is unchanged since it was signed but not who signed it. It exits 0 when every file verifies, 1 when any does not, and 2 when it cannot run; --format json prints one report per file. Verification uses exclusive C14N 1.0 and accepts only RSA-SHA256, RSA-PSS and ECDSA signatures with SHA-256 to SHA-512 digests over the whole document; the certificate's chain and validity dates are not checked.
Faces: pain001 face
A face projects a validated pain.001 document into another standard's JSON request body. --face uk_open_banking targets the Open Banking Read/Write API v4.0.1 domestic payment, --face berlin_group targets NextGenPSD2 v1.3.16 payment initiation, and --face iso_2018 renames every element to its ISO 20022 name in snake_case. A face refuses a document that lacks an element its target requires instead of inventing a value; --loss-report lists every source element it did not carry. Faces are outbound only.
Delivery: pain001 upload
pain001 upload sends a finished file to an SFTP server you name, and only after you have trusted its host key: from a known_hosts file (--known-hosts) or an OpenSSH SHA256 fingerprint you verified independently (--accept-host-key). --print-host-key shows the server's fingerprint without logging in. It logs in with a private key (--identity-file, with --passphrase-env), a password read from an environment variable (--password-env), or your SSH agent. The file is written under a temporary name and renamed on the server, so the receiving side never sees a partial file.
2. Python API#
# Generate a validated pain.001.001.09 file from CSV
每份產生的文件在寫出前都會通過三層檢查:
- 輸入驗證:每筆記錄都依該電文類型的 JSON Schema 檢查,並進行欄位別名正規化與 IBAN/BIC 語法檢查。
- 方案規則手冊(選用):您所指定支付系統的規則,從 SEPA(SCT、Instant、SDD Core、B2B)到英國 Faster Payments、CHAPS 與 Bacs、美國 ACH 與電匯等各國支付系統,以及 Swift CBPR+;
pain001 plugins list會列出全部名稱。 - XSD 驗證:產出的 XML 在寫入磁碟前,先透過
xmlschema依官方 ISO 20022 結構描述驗證。安裝選用的fast擴充(lxml)後,libxml2 能更快接受有效文件;被它拒絕的文件會由xmlschema再次檢查,並以其結論為準。
在 XML 產生與方案驗證過程中,貨幣金額一律以 decimal.Decimal 處理(絕不使用 IEEE 754 浮點數),且 NbOfTxs / CtrlSum 控制總計是根據已驗證的記錄重新計算,而非直接採信輸入。
除了產生 pain.001,核心函式庫還提供 pain.002 狀態報告解析器與產生器(可讀取銀行的受理/退件回覆)、供日終對帳使用的 camt.053 對帳單解析器與產生器,以及可在電文版本之間搬移記錄的 VersionMapper。
pain001.faces.project_face is the Python entry point for faces. sign_xml_document signs a document with XML-DSig, and verify_signature(signed_xml, trust_anchor=cert_pem) verifies one and returns a SignatureReport (valid, trust, algorithm, signer, reason); both need the sign extra. verify_xml_signature without a key or certificate still trusts the certificate inside the document, with a DeprecationWarning; pain001 0.0.91 refuses it.
Runnable, self-checking scripts for the public API and the CLI live in the library's examples/ directory.
3. REST 微服務#
所有端點皆掛載於 /api/v1 之下(並提供不含版本的 /api 別名):
| 方法與路徑 | 用途 |
|---|---|
GET /api/v1/health | 存活探測。 |
POST /api/v1/validate | 驗證記錄;回傳欄位層級錯誤。 |
POST /api/v1/generate | 同步產生 XML。 |
POST /api/v1/generate/async | 將大批次排入佇列進行背景產生。 |
GET /api/v1/status/{job_id} | 輪詢非同步工作。 |
GET /api/v1/download/{job_id} | 下載完成的 XML。 |
DELETE /api/v1/jobs/{job_id} | 清除已完成的工作。 |
GET /api/v1/faces | List the faces and the binding keys each accepts. |
POST /api/v1/faces/{face} | Project a pain.001 document sent as XML text; returns the payload and the loss report, or 422 with the reason the face refused it. |
GET /metrics | Prometheus 指標。 |
互動式文件位於 /api/docs(Swagger UI)、/api/redoc 與 /api/reference(Scalar),OpenAPI 文件則在 /openapi.json。
When the PAIN001_API_KEY environment variable is set, every endpoint except /health and /metrics requires it as a bearer token; when it is unset, the API is open. pain001 serve binds to 127.0.0.1 unless you pass --host.
4. 輸入正規化#
Pain001 會在驗證前將真實世界的匯出資料整理為有效記錄:
- 欄位別名:常見的 ERP 欄位名稱會對應到標準欄位(例如
amount→payment_amount)。 - IBAN / BIC 正規化:去除空白、統一大小寫後再行檢查(IBAN 採 ISO 13616 mod-97 檢核,BIC 採 ISO 9362 結構檢查)。
- 日期:依 ISO 8601
YYYY-MM-DD解析執行日期。 - 金額:一律經由
decimal.Decimal處理;格式錯誤的金額會直接驗證失敗,而不是被默默捨入。 - 字元集:轉寫輔助工具會將內容化約為 SWIFT 與 SEPA 接受的 ISO 20022 拉丁字元集。
- Formula cells: CSV cells that start with
=,+,-or@are kept as supplied by default, so phone numbers and references survive;load_csv_data(path, sanitize_formula=True)escapes them with a leading quote instead.
5. 外掛架構#
本套件可經由四個進入點群組擴充:pain001.loaders、pain001.validators、pain001.schemes 與 pain001.writers。pain001-loader-xlsx 透過此機制註冊,安裝後即自動被探索到;pain001-loader-mt101 則是可直接取用的獨立解析函式庫(MCP 伺服器的 convert_mt101 工具也使用它)。緊急停用開關 PAIN001_DISABLE_PLUGINS=1 可在高度管控環境中完全停用第三方外掛探索。
6. 品質關卡#
核心函式庫依循嚴格且可驗證的關卡開發:CI 強制 100% 行與分支涵蓋率(--cov-fail-under=100)、嚴格 mypy 型別檢查、100% docstring 涵蓋率,以及安全掃描(Bandit、pip-audit)。每個發行版建置都會產生 CycloneDX SBOM。
接著可閱讀安裝指南、給 AI 代理使用的 MCP 伺服器,或支付詞彙表。
