参考

Pain001 技术参考:CLI、Python API 与 REST

pain001 v0.0.90 的每个标志、端点与行为,均取自已发布的代码,而非愿景。

本参考文档介绍 pain001 v0.0.90 的命令行界面、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#

from pain001.core.core import process_files

# Generate a validated pain.001.001.09 file from CSV
process_files(
    xml_message_type="pain.001.001.09",
    xml_template_file_path="template.xml",
    xsd_schema_file_path="schema.xsd",
    data_file_path="payments.csv",
    output_path="out/payments.xml",
)

每个生成的文档在写出之前都要经过三层检查:

  1. 输入校验:每条记录都根据该报文类型的 JSON Schema 进行检查,并执行字段别名规范化与 IBAN/BIC 语法检查。
  2. 方案规则手册(可选):您所指定支付系统的规则,从 SEPA(SCT、Instant、SDD Core、B2B)到英国 Faster Payments、CHAPS 和 Bacs、美国 ACH 与电汇等各国支付系统,以及 Swift CBPR+;pain001 plugins list 会列出全部名称。
  3. 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.90 refuses it.

Runnable, self-checking scripts for the public API and the CLI live in the library's examples/ directory.


3. REST 微服务#

pip install "pain001[api]"
pain001 serve --host 0.0.0.0 --port 8000

所有端点均挂载在 /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 服务器或支付术语表。