rust_pay_wf 0.5.2

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
use std::collections::HashMap;
use crate::config::{Mode, WechatConfig};
use crate::errors::PayError;
use crate::utils::{gen_nonce, now_ts, rsa_sign_sha256_pem};
use crate::wechat::certs::PlatformCerts;
use reqwest::Client;
use serde_json::{json, Value};
use std::sync::Arc;
use url::Url;
use crate::wechat::notify::WechatNotify;

pub struct WechatClient {
    cfg: Arc<WechatConfig>,
    http: Client,
    certs: Arc<PlatformCerts>,
    base_url: String,
    mode: Mode,
    max_retries: usize,
}

impl WechatClient {
    pub fn with_mode(cfg: Arc<WechatConfig>, mode: Mode) -> Self {
        let http = Client::builder()
            .user_agent("rust_pay_wf")
            .build()
            .expect("client");
        let certs = Arc::new(PlatformCerts::new(cfg.clone()));

        // 根据模式设置基础URL
        let base_url = match mode {
            Mode::Sandbox => "https://api.mch.weixin.qq.com/sandboxnew".to_string(),
            _ => "https://api.mch.weixin.qq.com".to_string(),
        };

        Self {
            cfg,
            http,
            certs,
            base_url,
            mode,
            max_retries: 3,
        }
    }

    fn endpoint(&self, path: &str) -> String {
        format!("{}{}", self.base_url, path)
    }

    // 服务商模式下的URL路径不同
    fn get_service_url(&self, path: &str) -> String {
        if let Mode::Service = self.mode {
            // 服务商模式URL前缀为/partner
            if path.contains("/v3/pay/transactions/") {
                let path=path.replace("/v3/pay/transactions/", "/v3/pay/partner/transactions/");
                return self.endpoint(&path);
            }
            return self.endpoint(path);
        } else {
            self.endpoint(path)
        }
    }

    // 构建服务商模式参数
    fn build_service_params(&self, mut params: Value) -> Value {
        if let Mode::Service = self.mode {
            // 设置appid
            if !params.get("appid").is_some() && !params.get("sp_appid").is_some() {
                if let Some(appid) = &self.cfg.appid {
                    params["sp_appid"] = json!(appid.clone());
                }
            }
            // 添加服务商模式必需参数
            if !params.get("sp_appid").is_some() {
                if let Some(sp_appid) = &self.cfg.appid {
                    params["sp_appid"] = json!(sp_appid.clone());
                } else if let Some(appid) = &self.cfg.appid_mp {
                    params["sp_appid"] = json!(appid.clone());
                }
            }

            if !params.get("sp_mchid").is_some() {
                params["sp_mchid"] = json!(self.cfg.mchid.clone());
            }

            if !params.get("sub_mchid").is_some() {
                if let Some(sub_mchid) = &self.cfg.sub_mchid {
                    params["sub_mchid"] = json!(sub_mchid.clone());
                }
            }
            let old_params=params.clone();
            // 处理payer字段
            if let Some(payer) = params.get_mut("payer") {
                if let Value::Object(payer_obj) = payer {
                    // 服务商模式下使用sub_openid而不是openid
                    if old_params.get("sub_appid").is_some() {
                        if let Some(openid) = payer_obj.remove("openid") {
                            payer_obj.insert("sub_openid".to_string(), openid);
                        }
                    }else {
                        if let Some(openid) = payer_obj.remove("openid") {
                            payer_obj.insert("sp_openid".to_string(), openid);
                        }
                    }

                }
            }
        }else {
            params["mchid"] = json!(self.cfg.mchid.clone());
            params["appid"] = json!(self.cfg.appid.clone());
        }
        if !params.get("notify_url").is_some() {
            if let Some(notify_url) = &self.cfg.notify_url {
                params["notify_url"] = json!(notify_url.clone());
            }
        }
        params
    }

    pub async fn mp(&self, mut order: Value) -> Result<Value, PayError> {

        if let Mode::Service = self.mode {
            if !order.get("sub_appid").is_some() {
                if let Some(appid) = &self.cfg.appid_mp {
                    order["sub_appid"] = json!(appid.clone());
                }
            }
        }



        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = self.get_service_url("/v3/pay/transactions/jsapi");
        let resp = self.sign_and_post("POST", &url, &order).await?;
        if let Some(prepay_id) = resp.get("prepay_id").and_then(|v| v.as_str()) {
            let time_stamp = now_ts();
            let nonce_str = gen_nonce(32);
            let package = format!("prepay_id={}", prepay_id);

            // 根据模式确定appid
            let appid = if let Mode::Service = self.mode {
                order.get("sp_appid").and_then(|v| v.as_str()).unwrap_or("")
            } else {
                order.get("appid").and_then(|v| v.as_str()).unwrap_or("")
            };

            let sign_src = format!(
                "{}\n{}\n{}\n{}\n",
                appid,
                time_stamp,
                nonce_str,
                package
            );

            let pay_sign = rsa_sign_sha256_pem(&self.cfg.private_key_pem, &sign_src)
                .map_err(|e| PayError::Crypto(format!("{}", e)))?;

            return Ok(
                json!({
                    "appId": appid,
                    "timeStamp": time_stamp,
                    "nonceStr": nonce_str,
                    "package": package,
                    "signType": "RSA",
                    "paySign": pay_sign
                }),
            );
        }
        Ok(resp)
    }

    pub async fn miniapp(&self, mut order: Value) -> Result<Value, PayError> {
        if let Mode::Service = self.mode {
            if !order.get("sub_appid").is_some() {
                if let Some(appid) = &self.cfg.appid_mini {
                    order["sub_appid"] = json!(appid.clone());
                }
            }
        }

        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = self.get_service_url("/v3/pay/transactions/jsapi");
        let resp = self.sign_and_post("POST", &url, &order).await?;

        if let Some(prepay_id) = resp.get("prepay_id").and_then(|v| v.as_str()) {
            let time_stamp = now_ts();
            let nonce_str = gen_nonce(32);
            let package = format!("prepay_id={}", prepay_id);

            // 根据模式确定appid
            let appid = if let Mode::Service = self.mode {
                order.get("sp_appid").and_then(|v| v.as_str()).unwrap_or("")
            } else {
                order.get("appid").and_then(|v| v.as_str()).unwrap_or("")
            };

            let sign_src = format!(
                "{}\n{}\n{}\n{}\n",
                appid,
                time_stamp,
                nonce_str,
                package
            );

            let pay_sign = rsa_sign_sha256_pem(&self.cfg.private_key_pem, &sign_src)
                .map_err(|e| PayError::Crypto(format!("{}", e)))?;

            return Ok(
                json!({
                    "appId": appid,
                    "timeStamp": time_stamp,
                    "nonceStr": nonce_str,
                    "package": package,
                    "signType": "RSA",
                    "paySign": pay_sign
                }),
            );
        }
        Ok(resp)
    }

    pub async fn h5(&self, mut order: Value) -> Result<Value, PayError> {
        if let Mode::Service = self.mode {
            if !order.get("sub_appid").is_some() {
                if let Some(appid) = &self.cfg.appid_mini {
                    order["sub_appid"] = json!(appid.clone());
                }
            }
        }
        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = self.get_service_url("/v3/pay/transactions/h5");
        let resp = self.sign_and_post("POST", &url, &order).await?;
        Ok(resp)
    }

    pub async fn app(&self, mut order: Value) -> Result<Value, PayError> {

        if let Mode::Service = self.mode {
            if !order.get("sub_appid").is_some() {
                if let Some(appid) = &self.cfg.appid_app {
                    order["sub_appid"] = json!(appid.clone());
                }
            }
        }

        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = self.get_service_url("/v3/pay/transactions/app");
        let resp = self.sign_and_post("POST", &url, &order).await?;
        Ok(resp)
    }

    pub async fn native(&self, mut order: Value) -> Result<Value, PayError> {
        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = self.get_service_url("/v3/pay/transactions/native");
        let resp = self.sign_and_post("POST", &url, &order).await?;
        Ok(resp)
    }

    pub async fn micropay(&self, mut order: Value) -> Result<Value, PayError> {
        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = self.get_service_url("/v3/pay/transactions/micropay");
        let resp = self.sign_and_post("POST", &url, &order).await?;
        Ok(resp)
    }

    pub async fn query(&self, mut params: Value) -> Result<Value, PayError> {
        // 构建符合服务商模式的参数
        params = self.build_service_params(params);

        // 使用服务商模式URL
        let url = if let Mode::Service = self.mode {
            "/v3/pay/partner/transactions/id/{transaction_id}"
                .replace("{transaction_id}",
                         params.get("transaction_id")
                             .and_then(|v| v.as_str())
                             .unwrap_or("")
                )
        } else {
            "/v3/pay/transactions/id/{transaction_id}"
                .replace("{transaction_id}",
                         params.get("transaction_id")
                             .and_then(|v| v.as_str())
                             .unwrap_or("")
                )
        };

        let resp = self.sign_and_post("GET", &url, &params).await?;
        Ok(resp)
    }

    pub async fn close(&self, mut params: Value) -> Result<Value, PayError> {
        // 构建符合服务商模式的参数
        params = self.build_service_params(params);

        // 使用服务商模式URL
        let url = if let Mode::Service = self.mode {
            "/v3/pay/partner/transactions/out-trade-no/{out_trade_no}/close"
                .replace("{out_trade_no}",
                         params.get("out_trade_no")
                             .and_then(|v| v.as_str())
                             .unwrap_or("")
                )
        } else {
            "/v3/pay/transactions/out-trade-no/{out_trade_no}/close"
                .replace("{out_trade_no}",
                         params.get("out_trade_no")
                             .and_then(|v| v.as_str())
                             .unwrap_or("")
                )
        };

        let resp = self.sign_and_post("POST", &url, &params).await?;
        Ok(resp)
    }

    pub async fn refund(&self, mut order: Value) -> Result<Value, PayError> {
        // 构建符合服务商模式的参数
        order = self.build_service_params(order);

        // 使用服务商模式URL
        let url = if let Mode::Service = self.mode {
            "/v3/refund/domestic/refunds"
        } else {
            "/v3/refund/domestic/refunds"
        };

        let resp = self.sign_and_post("POST", &url, &order).await?;
        Ok(resp)
    }

    pub async fn query_refund(&self, mut params: Value) -> Result<Value, PayError> {
        // 构建符合服务商模式的参数
        params = self.build_service_params(params);

        // 使用服务商模式URL
        let url = if let Mode::Service = self.mode {
            "/v3/refund/domestic/refunds/{out_refund_no}"
                .replace("{out_refund_no}",
                         params.get("out_refund_no")
                             .and_then(|v| v.as_str())
                             .unwrap_or("")
                )
        } else {
            "/v3/refund/domestic/refunds/{out_refund_no}"
                .replace("{out_refund_no}",
                         params.get("out_refund_no")
                             .and_then(|v| v.as_str())
                             .unwrap_or("")
                )
        };

        let resp = self.sign_and_post("GET", &url, &params).await?;
        Ok(resp)
    }

    pub async fn transfer(&self, order: Value) -> Result<Value, PayError> {
        // 使用服务商模式URL
        let url = if let Mode::Service = self.mode {
            "/v3/transfer/batches"
        } else {
            "/v3/transfer/batches"
        };

        let resp = self.sign_and_post("POST", &url, &order).await?;
        Ok(resp)
    }

    pub async fn refresh_platform_certs(&self) -> Result<(), PayError> {
        self.certs
            .refresh()
            .await
            .map_err(|e| PayError::Other(format!("refresh platform certs: {}", e)))?;
        Ok(())
    }

    pub async fn sign_and_post(
        &self,
        method: &str,
        url: &str,
        body: &Value,
    ) -> Result<Value, PayError> {
        let body_str = if method == "GET" {
            "".to_string()
        } else {
            body.to_string()
        };
        println!("sign_and_post: method={}, url={}, body={}", method, url, body_str);
        let timestamp = now_ts();
        let nonce = gen_nonce(32);
        let parsed = Url::parse(url).map_err(|e| PayError::Other(format!("parse url: {}", e)))?;
        let path = if let Some(query) = parsed.query() {
            format!("{}?{}", parsed.path(), query)
        } else {
            parsed.path().to_string()
        };
        let sign_str = format!(
            "{}\n{}\n{}\n{}\n{}\n",
            method, path, timestamp, nonce, body_str
        );
        let signature = rsa_sign_sha256_pem(&self.cfg.private_key_pem, &sign_str)
            .map_err(|e| PayError::Crypto(format!("{}", e)))?;

        // 服务商模式使用服务商商户号
        let mchid = self.cfg.mchid.clone();

        let auth = format!(
            r#"WECHATPAY2-SHA256-RSA2048 mchid="{mchid}",nonce_str="{nonce}",timestamp="{ts}",serial_no="{serial}",signature="{sig}""#,
            mchid = mchid,
            nonce = nonce,
            ts = timestamp,
            serial = self.cfg.serial_no,
            sig = signature
        );
        let client = &self.http;
        let send_req = || async {
            let mut req = match method {
                "GET" => client.get(url),
                "POST" => client.post(url),
                _ => {
                    return Err(PayError::Other(format!("unsupported method: {}", method)));
                }
            };
            req = req
                .header("Authorization", auth.clone())
                .header("Accept", "application/json")
                .header("User-Agent", "rust_pay_wf");
            if method == "POST" {
                req = req
                    .header("Content-Type", "application/json")
                    .body(body_str.clone());
            }
            let resp = req.send().await?;
            let status = resp.status();
            let text = resp.text().await?;
            if !status.is_success() {
                return Err(PayError::Other(format!(
                    "HTTP request failed: {} - {}",
                    status, text
                )));
            }
            let v: Value = serde_json::from_str(&text)?;
            Ok(v)
        };
        let v = crate::utils::retry_async(self.max_retries, send_req)
            .await
            .map_err(|e| PayError::Other(format!(
                "HTTP request failed:{}",
                e
            )))?;
        Ok(v)
    }

    /// 处理回调
    pub async fn handle_notify(&self, headers: HashMap<String,String>, body_str: &str) -> Result<Value, PayError> {
        let notify = WechatNotify::new(self.cfg.clone(), self.certs.clone());
        notify.verify_and_decrypt(&headers, body_str)
    }

}