epay-sdk 1.0.0

EPay (易支付) SDK for Rust — 彩虹易支付 V1 compatible client with an axum integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# epay-sdk 进阶指南

README 只讲 Axum 的最短路径;这里是其余细节。所有代码片段都会作为 doctest 编译(`cargo test --all-features`)。

## 目录

- [架构](#架构)
- [Features](#features)
- [无 HTTP 的协议上下文](#无-http-的协议上下文)
- [CSP 友好的表单支付](#csp-友好的表单支付)
- [支付目标地址](#支付目标地址)
- [分支特有字段](#分支特有字段)
- [重试与单次调用选项](#重试与单次调用选项)
- [分页](#分页)
- [错误处理](#错误处理)
- [阻塞调用](#阻塞调用blocking-feature)
- [可观测性](#可观测性)
- [旧 HTTP 网关与本地回调](#旧-http-网关与本地回调)
- [其它 Web 框架](#其它-web-框架)
- [多商户回调](#多商户回调)
- [观察被拒绝的回调](#观察被拒绝的回调)
- [出站字段上限](#出站字段上限)
- [金额](#金额)
- [环境变量](#环境变量)
- [自定义 HTTP](#自定义-http)
- [测试回调](#测试回调)

## 架构

```text
ProtocolContext(无 HTTP / 无运行时依赖)
├── Config:商户号、密钥(共享、释放时清零)、网关地址、回调默认值
├── MD5 签名和验签
├── PreparedForm:签名后的 submit.php 部件(URL / HTML / 自渲染)
└── 严格通知验证(NotifyData / SuccessfulNotify)

Client
├── ProtocolContext
├── HttpConfig:per-attempt 超时、连接超时、响应大小上限、RetryPolicy
├── reqwest 或自定义 Transport
├── mapi.php / api.php 异步接口(按 Endpoint 枚举分发,出站大小受 limits 约束)
├── CallOptions:单次调用的超时 / 重试覆盖
└── PaymentDestination:下单响应里的支付入口

Error → ErrorKind / Endpoint:稳定的分类与端点,供指标和 HTTP 映射

axum feature(axum 关闭默认特性,不引入 tokio / hyper)
├── VerifiedNotify / VerifiedReturn:单商户验签抽取器
├── ParsedNotify:只解析不验签,多商户按路径选密钥
├── NotifyParams:诊断用,拒绝回 400
├── NotifyAck
├── callback_route:GET + POST 一次注册
└── payer_ip:反代后的付款者 IP

blocking feature  → blocking::Client
tracing feature   → 每次网关调用一个 span
test-util feature → MockTransport、NotifyFixture
```

- 网关响应先校验 `code` / `msg` 包络,再解析成功结构;成功结构不携带 `code`(退款回执保留 `msg`)。
- 请求 / 响应类型的 `Debug` 掩盖回调与支付链接的 query(无法解析的 URL 只显示长度);`param` / `qr_code` / `buyer` / 结算 `account` 只显示长度,`extra` 只显示键。
- `api.php` 只使用官方 `pid + key` 鉴权。
- 通知 query + form 合计最多 16 KiB,重复字段和冲突字段直接拒绝。

## Features

| Feature | 默认 | 用途 |
|---|---:|---|
| `reqwest-rustls` | 是 | reqwest + rustls |
| `reqwest-native-tls` | 否 | reqwest + native-tls |
| `axum` | 否 | Axum 0.8 抽取器与路由助手 |
| `blocking` | 否 | `blocking::Client`,面向脚本 / CLI / 对账任务 |
| `tracing` | 否 | 每次网关调用一个 `tracing` span,日志改走 `tracing`(不再发 `log`) |
| `test-util` | 否 | `test_util`:`MockTransport`、`NotifyFixture` |

## 无 HTTP 的协议上下文

只建表单、只收回调的服务不需要 reqwest 和 Tokio:

```rust
use epay_sdk::{FormPaymentRequest, Money, PayType, ProtocolContext};

let epay = ProtocolContext::builder(1001, "merchant-key", "https://pay.example.com")
    .notify_url("https://shop.example.com/notify")
    .return_url("https://shop.example.com/return")
    .build()?;

let request = FormPaymentRequest::new("ORDER001", "VIP会员", Money::from_yuan_str("9.90")?)
    .pay_type(PayType::Alipay);

let html = epay.build_form_payment(&request)?;
let url = epay.build_form_payment_url(&request)?;
# let _ = (html, url);
# Ok::<(), epay_sdk::Error>(())
```

`Client` 上的同名方法只是转发到 `client.protocol_context()`。

## CSP 友好的表单支付

`build_form_payment()` 返回的页面带内联 `<script>`,严格的 Content-Security-Policy 会拦截。`prepare_form_payment()` 只给你签名后的部件,渲染方式自定:

```rust
# fn demo(epay: &epay_sdk::ProtocolContext, request: &epay_sdk::FormPaymentRequest) -> epay_sdk::Result<()> {
let form = epay.prepare_form_payment(request)?;
// 方式一:自己的模板 + nonce 脚本 / 提交按钮
let html = format!(
    r#"<form id="pay" method="POST" action="{}">{}<button>前往支付</button></form>"#,
    form.action(), form.hidden_inputs()
);
// 方式二:GET 重定向
let redirect = form.redirect_url();
# let _ = (html, redirect);
# Ok(())
# }
```

`form.params()` 是只读的 `Params`(`Debug` 脱敏 `sign`);`into_parts()` 可以拿走所有权,但之后的修改不再受签名和大小限制保护。

## 支付目标地址

`mapi.php` 根据渠道 / 设备返回 `payurl`、`qrcode`、`urlscheme` 中的一个或多个。`PaymentResponse::destination()` / `destinations()` 按这个顺序给出非空项,`PaymentDestination::parse_url()` 方便你检查 scheme 和 host:

```rust
use epay_sdk::PaymentDestination;

# fn demo(response: &epay_sdk::PaymentResponse) -> epay_sdk::Result<()> {
match response.destination() {
    Some(PaymentDestination::PayUrl(url)) => {
        let parsed = PaymentDestination::PayUrl(url).parse_url()?;
        // 你的策略:只允许 https 和已知网关域名,再重定向浏览器
        let _ = parsed.scheme() == "https";
    }
    Some(PaymentDestination::QrCode(payload)) => { /* 渲染二维码 */ let _ = payload; }
    Some(PaymentDestination::UrlScheme(scheme)) => { /* 只放行 alipays:// weixin:// 等已知 scheme */ let _ = scheme; }
    Some(_) | None => {}
}
# Ok(())
# }
```

SDK 不替你做 allowlist:各分支返回的 scheme 和域名差异很大,安全策略必须由应用决定。

## 分支特有字段

每个响应结构体都有 `extra: BTreeMap<String, serde_json::Value>`,保留网关返回但 SDK 未建模的字段;包络字段 `code` 已被消费,回显的 `key` / `sign` 被剔除,都不会出现在其中。

```rust
# async fn demo(client: &epay_sdk::Client) -> epay_sdk::Result<()> {
let order = client.query_order_by_out_trade_no("ORDER001").await?;
if let Some(fee) = order.extra.get("pay_fee").and_then(|v| v.as_str()) {
    println!("手续费 {fee}");
}
# Ok(())
# }
```

## 重试与单次调用选项

默认不重试。`RetryPolicy` 只对 **GET** 端点(订单 / 商户 / 结算查询)且只对 `Error::is_retryable()` 为真的失败(超时、连接失败、502/503/504)生效;`mapi.php` 下单和退款永远不自动重试。

**超时是 per-attempt 的**:`timeout` 约束单次尝试,每次重试重新计时,退避延迟不计入;开启 2 次重试后一次 GET 最长可达 `3 × timeout + 退避`。需要总体 deadline 的地方(比如 durable job)保持 `RetryPolicy::NONE`,由外层调度器控制重试。`connect_timeout` 可单独约束 TCP/TLS 建连,只对 SDK 自建的 reqwest 客户端生效:与 `reqwest_client(…)` 同时设置会在 `build()` 报错,自定义 `Transport` 则需自行配置;值为 0 同样报错而不是静默禁用。

```rust
use std::time::Duration;
use epay_sdk::{CallOptions, Client, RetryPolicy};

# async fn demo() -> epay_sdk::Result<()> {
let client = Client::builder(1001, "merchant-key", "https://pay.example.com")
    .retry(RetryPolicy::reads()) // 2 次,200 ms → 2 s 指数退避
    .build()?;

// 单次调用覆盖超时和重试
let options = CallOptions::new()
    .timeout(Duration::from_secs(60))
    .retry(RetryPolicy::NONE);
let merchant = client.query_merchant_with(&options).await?;
println!("{}", merchant.money);
# Ok(())
# }
```

自定义 `Transport` 必须实现 `sleep`(用运行时的定时器),退避才能生效。

## 分页

`query_orders(limit, page)` 返回一页;`OrderListResponse::next_page(page, limit)` 在页满时给出下一页(不依赖各分支含义不一的 `count`)。`query_all_orders(limit, max_pages)` 有界地收集多页:

```rust
# async fn demo(client: &epay_sdk::Client) -> epay_sdk::Result<()> {
let recent = client.query_all_orders(50, 4).await?; // 最多 200 笔
# let _ = recent;
# Ok(())
# }
```

## 错误处理

```rust
use epay_sdk::{Endpoint, Error, TransportErrorKind};

fn classify(error: &Error) -> &'static str {
    match error {
        Error::Api { endpoint: Endpoint::Refund, code, .. } if *code < 0 => "refund rejected",
        Error::Api { .. } => "gateway error",
        Error::Transport { kind: TransportErrorKind::Timeout, .. } => "retry later",
        Error::VerifyFailed => "bad signature",
        _ => "other",
    }
}
```

`Error` 是 `#[non_exhaustive]`,业务代码不必匹配它:`Error::kind()` 返回稳定的低基数 `ErrorKind`(`Config` / `InvalidParameter` / `Verification` / `Provider` / `Transport` / `InvalidResponse`;同样是 `#[non_exhaustive]`,请保留兜底分支),`Error::endpoint()` 给出涉及的网关端点,适合指标标签和 HTTP 状态码映射;`Error::code()` 提供与 Go SDK 一致的数字码,`Error::transport_kind()` / `is_timeout()` / `is_retryable()` 提供传输层分类。所有错误文本都会对 `key` / `sign` 脱敏;内置 reqwest transport 的错误只包含固定分类消息,不含请求 URL。

SDK 有意不为 `Error` 实现 `IntoResponse`:网关错误文案不应该原样送到浏览器。在 Axum 里用一个 newtype 统一映射:

```rust
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use epay_sdk::Error;

struct AppError(Error);

impl From<Error> for AppError {
    fn from(error: Error) -> Self {
        Self(error)
    }
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        use epay_sdk::ErrorKind;
        let status = match self.0.kind() {
            ErrorKind::InvalidParameter => StatusCode::BAD_REQUEST,
            ErrorKind::Provider => StatusCode::BAD_GATEWAY,
            ErrorKind::Transport => StatusCode::SERVICE_UNAVAILABLE,
            ErrorKind::Config | ErrorKind::Verification | ErrorKind::InvalidResponse => {
                StatusCode::INTERNAL_SERVER_ERROR
            }
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        };
        log::warn!("epay call failed: {}", self.0);
        (status, "payment service error").into_response()
    }
}

// handler 返回 Result<_, AppError> 后就能直接 `?`
```

## 阻塞调用(`blocking` feature)

```rust,ignore
let client = epay_sdk::blocking::Client::new(
    epay_sdk::Client::new(1001, "merchant-key", "https://pay.example.com")?,
)?;
let merchant = client.query_merchant()?;
```

不要在 Tokio 运行时内部使用;那里直接用 async `Client`。

## 可观测性

`debug(true)` 时输出脱敏后的请求 / 响应。未开启 `tracing` feature 时走 `log`;开启后**只**走 `tracing`(不会同时发 `log`,因此安装了 `LogTracer` 的应用不会看到重复事件),每次网关调用都在 `epay.request` span(字段 `endpoint`、`method`)内执行。重试以 `warn` 记录;回调拒绝只记 `debug`(公开端点,避免日志放大,见下文“观察被拒绝的回调”)。

## 旧 HTTP 网关与本地回调

网关地址和回调地址默认都必须是 HTTPS,不安全 HTTP 不会被静默接受,两者各自有独立开关:

```rust,no_run
let client = epay_sdk::Client::builder(1001, "key", "http://legacy.example.com")
    .allow_insecure_http(true)                    // 网关是旧的 http:// 部署
    .notify_url("http://localhost:8080/notify")
    .allow_insecure_callback_http(true)           // 本地联调的 http:// 回调
    .build()?;
# Ok::<(), epay_sdk::Error>(())
```

回调策略同时约束配置默认值和请求级覆盖:未开启时,`FormPaymentRequest::notify_url("http://…")` 会在发送时被拒绝。回调携带签名后的支付结果,而协议没有防重放,明文传输意味着中间人可以读取并重放。生产环境应始终使用 HTTPS。

## 其它 Web 框架

```rust
# fn demo(protocol: &epay_sdk::ProtocolContext, query: Option<&str>, form_body: Option<&str>) -> epay_sdk::Result<()> {
let params = epay_sdk::parse_notify_params(query, form_body)?;
let data = protocol.verify_notify(&params)?;
# let _ = data;
# Ok(())
# }
```

调用方仍需先限制原始 HTTP 输入大小;也可以使用 `parse_raw_notify_params_with_limits`。回调必须同时接受 GET 和 POST。

## 多商户回调

一个服务代理多个易支付账户时,`VerifiedNotify`(绑定单个 `ProtocolContext`)不够用。用 `ParsedNotify`:它只做严格解析不验签,拒绝同样回 `200 fail`;账户从**路径**里来,用它加载对应的 `ProtocolContext` 再验签。绝不要根据未验证的 `pid` 去选密钥——那等于让攻击者指定用哪把钥验他的签名。

```rust
use axum::extract::{Path, State};
use epay_sdk::axum::{NotifyAck, ParsedNotify};
use epay_sdk::ProtocolContext;

# #[derive(Clone)] struct Accounts;
# impl Accounts { fn protocol_for(&self, _id: &str) -> Option<ProtocolContext> { None } }
async fn notify(
    State(accounts): State<Accounts>,
    Path(account_id): Path<String>,
    ParsedNotify(params): ParsedNotify,
) -> NotifyAck {
    let Some(epay) = accounts.protocol_for(&account_id) else {
        return NotifyAck::fail();
    };
    match epay.verify_notify(&params).and_then(|data| data.try_into_success()) {
        Ok(paid) => {
            let _ = paid; // 按 out_trade_no 幂等入账
            NotifyAck::ok()
        }
        Err(_) => NotifyAck::fail(),
    }
}
```

路由:`.route("/notify/{account_id}", callback_route(notify))`。

## 观察被拒绝的回调

`notify_url` 是公开端点,任何人都能向它发垃圾请求,所以 `VerifiedNotify` 对拒绝只记 `debug` 级日志,不会制造 warn 洪峰。需要计数、采样或告警时,把抽取器写成 `Result`,拒绝原因就交到 handler 手里(仍然返回 `fail`):

```rust
use epay_sdk::axum::{NotifyAck, NotifyRejection, VerifiedNotify};

async fn notify(result: Result<VerifiedNotify, NotifyRejection>) -> NotifyAck {
    match result {
        Ok(VerifiedNotify(data)) => {
            // 正常处理
            let _ = data;
            NotifyAck::ok()
        }
        Err(NotifyRejection(error)) => {
            // 在这里接入你的指标 / 采样日志;错误文本已脱敏
            metrics_counter("epay_notify_rejected", error.code());
            NotifyAck::fail()
        }
    }
}
# fn metrics_counter(_name: &str, _code: i32) {}
```

## 出站字段上限

下单和表单请求在本地校验长度,避免超长字段拼出异常大的 URL / 表单(常量在 `epay_sdk::limits`):

| 字段 | 上限 |
|---|---|
| `out_trade_no` | 64 字节,`[A-Za-z0-9._\|-]` |
| `name` | 255 字节 |
| `param` | 255 字节 |
| `sitename` | 64 字节 |
| `notify_url` / `return_url` | 1024 字节 |
| 自定义 `type` / `device` | 32 字节,`[A-Za-z0-9_-]` |
| 每个出站请求(query + form 编码后) | 4096 字节 |

`name` / `sitename` 另外拒绝控制字符。超限返回 `Error::Param`(如 `NAME_TOO_LONG`、`REQUEST_TOO_LARGE`)。总大小在 `Client` 的 GET / POST 路径上统一检查,所有端点(含查询、退款)都受约束;这些是保守值,官方 PHP 实现和数据库列都能容纳。

## 金额

```rust
assert!(epay_sdk::Money::from_yuan_str("9.999").is_err());
let exact = epay_sdk::Money::from_yuan_str("9.90")?;
let rounded = epay_sdk::Money::from_yuan_str_rounded("9.999")?;
assert_eq!(rounded.to_string(), "10.00");
assert_eq!(exact.try_to_fen()?, 990);
# Ok::<(), epay_sdk::Error>(())
```

只有显式带 `_rounded` 的 API 才会四舍五入。`try_to_fen()` 在超出 `i64` 范围时返回错误而不是饱和。核对回调金额请用 `NotifyData::money_matches(order.money)`,不要先把回调金额转成分再入账。`Money` 序列化为 `"9.90"` 字符串;反序列化只接受字符串和整数 JSON 数字,带小数的 JSON 数字会被拒绝(它到达时已经是 f64,无法证明精确)。

## 环境变量

```text
EPAY_PID=1001
EPAY_KEY=merchant-key
EPAY_API_URL=https://pay.example.com
EPAY_NOTIFY_URL=https://shop.example.com/notify
EPAY_RETURN_URL=https://shop.example.com/return
EPAY_DEBUG=false
EPAY_ALLOW_INSECURE_HTTP=false           # 允许 http:// 网关(旧部署)
EPAY_ALLOW_INSECURE_CALLBACK_HTTP=false  # 允许 http:// 回调地址(本地联调)
EPAY_TIMEOUT_SECS=30             # 仅 Client,per-attempt
EPAY_CONNECT_TIMEOUT_SECS=5      # 仅 Client,可选
EPAY_MAX_RESPONSE_BYTES=1048576  # 仅 Client
EPAY_MAX_RETRIES=0               # 仅 Client,GET 端点重试次数
```

`ProtocolContext::from_env` 读取前八项,`Client::from_env` 额外读取四项 HTTP 设置。非法数字或布尔值会在启动时失败,不会静默回退。

## 自定义 HTTP

```rust
use epay_sdk::{transport::BoxFuture, Error, Result, Transport, TransportErrorKind, TransportOptions, Url};

struct CustomTransport;

impl Transport for CustomTransport {
    fn get<'a>(
        &'a self,
        url: &'a Url,
        options: TransportOptions,
    ) -> BoxFuture<'a, Result<Vec<u8>>> {
        Box::pin(async move {
            let _ = (url, options.max_response_bytes, options.timeout);
            Err(Error::transport(TransportErrorKind::Other, "not implemented"))
        })
    }

    fn post_form<'a>(
        &'a self,
        url: &'a Url,
        form: &'a [(&'a str, &'a str)],
        options: TransportOptions,
    ) -> BoxFuture<'a, Result<Vec<u8>>> {
        Box::pin(async move {
            let _ = (url, form, options);
            Err(Error::transport(TransportErrorKind::Other, "not implemented"))
        })
    }

    fn sleep(&self, duration: std::time::Duration) -> BoxFuture<'_, ()> {
        Box::pin(tokio::time::sleep(duration))
    }
}
```

自定义 transport 必须边读边执行 `options.max_response_bytes`,尽量尊重 `options.timeout`(`CallOptions` 未设置时为 `HttpConfig` 的超时),用 `Error::transport` 构造传输错误、用 `Error::http(status, body)` 报告非 2xx 响应(会自动截断并脱敏 body)。`Error::transport` 只会遮盖 `key=` / `sign=` 片段,不会删除 URL,因此消息里不要放请求 URL(GET 请求的 URL 含商户密钥和订单号);`Client` 会在返回后再次检查长度并再次脱敏。

复用自定义 `reqwest::Client` 时,其 TLS 和重定向策略由调用方负责(SDK 不会替它关掉重定向);SDK 仍会逐请求应用超时、执行响应上限,并把 reqwest 错误分类成不含 URL 的固定消息。

## 测试回调

开启 `test-util` 后,`NotifyFixture` 一行生成签名正确的通知,配合 `tower::ServiceExt::oneshot` 就能测完整的回调链路:

```rust
use epay_sdk::test_util::NotifyFixture;
use epay_sdk::{Money, ProtocolContext};

# fn demo() -> epay_sdk::Result<()> {
let epay = ProtocolContext::new(1001, "testkey123", "https://pay.example.com")?;
let query = NotifyFixture::new(1001, "testkey123", "ORDER001", Money::from_yuan_str("9.90")?)
    .trade_no("T42")
    .query();
// GET /notify?{query}  → 期望 body "success"
// 篡改场景:直接改 query 验证拒绝路径,或用 unsigned_params() 改完再自己签
# let _ = (epay, query);
# Ok(())
# }
```

网关接口用 `MockTransport` 脚本化响应:`Client::builder(..).transport(MockTransport::new().push_json(r#"{"code":1,...}"#))`;`recorded()` 里的 `query` / `form` 是 `Params`,`Debug` 输出会脱敏 `key` / `sign`,用 `get()` 断言。

仓库自身的回归依赖两类附加测试:`tests/fixtures/*.json` 是脱敏后的真实分支响应(可空列、字符串数字、`data: null`、回显 key、退款 `code: 0` 等),遇到新分支的奇怪响应时把它脱敏后加进去即可;`tests/properties.rs` 用 proptest 对通知解析器、`Params` 编码 / 签名、`Money` 字符串和表单 HTML 转义做随机输入测试。

版本变更见 [CHANGELOG.md](../CHANGELOG.md)。