1use std::collections::HashMap;
2use crate::{PayMode, PayNotify, RefundNotify, RefundStatus, TradeState, TradeType, Types};
3use base64::engine::general_purpose::STANDARD;
4use base64::{Engine};
5use json::{object, JsonValue};
6use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
7use aes_gcm::aead::{Aead, Payload};
8use br_reqwest::Method;
9
10
11#[derive(Clone, Debug)]
12pub struct Wechat {
13 pub appid: String,
15 pub sp_mchid: String,
17 pub serial_no: String,
19 pub app_private: String,
21 pub apikey: String,
23 pub apiv2: String,
25 pub notify_url: String,
26
27}
28
29use chrono::{DateTime, Local, Utc};
30use log::error;
31use openssl::hash::MessageDigest;
32use openssl::pkey::{PKey};
33use openssl::rsa::Rsa;
34use openssl::sign::Signer;
35use rand::distr::Alphanumeric;
36use rand::{rng, Rng};
37
38impl Wechat {
39 pub fn http(&mut self, url: &str, method: Method, body: JsonValue) -> Result<JsonValue, String> {
40 let sign = self.sign(method.to_str().to_uppercase().as_str(), url, body.to_string().as_str())?;
41 let mut http = br_reqwest::Client::new();
42 let url = format!("https://api.mch.weixin.qq.com{url}");
43 let send = match method {
44 Method::GET => http.get(url.as_str()),
45 Method::POST => http.post(url.as_str()).raw_json(body),
46 _ => http.post(url.as_str()),
47 };
48 match send.header("Accept", "application/json").header("User-Agent", "api").header("Content-Type", "application/json").header("Authorization", sign.as_str()).send()?.json() {
49 Ok(e) => Ok(e),
50 Err(e) => Err(e)
51 }
52 }
53
54 pub fn sign_v2(&mut self, body: JsonValue) -> Result<String, String> {
55 let mut map = HashMap::new();
56 for (key, value) in body.entries() {
57 if key == "sign" {
58 continue;
59 }
60 if value.is_empty() {
61 continue;
62 }
63 map.insert(key, value);
64 }
65 let mut keys: Vec<_> = map.keys().cloned().collect();
66 keys.sort();
67 let mut txt = vec![];
68 for key in keys {
69 txt.push(format!("{}={}", key, map.get(&key).unwrap()));
70 }
71 let txt = txt.join("&");
72 let string_sign_temp = format!("{}&key={}", txt, self.apiv2);
73
74 let sign = br_crypto::md5::encrypt_hex(string_sign_temp.as_bytes()).to_uppercase();
75 Ok(sign)
76 }
77
78 pub fn sign(&mut self, method: &str, url: &str, body: &str) -> Result<String, String> {
79 let timestamp = Utc::now().timestamp(); let random_string: String = rng().sample_iter(&Alphanumeric) .take(10) .map(char::from).collect();
83
84 let sign_txt = format!("{method}\n{url}\n{timestamp}\n{random_string}\n{body}\n");
85 if self.app_private.contains("-----BEGIN PRIVATE KEY-----") {
86 self.app_private = self.app_private.replace("-----BEGIN PRIVATE KEY-----", "");
87 self.app_private = self.app_private.replace("-----END PRIVATE KEY-----", "");
88 self.app_private = self.app_private.replace(" ", "");
89 self.app_private = self.app_private.replace("\n", "");
90 self.app_private = self.app_private.trim().to_string();
91 }
92 let mut formatted = String::from("-----BEGIN PRIVATE KEY-----\n");
93 for chunk in self.app_private.as_bytes().chunks(64) {
94 formatted.push_str(&String::from_utf8_lossy(chunk));
95 formatted.push('\n');
96 }
97 formatted.push_str("-----END PRIVATE KEY-----\n");
98 self.app_private = formatted;
99
100 let rsa = match Rsa::private_key_from_pem(self.app_private.as_bytes()) {
102 Ok(e) => e,
103 Err(e) => {
104 return Err(format!("加载RSA私钥失败: {e}"));
105 }
106 };
107 let pkey = match PKey::from_rsa(rsa) {
108 Ok(e) => e,
109 Err(e) => {
110 return Err(format!("Failed to create PKey: {e}"))
111 }
112 };
113 let mut signer = match Signer::new(MessageDigest::sha256(), &pkey) {
115 Ok(e) => e,
116 Err(e) => {
117 return Err(format!("Failed to create signer:{e}"));
118 }
119 };
120 match signer.update(sign_txt.as_bytes()) {
122 Ok(_) => {}
123 Err(e) => {
124 return Err(e.to_string())
125 }
126 };
127 let signature = match signer.sign_to_vec() {
129 Ok(e) => e,
130 Err(e) => {
131 return Err(format!("Failed to sign: {e}"));
132 }
133 };
134 let signature_b64 = STANDARD.encode(signature);
135 let sign = format!(
136 r#"WECHATPAY2-SHA256-RSA2048 mchid="{}",nonce_str="{random_string}",signature="{signature_b64}",timestamp="{timestamp}",serial_no="{}""#,
137 self.sp_mchid.as_str(),
138 self.serial_no
139 );
140 Ok(sign)
141 }
142
143 pub fn paysign(&mut self, prepay_id: &str) -> Result<JsonValue, String> {
144 let timestamp = Utc::now().timestamp(); let random_string: String = rng().sample_iter(&Alphanumeric) .take(10) .map(char::from).collect();
148
149 let sign_txt = format!(
150 "{}\n{timestamp}\n{random_string}\n{prepay_id}\n",
151 self.appid
152 );
153
154 let rsa = match Rsa::private_key_from_pem(self.app_private.as_bytes()) {
156 Ok(e) => e,
157 Err(e) => {
158 return Err(e.to_string())
159 }
160 };
161 let pkey = match PKey::from_rsa(rsa) {
162 Ok(e) => e,
163 Err(e) => {
164 return Err(format!("Failed to create PKey: {e}"))
165 }
166 };
167 let mut signer = match Signer::new(MessageDigest::sha256(), &pkey) {
169 Ok(e) => e,
170 Err(e) => {
171 return Err(format!("Failed to create signer:{e}"));
172 }
173 };
174 match signer.update(sign_txt.as_bytes()) {
176 Ok(_) => {}
177 Err(e) => {
178 return Err(e.to_string())
179 }
180 };
181 let signature = match signer.sign_to_vec() {
183 Ok(e) => e,
184 Err(e) => {
185 return Err(format!("Failed to sign: {e}"));
186 }
187 };
188 let signature_b64 = STANDARD.encode(signature);
189 let sign = signature_b64;
190 Ok(object! {
191 timeStamp:timestamp,
192 nonceStr:random_string,
193 package:prepay_id,
194 signType:"RSA",
195 paySign:sign
196 })
197 }
198}
199impl PayMode for Wechat {
200 fn check(&mut self) -> Result<bool, String> {
201 let timestamp = Utc::now().timestamp(); let now = Local::now();
203 let formatted = now.format("%Y%m%d").to_string();
204 let order_no = format!("test_{formatted}_{timestamp}");
205 match self.clone().pay("", Types::MiniJsapi, self.sp_mchid.as_str(), order_no.as_str(), "测试", 0.01, "") {
206 Ok(_) => Ok(true),
207 Err(e) => {
208 if e.contains("受理机构发起支付时, 子商户mchid不能与自身mchid相同") {
209 return Ok(true);
210 }
211 Ok(false)
212 }
213 }
214 }
215
216 fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String> {
217 let url = format!("/v3/apply4sub/sub_merchants/{sub_mchid}/settlement");
218 let res = self.http(url.as_str(), Method::GET, "".into())?;
219 if res.has_key("verify_result") && res["verify_result"] == "VERIFY_SUCCESS" {
220 return Ok(true.into());
221 }
222 Err(res.to_string())
223 }
224
225 fn notify(&mut self, _data: JsonValue) -> Result<JsonValue, String> {
226 todo!()
227 }
228
229 fn config(&mut self) -> JsonValue {
230 todo!()
231 }
232
233
234 fn auth(&mut self, _code: &str) -> Result<JsonValue, String> {
235 todo!()
236 }
237 fn pay(&mut self, _channel: &str, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String> {
238 let url = match types {
239 Types::Jsapi => "/v3/pay/partner/transactions/jsapi",
240 Types::Native => "/v3/pay/partner/transactions/native",
241 Types::H5 => "/v3/pay/partner/transactions/h5",
242 Types::MiniJsapi => "/v3/pay/partner/transactions/jsapi",
243 Types::App => "/v3/pay/partner/transactions/app",
244 Types::Micropay => "/pay/micropay"
245 };
246 let total = format!("{:.0}", total_fee * 100.0);
247 let mut body = object! {
248 "sp_appid" => self.appid.clone(),
249 "sp_mchid"=> self.sp_mchid.clone(),
250 "sub_mchid"=> sub_mchid,
251 "description"=>description,
252 "out_trade_no"=>out_trade_no,
253 "notify_url"=>self.notify_url.clone(),
254 "support_fapiao"=>true,
255 "amount"=>object! {
256 total: total.parse::<i64>().unwrap(),
257 currency:"CNY"
258 }
259 };
260 match types {
261 Types::Native => {}
262 _ => {
263 body["payer"] = object! {
264 sp_openid:sp_openid
265 };
266 }
267 };
268 match self.http(url, Method::POST, body) {
269 Ok(e) => {
270 match types {
271 Types::Native => {
272 if e.has_key("code_url") {
273 Ok(e["code_url"].clone())
274 } else {
275 Err(e["message"].to_string())
276 }
277 }
278 Types::Jsapi | Types::MiniJsapi => {
279 if e.has_key("prepay_id") {
280 let signinfo = self.paysign(format!("prepay_id={}", e["prepay_id"]).as_str())?;
281 Ok(signinfo)
282 } else {
283 Err(e["message"].to_string())
284 }
285 }
286 _ => {
287 Ok(e)
288 }
289 }
290 }
291 Err(e) => Err(e),
292 }
293 }
294
295 fn micropay(&mut self, _channel: &str, auth_code: &str, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, org_openid: &str, ip: &str) -> Result<JsonValue, String> {
296 let url = "/pay/micropay";
297 let total = format!("{:.0}", total_fee * 100.0);
298
299 let nonce_str: String = rand::rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect();
300
301 let mut body = object! {
302 "appid": self.appid.clone(),
303 "mch_id"=> self.sp_mchid.clone(),
304 "sub_mch_id"=> sub_mchid,
305 "nonce_str"=>nonce_str,
306 "body"=> description,
307 "out_trade_no"=>out_trade_no,
308 "total_fee"=>total.parse::<i64>().unwrap(),
309 "fee_type":"CNY",
310 "spbill_create_ip":ip,
311 "device_info":org_openid,
312 "auth_code":auth_code
313 };
314 body["sign"] = self.sign_v2(body.clone())?.into();
315 let mut xml = vec!["<xml>".to_owned()];
316 for (key, value) in body.entries() {
317 let t = format!("<{}>{}</{00}>", key, value.clone().clone());
318 xml.push(t);
319 }
320 xml.push("</xml>".to_owned());
321 let xml = xml.join("");
322 let mut http = br_reqwest::Client::new();
323 match http.post(format!("https://api.mch.weixin.qq.com{url}").as_str()).header("Content-Type", "application/xml").raw_xml(xml.into()).send()?.xml() {
324 Ok(e) => Ok(e),
325 Err(e) => Err(e),
326 }
327 }
328
329 fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
330 let url = format!("/v3/pay/partner/transactions/out-trade-no/{out_trade_no}/close");
331 let body = object! {
332 "sp_mchid"=> self.sp_mchid.clone(),
333 "sub_mchid"=> sub_mchid
334 };
335 match self.http(&url, Method::POST, body) {
336 Ok(_) => Ok(true.into()),
337 Err(e) => Err(e)
338 }
339 }
340
341 fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
342 let url = format!(
343 "/v3/pay/partner/transactions/out-trade-no/{}?sub_mchid={}&sp_mchid={}",
344 out_trade_no, sub_mchid, self.sp_mchid
345 );
346 match self.http(&url, Method::GET, "".into()) {
347 Ok(e) => {
348 if e.has_key("message") {
349 return Err(e["message"].to_string());
350 }
351 let res = PayNotify {
352 trade_type: TradeType::from(e["trade_type"].to_string().as_str()),
353 out_trade_no: e["out_trade_no"].as_str().unwrap().to_string(),
354 sp_mchid: e["sp_mchid"].as_str().unwrap().to_string(),
355 sub_mchid: e["sub_mchid"].as_str().unwrap().to_string(),
356 sp_appid: e["sp_appid"].as_str().unwrap().to_string(),
357 transaction_id: e["transaction_id"].to_string(),
358 success_time: PayNotify::success_time(e["success_time"].as_str().unwrap_or("")),
359 sp_openid: e["payer"]["sp_openid"].to_string(),
360 sub_openid: e["payer"]["sub_openid"].to_string(),
361 total: e["amount"]["total"].as_f64().unwrap_or(0.0) / 100.0,
362 currency: e["amount"]["currency"].to_string(),
363 payer_total: e["amount"]["payer_total"].as_f64().unwrap_or(0.0) / 100.0,
364 payer_currency: e["amount"]["payer_currency"].to_string(),
365 trade_state: TradeState::from(e["trade_state"].as_str().unwrap()),
366 };
367 Ok(res.json())
368 }
369 Err(e) => Err(e),
370 }
371 }
372
373 fn pay_micropay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
374 let nonce_str: String = rand::rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect();
375 let mut body = object! {
376 "appid": self.appid.clone(),
377 "mch_id"=> self.sp_mchid.clone(),
378 "sub_mch_id"=> sub_mchid,
379 "nonce_str"=>nonce_str,
380 "out_trade_no"=>out_trade_no
381 };
382 body["sign"] = self.sign_v2(body.clone())?.into();
383 let mut xml = vec!["<xml>".to_owned()];
384 for (key, value) in body.entries() {
385 let t = format!("<{}>{}</{00}>", key, value.clone().clone());
386 xml.push(t);
387 }
388 xml.push("</xml>".to_owned());
389 let xml = xml.join("");
390 let mut http = br_reqwest::Client::new();
391 match http.post("https://api.mch.weixin.qq.com/pay/orderquery".to_string().as_str()).header("Content-Type", "application/xml").raw_xml(xml.into()).send()?.xml() {
392 Ok(e) => {
393 if e.has_key("result_code") && e["result_code"] != "SUCCESS" {
394 error!("pay_micropay_query: {e:#}");
395 return Err(e["return_msg"].to_string());
396 }
397
398 let res = PayNotify {
399 trade_type: TradeType::from(e["trade_type"].to_string().as_str()),
400 out_trade_no: e["out_trade_no"].as_str().unwrap().to_string(),
401 sp_mchid: e["mch_id"].as_str().unwrap().to_string(),
402 sub_mchid: e["sub_mch_id"].as_str().unwrap().to_string(),
403 sp_appid: e["appid"].as_str().unwrap().to_string(),
404 transaction_id: e["transaction_id"].to_string(),
405 success_time: PayNotify::datetime_to_timestamp(e["time_end"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
406 sp_openid: e["device_info"].to_string(),
407 sub_openid: e["openid"].to_string(),
408 total: e["total_fee"].to_string().parse::<f64>().unwrap_or(0.0) / 100.0,
409 currency: e["fee_type"].to_string(),
410 payer_total: e["cash_fee"].to_string().parse::<f64>().unwrap_or(0.0) / 100.0,
411 payer_currency: e["cash_fee_type"].to_string(),
412 trade_state: TradeState::from(e["trade_state"].as_str().unwrap()),
413 };
414 Ok(res.json())
415 }
416 Err(e) => Err(e),
417 }
418 }
419 fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
420 if self.apikey.is_empty() {
421 return Err("apikey 不能为空".to_string());
422 }
423 let key = Key::<Aes256Gcm>::from_slice(self.apikey.as_bytes());
424 let cipher = Aes256Gcm::new(key);
425 let nonce = Nonce::from_slice(nonce.as_bytes());
426 let data = match STANDARD.decode(ciphertext) {
427 Ok(e) => e,
428 Err(e) => return Err(format!("Invalid data received from API :{e}"))
429 };
430 let payload = Payload {
432 msg: &data,
433 aad: associated_data.as_bytes(),
434 };
435
436 let plaintext = match cipher.decrypt(nonce, payload) {
438 Ok(e) => e,
439 Err(e) => {
440 return Err(format!("解密 API:{e}"));
441 }
442 };
443 let rr = match String::from_utf8(plaintext) {
444 Ok(d) => d,
445 Err(_) => return Err("utf8 error".to_string())
446 };
447 let json = match json::parse(rr.as_str()) {
448 Ok(e) => e,
449 Err(_) => return Err("json error".to_string())
450 };
451 let res = PayNotify {
452 trade_type: TradeType::from(json["trade_type"].as_str().unwrap()),
453 out_trade_no: json["out_trade_no"].as_str().unwrap().to_string(),
454 sp_mchid: json["sp_mchid"].as_str().unwrap().to_string(),
455 sub_mchid: json["sub_mchid"].as_str().unwrap().to_string(),
456 sp_appid: json["sp_appid"].as_str().unwrap().to_string(),
457 transaction_id: json["transaction_id"].as_str().unwrap().to_string(),
458 success_time: PayNotify::success_time(json["success_time"].as_str().unwrap_or("")),
459 sp_openid: json["payer"]["sp_openid"].as_str().unwrap().to_string(),
460 sub_openid: json["payer"]["sub_openid"].as_str().unwrap().to_string(),
461 total: json["amount"]["total"].to_string().parse::<f64>().unwrap_or(0.0) / 100.0,
462 payer_total: json["amount"]["payer_total"].to_string().parse::<f64>().unwrap_or(0.0) / 100.0,
463 currency: json["amount"]["currency"].to_string(),
464 payer_currency: json["amount"]["payer_currency"].to_string(),
465 trade_state: TradeState::from(json["trade_state"].as_str().unwrap()),
466 };
467 Ok(res.json())
468 }
469
470 fn refund(
471 &mut self,
472 sub_mchid: &str,
473 out_trade_no: &str,
474 transaction_id: &str,
475 out_refund_no: &str,
476 amount: f64,
477 total: f64,
478 currency: &str,
479 ) -> Result<JsonValue, String> {
480 let url = "/v3/refund/domestic/refunds";
481
482 let refund = format!("{:.0}", amount * 100.0);
483 let total = format!("{:.0}", total * 100.0);
484
485 let body = object! {
486 "sub_mchid"=> sub_mchid,
487 "transaction_id"=>transaction_id,
488 "out_trade_no"=>out_trade_no,
489 "out_refund_no"=>out_refund_no,
490 "amount"=>object! {
491 refund: refund.parse::<i64>().unwrap(),
492 total: total.parse::<i64>().unwrap(),
493 currency:currency
494 }
495 };
496 match self.http(url, Method::POST, body) {
497 Ok(e) => {
498 if e.is_empty() {
499 return Err("已执行".to_string());
500 }
501 if e.has_key("message") {
502 return Err(e["message"].to_string());
503 }
504 let mut refund_time = 0.0;
505 if e.has_key("success_time") {
506 let success_time = e["success_time"].as_str().unwrap_or("").to_string();
507 if !success_time.is_empty() {
508 let datetime = DateTime::parse_from_rfc3339(success_time.as_str()).unwrap();
509 refund_time = datetime.timestamp() as f64;
510 }
511 }
512
513 let status = match e["status"].as_str().unwrap() {
514 "PROCESSING" => "退款中",
515 "SUCCESS" => "已退款",
516 _ => "无退款",
517 };
518 let info = object! {
519 refund_id: e["refund_id"].clone(),
520 user_received_account:e["user_received_account"].clone(),
521 status:status,
522 refund_time:refund_time,
523 out_refund_no: e["out_refund_no"].clone(),
524 };
525 Ok(info)
526 }
527 Err(e) => Err(e)
528 }
529 }
530
531 fn micropay_refund(&mut self, sub_mchid: &str, out_trade_no: &str, transaction_id: &str, out_refund_no: &str, amount: f64, total: f64, currency: &str, refund_text: &str) -> Result<JsonValue, String> {
532 let refund = format!("{:.0}", amount * 100.0);
533 let total = format!("{:.0}", total * 100.0);
534
535
536 let nonce_str: String = rand::rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect();
537 let mut body = object! {
538 "appid": self.appid.clone(),
539 "mch_id"=> self.sp_mchid.clone(),
540 "sub_mch_id"=> sub_mchid,
541 "nonce_str"=>nonce_str,
542 "out_trade_no"=>out_trade_no,
543 "transaction_id"=>transaction_id,
544 "out_refund_no"=>out_refund_no,
545 "total_fee"=>total,
546 "refund_fee"=>refund,
547 "refund_fee_type"=> currency,
548 "refund_desc"=>refund_text
549 };
550 body["sign"] = self.sign_v2(body.clone())?.into();
551 let mut xml = vec!["<xml>".to_owned()];
552 for (key, value) in body.entries() {
553 let t = format!("<{}>{}</{00}>", key, value.clone().clone());
554 xml.push(t);
555 }
556 xml.push("</xml>".to_owned());
557 let xml = xml.join("");
558 let mut http = br_reqwest::Client::new();
559 match http.post("https://api.mch.weixin.qq.com/secapi/pay/refund".to_string().as_str()).header("Content-Type", "application/xml").raw_xml(xml.into()).send()?.xml() {
560 Ok(e) => {
561 println!("{e:#}");
562 if e.is_empty() {
563 return Err("已执行".to_string());
564 }
565 if e.has_key("message") {
566 return Err(e["message"].to_string());
567 }
568 let mut refund_time = 0.0;
569 if e.has_key("success_time") {
570 let success_time = e["success_time"].as_str().unwrap_or("").to_string();
571 if !success_time.is_empty() {
572 let datetime = DateTime::parse_from_rfc3339(success_time.as_str()).unwrap();
573 refund_time = datetime.timestamp() as f64;
574 }
575 }
576
577 let status = match e["status"].as_str().unwrap() {
578 "PROCESSING" => "退款中",
579 "SUCCESS" => "已退款",
580 _ => "无退款",
581 };
582 let info = object! {
583 refund_id: e["refund_id"].clone(),
584 user_received_account:e["user_received_account"].clone(),
585 status:status,
586 refund_time:refund_time,
587 out_refund_no: e["out_refund_no"].clone(),
588 };
589 Ok(info)
590 }
591 Err(e) => Err(e),
592 }
593 }
594
595 fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
596 if self.apikey.is_empty() {
597 return Err("apikey 不能为空".to_string());
598 }
599 let key = Key::<Aes256Gcm>::from_slice(self.apikey.as_bytes());
600 let cipher = Aes256Gcm::new(key);
601 let nonce = Nonce::from_slice(nonce.as_bytes());
602 let data = match STANDARD.decode(ciphertext) {
603 Ok(e) => e,
604 Err(e) => return Err(format!("Invalid data received from API :{e}"))
605 };
606 let payload = Payload {
608 msg: &data,
609 aad: associated_data.as_bytes(),
610 };
611
612 let plaintext = match cipher.decrypt(nonce, payload) {
614 Ok(e) => e,
615 Err(e) => {
616 return Err(format!("解密 API:{e}"));
617 }
618 };
619 let rr = match String::from_utf8(plaintext) {
620 Ok(d) => d,
621 Err(_) => return Err("utf8 error".to_string())
622 };
623 let json = match json::parse(rr.as_str()) {
624 Ok(e) => e,
625 Err(_) => return Err("json error".to_string())
626 };
627 let res = RefundNotify {
628 out_trade_no: json["out_trade_no"].to_string(),
629 refund_no: json["out_refund_no"].to_string(),
630 refund_id: json["refund_id"].to_string(),
631 sp_mchid: json["sp_mchid"].as_str().unwrap().to_string(),
632 sub_mchid: json["sub_mchid"].as_str().unwrap().to_string(),
633 transaction_id: json["transaction_id"].as_str().unwrap().to_string(),
634 success_time: PayNotify::success_time(json["success_time"].as_str().unwrap_or("")),
635 total: json["amount"]["total"].as_f64().unwrap_or(0.0) / 100.0,
636 refund: json["amount"]["refund"].as_f64().unwrap_or(0.0) / 100.0,
637 payer_total: json["amount"]["payer_total"].as_f64().unwrap() / 100.0,
638 payer_refund: json["amount"]["payer_refund"].as_f64().unwrap() / 100.0,
639 status: RefundStatus::from(json["refund_status"].as_str().unwrap()),
640 };
641 Ok(res.json())
642 }
643
644 fn refund_query(&mut self, _trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
645 let url = format!("/v3/refund/domestic/refunds/{out_refund_no}?sub_mchid={sub_mchid}");
646 match self.http(&url, Method::GET, "".into()) {
647 Ok(e) => {
648 if e.is_empty() {
649 return Err("已执行".to_string());
650 }
651 if e.has_key("message") {
652 return Err(e["message"].to_string());
653 }
654
655
656 let res = RefundNotify {
657 out_trade_no: e["out_trade_no"].to_string(),
658 refund_no: e["out_refund_no"].to_string(),
659 sp_mchid: "".to_string(),
660 sub_mchid: sub_mchid.to_string(),
661 transaction_id: e["transaction_id"].to_string(),
662 refund_id: e["refund_id"].to_string(),
663 success_time: PayNotify::success_time(e["success_time"].as_str().unwrap_or("")),
664 total: e["amount"]["total"].to_string().parse::<f64>().unwrap(),
665 payer_total: e["amount"]["total"].to_string().parse::<f64>().unwrap(),
666 refund: e["amount"]["refund"].to_string().parse::<f64>().unwrap(),
667 payer_refund: e["amount"]["refund"].to_string().parse::<f64>().unwrap(),
668 status: RefundStatus::from(e["status"].as_str().unwrap()),
669 };
670
671 Ok(res.json())
672 }
673 Err(e) => Err(e),
674 }
675 }
676
677 fn incoming(&mut self, business_code: &str, contact_info: JsonValue, _subject_info: JsonValue, _business_info: JsonValue, _settlement_info: JsonValue, _bank_account_info: JsonValue) -> Result<JsonValue, String> {
678 let contact_info_data = object! {
679 contact_type:contact_info["contact_type"].clone(),
681 contact_name:contact_info["contact_name"].clone(),
682 };
683
684 let body = object! {
685 business_code:business_code,
686 contact_info:contact_info_data
687 };
688 println!("{body:#}");
689 match self.http("/v3/applyment4sub/applyment/", Method::POST, body) {
690 Ok(e) => {
691 println!("{e:#}");
692 if e.is_empty() {
693 return Err("已执行".to_string());
694 }
695 if e.has_key("message") {
696 return Err(e["message"].to_string());
697 }
698 Ok(e)
699 }
700 Err(e) => Err(e),
701 }
702 }
703}