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