wxpay-rs 2.0.1

WeChat Pay API v3 Rust SDK
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! 通知处理器模块
//!
//! 提供处理微信支付回调通知的功能。

use serde::{Deserialize, Serialize};
use std::sync::Arc;

use crate::auth::Verifier;
use crate::config::NotifyConfig;
use crate::crypto::Aes256GcmCipher;
use crate::error::{WxPayError, WxPayResult};

/// 通知请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotifyRequest {
    /// 通知 ID
    pub id: String,

    /// 通知创建时间
    pub create_time: String,

    /// 通知类型
    #[serde(rename = "type")]
    pub notify_type: String,

    /// 通知数据
    pub resource: NotifyResource,
}

/// 通知资源
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotifyResource {
    /// 加密算法
    pub algorithm: String,

    /// 密文
    pub ciphertext: String,

    /// 附加数据
    pub associated_data: Option<String>,

    /// 随机串
    pub nonce: String,
}

/// 支付通知数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentNotifyData {
    /// 应用 ID
    pub appid: String,

    /// 商户号
    pub mchid: String,

    /// 商户订单号
    pub out_trade_no: String,

    /// 微信支付订单号
    pub transaction_id: String,

    /// 交易类型
    pub trade_type: String,

    /// 交易状态
    pub trade_state: String,

    /// 交易状态描述
    pub trade_state_desc: String,

    /// 付款银行
    pub bank_type: String,

    /// 附加数据
    pub attach: Option<String>,

    /// 支付完成时间
    pub success_time: String,

    /// 支付者
    pub payer: Option<NotifyPayer>,

    /// 订单金额
    pub amount: Option<NotifyAmount>,
}

/// 通知支付者
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotifyPayer {
    /// 用户标识
    pub openid: String,
}

/// 通知金额
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotifyAmount {
    /// 总金额
    pub total: u64,

    /// 用户支付金额
    pub payer_total: Option<u64>,

    /// 货币类型
    pub currency: String,

    /// 用户支付币种
    pub payer_currency: Option<String>,
}

/// 退款通知数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundNotifyData {
    /// 商户号
    pub mchid: String,

    /// 商户订单号
    pub out_trade_no: String,

    /// 微信支付订单号
    pub transaction_id: String,

    /// 商户退款单号
    pub out_refund_no: String,

    /// 微信退款单号
    pub refund_id: String,

    /// 退款状态
    pub refund_status: String,

    /// 退款成功时间
    pub success_time: Option<String>,

    /// 退款金额
    pub amount: Option<RefundNotifyAmount>,
}

/// 退款通知金额
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundNotifyAmount {
    /// 退款金额
    pub total: u64,

    /// 退款金额
    pub refund: u64,

    /// 用户支付金额
    pub payer_total: u64,

    /// 用户退款金额
    pub payer_refund: u64,
}

/// 通知处理器
///
/// 用于处理微信支付回调通知。
///
/// # 示例
///
/// ```rust,no_run
/// use std::sync::Arc;
///
/// use wxpay_rs::{
///     auth::{Sha256RsaVerifier, Verifier},
///     config::NotifyConfig,
///     notify::NotifyHandler,
/// };
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let config = NotifyConfig {
///         api_v3_key: "abcdefghijklmnopqrstuvwxyz123456".to_string(),
///         cert_serial_number: "CERT123456".to_string(),
///         platform_certificate: vec![],
///     };
///     let verifier = Sha256RsaVerifier::new(vec![b"dummy certificate".to_vec()])?;
///     let verifier: Arc<dyn Verifier> = Arc::new(verifier);
///     let handler = NotifyHandler::new(config, verifier)?;
///
///     let _ = handler;
///     Ok(())
/// }
/// ```
pub struct NotifyHandler {
    /// 通知配置
    config: NotifyConfig,

    /// 验签器
    verifier: Arc<dyn Verifier>,

    /// AES 加密器
    cipher: Aes256GcmCipher,
}

impl NotifyHandler {
    /// 创建新的通知处理器
    pub fn new(config: NotifyConfig, verifier: Arc<dyn Verifier>) -> WxPayResult<Self> {
        let cipher = Aes256GcmCipher::new(&config.api_v3_key)?;
        Ok(Self {
            config,
            verifier,
            cipher,
        })
    }

    /// 处理支付通知
    pub async fn handle_payment_notify(
        &self,
        request: &NotifyRequest,
    ) -> WxPayResult<PaymentNotifyData> {
        // 验证通知类型
        if request.notify_type != "TRANSACTION.SUCCESS" {
            return Err(WxPayError::InvalidNotifyType(request.notify_type.clone()));
        }

        // 解密通知数据
        let data = self.decrypt_notify_data(request)?;

        // 解析支付数据
        let payment_data: PaymentNotifyData = serde_json::from_str(&data)?;

        Ok(payment_data)
    }

    /// 处理退款通知
    pub async fn handle_refund_notify(
        &self,
        request: &NotifyRequest,
    ) -> WxPayResult<RefundNotifyData> {
        // 验证通知类型
        if request.notify_type != "REFUND.SUCCESS" {
            return Err(WxPayError::InvalidNotifyType(request.notify_type.clone()));
        }

        // 解密通知数据
        let data = self.decrypt_notify_data(request)?;

        // 解析退款数据
        let refund_data: RefundNotifyData = serde_json::from_str(&data)?;

        Ok(refund_data)
    }

    /// 解密通知数据
    fn decrypt_notify_data(&self, request: &NotifyRequest) -> WxPayResult<String> {
        let resource = &request.resource;

        match resource.algorithm.as_str() {
            "AEAD_AES_256_GCM" => {
                let associated_data = resource.associated_data.as_deref().unwrap_or("");
                self.cipher.decrypt_notification(
                    &resource.nonce,
                    &resource.ciphertext,
                    associated_data,
                )
            }
            _ => Err(WxPayError::DecryptionError(format!(
                "不支持的加密算法: {}",
                resource.algorithm
            ))),
        }
    }

    /// 验证通知签名
    pub async fn verify_notify_signature(
        &self,
        timestamp: &str,
        nonce: &str,
        body: &str,
        signature: &str,
    ) -> WxPayResult<bool> {
        // 构建验签消息
        let message = format!("{}\n{}\n{}\n", timestamp, nonce, body);

        // 验证签名
        self.verifier.verify(&message, signature).await
    }

    /// 验证通知时间戳
    pub fn verify_timestamp(&self, timestamp: &str, tolerance_seconds: i64) -> WxPayResult<bool> {
        let timestamp: i64 = timestamp
            .parse()
            .map_err(|e| WxPayError::InvalidNotifyFormat(format!("无效的时间戳: {}", e)))?;

        Ok(crate::utils::timestamp::is_timestamp_valid(
            timestamp,
            tolerance_seconds,
        ))
    }
}

impl std::fmt::Debug for NotifyHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NotifyHandler")
            .field("config", &self.config)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::Sha256RsaVerifier;
    use aes_gcm::{Aes256Gcm, KeyInit, Nonce, aead::Aead};
    use base64::Engine;
    use std::sync::Arc;

    const API_V3_KEY: &str = "abcdefghijklmnopqrstuvwxyz123456";

    fn test_handler() -> NotifyHandler {
        // verifier 仅用于满足构造签名,验签逻辑由专门测试覆盖;这里传一个真实 DER 解析会失败,
        // 因此用一个最小可用的“空证书列表” verifier(Sha256RsaVerifier::new(vec![]) 可成功构造)。
        let verifier: Arc<dyn Verifier> = Arc::new(Sha256RsaVerifier::new(vec![]).unwrap());
        let config = NotifyConfig {
            api_v3_key: API_V3_KEY.to_string(),
            cert_serial_number: "CERT123456".to_string(),
            platform_certificate: vec![],
        };
        NotifyHandler::new(config, verifier).unwrap()
    }

    /// 用真实 AES-256-GCM 加密一段支付通知明文,返回可被 NotifyRequest 引用的字段值。
    fn encrypt_resource(plaintext: &str, associated_data: &str, nonce: &str) -> (String, String) {
        let mut hasher = sha2::Sha256::new();
        use sha2::Digest;
        hasher.update(API_V3_KEY.as_bytes());
        let key = hasher.finalize();
        let cipher = Aes256Gcm::new_from_slice(&key).unwrap();
        let nonce_bytes: [u8; 12] = nonce.as_bytes().try_into().unwrap();
        let nonce_value = Nonce::from(nonce_bytes);
        let ct = cipher
            .encrypt(
                &nonce_value,
                aes_gcm::aead::Payload {
                    msg: plaintext.as_bytes(),
                    aad: associated_data.as_bytes(),
                },
            )
            .unwrap();
        let ciphertext_b64 = base64::engine::general_purpose::STANDARD.encode(ct);
        // 返回原始 nonce 字符串(与微信通知一致,明文 nonce)。
        (ciphertext_b64, nonce.to_string())
    }

    fn make_request(
        notify_type: &str,
        algorithm: &str,
        ciphertext: &str,
        nonce: &str,
        associated_data: &str,
    ) -> NotifyRequest {
        NotifyRequest {
            id: "EV-TEST".to_string(),
            create_time: "2024-01-01T00:00:00+08:00".to_string(),
            notify_type: notify_type.to_string(),
            resource: NotifyResource {
                algorithm: algorithm.to_string(),
                ciphertext: ciphertext.to_string(),
                associated_data: Some(associated_data.to_string()),
                nonce: nonce.to_string(),
            },
        }
    }

    #[test]
    fn test_notify_request_deserialization() {
        let json = r#"{
            "id": "EV-2018022511223320873",
            "create_time": "2015-05-20T13:29:35+08:00",
            "type": "TRANSACTION.SUCCESS",
            "resource": {
                "algorithm": "AEAD_AES_256_GCM",
                "ciphertext": "...",
                "associated_data": "transaction",
                "nonce": "..."
            }
        }"#;

        let request: NotifyRequest = serde_json::from_str(json).unwrap();
        assert_eq!(request.id, "EV-2018022511223320873");
        assert_eq!(request.notify_type, "TRANSACTION.SUCCESS");
        assert_eq!(request.resource.algorithm, "AEAD_AES_256_GCM");
    }

    #[test]
    fn test_payment_notify_data_deserialization() {
        let json = r#"{
            "appid": "wx88888888",
            "mchid": "1900000109",
            "out_trade_no": "test_trade_no",
            "transaction_id": "1217752501201407033233368018",
            "trade_type": "JSAPI",
            "trade_state": "SUCCESS",
            "trade_state_desc": "支付成功",
            "bank_type": "CMB_CREDIT",
            "success_time": "2018-06-08T10:34:56+08:00"
        }"#;

        let data: PaymentNotifyData = serde_json::from_str(json).unwrap();
        assert_eq!(data.trade_state, "SUCCESS");
        assert_eq!(data.transaction_id, "1217752501201407033233368018");
    }

    #[tokio::test]
    async fn test_handle_payment_notify_decrypts_and_parses() {
        let handler = test_handler();

        let plaintext = r#"{
            "appid": "wx88888888",
            "mchid": "1900000109",
            "out_trade_no": "out_20240101",
            "transaction_id": "4200000001",
            "trade_type": "JSAPI",
            "trade_state": "SUCCESS",
            "trade_state_desc": "支付成功",
            "bank_type": "CMB_CREDIT",
            "success_time": "2024-01-01T00:00:00+08:00"
        }"#;
        let nonce = "nonce1234567"; // 12 字节
        let (ciphertext, nonce) = encrypt_resource(plaintext, "transaction", nonce);

        let request = make_request(
            "TRANSACTION.SUCCESS",
            "AEAD_AES_256_GCM",
            &ciphertext,
            &nonce,
            "transaction",
        );
        let data = handler.handle_payment_notify(&request).await.unwrap();

        assert_eq!(data.out_trade_no, "out_20240101");
        assert_eq!(data.transaction_id, "4200000001");
        assert_eq!(data.trade_state, "SUCCESS");
    }

    #[tokio::test]
    async fn test_handle_refund_notify_decrypts_and_parses() {
        let handler = test_handler();

        let plaintext = r#"{
            "mchid": "1900000109",
            "out_trade_no": "out_20240101",
            "transaction_id": "4200000001",
            "out_refund_no": "refund_001",
            "refund_id": "5000000038",
            "refund_status": "SUCCESS"
        }"#;
        let nonce = "refundnonce1"; // 12 字节
        let (ciphertext, nonce) = encrypt_resource(plaintext, "refund", nonce);

        let request = make_request(
            "REFUND.SUCCESS",
            "AEAD_AES_256_GCM",
            &ciphertext,
            &nonce,
            "refund",
        );
        let data = handler.handle_refund_notify(&request).await.unwrap();

        assert_eq!(data.out_refund_no, "refund_001");
        assert_eq!(data.refund_id, "5000000038");
        assert_eq!(data.refund_status, "SUCCESS");
    }

    #[tokio::test]
    async fn test_handle_payment_notify_rejects_wrong_type() {
        let handler = test_handler();
        let request = make_request(
            "REFUND.SUCCESS",
            "AEAD_AES_256_GCM",
            "x",
            "n",
            "transaction",
        );
        let err = handler.handle_payment_notify(&request).await.unwrap_err();
        assert!(matches!(err, WxPayError::InvalidNotifyType(_)));
    }

    #[tokio::test]
    async fn test_handle_notify_rejects_unsupported_algorithm() {
        let handler = test_handler();
        let request = make_request("TRANSACTION.SUCCESS", "RSA-OAEP", "x", "n", "transaction");
        let err = handler.handle_payment_notify(&request).await.unwrap_err();
        assert!(matches!(err, WxPayError::DecryptionError(_)));
    }

    #[tokio::test]
    async fn test_handle_payment_notify_rejects_tampered_ciphertext() {
        let handler = test_handler();
        let nonce = "nonce1234567";
        let (ciphertext, nonce) = encrypt_resource("{}", "transaction", nonce);

        // 篡改密文:base64 解码后翻转首字节再重新编码,保证 base64 仍合法但 GCM 认证失败。
        let mut bytes = base64::engine::general_purpose::STANDARD
            .decode(&ciphertext)
            .unwrap();
        bytes[0] ^= 0xff;
        let tampered = base64::engine::general_purpose::STANDARD.encode(&bytes);

        let request = make_request(
            "TRANSACTION.SUCCESS",
            "AEAD_AES_256_GCM",
            &tampered,
            &nonce,
            "transaction",
        );
        let err = handler.handle_payment_notify(&request).await.unwrap_err();
        assert!(matches!(err, WxPayError::DecryptionError(_)));
    }

    #[tokio::test]
    async fn test_verify_notify_signature_delegates_to_verifier() {
        // 空 verifier 的 verify 会返回错误;这里仅验证签名校验入口正确委托给 verifier。
        let handler = test_handler();
        let result = handler
            .verify_notify_signature("ts", "nonce", "body", "sig")
            .await;
        assert!(result.is_err());
    }

    #[test]
    fn test_verify_timestamp_validity() {
        let handler = test_handler();
        let now = crate::utils::timestamp::get_timestamp();

        // 当前时间戳在 300s 容差内有效。
        let valid = handler.verify_timestamp(&now.to_string(), 300).unwrap();
        assert!(valid);

        // 远古时间戳无效。
        let invalid = handler.verify_timestamp("0", 300).unwrap();
        assert!(!invalid);

        // 非法时间戳字符串应报错。
        let bad = handler.verify_timestamp("not-a-number", 300);
        assert!(bad.is_err());
    }

    #[test]
    fn test_new_rejects_invalid_api_v3_key() {
        let verifier: Arc<dyn Verifier> = Arc::new(Sha256RsaVerifier::new(vec![]).unwrap());
        let config = NotifyConfig {
            api_v3_key: "too-short".to_string(),
            cert_serial_number: "CERT".to_string(),
            platform_certificate: vec![],
        };
        let result = NotifyHandler::new(config, verifier);
        assert!(matches!(result, Err(WxPayError::InvalidKey(_))));
    }
}