br-pay 0.0.54

This is an pay
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::collections::{HashMap};
use chrono::Local;
use json::{object, JsonValue};
use log::{warn};
use reqwest::header;
use reqwest::tls::Version;
use xmltree::Element;
use crate::{PayMode, PayNotify, TradeState, TradeType, Types};

/// 建设银行
#[derive(Clone, Debug)]
pub struct Ccbc {
    /// 服务商APPID
    pub appid: String,
    /// 密钥
    pub secret: String,
    /// 登录密码
    pub pass: String,
    /// 银行商户号
    pub mchid: String,
    /// 微信商户号
    pub sp_mchid: String,
    /// 通知地址
    pub notify_url: String,
    /// 商户柜台代码
    pub posid: String,
    /// 分行代码
    pub branchid: String,
    /// 二级商户名称
    pub smername: String,
    /// 二级商户类别代码
    pub smertypeid: String,
    /// 二级商户类别名称
    pub smertype: String,
    /// 二级商户公钥
    pub public_key: String,
    pub client_ip: String,
    /// 重试次
    pub retry: usize,
}

impl Ccbc {
    pub fn http(&mut self, url: &str, mut body: JsonValue) -> Result<JsonValue, String> {
        let mut mac = vec![];
        let mut path = vec![];
        let fields = ["MAC"];
        for (key, value) in body.entries() {
            if value.is_empty() && fields.contains(&key) {
                continue;
            }
            if key != "PUB" {
                path.push(format!("{key}={value}"));
            }
            mac.push(format!("{key}={value}"));
        }


        let mac_text = mac.join("&");
        let path = path.join("&");
        body["MAC"] = br_crypto::md5::encrypt_hex(mac_text.as_bytes()).into();
        body.remove("PUB");
        let mac = format!("{}&MAC={}", path, body["MAC"]);

        let urls = format!("{url}&{mac}");


        let mut map = HashMap::new();
        for (key, value) in body.entries_mut() {
            map.insert(key, value.to_string());
        }

        let http = match reqwest::blocking::Client::builder().build() {
            Ok(e) => e,
            Err(e) => return Err(e.to_string())
        };

        let res = match http.post(urls).json(&map).send() {
            Ok(e) => e,
            Err(e) => {
                if self.retry > 2 {
                    return Err(e.to_string());
                }
                self.retry += 1;
                warn!("建行接口重试: {}", self.retry);
                body.remove("MAC");
                let res = self.http(url, body.clone())?;
                return Ok(res);
            }
        };
        let res = res.text().unwrap();
        match json::parse(&res) {
            Ok(e) => Ok(e),
            Err(_) => Err(res)
        }
    }
    fn escape_unicode(&mut self, s: &str) -> String {
        s.chars().map(|c| {
            if c.is_ascii() {
                c.to_string()
            } else {
                format!("%u{:04X}", c as u32)
            }
        }).collect::<String>()
    }
    fn _unescape_unicode(&mut self, s: &str) -> String {
        let mut output = String::new();
        let mut chars = s.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '%' && chars.peek() == Some(&'u') {
                chars.next(); // consume 'u'
                let codepoint: String = chars.by_ref().take(4).collect();
                if let Ok(value) = u32::from_str_radix(&codepoint, 16) {
                    if let Some(ch) = std::char::from_u32(value) {
                        output.push(ch);
                    }
                }
            } else {
                output.push(c);
            }
        }
        output
    }
    pub fn http_q(&mut self, url: &str, mut body: JsonValue) -> Result<JsonValue, String> {
        let mut path = vec![];
        let fields = ["MAC"];
        for (key, value) in body.entries() {
            if value.is_empty() && fields.contains(&key) {
                continue;
            }
            if key.contains("QUPWD") {
                path.push(format!("{key}="));
                continue;
            }
            path.push(format!("{key}={value}"));
        }

        let mac = path.join("&");
        body["MAC"] = br_crypto::md5::encrypt_hex(mac.as_bytes()).into();

        let mut map = vec![];
        for (key, value) in body.entries() {
            map.push((key, value.to_string()));
        }
        let mut headers = header::HeaderMap::new();
        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"));

        let http = match reqwest::blocking::Client::builder().default_headers(headers).build() {
            Ok(e) => e,
            Err(e) => return Err(e.to_string())
        };

        let res = match http.post(url).form(&map).send() {
            Ok(e) => e,
            Err(e) => {
                if self.retry > 2 {
                    return Err(e.to_string());
                }
                self.retry += 1;
                warn!("建行查询接口重试: {}", self.retry);
                body.remove("MAC");
                let res = self.http_q(url, body)?;
                return Ok(res);
            }
        };
        let res = res.text().unwrap().trim().to_string();
        match Element::parse(res.as_bytes()) {
            Ok(e) => Ok(xml_element_to_json(&e)),
            Err(e) => Err(e.to_string())
        }
    }
}
impl PayMode for Ccbc {
    fn check(&mut self) -> Result<bool, String> {
        todo!()
    }

    fn get_sub_mchid(&mut self, _sub_mchid: &str) -> Result<JsonValue, String> {
        todo!()
    }

    fn notify(&mut self, _data: JsonValue) -> Result<JsonValue, String> {
        todo!()
    }

    fn config(&mut self) -> JsonValue {
        todo!()
    }


    fn auth(&mut self, _code: &str) -> Result<JsonValue, String> {
        todo!()
    }

    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> {
        if self.public_key.is_empty() {
            return Err(String::from("Public key is empty"));
        }
        let pubtext = self.public_key[self.public_key.len() - 30..].to_string();
        let mut body = object! {
            MERCHANTID:self.mchid.clone(),
            POSID:self.posid.clone(),
            BRANCHID:self.branchid.clone(),
            ORDERID:out_trade_no,
            PAYMENT:total_fee,
            CURCODE:"01",
            TXCODE:"530590",
            REMARK1:"",
            REMARK2:"",
            TYPE:"1",
            PUB:pubtext,
            GATEWAY:"0",
            CLIENTIP:self.client_ip.clone(),
            REGINFO:self.escape_unicode(&self.smername.clone()),
            PROINFO: self.escape_unicode(description),
            REFERER:"",
            TRADE_TYPE:"",
            MAC:"",
        };

        let url = match channel {
            "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
            "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
            _ => return Err(format!("Invalid channel: {channel}")),
        };

        match channel {
            "wechat" => {
                body["TRADE_TYPE"] = match types {
                    Types::Jsapi => "JSAPI",
                    Types::MiniJsapi => "MINIPRO",
                    _ => return Err(format!("Invalid channel: {types:?}")),
                }.into();
                body["SUB_APPID"] = self.appid.clone().into();
                body["SUB_OPENID"] = sp_openid.into();

                //body["WX_CHANNELID"] = self.sp_mchid.clone().into();

                //body["SMERID"] = sub_mchid.into();
                //body["SMERNAME"] = self.escape_unicode(self.smername.clone().as_str()).into();
                //body["SMERTYPEID"] = self.smertypeid.clone().into();
                //body["SMERTYPE"] = self.escape_unicode(self.smertype.clone().as_str()).into();

                //body["SMERNAME"] = self.escape_unicode(self.smername.clone().as_str()).into();
                //body["SMERTYPEID"] = 1.into();
                //body["SMERTYPE"] = self.escape_unicode("宾馆餐娱类").into();

                //body["TRADECODE"] = "交易类型代码".into();
                //body["TRADENAME"] = self.escape_unicode("消费").into();
                //body["SMEPROTYPE"] = "商品类别代码".into();
                //body["PRONAME"] = self.escape_unicode("商品").into();
            }
            "alipay" => {
                body["TXCODE"] = "530591".into();
                body["TRADE_TYPE"] = match types {
                    Types::Jsapi => "JSAPI",
                    Types::MiniJsapi => "JSAPI",
                    _ => return Err(format!("Invalid channel: {types:?}")),
                }.into();
                body["USERID"] = sp_openid.into();
            }
            _ => return Err(format!("Invalid channel: {channel}")),
        }
        let res = self.http(url, body)?;
        match types {
            Types::Jsapi | Types::MiniJsapi => {
                if res.has_key("PAYURL") {
                    let url = res["PAYURL"].to_string();

                    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() {
                        Ok(e) => e,
                        Err(e) => return Err(e.to_string())
                    };
                    let re = match http.post(url.as_str()).send() {
                        Ok(e) => e,
                        Err(e) => {
                            return Err(e.to_string());
                        }
                    };
                    let re = re.text().unwrap();
                    let res = match json::parse(&re) {
                        Ok(e) => e,
                        Err(_) => return Err(re)
                    };
                    if res.has_key("ERRCODE") && res["ERRCODE"] != "000000" {
                        return Err(format!("获取支付参数: 错误码: [{}] {} 失败", res["ERRCODE"], res["ERRMSG"]));
                    }
                    Ok(res)
                } else {
                    Err(res.to_string())
                }
            }
            _ => {
                Ok(res)
            }
        }
    }

    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> {
        let mut body = object! {
            MERCHANTID:self.sp_mchid.clone(),
            POSID:self.posid.clone(),
            BRANCHID:self.branchid.clone(),
            ccbParam:"",
            TXCODE:"PAY100",
            MERFLAG:"1",
            ORDERID:out_trade_no,
            QRCODE:auth_code,
            AMOUNT:total_fee,
            PROINFO:"商品名称",
            REMARK1:description
        };

        let url = match channel {
            "wechat" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
            "alipay" => "https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6",
            _ => return Err(format!("Invalid channel: {channel}")),
        };

        match channel {
            "wechat" => {
                body["SUB_APPID"] = self.appid.clone().into();
            }
            "alipay" => {}
            _ => return Err(format!("Invalid channel: {channel}")),
        }

        let res = self.http(url, body)?;
        Ok(res)
    }

    fn close(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
        Ok(true.into())
    }

    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
        let today = Local::now().date_naive();
        let date_str = today.format("%Y%m%d").to_string();
        let body = object! {
            MERCHANTID:self.mchid.clone(),
            BRANCHID:self.branchid.clone(),
            POSID:self.posid.clone(),
            ORDERDATE:date_str,
            BEGORDERTIME:"00:00:00",
            ENDORDERTIME:"23:59:59",
            ORDERID:out_trade_no,
            QUPWD:self.pass.clone(),
            TXCODE:"410408",
            TYPE:"0",
            KIND:"0",
            STATUS:"1",
            SEL_TYPE:"3",
            PAGE:"1",
            OPERATOR:"",
            CHANNEL:"",
            MAC:""
        };
        let res = self.http_q("https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain", body)?;
        if res["RETURN_CODE"] != "000000" {
            if res["RETURN_MSG"].eq("流水记录不存在") {
                let res = PayNotify {
                    trade_type: TradeType::None,
                    out_trade_no: "".to_string(),
                    sp_mchid: "".to_string(),
                    sub_mchid: "".to_string(),
                    sp_appid: "".to_string(),
                    transaction_id: "".to_string(),
                    success_time: 0,
                    sp_openid: "".to_string(),
                    sub_openid: "".to_string(),
                    total: 0.0,
                    payer_total: 0.0,
                    currency: "".to_string(),
                    payer_currency: "".to_string(),
                    trade_state: TradeState::NOTPAY,
                };
                return Ok(res.json());
            }
            return Err(res["RETURN_MSG"].to_string());
        }
        let data = res["QUERYORDER"].clone();
        let res = PayNotify {
            trade_type: TradeType::None,
            out_trade_no: data["ORDERID"].to_string(),
            sp_mchid: "".to_string(),
            sub_mchid: sub_mchid.to_string(),
            sp_appid: "".to_string(),
            transaction_id: data["ORDERID"].to_string(),
            success_time: PayNotify::datetime_to_timestamp(data["ORDERDATE"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
            sp_openid: "".to_string(),
            sub_openid: "".to_string(),
            total: data["AMOUNT"].as_f64().unwrap_or(0.0),
            currency: "CNY".to_string(),
            payer_total: data["AMOUNT"].as_f64().unwrap_or(0.0),
            payer_currency: "CNY".to_string(),
            trade_state: TradeState::from(data["STATUS"].as_str().unwrap()),
        };
        Ok(res.json())
    }

    fn pay_micropay_query(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
        todo!()
    }

    fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
        todo!()
    }

    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> {
        todo!()
    }

    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> {
        todo!()
    }

    fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
        todo!()
    }

    fn refund_query(&mut self, _trade_no: &str, _out_refund_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
        todo!()
    }

    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> {
        todo!()
    }
}

fn xml_element_to_json(elem: &Element) -> JsonValue {
    let mut obj = object! {};

    for child in &elem.children {
        if let xmltree::XMLNode::Element(e) = child {
            obj[e.name.clone()] = xml_element_to_json(e);
        }
    }

    match elem.get_text() {
        None => obj,
        Some(text) => JsonValue::from(text.to_string()),
    }
}