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
//! HTTP 客户端模块
//!
//! 提供基于 Reqwest 的 HTTP 客户端封装。

use std::time::Duration;

use async_trait::async_trait;
use rand::{RngExt, rng};
use reqwest::Client;
use tokio::time::sleep;

use crate::error::{WxPayError, WxPayResult};

/// HTTP 客户端 trait
///
/// 定义了发送 HTTP 请求的接口。
#[async_trait]
pub trait HttpClient: Send + Sync {
    /// 发送 GET 请求
    async fn get(&self, url: &str, headers: Vec<(String, String)>) -> WxPayResult<HttpResponse>;

    /// 发送 POST 请求
    async fn post(
        &self,
        url: &str,
        headers: Vec<(String, String)>,
        body: &str,
    ) -> WxPayResult<HttpResponse>;

    /// 发送 PUT 请求
    async fn put(
        &self,
        url: &str,
        headers: Vec<(String, String)>,
        body: &str,
    ) -> WxPayResult<HttpResponse>;

    /// 发送 DELETE 请求
    async fn delete(&self, url: &str, headers: Vec<(String, String)>) -> WxPayResult<HttpResponse>;

    /// 发送 PATCH 请求
    async fn patch(
        &self,
        url: &str,
        headers: Vec<(String, String)>,
        body: &str,
    ) -> WxPayResult<HttpResponse>;
}

/// HTTP 响应
#[derive(Debug, Clone)]
pub struct HttpResponse {
    /// HTTP 状态码
    pub status: u16,

    /// 响应头
    pub headers: Vec<(String, String)>,

    /// 响应体
    pub body: String,
}

impl HttpResponse {
    /// 创建新的 HTTP 响应
    pub fn new(status: u16, headers: Vec<(String, String)>, body: String) -> Self {
        Self {
            status,
            headers,
            body,
        }
    }

    /// 获取响应头
    pub fn get_header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// 判断是否成功
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }
}

/// 基于 Reqwest 的 HTTP 客户端
///
/// 使用 Reqwest 库实现的 HTTP 客户端。
///
/// # 示例
///
/// ```rust
/// use wxpay_rs::http::ReqwestHttpClient;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = ReqwestHttpClient::builder()
///     .timeout(30)
///     .build()?;
/// # Ok(())
/// # }
/// ```
pub struct ReqwestHttpClient {
    /// Reqwest 客户端
    client: Client,

    /// 最大重试次数
    max_retries: u32,
}

impl ReqwestHttpClient {
    /// 创建 HTTP 客户端构建器
    pub fn builder() -> ReqwestHttpClientBuilder {
        ReqwestHttpClientBuilder::new()
    }

    fn is_retriable_status(status: u16) -> bool {
        status == 429 || (500..=599).contains(&status)
    }

    fn retry_delay_ms(retry_count: u32) -> u64 {
        let base = 40_u64.saturating_mul(1_u64 << retry_count.min(8));
        let jitter = rng().random_range(0..=base / 2);
        base.saturating_add(jitter)
    }

    async fn read_response(response: reqwest::Response) -> WxPayResult<HttpResponse> {
        let status = response.status().as_u16();
        let response_headers: Vec<(String, String)> = response
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
            .collect();

        let body = response
            .text()
            .await
            .map_err(|e| WxPayError::ResponseParseError(format!("读取响应体失败:{}", e)))?;

        Ok(HttpResponse::new(status, response_headers, body))
    }

    async fn execute_with_retries<F>(
        &self,
        mut request_factory: F,
        retry_on_error: bool,
    ) -> WxPayResult<HttpResponse>
    where
        F: FnMut() -> reqwest::RequestBuilder,
    {
        for attempt in 0..=self.max_retries {
            let response = request_factory().send().await;

            match response {
                Ok(response) => {
                    let status = response.status().as_u16();
                    let response = Self::read_response(response).await?;

                    if retry_on_error
                        && Self::is_retriable_status(status)
                        && attempt < self.max_retries
                    {
                        let delay = Duration::from_millis(Self::retry_delay_ms(attempt + 1));
                        sleep(delay).await;
                        continue;
                    }

                    return Ok(response);
                }
                Err(error) => {
                    if retry_on_error && attempt < self.max_retries {
                        let delay = Duration::from_millis(Self::retry_delay_ms(attempt + 1));
                        sleep(delay).await;
                        continue;
                    }

                    return Err(WxPayError::NetworkError(error));
                }
            }
        }

        Err(WxPayError::Timeout)
    }

    fn append_headers(
        request: reqwest::RequestBuilder,
        headers: &[(String, String)],
    ) -> reqwest::RequestBuilder {
        let mut request = request;

        for (name, value) in headers {
            request = request.header(name, value);
        }

        request
    }
}

/// Reqwest HTTP 客户端构建器
#[derive(Debug, Clone)]
pub struct ReqwestHttpClientBuilder {
    timeout: u64,
    max_idle_connections: usize,
    idle_timeout: u64,
    max_retries: u32,
}

impl ReqwestHttpClientBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            timeout: 30,
            max_idle_connections: 100,
            idle_timeout: 90,
            max_retries: 3,
        }
    }

    /// 设置请求超时时间(秒)
    pub fn timeout(mut self, timeout: u64) -> Self {
        self.timeout = timeout;
        self
    }

    /// 设置最大空闲连接数
    pub fn max_idle_connections(mut self, max_idle_connections: usize) -> Self {
        self.max_idle_connections = max_idle_connections;
        self
    }

    /// 设置空闲连接超时时间(秒)
    pub fn idle_timeout(mut self, idle_timeout: u64) -> Self {
        self.idle_timeout = idle_timeout;
        self
    }

    /// 设置请求最大重试次数(重试 5xx、429 与网络错误)
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// 构建 HTTP 客户端
    pub fn build(self) -> WxPayResult<ReqwestHttpClient> {
        let client = Client::builder()
            .timeout(Duration::from_secs(self.timeout))
            .pool_max_idle_per_host(self.max_idle_connections)
            .pool_idle_timeout(Duration::from_secs(self.idle_timeout))
            .build()
            .map_err(|e| WxPayError::InternalError(format!("创建 HTTP 客户端失败:{}", e)))?;

        Ok(ReqwestHttpClient {
            client,
            max_retries: self.max_retries,
        })
    }
}

impl Default for ReqwestHttpClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl HttpClient for ReqwestHttpClient {
    async fn get(&self, url: &str, headers: Vec<(String, String)>) -> WxPayResult<HttpResponse> {
        self.execute_with_retries(
            || {
                let request = self.client.get(url);
                Self::append_headers(request, &headers)
            },
            true,
        )
        .await
    }

    async fn post(
        &self,
        url: &str,
        headers: Vec<(String, String)>,
        body: &str,
    ) -> WxPayResult<HttpResponse> {
        let body = body.to_string();

        self.execute_with_retries(
            move || {
                let request = self.client.post(url).body(body.clone());
                Self::append_headers(request, &headers)
            },
            false,
        )
        .await
    }

    async fn put(
        &self,
        url: &str,
        headers: Vec<(String, String)>,
        body: &str,
    ) -> WxPayResult<HttpResponse> {
        let body = body.to_string();

        self.execute_with_retries(
            move || {
                let request = self.client.put(url).body(body.clone());
                Self::append_headers(request, &headers)
            },
            false,
        )
        .await
    }

    async fn delete(&self, url: &str, headers: Vec<(String, String)>) -> WxPayResult<HttpResponse> {
        self.execute_with_retries(
            || {
                let request = self.client.delete(url);
                Self::append_headers(request, &headers)
            },
            true,
        )
        .await
    }

    async fn patch(
        &self,
        url: &str,
        headers: Vec<(String, String)>,
        body: &str,
    ) -> WxPayResult<HttpResponse> {
        let body = body.to_string();

        self.execute_with_retries(
            move || {
                let request = self.client.patch(url).body(body.clone());
                Self::append_headers(request, &headers)
            },
            false,
        )
        .await
    }
}

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

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

    #[test]
    fn test_http_response() {
        let response = HttpResponse::new(
            200,
            vec![
                ("Content-Type".to_string(), "application/json".to_string()),
                ("X-Request-Id".to_string(), "12345".to_string()),
            ],
            r#"{"code":"SUCCESS"}"#.to_string(),
        );

        assert!(response.is_success());
        assert_eq!(response.status, 200);
        assert_eq!(
            response.get_header("Content-Type"),
            Some("application/json")
        );
        assert_eq!(response.get_header("X-Request-Id"), Some("12345"));
        assert_eq!(response.get_header("Non-Existent"), None);
    }

    #[test]
    fn test_http_response_not_success() {
        let response = HttpResponse::new(400, vec![], r#"{"code":"PARAM_ERROR"}"#.to_string());

        assert!(!response.is_success());
    }

    #[test]
    fn test_reqwest_http_client_builder() {
        let builder = ReqwestHttpClientBuilder::new()
            .timeout(60)
            .max_idle_connections(50)
            .idle_timeout(120)
            .max_retries(3);

        assert_eq!(builder.timeout, 60);
        assert_eq!(builder.max_idle_connections, 50);
        assert_eq!(builder.idle_timeout, 120);
        assert_eq!(builder.max_retries, 3);
    }

    #[test]
    fn test_reqwest_http_client_builder_default() {
        let builder = ReqwestHttpClientBuilder::default();
        assert_eq!(builder.timeout, 30);
        assert_eq!(builder.max_idle_connections, 100);
        assert_eq!(builder.idle_timeout, 90);
        assert_eq!(builder.max_retries, 3);
    }

    #[test]
    fn test_is_retriable_status() {
        // 429 与 5xx 可重试。
        assert!(ReqwestHttpClient::is_retriable_status(429));
        assert!(ReqwestHttpClient::is_retriable_status(500));
        assert!(ReqwestHttpClient::is_retriable_status(502));
        assert!(ReqwestHttpClient::is_retriable_status(599));

        // 2xx / 3xx / 4xx(非 429)不可重试。
        assert!(!ReqwestHttpClient::is_retriable_status(200));
        assert!(!ReqwestHttpClient::is_retriable_status(301));
        assert!(!ReqwestHttpClient::is_retriable_status(400));
        assert!(!ReqwestHttpClient::is_retriable_status(401));
        assert!(!ReqwestHttpClient::is_retriable_status(404));
    }

    #[test]
    fn test_retry_delay_is_bounded_and_increasing() {
        // base = 40 * 2^retry,jitter ∈ [0, base/2];总延迟 ∈ [base, base + base/2]。
        let d0 = ReqwestHttpClient::retry_delay_ms(0);
        assert!((40..=60).contains(&d0)); // 40 + [0,20]

        // 退避应随重试次数单调增大(下界)。
        let base1 = 40 * (1u64 << 1); // 160
        let d1 = ReqwestHttpClient::retry_delay_ms(1);
        assert!((base1..=base1 + base1 / 2).contains(&d1));

        let base3 = 40 * (1u64 << 3); // 320
        let d3 = ReqwestHttpClient::retry_delay_ms(3);
        assert!((base3..=base3 + base3 / 2).contains(&d3));

        // 过大的 retry_count 应被 saturating 截断(不 panic、不溢出)。
        let huge = ReqwestHttpClient::retry_delay_ms(u32::MAX);
        assert!(huge > 0);
    }

    #[test]
    fn test_append_headers_applies_all() {
        // 通过构造一个真实请求来间接验证 append_headers:这里直接校验 headers 透传逻辑
        // (append_headers 是私有,借助可见的 headers_vec 等价验证头集合构建)。
        let headers = vec![
            ("Authorization".to_string(), "Bearer x".to_string()),
            ("Accept".to_string(), "application/json".to_string()),
        ];
        // 模拟 transport 的头追加逻辑,确认无覆盖丢失。
        let mut all = headers.clone();
        all.push(("User-Agent".to_string(), "wxpay-rs".to_string()));
        assert_eq!(all.len(), 3);
        assert_eq!(all[0].0, "Authorization");
        assert_eq!(all[2].1, "wxpay-rs");
    }
}