use chrono::Local;
use json::{object, JsonValue};
use log::{warn};
use xmltree::Element;
use crate::{PayMode, PayNotify, RefundNotify, RefundStatus, TradeState, TradeType, Types};
#[derive(Clone, Debug)]
pub struct Ccbc {
pub appid: String,
pub appid_subscribe: String,
pub pass: String,
pub sp_mchid: String,
pub notify_url: String,
pub posid: String,
pub branchid: String,
pub public_key: String,
pub client_ip: String,
pub wechat_mchid: 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", "SUBJECT", "AREA_INFO"];
for (key, value) in body.entries() {
if value.is_empty() && fields.contains(&key) {
continue;
}
if 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 http = br_reqwest::Client::new();
let res = match http.post(urls.as_str()).raw_json(body.clone()).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.body().to_string();
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(); 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 http = br_reqwest::Client::new();
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");
let res = match http.post(url).form_urlencoded(body.clone()).send() {
Ok(d) => d,
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.clone())?;
return Ok(res);
}
};
let res = res.body().to_string().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 config(&mut self) -> JsonValue {
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() || self.public_key.len() < 30 {
return Err(String::from("Public key is empty"));
}
let pubtext = self.public_key[self.public_key.len() - 30..].to_string();
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}")),
};
let body = match channel {
"wechat" => {
let mut body = object! {
MERCHANTID:sub_mchid,
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:"",
PROINFO: self.escape_unicode(description),
REFERER:"",
TRADE_TYPE:"",
SUB_APPID: "",
SUB_OPENID:sp_openid,
MAC:"",
};
body["TRADE_TYPE"] = match types {
Types::Jsapi => {
body["SUB_APPID"] = self.appid_subscribe.clone().into();
"JSAPI"
}
Types::MiniJsapi => {
body["SUB_APPID"] = self.appid.clone().into();
"MINIPRO"
}
_ => return Err(format!("Invalid types: {types:?}")),
}.into();
body
}
"alipay" => {
let body = match types {
Types::Jsapi | Types::MiniJsapi => object! {
MERCHANTID:sub_mchid,
POSID:self.posid.clone(),
BRANCHID:self.branchid.clone(),
ORDERID:out_trade_no,
PAYMENT:total_fee,
CURCODE:"01",
TXCODE:"530591",
TRADE_TYPE:"JSAPI",
USERID:sp_openid,
PUB:pubtext,
MAC:""
},
Types::H5 => object! {
BRANCHID:self.branchid.clone(),
MERCHANTID:sub_mchid,
POSID:self.posid.clone(),
TXCODE:"ZFBWAP",
ORDERID:out_trade_no,
AMOUNT:total_fee,
TIMEOUT:"",
REMARK1:"",
REMARK2:"",
PUB:pubtext,
MAC:"",
SUBJECT:description,
AREA_INFO:""
},
_ => return Err(format!("Invalid types: {types:?}")),
};
body
}
_ => return Err(format!("Invalid channel: {channel}")),
};
let res = self.http(url, body)?;
match (channel, types) {
("wechat", Types::Jsapi | Types::MiniJsapi) => {
if res.has_key("PAYURL") {
let url = res["PAYURL"].to_string();
let mut http = br_reqwest::Client::new();
let re = match http.post(url.as_str()).send() {
Ok(e) => e,
Err(e) => {
return Err(e.to_string());
}
};
let re = re.body().to_string();
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())
}
}
("alipay", Types::MiniJsapi) => {
if res.has_key("PAYURL") {
let url = res["PAYURL"].to_string();
let mut http = br_reqwest::Client::new();
let re = match http.post(url.as_str()).send() {
Ok(e) => e,
Err(e) => {
return Err(e.to_string());
}
};
let re = re.body().to_string();
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())
}
}
("alipay", Types::H5) => {
println!("alipay");
Ok(res)
}
_ => {
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:sub_mchid,
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> {
Err("暂未开通".to_string())
}
fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
Err("暂未开通".to_string())
}
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> {
Err("暂未开通".to_string())
}
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> {
Err("暂未开通".to_string())
}
fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
Err("暂未开通".to_string())
}
fn refund_query(&mut self, trade_no: &str, out_refund_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:sub_mchid,
BRANCHID:self.branchid.clone(),
POSID:self.posid.clone(),
ORDERDATE:date_str,
BEGORDERTIME:"00:00:00",
ENDORDERTIME:"23:59:59",
ORDERID:out_refund_no,
QUPWD:self.pass.clone(),
TXCODE:"410408",
TYPE:"1",
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());
}
println!("refund_query: {res:#}");
let data = res["QUERYORDER"].clone();
let res = RefundNotify {
out_trade_no: trade_no.to_string(),
refund_no: out_refund_no.to_string(),
sp_mchid: "".to_string(),
sub_mchid: sub_mchid.to_string(),
transaction_id: data["ORDERID"].to_string(),
refund_id: data["refund_id"].to_string(),
success_time: PayNotify::datetime_to_timestamp(data["ORDERDATE"].as_str().unwrap_or(""), "%Y%m%d%H%M%S"),
total: data["AMOUNT"].as_f64().unwrap_or(0.0),
payer_total: data["amount"]["total"].to_string().parse::<f64>().unwrap(),
refund: data["amount"]["refund"].to_string().parse::<f64>().unwrap(),
payer_refund: data["amount"]["refund"].to_string().parse::<f64>().unwrap(),
status: RefundStatus::from(data["STATUS"].as_str().unwrap()),
};
Ok(res.json())
}
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()),
}
}