1use std::collections::{HashMap};
2use chrono::Local;
3use json::{object, JsonValue};
4use log::{warn};
5use reqwest::header;
6use reqwest::tls::Version;
7use xmltree::Element;
8use crate::{PayMode, PayNotify, TradeState, TradeType, Types};
9
10#[derive(Clone, Debug)]
12pub struct Ccbc {
13 pub appid: String,
15 pub secret: String,
17 pub pass: String,
19 pub mchid: String,
21 pub sp_mchid: String,
23 pub notify_url: String,
25 pub posid: String,
27 pub branchid: String,
29 pub smername: String,
31 pub smertypeid: String,
33 pub smertype: String,
35 pub public_key: String,
37 pub client_ip: String,
38 pub retry: usize,
40}
41
42impl Ccbc {
43 pub fn http(&mut self, url: &str, mut body: JsonValue) -> Result<JsonValue, String> {
44 let mut mac = vec![];
45 let mut path = vec![];
46 let fields = ["MAC"];
47 for (key, value) in body.entries() {
48 if value.is_empty() && fields.contains(&key) {
49 continue;
50 }
51 if key != "PUB" {
52 path.push(format!("{key}={value}"));
53 }
54 mac.push(format!("{key}={value}"));
55 }
56
57
58 let mac_text = mac.join("&");
59 let path = path.join("&");
60 body["MAC"] = br_crypto::md5::encrypt_hex(mac_text.as_bytes()).into();
61 body.remove("PUB");
62 let mac = format!("{}&MAC={}", path, body["MAC"]);
63
64 let urls = format!("{url}&{mac}");
65
66
67 let mut map = HashMap::new();
68 for (key, value) in body.entries_mut() {
69 map.insert(key, value.to_string());
70 }
71
72 let http = match reqwest::blocking::Client::builder().build() {
73 Ok(e) => e,
74 Err(e) => return Err(e.to_string())
75 };
76
77 let res = match http.post(urls).json(&map).send() {
78 Ok(e) => e,
79 Err(e) => {
80 if self.retry > 2 {
81 return Err(e.to_string());
82 }
83 self.retry += 1;
84 warn!("建行接口重试: {}", self.retry);
85 body.remove("MAC");
86 let res = self.http(url, body.clone())?;
87 return Ok(res);
88 }
89 };
90 let res = res.text().unwrap();
91 match json::parse(&res) {
92 Ok(e) => Ok(e),
93 Err(_) => Err(res)
94 }
95 }
96 fn escape_unicode(&mut self, s: &str) -> String {
97 s.chars().map(|c| {
98 if c.is_ascii() {
99 c.to_string()
100 } else {
101 format!("%u{:04X}", c as u32)
102 }
103 }).collect::<String>()
104 }
105 fn _unescape_unicode(&mut self, s: &str) -> String {
106 let mut output = String::new();
107 let mut chars = s.chars().peekable();
108 while let Some(c) = chars.next() {
109 if c == '%' && chars.peek() == Some(&'u') {
110 chars.next(); let codepoint: String = chars.by_ref().take(4).collect();
112 if let Ok(value) = u32::from_str_radix(&codepoint, 16) {
113 if let Some(ch) = std::char::from_u32(value) {
114 output.push(ch);
115 }
116 }
117 } else {
118 output.push(c);
119 }
120 }
121 output
122 }
123 pub fn http_q(&mut self, url: &str, mut body: JsonValue) -> Result<JsonValue, String> {
124 let mut path = vec![];
125 let fields = ["MAC"];
126 for (key, value) in body.entries() {
127 if value.is_empty() && fields.contains(&key) {
128 continue;
129 }
130 if key.contains("QUPWD") {
131 path.push(format!("{key}="));
132 continue;
133 }
134 path.push(format!("{key}={value}"));
135 }
136
137 let mac = path.join("&");
138 body["MAC"] = br_crypto::md5::encrypt_hex(mac.as_bytes()).into();
139
140 let mut map = vec![];
141 for (key, value) in body.entries() {
142 map.push((key, value.to_string()));
143 }
144 let mut headers = header::HeaderMap::new();
145 headers.insert("user-agent", header::HeaderValue::from_static("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"));
146
147 let http = match reqwest::blocking::Client::builder().default_headers(headers).build() {
148 Ok(e) => e,
149 Err(e) => return Err(e.to_string())
150 };
151
152 let res = match http.post(url).form(&map).send() {
153 Ok(e) => e,
154 Err(e) => {
155 if self.retry > 2 {
156 return Err(e.to_string());
157 }
158 self.retry += 1;
159 warn!("建行查询接口重试: {}", self.retry);
160 body.remove("MAC");
161 let res = self.http_q(url, body)?;
162 return Ok(res);
163 }
164 };
165 let res = res.text().unwrap().trim().to_string();
166 match Element::parse(res.as_bytes()) {
167 Ok(e) => Ok(xml_element_to_json(&e)),
168 Err(e) => Err(e.to_string())
169 }
170 }
171}
172impl PayMode for Ccbc {
173 fn check(&mut self) -> Result<bool, String> {
174 todo!()
175 }
176
177 fn get_sub_mchid(&mut self, _sub_mchid: &str) -> Result<JsonValue, String> {
178 todo!()
179 }
180
181 fn config(&mut self) -> JsonValue {
182 todo!()
183 }
184
185
186
187 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> {
188 if self.public_key.is_empty() {
189 return Err(String::from("Public key is empty"));
190 }
191 let pubtext = self.public_key[self.public_key.len() - 30..].to_string();
192 let mut body = object! {
193 MERCHANTID:self.mchid.clone(),
194 POSID:self.posid.clone(),
195 BRANCHID:self.branchid.clone(),
196 ORDERID:out_trade_no,
197 PAYMENT:total_fee,
198 CURCODE:"01",
199 TXCODE:"530590",
200 REMARK1:"",
201 REMARK2:"",
202 TYPE:"1",
203 PUB:pubtext,
204 GATEWAY:"0",
205 CLIENTIP:self.client_ip.clone(),
206 REGINFO:self.escape_unicode(&self.smername.clone()),
207 PROINFO: self.escape_unicode(description),
208 REFERER:"",
209 TRADE_TYPE:"",
210 MAC:"",
211 };
212
213 let url = match channel {
214 "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
215 "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
216 _ => return Err(format!("Invalid channel: {channel}")),
217 };
218
219 match channel {
220 "wechat" => {
221 body["TRADE_TYPE"] = match types {
222 Types::Jsapi => "JSAPI",
223 Types::MiniJsapi => "MINIPRO",
224 _ => return Err(format!("Invalid channel: {types:?}")),
225 }.into();
226 body["SUB_APPID"] = self.appid.clone().into();
227 body["SUB_OPENID"] = sp_openid.into();
228
229 }
245 "alipay" => {
246 body["TXCODE"] = "530591".into();
247 body["TRADE_TYPE"] = match types {
248 Types::Jsapi => "JSAPI",
249 Types::MiniJsapi => "JSAPI",
250 _ => return Err(format!("Invalid channel: {types:?}")),
251 }.into();
252 body["USERID"] = sp_openid.into();
253 }
254 _ => return Err(format!("Invalid channel: {channel}")),
255 }
256 let res = self.http(url, body)?;
257 match types {
258 Types::Jsapi | Types::MiniJsapi => {
259 if res.has_key("PAYURL") {
260 let url = res["PAYURL"].to_string();
261
262 let http = match reqwest::blocking::Client::builder().min_tls_version(Version::TLS_1_1).max_tls_version(Version::TLS_1_1).danger_accept_invalid_certs(true).build() {
263 Ok(e) => e,
264 Err(e) => return Err(e.to_string())
265 };
266 let re = match http.post(url.as_str()).send() {
267 Ok(e) => e,
268 Err(e) => {
269 return Err(e.to_string());
270 }
271 };
272 let re = re.text().unwrap();
273 let res = match json::parse(&re) {
274 Ok(e) => e,
275 Err(_) => return Err(re)
276 };
277 if res.has_key("ERRCODE") && res["ERRCODE"] != "000000" {
278 return Err(format!("获取支付参数: 错误码: [{}] {} 失败", res["ERRCODE"], res["ERRMSG"]));
279 }
280 Ok(res)
281 } else {
282 Err(res.to_string())
283 }
284 }
285 _ => {
286 Ok(res)
287 }
288 }
289 }
290
291 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> {
292 let mut body = object! {
293 MERCHANTID:self.sp_mchid.clone(),
294 POSID:self.posid.clone(),
295 BRANCHID:self.branchid.clone(),
296 ccbParam:"",
297 TXCODE:"PAY100",
298 MERFLAG:"1",
299 ORDERID:out_trade_no,
300 QRCODE:auth_code,
301 AMOUNT:total_fee,
302 PROINFO:"商品名称",
303 REMARK1:description
304 };
305
306 let url = match channel {
307 "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
308 "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
309 _ => return Err(format!("Invalid channel: {channel}")),
310 };
311
312 match channel {
313 "wechat" => {
314 body["SUB_APPID"] = self.appid.clone().into();
315 }
316 "alipay" => {}
317 _ => return Err(format!("Invalid channel: {channel}")),
318 }
319
320 let res = self.http(url, body)?;
321 Ok(res)
322 }
323
324 fn close(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
325 Ok(true.into())
326 }
327
328 fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
329 let today = Local::now().date_naive();
330 let date_str = today.format("%Y%m%d").to_string();
331 let body = object! {
332 MERCHANTID:self.mchid.clone(),
333 BRANCHID:self.branchid.clone(),
334 POSID:self.posid.clone(),
335 ORDERDATE:date_str,
336 BEGORDERTIME:"00:00:00",
337 ENDORDERTIME:"23:59:59",
338 ORDERID:out_trade_no,
339 QUPWD:self.pass.clone(),
340 TXCODE:"410408",
341 TYPE:"0",
342 KIND:"0",
343 STATUS:"1",
344 SEL_TYPE:"3",
345 PAGE:"1",
346 OPERATOR:"",
347 CHANNEL:"",
348 MAC:""
349 };
350 let res = self.http_q("https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain", body)?;
351 if res["RETURN_CODE"] != "000000" {
352 if res["RETURN_MSG"].eq("流水记录不存在") {
353 let res = PayNotify {
354 trade_type: TradeType::None,
355 out_trade_no: "".to_string(),
356 sp_mchid: "".to_string(),
357 sub_mchid: "".to_string(),
358 sp_appid: "".to_string(),
359 transaction_id: "".to_string(),
360 success_time: 0,
361 sp_openid: "".to_string(),
362 sub_openid: "".to_string(),
363 total: 0.0,
364 payer_total: 0.0,
365 currency: "".to_string(),
366 payer_currency: "".to_string(),
367 trade_state: TradeState::NOTPAY,
368 };
369 return Ok(res.json());
370 }
371 return Err(res["RETURN_MSG"].to_string());
372 }
373 let data = res["QUERYORDER"].clone();
374 let res = PayNotify {
375 trade_type: TradeType::None,
376 out_trade_no: data["ORDERID"].to_string(),
377 sp_mchid: "".to_string(),
378 sub_mchid: sub_mchid.to_string(),
379 sp_appid: "".to_string(),
380 transaction_id: data["ORDERID"].to_string(),
381 success_time: PayNotify::datetime_to_timestamp(data["ORDERDATE"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
382 sp_openid: "".to_string(),
383 sub_openid: "".to_string(),
384 total: data["AMOUNT"].as_f64().unwrap_or(0.0),
385 currency: "CNY".to_string(),
386 payer_total: data["AMOUNT"].as_f64().unwrap_or(0.0),
387 payer_currency: "CNY".to_string(),
388 trade_state: TradeState::from(data["STATUS"].as_str().unwrap()),
389 };
390 Ok(res.json())
391 }
392
393 fn pay_micropay_query(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
394 todo!()
395 }
396
397 fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
398 todo!()
399 }
400
401 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> {
402 todo!()
403 }
404
405 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> {
406 todo!()
407 }
408
409 fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
410 todo!()
411 }
412
413 fn refund_query(&mut self, _trade_no: &str, _out_refund_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
414 todo!()
415 }
416
417 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> {
418 todo!()
419 }
420}
421
422fn xml_element_to_json(elem: &Element) -> JsonValue {
423 let mut obj = object! {};
424
425 for child in &elem.children {
426 if let xmltree::XMLNode::Element(e) = child {
427 obj[e.name.clone()] = xml_element_to_json(e);
428 }
429 }
430
431 match elem.get_text() {
432 None => obj,
433 Some(text) => JsonValue::from(text.to_string()),
434 }
435}