br_pay/
ccbc.rs

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/// 建设银行
11#[derive(Clone, Debug)]
12pub struct Ccbc {
13    /// 服务商APPID
14    pub appid: String,
15    /// 密钥
16    pub secret: String,
17    /// 登录密码
18    pub pass: String,
19    /// 银行商户号
20    pub mchid: String,
21    /// 微信商户号
22    pub sp_mchid: String,
23    /// 通知地址
24    pub notify_url: String,
25    /// 商户柜台代码
26    pub posid: String,
27    /// 分行代码
28    pub branchid: String,
29    /// 二级商户名称
30    pub smername: String,
31    /// 二级商户类别代码
32    pub smertypeid: String,
33    /// 二级商户类别名称
34    pub smertype: String,
35    /// 二级商户公钥
36    pub public_key: String,
37    pub client_ip: String,
38    /// 重试次
39    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(); // consume 'u'
111                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    fn auth(&mut self, _code: &str) -> Result<JsonValue, String> {
187        todo!()
188    }
189
190    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> {
191        if self.public_key.is_empty() {
192            return Err(String::from("Public key is empty"));
193        }
194        let pubtext = self.public_key[self.public_key.len() - 30..].to_string();
195        let mut body = object! {
196            MERCHANTID:self.mchid.clone(),
197            POSID:self.posid.clone(),
198            BRANCHID:self.branchid.clone(),
199            ORDERID:out_trade_no,
200            PAYMENT:total_fee,
201            CURCODE:"01",
202            TXCODE:"530590",
203            REMARK1:"",
204            REMARK2:"",
205            TYPE:"1",
206            PUB:pubtext,
207            GATEWAY:"0",
208            CLIENTIP:self.client_ip.clone(),
209            REGINFO:self.escape_unicode(&self.smername.clone()),
210            PROINFO: self.escape_unicode(description),
211            REFERER:"",
212            TRADE_TYPE:"",
213            MAC:"",
214        };
215
216        let url = match channel {
217            "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
218            "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
219            _ => return Err(format!("Invalid channel: {channel}")),
220        };
221
222        match channel {
223            "wechat" => {
224                body["TRADE_TYPE"] = match types {
225                    Types::Jsapi => "JSAPI",
226                    Types::MiniJsapi => "MINIPRO",
227                    _ => return Err(format!("Invalid channel: {types:?}")),
228                }.into();
229                body["SUB_APPID"] = self.appid.clone().into();
230                body["SUB_OPENID"] = sp_openid.into();
231
232                //body["WX_CHANNELID"] = self.sp_mchid.clone().into();
233
234                //body["SMERID"] = sub_mchid.into();
235                //body["SMERNAME"] = self.escape_unicode(self.smername.clone().as_str()).into();
236                //body["SMERTYPEID"] = self.smertypeid.clone().into();
237                //body["SMERTYPE"] = self.escape_unicode(self.smertype.clone().as_str()).into();
238
239                //body["SMERNAME"] = self.escape_unicode(self.smername.clone().as_str()).into();
240                //body["SMERTYPEID"] = 1.into();
241                //body["SMERTYPE"] = self.escape_unicode("宾馆餐娱类").into();
242
243                //body["TRADECODE"] = "交易类型代码".into();
244                //body["TRADENAME"] = self.escape_unicode("消费").into();
245                //body["SMEPROTYPE"] = "商品类别代码".into();
246                //body["PRONAME"] = self.escape_unicode("商品").into();
247            }
248            "alipay" => {
249                body["TXCODE"] = "530591".into();
250                body["TRADE_TYPE"] = match types {
251                    Types::Jsapi => "JSAPI",
252                    Types::MiniJsapi => "JSAPI",
253                    _ => return Err(format!("Invalid channel: {types:?}")),
254                }.into();
255                body["USERID"] = sp_openid.into();
256            }
257            _ => return Err(format!("Invalid channel: {channel}")),
258        }
259        let res = self.http(url, body)?;
260        match types {
261            Types::Jsapi | Types::MiniJsapi => {
262                if res.has_key("PAYURL") {
263                    let url = res["PAYURL"].to_string();
264
265                    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() {
266                        Ok(e) => e,
267                        Err(e) => return Err(e.to_string())
268                    };
269                    let re = match http.post(url.as_str()).send() {
270                        Ok(e) => e,
271                        Err(e) => {
272                            return Err(e.to_string());
273                        }
274                    };
275                    let re = re.text().unwrap();
276                    let res = match json::parse(&re) {
277                        Ok(e) => e,
278                        Err(_) => return Err(re)
279                    };
280                    if res.has_key("ERRCODE") && res["ERRCODE"] != "000000" {
281                        return Err(format!("获取支付参数: 错误码: [{}] {} 失败", res["ERRCODE"], res["ERRMSG"]));
282                    }
283                    Ok(res)
284                } else {
285                    Err(res.to_string())
286                }
287            }
288            _ => {
289                Ok(res)
290            }
291        }
292    }
293
294    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> {
295        let mut body = object! {
296            MERCHANTID:self.sp_mchid.clone(),
297            POSID:self.posid.clone(),
298            BRANCHID:self.branchid.clone(),
299            ccbParam:"",
300            TXCODE:"PAY100",
301            MERFLAG:"1",
302            ORDERID:out_trade_no,
303            QRCODE:auth_code,
304            AMOUNT:total_fee,
305            PROINFO:"商品名称",
306            REMARK1:description
307        };
308
309        let url = match channel {
310            "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
311            "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
312            _ => return Err(format!("Invalid channel: {channel}")),
313        };
314
315        match channel {
316            "wechat" => {
317                body["SUB_APPID"] = self.appid.clone().into();
318            }
319            "alipay" => {}
320            _ => return Err(format!("Invalid channel: {channel}")),
321        }
322
323        let res = self.http(url, body)?;
324        Ok(res)
325    }
326
327    fn close(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
328        Ok(true.into())
329    }
330
331    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
332        let today = Local::now().date_naive();
333        let date_str = today.format("%Y%m%d").to_string();
334        let body = object! {
335            MERCHANTID:self.mchid.clone(),
336            BRANCHID:self.branchid.clone(),
337            POSID:self.posid.clone(),
338            ORDERDATE:date_str,
339            BEGORDERTIME:"00:00:00",
340            ENDORDERTIME:"23:59:59",
341            ORDERID:out_trade_no,
342            QUPWD:self.pass.clone(),
343            TXCODE:"410408",
344            TYPE:"0",
345            KIND:"0",
346            STATUS:"1",
347            SEL_TYPE:"3",
348            PAGE:"1",
349            OPERATOR:"",
350            CHANNEL:"",
351            MAC:""
352        };
353        let res = self.http_q("https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain", body)?;
354        if res["RETURN_CODE"] != "000000" {
355            if res["RETURN_MSG"].eq("流水记录不存在") {
356                let res = PayNotify {
357                    trade_type: TradeType::None,
358                    out_trade_no: "".to_string(),
359                    sp_mchid: "".to_string(),
360                    sub_mchid: "".to_string(),
361                    sp_appid: "".to_string(),
362                    transaction_id: "".to_string(),
363                    success_time: 0,
364                    sp_openid: "".to_string(),
365                    sub_openid: "".to_string(),
366                    total: 0.0,
367                    payer_total: 0.0,
368                    currency: "".to_string(),
369                    payer_currency: "".to_string(),
370                    trade_state: TradeState::NOTPAY,
371                };
372                return Ok(res.json());
373            }
374            return Err(res["RETURN_MSG"].to_string());
375        }
376        let data = res["QUERYORDER"].clone();
377        let res = PayNotify {
378            trade_type: TradeType::None,
379            out_trade_no: data["ORDERID"].to_string(),
380            sp_mchid: "".to_string(),
381            sub_mchid: sub_mchid.to_string(),
382            sp_appid: "".to_string(),
383            transaction_id: data["ORDERID"].to_string(),
384            success_time: PayNotify::datetime_to_timestamp(data["ORDERDATE"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
385            sp_openid: "".to_string(),
386            sub_openid: "".to_string(),
387            total: data["AMOUNT"].as_f64().unwrap_or(0.0),
388            currency: "CNY".to_string(),
389            payer_total: data["AMOUNT"].as_f64().unwrap_or(0.0),
390            payer_currency: "CNY".to_string(),
391            trade_state: TradeState::from(data["STATUS"].as_str().unwrap()),
392        };
393        Ok(res.json())
394    }
395
396    fn pay_micropay_query(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
397        todo!()
398    }
399
400    fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
401        todo!()
402    }
403
404    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> {
405        todo!()
406    }
407
408    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> {
409        todo!()
410    }
411
412    fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
413        todo!()
414    }
415
416    fn refund_query(&mut self, _trade_no: &str, _out_refund_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
417        todo!()
418    }
419
420    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> {
421        todo!()
422    }
423}
424
425fn xml_element_to_json(elem: &Element) -> JsonValue {
426    let mut obj = object! {};
427
428    for child in &elem.children {
429        if let xmltree::XMLNode::Element(e) = child {
430            obj[e.name.clone()] = xml_element_to_json(e);
431        }
432    }
433
434    match elem.get_text() {
435        None => obj,
436        Some(text) => JsonValue::from(text.to_string()),
437    }
438}