use crate::PayMode;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use json::{object, JsonValue};
use std::fs;
#[derive(Clone)]
pub struct Wechat {
pub appid: String,
pub secret: String,
pub mchid: String,
pub serial_no: String,
pub cert_path: String,
}
use chrono::{DateTime, Utc};
use openssl::hash::MessageDigest;
use openssl::pkey::PKey;
use openssl::rsa::Rsa;
use openssl::sign::Signer;
use rand::distr::Alphanumeric;
use rand::{rng, Rng};
impl Wechat {
pub fn sign(&mut self, method: &str, url: &str, body: &str) -> String {
let timestamp = Utc::now().timestamp(); let random_string: String = rng()
.sample_iter(&Alphanumeric) .take(10) .map(char::from)
.collect();
let sign_txt = format!("{method}\n{url}\n{timestamp}\n{random_string}\n{body}\n");
let private_key_pem = fs::read(self.cert_path.as_str()).expect("Failed to read key file");
let rsa = Rsa::private_key_from_pem(&private_key_pem).expect("Failed to load private key");
let pkey = PKey::from_rsa(rsa).expect("Failed to create PKey");
let mut signer =
Signer::new(MessageDigest::sha256(), &pkey).expect("Failed to create signer");
signer
.update(sign_txt.as_bytes())
.expect("Failed to update signer");
let signature = signer.sign_to_vec().expect("Failed to sign");
let signature_b64 = STANDARD.encode(signature);
let sign = format!(
r#"WECHATPAY2-SHA256-RSA2048 mchid="{}",nonce_str="{random_string}",signature="{signature_b64}",timestamp="{timestamp}",serial_no="{}""#,
self.mchid.as_str(),
self.serial_no
);
sign
}
pub fn paysign(&mut self, prepay_id: &str) -> JsonValue {
let timestamp = Utc::now().timestamp(); let random_string: String = rng()
.sample_iter(&Alphanumeric) .take(10) .map(char::from)
.collect();
let sign_txt = format!(
"{}\n{timestamp}\n{random_string}\n{prepay_id}\n",
self.appid
);
let private_key_pem = fs::read(self.cert_path.as_str()).expect("Failed to read key file");
let rsa = Rsa::private_key_from_pem(&private_key_pem).expect("Failed to load private key");
let pkey = PKey::from_rsa(rsa).expect("Failed to create PKey");
let mut signer =
Signer::new(MessageDigest::sha256(), &pkey).expect("Failed to create signer");
signer
.update(sign_txt.as_bytes())
.expect("Failed to update signer");
let signature = signer.sign_to_vec().expect("Failed to sign");
let signature_b64 = STANDARD.encode(signature);
let sign = signature_b64;
object! {
timeStamp:timestamp,
nonceStr:random_string,
package:prepay_id,
signType:"RSA",
paySign:sign
}
}
}
impl PayMode for Wechat {
fn login(&self, code: &str) -> Result<JsonValue, String> {
let mut http = br_http::Http::new();
match http
.get(
"https://api.weixin.qq.com/sns/jscode2session"
.to_string()
.as_str(),
)
.header("Accept", "application/json")
.header("User-Agent", "api")
.header("Content-Type", "application/json")
.query(object! {
appid: self.appid.as_str(),
secret: self.secret.as_str(),
js_code:code,
grant_type:"authorization_code",
})
.json()
{
Ok(e) => Ok(e),
Err(e) => Err(e),
}
}
fn jsapi(
&mut self,
sub_mchid: &str,
out_trade_no: &str,
description: &str,
total_fee: f64,
notify_url: &str,
sp_openid: &str,
) -> Result<JsonValue, String> {
let url = "/v3/pay/partner/transactions/jsapi";
let total = (total_fee * 100.0) as u64;
let body = object! {
"sp_appid" => self.appid.clone(),
"sp_mchid"=> self.mchid.clone(),
"sub_mchid"=> sub_mchid,
"description"=>description,
"out_trade_no"=>out_trade_no,
"notify_url"=>notify_url,
"support_fapiao"=>true,
"amount"=>object! {
total: total,
currency:"CNY"
},
"payer"=>object! {
sp_openid:sp_openid
}
};
let sign = self.sign("POST", url, body.to_string().as_str());
let mut http = br_http::Http::new();
match http
.post(format!("https://api.mch.weixin.qq.com{}", url).as_str())
.header("Accept", "application/json")
.header("User-Agent", "api")
.header("Content-Type", "application/json")
.header("Authorization", sign.as_str())
.raw_json(body)
.json()
{
Ok(e) => {
if e.has_key("prepay_id") {
let signinfo = self.paysign(format!("prepay_id={}", e["prepay_id"]).as_str());
Ok(signinfo)
} else {
Err(e["message"].to_string())
}
}
Err(e) => Err(e),
}
}
fn order_trade(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
let url = format!(
"/v3/pay/partner/transactions/out-trade-no/{}?sub_mchid={}&sp_mchid={}",
out_trade_no, sub_mchid, self.mchid
);
let sign = self.sign("GET", url.as_str(), "");
let mut http = br_http::Http::new();
match http
.get(format!("https://api.mch.weixin.qq.com{}", url.clone()).as_str())
.header("Accept", "application/json")
.header("User-Agent", "api")
.header("Content-Type", "application/json")
.header("Authorization", sign.as_str())
.json()
{
Ok(e) => {
if e.has_key("message") {
return Err(e["message"].to_string());
}
let pay_time = e["success_time"].as_str().unwrap();
let datetime = DateTime::parse_from_rfc3339(pay_time).unwrap();
let pay_time = datetime.timestamp();
let mut info = object! {
pay_time:pay_time,
sp_appid:e["sp_appid"].clone(),
transaction_id:e["transaction_id"].clone(),
sp_mchid:e["sp_mchid"].clone(),
sub_mchid:e["sub_mchid"].clone(),
order_no:e["out_trade_no"].clone(),
status:"",
sp_openid:e["payer"]["sp_openid"].clone(),
sub_openid:e["payer"]["sub_openid"].clone(),
amount_currency:e["amount"]["currency"].clone(),
amount_total:e["amount"]["total"].clone(),
trade_state_desc:e["trade_state_desc"].clone(),
trade_type:e["trade_type"].clone(),
};
info["status"] = match e["trade_state"].as_str().unwrap() {
"SUCCESS" => "已支付",
_ => "未知",
}
.into();
Ok(info)
}
Err(e) => Err(e),
}
}
fn refunds(
&mut self,
sub_mchid: &str,
out_trade_no: &str,
transaction_id: &str,
out_refund_no: &str,
refund: f64,
total: f64,
currency: &str,
) -> Result<JsonValue, String> {
let url = "/v3/refund/domestic/refunds";
let refund = (refund * 100.0) as u64;
let total = (total * 100.0) as u64;
let body = object! {
"sub_mchid"=> sub_mchid,
"transaction_id"=>transaction_id,
"out_trade_no"=>out_trade_no,
"out_refund_no"=>out_refund_no,
"amount"=>object! {
refund: refund,
total: total,
currency:currency
}
};
let sign = self.sign("POST", url, body.to_string().as_str());
let mut http = br_http::Http::new();
match http
.post(format!("https://api.mch.weixin.qq.com{}", url).as_str())
.header("Accept", "application/json")
.header("User-Agent", "api")
.header("Content-Type", "application/json")
.header("Authorization", sign.as_str())
.raw_json(body)
.json()
{
Ok(e) => {
if e.has_key("message") {
return Err(e["message"].to_string());
}
let mut refund_time = 0.0;
if e.has_key("success_time"){
let success_time = e["success_time"].as_str().unwrap_or("").to_string();
if !success_time.is_empty() {
let datetime = DateTime::parse_from_rfc3339(success_time.as_str()).unwrap();
refund_time = datetime.timestamp() as f64;
}
}
let status = match e["status"].as_str().unwrap() {
"PROCESSING" => "退款中",
"SUCCESS" => "已退款",
_ => "无退款",
};
let info = object! {
refund_id: e["refund_id"].clone(),
user_received_account:e["user_received_account"].clone(),
status:status,
refund_time:refund_time,
out_refund_no: e["out_refund_no"].clone(),
};
Ok(info)
}
Err(e) => Err(e),
}
}
}