br_pay/
alipay.rs

1use br_reqwest::Client;
2use std::collections::{HashMap};
3use base64::{Engine};
4use base64::engine::general_purpose::STANDARD;
5use chrono::{Local};
6use crate::{PayMode, PayNotify, RefundNotify, RefundStatus, TradeState, TradeType, Types};
7use json::{array, object, JsonValue};
8use openssl::hash::MessageDigest;
9use openssl::pkey::{PKey};
10use openssl::rsa::Rsa;
11use openssl::sign::{Signer, Verifier};
12use urlencoding::{decode, encode};
13use log::error;
14
15#[derive(Clone)]
16pub struct AliPay {
17    /// 应用appid
18    pub appid: String,
19    /// 服务商商家号
20    pub sp_mchid: String,
21    /// 授权token
22    pub app_auth_token: String,
23    /// 应用私钥证书路径
24    pub app_private: String,
25    /// 接口内容加密密钥
26    pub content_encryp: String,
27    /// 支付宝公钥
28    pub alipay_public_key: String,
29    pub notify_url: String,
30}
31impl AliPay {
32    pub fn sign(&mut self, txt: &str) -> Result<JsonValue, String> {
33        let t = self.app_private.as_bytes().chunks(64).map(|chunk| std::str::from_utf8(chunk).unwrap_or("")).collect::<Vec<&str>>().join("\n");
34        let cart = format!("-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n", t);
35
36        // 1. 加载私钥
37        let rsa = match Rsa::private_key_from_pem(cart.as_bytes()) {
38            Ok(e) => e,
39            Err(e) => return Err(e.to_string())
40        };
41
42        let pkey = match PKey::from_rsa(rsa) {
43            Ok(e) => e,
44            Err(e) => return Err(e.to_string())
45        };
46
47        // 2. 创建签名器,使用 SHA256
48        let mut signer = match Signer::new(MessageDigest::sha256(), &pkey) {
49            Ok(e) => e,
50            Err(e) => return Err(e.to_string())
51        };
52        match signer.update(txt.as_bytes()) {
53            Ok(()) => {}
54            Err(e) => return Err(e.to_string())
55        };
56        // 3. 生成签名
57        let signature = match signer.sign_to_vec() {
58            Ok(e) => e,
59            Err(e) => return Err(e.to_string())
60        };
61        // 4. Base64 编码输出
62        Ok(STANDARD.encode(signature).into())
63    }
64    pub fn http(&mut self, method: &str, biz_content: JsonValue) -> Result<JsonValue, String> {
65        let mut http = Client::new();
66        //http.debug();
67        let sign = "";
68
69        let now = Local::now();
70        let timestamp = now.format("%Y-%m-%d %H:%M:%S").to_string();
71
72        let mut data = object! {
73                    "charset":"UTF-8",
74                    "method":method,
75                    "app_id":self.appid.clone(),
76                    "app_private_key":self.app_private.clone(),
77                    "version":"1.0",
78                    "sign_type":"RSA2",
79                    "timestamp":timestamp,
80                    "alipay_public_key":self.alipay_public_key.clone(),
81                    "sign":sign
82        };
83        if !self.app_auth_token.is_empty() {
84            data["app_auth_token"] = self.app_auth_token.clone().into();
85        }
86        if method.contains("alipay.trade.") {
87            data["notify_url"] = self.notify_url.clone().into();
88        }
89        for (key, value) in biz_content.entries() {
90            data[key] = value.clone()
91        }
92        let mut map = HashMap::new();
93        for (key, value) in data.entries() {
94            if key == "sign" {
95                continue;
96            }
97            if value.is_empty() {
98                continue;
99            }
100            map.insert(key, value);
101        }
102
103        let mut keys: Vec<_> = map.keys().cloned().collect();
104        keys.sort();
105        let mut txt = vec![];
106        for key in keys {
107            txt.push(format!("{}={}", key, map.get(&key).unwrap()));
108        }
109        let txt = txt.join("&");
110        data["sign"] = self.sign(&txt)?;
111
112        let mut new_data = object! {};
113        for (key, value) in data.entries() {
114            let t = encode(value.to_string().as_str()).to_string();
115            new_data[key] = t.into();
116        }
117        data = new_data;
118        let url = "https://openapi.alipay.com/gateway.do".to_string();
119        let res = match method {
120            "alipay.trade.wap.pay" => {
121                let tt = http.get(url.as_str()).query(data);
122                return Ok(tt.url.clone().into());
123            }
124            _ => {
125                match http.get(&url).query(data).form_data(biz_content).send() {
126                    Ok(e) => e,
127                    Err(e) => return Err(e.to_string())
128                }
129            }
130        };
131
132        let res = res.json()?;
133        if res.has_key("error_response") {
134            return Err(res["error_response"]["sub_msg"].to_string());
135        }
136        let key = method.replace(".", "_");
137        let key = format!("{}_response", key);
138        let data = res[key].clone();
139        if data.has_key("code") {
140            if data["code"] != "10000" {
141                Err(data["sub_msg"].to_string())
142            } else {
143                Ok(data)
144            }
145        } else {
146            Err(data.to_string())
147        }
148    }
149    pub fn https(&mut self, method: &str, biz_content: JsonValue) -> Result<JsonValue, String> {
150        let mut http = Client::new();
151        //http.debug();
152        let sign = "";
153
154        let now = Local::now();
155        let timestamp = now.format("%Y-%m-%d %H:%M:%S").to_string();
156
157        let mut data = object! {
158                    "charset":"UTF-8",
159                    "method":method,
160                    "app_id":self.appid.clone(),
161                    "app_private_key":self.app_private.clone(),
162                    "version":"1.0",
163                    "sign_type":"RSA2",
164                    "timestamp":timestamp,
165                    "alipay_public_key":self.alipay_public_key.clone(),
166                    "sign":sign
167        };
168        if !self.app_auth_token.is_empty() {
169            data["app_auth_token"] = self.app_auth_token.clone().into();
170        }
171        if method.contains("alipay.trade.") {
172            data["notify_url"] = self.notify_url.clone().into();
173        }
174        for (key, value) in biz_content.entries() {
175            data[key] = value.clone()
176        }
177        let mut map = HashMap::new();
178        for (key, value) in data.entries() {
179            if key == "sign" {
180                continue;
181            }
182            if value.is_empty() {
183                continue;
184            }
185            map.insert(key, value);
186        }
187
188        let mut keys: Vec<_> = map.keys().cloned().collect();
189        keys.sort();
190        let mut txt = vec![];
191        for key in keys {
192            txt.push(format!("{}={}", key, map.get(&key).unwrap()));
193        }
194        let txt = txt.join("&");
195        data["sign"] = self.sign(&txt)?;
196
197        let mut new_data = object! {};
198        for (key, value) in data.entries() {
199            let t = encode(value.to_string().as_str()).to_string();
200            new_data[key] = t.into();
201        }
202        data = new_data;
203        let url = "https://openapi.alipay.com/gateway.do".to_string();
204        let res = match method {
205            "alipay.trade.wap.pay" => {
206                let tt = http.get(url.as_str()).query(data);
207                return Ok(tt.url.clone().into());
208            }
209            _ => {
210                match http.get(&url).query(data).form_data(biz_content).send() {
211                    Ok(e) => e,
212                    Err(e) => return Err(e.to_string())
213                }
214            }
215        };
216
217        let res = res.json()?;
218        if res.has_key("error_response") {
219            return Err(res["error_response"]["sub_msg"].to_string());
220        }
221        let key = method.replace(".", "_");
222        let key = format!("{}_response", key);
223        let data = res[key].clone();
224        Ok(data)
225    }
226}
227impl PayMode for AliPay {
228    fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String> {
229        let res = self.https("alipay.open.agent.signstatus.query", object! {
230            "biz_content":{
231              "pid":sub_mchid,
232            "product_codes":array!["QUICK_WAP_WAY"]   
233            }
234        })?;
235        if !res["code"].eq("10000") {
236            return Err(res["msg"].to_string());
237        }
238        for item in res["sign_status_list"].members() {
239            if item["status"].eq("none") {
240                return Err(format!("{} 未开通", res["product_name"]));
241            }
242        }
243        Ok(true.into())
244    }
245
246    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String> {
247        let sign = match STANDARD.decode(data["sign"].to_string()) {
248            Ok(e) => e,
249            Err(e) => return Err(format!("decode sign: {}", e))
250        };
251        let mut map = HashMap::new();
252        for (key, value) in data.entries() {
253            if key == "sign" {
254                continue;
255            }
256            if value.is_empty() {
257                continue;
258            }
259            map.insert(key, value);
260        }
261
262        let mut keys: Vec<_> = map.keys().cloned().collect();
263        keys.sort();
264
265        let mut txt = vec![];
266        for key in keys {
267            let value = decode(map.get(&key).unwrap().to_string().as_str()).unwrap().to_string();
268            txt.push(format!("{}={}", key, value));
269        }
270        let txt = txt.join("&");
271
272        let public_key_pem = self.alipay_public_key.clone();
273        let public_key_pem = format!("-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n", public_key_pem);
274        let public_key = match PKey::public_key_from_pem(public_key_pem.as_bytes()) {
275            Ok(e) => e,
276            Err(e) => return Err(format!("Invalid public key: {}", e))
277        };
278
279        // 4. 验签
280        let mut verifier = match Verifier::new(MessageDigest::sha256(), &public_key) {
281            Ok(e) => e,
282            Err(e) => return Err(format!("Invalid verifier: {}", e))
283        };
284        match verifier.update(txt.as_bytes()) {
285            Ok(_) => {}
286            Err(_) => return Err("Invalid transaction signature".to_string())
287        };
288
289        let result = match verifier.verify(&sign) {
290            Ok(e) => e,
291            Err(_) => return Err("Invalid transaction signature".to_string())
292        };
293        if !result {
294            return Err("sign error".to_string());
295        }
296        if data.has_key("service") {
297            let service = data["service"].to_string();
298            if service.as_str() == "alipay.service.check" {
299                let sign_txt = "<success>true</success>";
300                let sign = self.sign(sign_txt)?;
301                let text = format!(r#"<?xml version="1.0" encoding="GBK"?><alipay><response><success>true</success></response><sign>{}</sign><sign_type>RSA2</sign_type></alipay>"#, sign);
302                return Ok(JsonValue::String(text));
303            }
304        }
305        Ok(result.into())
306    }
307
308    fn config(&mut self) -> JsonValue {
309        todo!()
310    }
311
312    fn login(&mut self, code: &str) -> Result<JsonValue, String> {
313        let res = self.https("alipay.system.oauth.token", object! {
314            "grant_type":"authorization_code",
315            "code":code
316        })?;
317        Ok(res)
318    }
319
320    fn auth(&mut self, code: &str) -> Result<JsonValue, String> {
321        let biz_content = object! {
322            "biz_content":{
323                "grant_type":"authorization_code",
324                "code":code
325            }
326        };
327        let res = match self.http("alipay.open.auth.token.app", biz_content) {
328            Ok(e) => e,
329            Err(e) => {
330                error!("Err: {:#}", e);
331                return Err(e);
332            }
333        };
334
335        let data = object! {
336            data:res.clone(),
337            user_id : res["user_id"].clone(),
338            auth_app_id : res["auth_app_id"].clone(),
339            re_expires_in :res["re_expires_in"].clone(),
340            app_auth_token:res["app_auth_token"].clone(),
341            app_refresh_token:res["app_refresh_token"].clone()
342        };
343        Ok(data)
344    }
345
346    fn pay(&mut self, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String> {
347        let mut api = "";
348        let mut order = object! {
349            out_trade_no:out_trade_no,
350            total_amount:total_fee,
351            subject:description,
352            product_code:"JSAPI_PAY",
353            op_app_id:sub_mchid,
354            buyer_open_id:sp_openid
355        };
356
357        match types {
358            Types::MiniJsapi => {
359                api = "alipay.trade.create";
360                order["product_code"] = "JSAPI_PAY".into();
361                order["op_app_id"] = self.appid.clone().into();
362                order["buyer_open_id"] = sp_openid.into();
363                self.app_auth_token = "".to_string();
364            }
365            Types::Jsapi => {
366                api = "alipay.trade.create";
367                order["product_code"] = "JSAPI_PAY".into();
368            }
369            Types::H5 => {
370                api = "alipay.trade.wap.pay";
371                order["product_code"] = "QUICK_WAP_WAY".into();
372            }
373            Types::Native => {
374                api = "alipay.trade.wap.pay";
375                order["product_code"] = "QUICK_WAP_WAY".into();
376            }
377            _ => {
378                order["product_code"] = "JSAPI_PAY".into();
379            }
380        };
381        match self.http(api, object! {"biz_content":order}) {
382            Ok(e) => {
383                match types {
384                    Types::Jsapi => {}
385                    Types::Native => {}
386                    Types::H5 => {
387                        return Ok(object! {url:e});
388                    }
389                    Types::MiniJsapi => {
390                        println!("alipay.trade.wap.pay:{:#}", e);
391                        return Ok(e);
392                    }
393                    Types::App => {}
394                    Types::Micropay => {}
395                }
396                Ok(e)
397            }
398            Err(e) => {
399                println!("Err: {:#}", e);
400                Err(e)
401            }
402        }
403    }
404
405    fn micropay(&mut self, auth_code: &str, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, org_openid: &str, _ip: &str) -> Result<JsonValue, String> {
406        let order = object! {
407            out_trade_no:out_trade_no,
408            total_amount:total_fee,
409            subject:description,
410            seller_id:sub_mchid,
411            auth_code:auth_code,
412            scene:"bar_code",
413            operator_id:org_openid,
414        };
415
416        match self.http("alipay.trade.create", object! {"biz_content":order}) {
417            Ok(e) => {
418                Ok(e)
419            }
420            Err(e) => {
421                println!("Err: {:#}", e);
422                Err(e)
423            }
424        }
425    }
426
427
428    fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
429        let order = object! {
430              "biz_content"=> object! {
431                out_trade_no:out_trade_no,
432                operator_id:sub_mchid
433              }
434        };
435        match self.http("alipay.trade.close", order) {
436            Ok(_) => {
437                Ok(true.into())
438            }
439            Err(e) => {
440                if e.contains("交易不存在") {
441                    return Ok(true.into());
442                }
443                Err(e)
444            }
445        }
446    }
447
448    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
449        let order = object! {
450              "biz_content"=> object! {
451               out_trade_no:out_trade_no
452              }
453        };
454        match self.http("alipay.trade.query", order) {
455            Ok(e) => {
456                if e.has_key("code") && e["code"].as_str().unwrap() != "10000" {
457                    return Err(e["msg"].to_string());
458                }
459                let buyer_open_id = if e.has_key("buyer_open_id") {
460                    e["buyer_open_id"].to_string()
461                } else {
462                    e["buyer_user_id"].to_string()
463                };
464                let res = PayNotify {
465                    trade_type: TradeType::None,
466                    out_trade_no: e["out_trade_no"].to_string(),
467                    sp_mchid: "".to_string(),
468                    sub_mchid: sub_mchid.to_string(),
469                    sp_appid: "".to_string(),
470                    transaction_id: e["trade_no"].to_string(),
471                    success_time: PayNotify::alipay_time(e["send_pay_date"].as_str().unwrap()),
472                    sp_openid: buyer_open_id.clone(),
473                    sub_openid: buyer_open_id.clone(),
474                    total: (e["total_amount"].to_string().parse::<f64>().unwrap_or(0.0)),
475                    payer_total: (e["total_amount"].to_string().parse::<f64>().unwrap_or(0.0)),
476                    currency: "CNY".to_string(),
477                    payer_currency: "CNY".to_string(),
478                    trade_state: TradeState::from(e["trade_status"].as_str().unwrap()),
479                };
480                Ok(res.json())
481            }
482            Err(e) => Err(e)
483        }
484    }
485
486    fn pay_micropay_query(&mut self, _out_trade_no: &str, _sub_mchid: &str) -> Result<JsonValue, String> {
487        todo!()
488    }
489
490    fn pay_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
491        todo!()
492    }
493
494    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> {
495        let body = object! {
496            "biz_content"=> object! {
497                "trade_no"=>transaction_id,
498                "out_trade_no"=>out_trade_no,
499                "out_request_no"=>out_refund_no,
500                "refund_amount"=>format!("{:.2}",amount),
501            }
502        };
503        match self.http("alipay.trade.refund", body.clone()) {
504            Ok(e) => {
505                if e.has_key("code") && e["code"].as_str().unwrap() != "10000" {
506                    return Err(e["msg"].to_string());
507                }
508                let res = RefundNotify {
509                    out_trade_no: e["out_trade_no"].to_string(),
510                    refund_no: out_refund_no.to_string(),
511                    sp_mchid: "".to_string(),
512                    sub_mchid: sub_mchid.to_string(),
513                    transaction_id: e["trade_no"].to_string(),
514                    refund_id: out_refund_no.to_string(),
515                    success_time: PayNotify::alipay_time(e["gmt_refund_pay"].as_str().unwrap()),
516                    total,
517                    refund: e["refund_fee"].to_string().parse::<f64>().unwrap(),
518                    payer_total: e["refund_fee"].to_string().parse::<f64>().unwrap(),
519                    payer_refund: e["send_back_fee"].to_string().parse::<f64>().unwrap(),
520                    status: RefundStatus::from(e["fund_change"].as_str().unwrap()),
521                };
522                Ok(res.json())
523            }
524            Err(e) => Err(e)
525        }
526    }
527
528    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> {
529        todo!()
530    }
531
532    fn refund_notify(&mut self, _nonce: &str, _ciphertext: &str, _associated_data: &str) -> Result<JsonValue, String> {
533        todo!()
534    }
535
536    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
537        let body = object! {
538             "biz_content"=> object! {
539               "out_request_no"=>out_refund_no,
540            "trade_no"=>trade_no,
541             }
542        };
543        match self.http("alipay.trade.fastpay.refund.query", body.clone()) {
544            Ok(e) => {
545                if e.has_key("code") && e["code"].as_str().unwrap() != "10000" {
546                    return Err(e["msg"].to_string());
547                }
548                let res = RefundNotify {
549                    out_trade_no: e["out_trade_no"].to_string(),
550                    refund_no: e["out_request_no"].to_string(),
551                    sp_mchid: "".to_string(),
552                    sub_mchid: sub_mchid.to_string(),
553                    transaction_id: e["trade_no"].to_string(),
554                    refund_id: e["out_request_no"].to_string(),
555                    success_time: Local::now().timestamp(),
556                    total: e["total_amount"].to_string().parse::<f64>().unwrap(),
557                    payer_total: e["total_amount"].to_string().parse::<f64>().unwrap(),
558                    refund: e["refund_amount"].to_string().parse::<f64>().unwrap(),
559                    payer_refund: e["refund_amount"].to_string().parse::<f64>().unwrap(),
560                    status: RefundStatus::from(e["refund_status"].as_str().unwrap()),
561                };
562                Ok(res.json())
563            }
564            Err(e) => Err(e)
565        }
566    }
567}