wxpay-rs 2.0.2

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
//! 证书下载器模块
//!
//! 提供从微信支付 API 下载平台证书的功能。

use async_trait::async_trait;
use std::sync::Arc;

use crate::auth::Signer;
use crate::cert::CertManager;
use crate::crypto::Aes256GcmCipher;
use crate::error::{WxPayError, WxPayResult};
use crate::http::HttpClient;
use crate::utils::nonce::generate_nonce;
use crate::utils::timestamp::get_timestamp;
use serde::Deserialize;

use base64::Engine;

#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
struct EncryptedCertificate {
    #[serde(default)]
    algorithm: String,

    #[serde(default)]
    associated_data: String,

    nonce: String,

    ciphertext: String,
}

#[derive(Debug, Clone, Deserialize)]
struct CertificateEntry {
    serial_no: String,

    #[serde(default)]
    _effective_time: Option<String>,

    #[serde(default)]
    _expire_time: Option<String>,

    #[serde(default)]
    certificate: Option<String>,

    #[serde(default)]
    encrypt_certificate: Option<EncryptedCertificate>,
}

/// 证书下载器 trait
///
/// 定义了下载平台证书的接口。
#[async_trait]
pub trait CertificateDownloader: Send + Sync {
    /// 下载平台证书
    ///
    /// # 返回
    ///
    /// 返回下载的证书列表(序列号 -> DER 格式)
    async fn download(&self) -> WxPayResult<Vec<(String, Vec<u8>)>>;
}

/// 微信支付证书下载器
///
/// 从微信支付 API 下载平台证书。
///
/// # 示例
///
/// ```rust,no_run
/// use std::sync::Arc;
///
/// use wxpay_rs::{
///     auth::{Signer, Sha256RsaSigner},
///     cert::{CertDownloader, CertManager},
///     cert::downloader::CertificateDownloader,
///     config::WxPayConfig,
///     http::ReqwestHttpClient,
/// };
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let _config = WxPayConfig::builder()
///         .app_id("wx88888888")
///         .merchant_id("1900000109")
///         .api_v3_key("abcdefghijklmnopqrstuvwxyz123456")
///         .private_key_from_file("path/to/private_key.pem")
///         .cert_serial_number("CERT123456")
///         .build()?;
///
///     let signer: Arc<dyn Signer> = Arc::new(Sha256RsaSigner::new(
///         "1900000109",
///         b"PRIVATE KEY",
///         "CERT123456",
///     )?);
///     let http_client = Arc::new(ReqwestHttpClient::builder().build()?);
///     let cert_manager = Arc::new(CertManager::new());
///
///     let downloader = CertDownloader::new(
///         "https://api.mch.weixin.qq.com",
///         "1900000109",
///         signer,
///         http_client,
///         cert_manager,
///     );
///
///     let certificates = downloader.download().await?;
///     let _ = certificates;
///     Ok(())
/// }
/// ```
pub struct CertDownloader {
    /// API 基础 URL
    base_url: String,

    /// 商户号
    merchant_id: String,

    /// 签名器
    signer: Arc<dyn Signer>,

    /// HTTP 客户端
    http_client: Arc<dyn HttpClient>,

    /// 证书管理器
    cert_manager: Arc<CertManager>,

    /// APIv3 秘钥
    api_v3_key: Option<String>,
}

impl CertDownloader {
    /// 创建新的证书下载器
    ///
    /// # 参数
    ///
    /// * `base_url` - API 基础 URL
    /// * `merchant_id` - 商户号
    /// * `signer` - 签名器
    /// * `http_client` - HTTP 客户端
    /// * `cert_manager` - 证书管理器
    ///
    /// # 返回
    ///
    /// 返回证书下载器实例
    pub fn new(
        base_url: impl Into<String>,
        merchant_id: impl Into<String>,
        signer: Arc<dyn Signer>,
        http_client: Arc<dyn HttpClient>,
        cert_manager: Arc<CertManager>,
    ) -> Self {
        Self {
            base_url: base_url.into(),
            merchant_id: merchant_id.into(),
            signer,
            http_client,
            cert_manager,
            api_v3_key: None,
        }
    }

    /// 配置 APIv3 密钥(用于解密加密证书)
    pub fn with_api_v3_key(mut self, api_v3_key: impl Into<String>) -> Self {
        self.api_v3_key = Some(api_v3_key.into());
        self
    }

    /// 构建下载证书的请求 URL
    fn build_url(&self) -> String {
        format!("{}/v3/certificates", self.base_url)
    }

    /// 构建请求头
    async fn build_headers(&self) -> WxPayResult<Vec<(String, String)>> {
        let timestamp = get_timestamp();
        let nonce = generate_nonce();
        let url = "/v3/certificates";
        let body = "";

        // 构建签名消息
        let message = format!("GET\n{}\n{}\n{}\n{}\n", url, timestamp, nonce, body);

        // 生成签名
        let signature = self.signer.sign(&message).await?;

        // 构建 Authorization header
        let authorization = format!(
            r#"WECHATPAY2-SHA256-RSA2048 mchid="{}",nonce_str="{}",timestamp="{}",serial_no="{}",signature="{}"#,
            self.merchant_id,
            nonce,
            timestamp,
            self.signer.cert_serial_number(),
            signature
        );

        Ok(vec![
            ("Authorization".to_string(), authorization),
            ("Accept".to_string(), "application/json".to_string()),
            ("User-Agent".to_string(), "wxpay-rs/0.1.0".to_string()),
        ])
    }
}

#[async_trait]
impl CertificateDownloader for CertDownloader {
    async fn download(&self) -> WxPayResult<Vec<(String, Vec<u8>)>> {
        let url = self.build_url();
        let headers = self.build_headers().await?;

        // 发送请求
        let response = self.http_client.get(&url, headers).await?;

        // 检查响应状态
        if !response.is_success() {
            return Err(WxPayError::CertificateDownloadError(format!(
                "下载证书失败,HTTP 状态码: {}",
                response.status
            )));
        }

        // 解析响应
        let body = &response.body;

        let response: serde_json::Value = serde_json::from_str(body)?;
        let mut items: Vec<CertificateEntry> =
            serde_json::from_value(response.clone()).or_else(|_| {
                response
                    .get("data")
                    .cloned()
                    .and_then(|v| serde_json::from_value(v).ok())
                    .ok_or_else(|| {
                        WxPayError::CertificateParseError("证书响应解析失败".to_string())
                    })
            })?;

        if items.is_empty()
            && let Some(certs) = response.get("data").and_then(|v| v.as_array())
        {
            items = certs
                .iter()
                .filter_map(|item| serde_json::from_value::<CertificateEntry>(item.clone()).ok())
                .collect();
        }

        let mut result = Vec::new();

        for item in items {
            let serial = item.serial_no.clone();
            let cert_der = if let Some(cert_data) = item.certificate {
                decode_certificate_der(&cert_data)?
            } else if let Some(encrypted) = item.encrypt_certificate {
                let cipher =
                    Aes256GcmCipher::new(self.api_v3_key.as_deref().ok_or_else(|| {
                        WxPayError::CertificateParseError("加密证书缺少 API v3 Key".to_string())
                    })?)?;

                let plaintext = cipher.decrypt_notification(
                    &encrypted.nonce,
                    &encrypted.ciphertext,
                    &encrypted.associated_data,
                )?;

                decode_certificate_der(&plaintext)?
            } else {
                return Err(WxPayError::CertificateParseError(format!(
                    "证书 {} 无 certificate/ encrypt_certificate 字段",
                    item.serial_no
                )));
            };

            self.cert_manager
                .add_certificate(serial.to_string(), cert_der.clone())
                .await?;

            result.push((serial.to_string(), cert_der));
        }

        Ok(result)
    }
}

fn decode_certificate_der(certificate_data: &str) -> WxPayResult<Vec<u8>> {
    let trimmed = certificate_data.trim();

    if trimmed.contains("BEGIN CERTIFICATE") {
        let body = trimmed
            .lines()
            .filter(|line| !line.starts_with("-----"))
            .collect::<String>();

        return base64::engine::general_purpose::STANDARD
            .decode(body)
            .map_err(|e| WxPayError::CertificateParseError(format!("证书 PEM 解码失败:{}", e)));
    }

    base64::engine::general_purpose::STANDARD
        .decode(trimmed)
        .map_err(|e| WxPayError::CertificateParseError(format!("证书 Base64 解码失败: {}", e)))
}

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

/// 证书自动刷新器
///
/// 定期刷新平台证书。
pub struct CertRefresher {
    /// 证书下载器
    downloader: Arc<CertDownloader>,

    /// 刷新间隔(秒)
    interval: u64,
}

impl CertRefresher {
    /// 创建新的证书刷新器
    ///
    /// # 参数
    ///
    /// * `downloader` - 证书下载器
    /// * `interval` - 刷新间隔(秒)
    ///
    /// # 返回
    ///
    /// 返回证书刷新器实例
    pub fn new(downloader: Arc<CertDownloader>, interval: u64) -> Self {
        Self {
            downloader,
            interval,
        }
    }

    /// 启动自动刷新
    ///
    /// 在后台任务中定期刷新证书。
    pub fn start_auto_refresh(&self) {
        let downloader = self.downloader.clone();
        let interval = self.interval;

        tokio::spawn(async move {
            loop {
                // 等待指定间隔
                tokio::time::sleep(tokio::time::Duration::from_secs(interval)).await;

                // 下载证书
                match downloader.download().await {
                    Ok(certificates) => {
                        tracing::info!("成功刷新 {} 个证书", certificates.len());
                    }
                    Err(e) => {
                        tracing::error!("刷新证书失败: {}", e);
                    }
                }
            }
        });
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_certificate_der_plain_base64() {
        // 纯 base64(无 PEM 头)输入应直接解码。
        let original = vec![0x30u8, 0x82, 0x01, 0x23, 0xAB, 0xCD];
        let b64 = base64::engine::general_purpose::STANDARD.encode(&original);

        let decoded = decode_certificate_der(&b64).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_decode_certificate_der_pem_form() {
        // PEM 形式(带 BEGIN/END CERTIFICATE)应剥离头尾行后再解码。
        let original = vec![0xAAu8, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
        let b64 = base64::engine::general_purpose::STANDARD.encode(&original);
        let pem = format!("-----BEGIN CERTIFICATE-----\n{b64}\n-----END CERTIFICATE-----");

        let decoded = decode_certificate_der(&pem).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_decode_certificate_der_rejects_invalid() {
        // 非法 base64 应返回解析错误。
        let result = decode_certificate_der("!!!not-base64!!!");
        assert!(matches!(result, Err(WxPayError::CertificateParseError(_))));
    }

    #[test]
    fn test_decode_certificate_der_handles_whitespace() {
        // 前后空白应被 trim,仍可正确解码。
        let original = vec![0x01u8, 0x02, 0x03];
        let b64 = base64::engine::general_purpose::STANDARD.encode(&original);

        let decoded = decode_certificate_der(&format!("  {b64}  ")).unwrap();
        assert_eq!(decoded, original);
    }
}