1use chrono::Local;
2use json::{object, JsonValue};
3use log::{warn};
4use xmltree::Element;
5use crate::{PayMode, PayNotify, RefundNotify, RefundStatus, TradeState, TradeType, Types};
6
7#[derive(Clone, Debug)]
9pub struct Ccbc {
10 pub appid: String,
12 pub appid_subscribe: String,
14 pub pass: String,
16 pub sp_mchid: String,
18 pub notify_url: String,
20 pub posid: String,
22 pub branchid: String,
24 pub public_key: String,
26 pub client_ip: String,
27 pub wechat_mchid: String,
29 pub retry: usize,
31}
32
33impl Ccbc {
34 pub fn http(&mut self, url: &str, mut body: JsonValue) -> Result<JsonValue, String> {
35 let mut mac = vec![];
36 let mut path = vec![];
37 let fields = ["MAC", "SUBJECT", "AREA_INFO"];
38 for (key, value) in body.entries() {
39 if value.is_empty() && fields.contains(&key) {
40 continue;
41 }
42 if fields.contains(&key) {
43 continue;
44 }
45 if key != "PUB" {
46 path.push(format!("{key}={value}"));
47 }
48 mac.push(format!("{key}={value}"));
49 }
50
51
52 let mac_text = mac.join("&");
53 let path = path.join("&");
54 body["MAC"] = br_crypto::md5::encrypt_hex(mac_text.as_bytes()).into();
55 body.remove("PUB");
56 let mac = format!("{}&MAC={}", path, body["MAC"]);
57
58 let urls = format!("{url}&{mac}");
59
60 let mut http = br_reqwest::Client::new();
61
62 let res = match http.post(urls.as_str()).raw_json(body.clone()).send() {
63 Ok(e) => e,
64 Err(e) => {
65 if self.retry > 2 {
66 return Err(e.to_string());
67 }
68 self.retry += 1;
69 warn!("建行接口重试: {}", self.retry);
70 body.remove("MAC");
71 let res = self.http(url, body.clone())?;
72 return Ok(res);
73 }
74 };
75 let res = res.body().to_string();
76 match json::parse(&res) {
77 Ok(e) => Ok(e),
78 Err(_) => Err(res)
79 }
80 }
81 fn escape_unicode(&mut self, s: &str) -> String {
82 s.chars().map(|c| {
83 if c.is_ascii() {
84 c.to_string()
85 } else {
86 format!("%u{:04X}", c as u32)
87 }
88 }).collect::<String>()
89 }
90 fn _unescape_unicode(&mut self, s: &str) -> String {
91 let mut output = String::new();
92 let mut chars = s.chars().peekable();
93 while let Some(c) = chars.next() {
94 if c == '%' && chars.peek() == Some(&'u') {
95 chars.next(); let codepoint: String = chars.by_ref().take(4).collect();
97 if let Ok(value) = u32::from_str_radix(&codepoint, 16) {
98 if let Some(ch) = std::char::from_u32(value) {
99 output.push(ch);
100 }
101 }
102 } else {
103 output.push(c);
104 }
105 }
106 output
107 }
108 pub fn http_q(&mut self, url: &str, mut body: JsonValue) -> Result<JsonValue, String> {
109 let mut path = vec![];
110 let fields = ["MAC"];
111 for (key, value) in body.entries() {
112 if value.is_empty() && fields.contains(&key) {
113 continue;
114 }
115 if key.contains("QUPWD") {
116 path.push(format!("{key}="));
117 continue;
118 }
119 path.push(format!("{key}={value}"));
120 }
121
122 let mac = path.join("&");
123 body["MAC"] = br_crypto::md5::encrypt_hex(mac.as_bytes()).into();
124
125 let mut map = vec![];
126 for (key, value) in body.entries() {
127 map.push((key, value.to_string()));
128 }
129
130 let mut http = br_reqwest::Client::new();
131
132 http.header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");
133
134 let res = match http.post(url).form_urlencoded(body.clone()).send() {
135 Ok(d) => d,
136 Err(e) => {
137 if self.retry > 2 {
138 return Err(e.to_string());
139 }
140 self.retry += 1;
141 warn!("建行查询接口重试: {}", self.retry);
142 body.remove("MAC");
143 let res = self.http_q(url, body.clone())?;
144 return Ok(res);
145 }
146 };
147 let res = res.body().to_string().trim().to_string();
148 match Element::parse(res.as_bytes()) {
149 Ok(e) => Ok(xml_element_to_json(&e)),
150 Err(e) => Err(e.to_string())
151 }
152 }
153}
154impl PayMode for Ccbc {
155 fn check(&mut self) -> Result<bool, String> {
156 todo!()
157 }
158
159 fn get_sub_mchid(&mut self, _sub_mchid: &str) -> Result<JsonValue, String> {
160 todo!()
161 }
162
163 fn config(&mut self) -> JsonValue {
164 todo!()
165 }
166
167
168 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> {
169 if self.public_key.is_empty() || self.public_key.len() < 30 {
170 return Err(String::from("Public key is empty"));
171 }
172 let pubtext = self.public_key[self.public_key.len() - 30..].to_string();
173
174 let url = match channel {
175 "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
176 "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
177 _ => return Err(format!("Invalid channel: {channel}")),
178 };
179
180 let body = match channel {
181 "wechat" => {
182 let mut body = object! {
183 MERCHANTID:sub_mchid,
184 POSID:self.posid.clone(),
185 BRANCHID:self.branchid.clone(),
186 ORDERID:out_trade_no,
187 PAYMENT:total_fee,
188 CURCODE:"01",
189 TXCODE:"530590",
190 REMARK1:"",
191 REMARK2:"",
192 TYPE:"1",
193 PUB:pubtext,
194 GATEWAY:"0",
195 CLIENTIP:self.client_ip.clone(),
196 REGINFO:"",
197 PROINFO: self.escape_unicode(description),
198 REFERER:"",
199 TRADE_TYPE:"",
200 SUB_APPID: "",
201 SUB_OPENID:sp_openid,
202 MAC:"",
203 };
204 body["TRADE_TYPE"] = match types {
205 Types::Jsapi => {
206 body["SUB_APPID"] = self.appid_subscribe.clone().into();
207 "JSAPI"
208 }
209 Types::MiniJsapi => {
210 body["SUB_APPID"] = self.appid.clone().into();
211 "MINIPRO"
212 }
213 _ => return Err(format!("Invalid types: {types:?}")),
214 }.into();
215
216 body
232 }
233 "alipay" => {
234 let body = match types {
235 Types::Jsapi | Types::MiniJsapi => object! {
236 MERCHANTID:sub_mchid,
237 POSID:self.posid.clone(),
238 BRANCHID:self.branchid.clone(),
239 ORDERID:out_trade_no,
240 PAYMENT:total_fee,
241 CURCODE:"01",
242 TXCODE:"530591",
243 TRADE_TYPE:"JSAPI",
244 USERID:sp_openid,
245 PUB:pubtext,
246 MAC:""
247 },
248 Types::H5 => object! {
249 BRANCHID:self.branchid.clone(),
250 MERCHANTID:sub_mchid,
251 POSID:self.posid.clone(),
252 TXCODE:"ZFBWAP",
253 ORDERID:out_trade_no,
254 AMOUNT:total_fee,
255 TIMEOUT:"",
256 REMARK1:"",
257 REMARK2:"",
258 PUB:pubtext,
259 MAC:"",
260 SUBJECT:description,
261 AREA_INFO:""
262 },
263 _ => return Err(format!("Invalid types: {types:?}")),
264 };
265 body
266 }
267 _ => return Err(format!("Invalid channel: {channel}")),
268 };
269 let res = self.http(url, body)?;
270 match (channel, types) {
271 ("wechat", Types::Jsapi | Types::MiniJsapi) => {
272 if res.has_key("PAYURL") {
273 let url = res["PAYURL"].to_string();
274 let mut http = br_reqwest::Client::new();
275
276 let re = match http.post(url.as_str()).send() {
277 Ok(e) => e,
278 Err(e) => {
279 return Err(e.to_string());
280 }
281 };
282 let re = re.body().to_string();
283 let res = match json::parse(&re) {
284 Ok(e) => e,
285 Err(_) => return Err(re)
286 };
287 if res.has_key("ERRCODE") && res["ERRCODE"] != "000000" {
288 return Err(format!("获取支付参数: 错误码: [{}] {} 失败", res["ERRCODE"], res["ERRMSG"]));
289 }
290 Ok(res)
291 } else {
292 Err(res.to_string())
293 }
294 }
295 ("alipay", Types::MiniJsapi) => {
296 if res.has_key("PAYURL") {
297 let url = res["PAYURL"].to_string();
298 let mut http = br_reqwest::Client::new();
299
300 let re = match http.post(url.as_str()).send() {
301 Ok(e) => e,
302 Err(e) => {
303 return Err(e.to_string());
304 }
305 };
306 let re = re.body().to_string();
307 let res = match json::parse(&re) {
308 Ok(e) => e,
309 Err(_) => return Err(re)
310 };
311 if res.has_key("ERRCODE") && res["ERRCODE"] != "000000" {
312 return Err(format!("获取支付参数: 错误码: [{}] {} 失败", res["ERRCODE"], res["ERRMSG"]));
313 }
314 Ok(res)
315 } else {
316 Err(res.to_string())
317 }
318 }
319 ("alipay", Types::H5) => {
320 println!("alipay");
321 Ok(res)
322 }
323 _ => {
324 Ok(res)
325 }
326 }
327 }
328
329 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> {
330 let mut body = object! {
331 MERCHANTID:self.sp_mchid.clone(),
332 POSID:self.posid.clone(),
333 BRANCHID:self.branchid.clone(),
334 ccbParam:"",
335 TXCODE:"PAY100",
336 MERFLAG:"1",
337 ORDERID:out_trade_no,
338 QRCODE:auth_code,
339 AMOUNT:total_fee,
340 PROINFO:"商品名称",
341 REMARK1:description
342 };
343
344 let url = match channel {
345 "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
346 "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
347 _ => return Err(format!("Invalid channel: {channel}")),
348 };
349
350 match channel {
351 "wechat" => {
352 body["SUB_APPID"] = self.appid.clone().into();
353 }
354 "alipay" => {}
355 _ => return Err(format!("Invalid channel: {channel}")),
356 }
357
358 let res = self.http(url, body)?;
359 Ok(res)
360 }
361
362 fn close(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
363 Ok(true.into())
364 }
365
366 fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
367 let today = Local::now().date_naive();
368 let date_str = today.format("%Y%m%d").to_string();
369 let body = object! {
370 MERCHANTID:sub_mchid,
371 BRANCHID:self.branchid.clone(),
372 POSID:self.posid.clone(),
373 ORDERDATE:date_str,
374 BEGORDERTIME:"00:00:00",
375 ENDORDERTIME:"23:59:59",
376 ORDERID:out_trade_no,
377 QUPWD:self.pass.clone(),
378 TXCODE:"410408",
379 TYPE:"0",
380 KIND:"0",
381 STATUS:"1",
382 SEL_TYPE:"3",
383 PAGE:"1",
384 OPERATOR:"",
385 CHANNEL:"",
386 MAC:""
387 };
388 let res = self.http_q("https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain", body)?;
389 if res["RETURN_CODE"] != "000000" {
390 if res["RETURN_MSG"].eq("流水记录不存在") {
391 let res = PayNotify {
392 trade_type: TradeType::None,
393 out_trade_no: "".to_string(),
394 sp_mchid: "".to_string(),
395 sub_mchid: "".to_string(),
396 sp_appid: "".to_string(),
397 transaction_id: "".to_string(),
398 success_time: 0,
399 sp_openid: "".to_string(),
400 sub_openid: "".to_string(),
401 total: 0.0,
402 payer_total: 0.0,
403 currency: "".to_string(),
404 payer_currency: "".to_string(),
405 trade_state: TradeState::NOTPAY,
406 };
407 return Ok(res.json());
408 }
409 return Err(res["RETURN_MSG"].to_string());
410 }
411 let data = res["QUERYORDER"].clone();
412 let res = PayNotify {
413 trade_type: TradeType::None,
414 out_trade_no: data["ORDERID"].to_string(),
415 sp_mchid: "".to_string(),
416 sub_mchid: sub_mchid.to_string(),
417 sp_appid: "".to_string(),
418 transaction_id: data["ORDERID"].to_string(),
419 success_time: PayNotify::datetime_to_timestamp(data["ORDERDATE"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
420 sp_openid: "".to_string(),
421 sub_openid: "".to_string(),
422 total: data["AMOUNT"].as_f64().unwrap_or(0.0),
423 currency: "CNY".to_string(),
424 payer_total: data["AMOUNT"].as_f64().unwrap_or(0.0),
425 payer_currency: "CNY".to_string(),
426 trade_state: TradeState::from(data["STATUS"].as_str().unwrap()),
427 };
428 Ok(res.json())
429 }
430
431 fn pay_micropay_query(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
432 Err("暂未开通".to_string())
433 }
434
435 fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
436 Err("暂未开通".to_string())
437 }
438
439 fn refund(&mut self, _sub_mchid: &str, _out_trade_no: &str, _transaction_id: &str, _out_refund_no: &str, _amount: f64, _total: f64, _currency: &str) -> Result<JsonValue, String> {
440 Err("暂未开通".to_string())
449 }
450
451 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> {
452 Err("暂未开通".to_string())
453 }
454
455 fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
456 Err("暂未开通".to_string())
457 }
458
459 fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
460 let today = Local::now().date_naive();
461 let date_str = today.format("%Y%m%d").to_string();
462 let body = object! {
463 MERCHANTID:sub_mchid,
464 BRANCHID:self.branchid.clone(),
465 POSID:self.posid.clone(),
466 ORDERDATE:date_str,
467 BEGORDERTIME:"00:00:00",
468 ENDORDERTIME:"23:59:59",
469 ORDERID:out_refund_no,
470 QUPWD:self.pass.clone(),
471 TXCODE:"410408",
472 TYPE:"1",
473 KIND:"0",
474 STATUS:"1",
475 SEL_TYPE:"3",
476 PAGE:"1",
477 OPERATOR:"",
478 CHANNEL:"",
479 MAC:""
480 };
481 let res = self.http_q("https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain", body)?;
482 if res["RETURN_CODE"] != "000000" {
483 if res["RETURN_MSG"].eq("流水记录不存在") {
484 let res = PayNotify {
485 trade_type: TradeType::None,
486 out_trade_no: "".to_string(),
487 sp_mchid: "".to_string(),
488 sub_mchid: "".to_string(),
489 sp_appid: "".to_string(),
490 transaction_id: "".to_string(),
491 success_time: 0,
492 sp_openid: "".to_string(),
493 sub_openid: "".to_string(),
494 total: 0.0,
495 payer_total: 0.0,
496 currency: "".to_string(),
497 payer_currency: "".to_string(),
498 trade_state: TradeState::NOTPAY,
499 };
500 return Ok(res.json());
501 }
502 return Err(res["RETURN_MSG"].to_string());
503 }
504 println!("refund_query: {res:#}");
505 let data = res["QUERYORDER"].clone();
506
507 let res = RefundNotify {
508 out_trade_no: trade_no.to_string(),
509 refund_no: out_refund_no.to_string(),
510 sp_mchid: "".to_string(),
511 sub_mchid: sub_mchid.to_string(),
512 transaction_id: data["ORDERID"].to_string(),
513 refund_id: data["refund_id"].to_string(),
514 success_time: PayNotify::datetime_to_timestamp(data["ORDERDATE"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
515 total: data["AMOUNT"].as_f64().unwrap_or(0.0),
516 payer_total: data["amount"]["total"].to_string().parse::<f64>().unwrap(),
517 refund: data["amount"]["refund"].to_string().parse::<f64>().unwrap(),
518 payer_refund: data["amount"]["refund"].to_string().parse::<f64>().unwrap(),
519 status: RefundStatus::from(data["STATUS"].as_str().unwrap()),
520 };
521
522 Ok(res.json())
523 }
524
525 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> {
526 todo!()
527 }
528}
529
530fn xml_element_to_json(elem: &Element) -> JsonValue {
531 let mut obj = object! {};
532
533 for child in &elem.children {
534 if let xmltree::XMLNode::Element(e) = child {
535 obj[e.name.clone()] = xml_element_to_json(e);
536 }
537 }
538
539 match elem.get_text() {
540 None => obj,
541 Some(text) => JsonValue::from(text.to_string()),
542 }
543}