br_pay/
lib.rs

1use chrono::{DateTime, FixedOffset, Local, NaiveDateTime};
2use crate::wechat::{Wechat};
3use json::{object, JsonValue};
4use crate::alipay::AliPay;
5use crate::ccbc::Ccbc;
6use crate::yrcc::Yrcc;
7
8pub mod alipay;
9pub mod wechat;
10pub mod ccbc;
11pub mod yrcc;
12
13#[derive(Clone, Debug)]
14pub enum Pay {
15    Wechat(Wechat),
16    Alipay(AliPay),
17    /// 建设银行
18    Ccbc(Ccbc),
19    /// 农村商业银行
20    Yrcc(Yrcc),
21    None,
22}
23
24impl Pay {
25    pub fn new(data: JsonValue) -> Self {
26        match data["mode"].as_str().unwrap_or("") {
27            "wechat" => {
28                Pay::Wechat(Wechat {
29                    appid: data["appid"].to_string(),
30                    sp_mchid: data["sp_mchid"].to_string(),
31                    serial_no: data["serial_no"].to_string(),
32                    app_private: data["app_private"].to_string(),
33                    apikey: data["apikey"].to_string(),
34                    apiv2: data["apiv2"].to_string(),
35                    notify_url: data["notify_url"].to_string(),
36                })
37            }
38            "alipay" => Pay::Alipay(AliPay {
39                appid: data["appid"].to_string(),
40                sp_mchid: data["sp_mchid"].to_string(),
41                app_private: data["app_private"].to_string(),
42                app_auth_token: data["app_auth_token"].as_str().unwrap_or("").to_string(),
43                content_encryp: data["content_encryp"].to_string(),
44                alipay_public_key: data["alipay_public_key"].to_string(),
45                notify_url: data["notify_url"].to_string(),
46                appid_mini: data["appid_mini"].to_string(),
47            }),
48            "yrcc" => Pay::Yrcc(Yrcc {
49                appid: "".to_string(),
50                secret: "".to_string(),
51                terminal_number: data["terminal_number"].to_string(),
52                sp_mchid: data["sp_mchid"].to_string(),
53                app_private: data["app_private"].to_string(),
54                app_public: data["app_public"].to_string(),
55                notify_url: data["notify_url"].as_str().unwrap_or("").to_string(),
56                key_name: data["key_name"].to_string(),
57                service_provider: data["service_provider"].to_string(),
58            }),
59            "ccbc" => Pay::Ccbc(Ccbc {
60                appid: data["appid"].as_str().unwrap_or("").to_string(),
61                wechat_mchid: data["wechat_mchid"].as_str().unwrap_or("").to_string(),
62                sp_mchid: data["sp_mchid"].as_str().unwrap_or("").to_string(),
63                notify_url: data["notify_url"].as_str().unwrap_or("").to_string(),
64                posid: data["posid"].as_str().unwrap_or("").to_string(),
65                branchid: data["branchid"].as_str().unwrap_or("").to_string(),
66                public_key: data["public_key"].as_str().unwrap_or("").to_string(),
67                client_ip: data["client_ip"].as_str().unwrap_or("").to_string(),
68                pass: data["pass"].as_str().unwrap_or("").to_string(),
69                retry: 0,
70                appid_subscribe: data["appid_subscribe"].as_str().unwrap_or("").to_string(),
71                debug: data["debug"].as_bool().unwrap_or(false),
72            }),
73            _ => Pay::None
74        }
75    }
76}
77impl PayMode for Pay {
78    fn check(&mut self) -> Result<bool, String> {
79        match self {
80            Self::Wechat(e) => e.check(),
81            Self::Alipay(e) => e.check(),
82            Self::Ccbc(_) => todo!(),
83            Self::Yrcc(_) => todo!(),
84            Self::None => Err("No login data".to_owned()),
85        }
86    }
87
88    fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String> {
89        match self {
90            Self::Wechat(e) => e.get_sub_mchid(sub_mchid),
91            Self::Alipay(e) => e.get_sub_mchid(sub_mchid),
92            Pay::None => Err("No login data".to_owned()),
93            &mut Pay::Ccbc(_) => todo!(),
94            &mut Pay::Yrcc(_) => todo!()
95        }
96    }
97
98
99    fn config(&mut self) -> JsonValue {
100        match self {
101            Self::Wechat(e) => object! {
102                sp_mchid:e.sp_mchid.clone(),
103                appid:e.appid.clone(),
104            },
105            Self::Alipay(e) => object! {
106                appid:e.appid.clone(),
107                sp_mchid:e.sp_mchid.clone()
108            },
109            Pay::None => object! {
110                appid:"",
111                sp_mchid:""
112            },
113            Pay::Ccbc(e) => object! {
114                appid:e.appid.clone(),
115                sp_mchid:e.sp_mchid.clone()
116            },
117            Pay::Yrcc(e) => object! {
118                appid:e.appid.clone(),
119                sp_mchid:e.sp_mchid.clone()
120            },
121        }
122    }
123    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> {
124        match self {
125            Self::Wechat(e) => e.pay(channel,
126                                     types,
127                                     sub_mchid,
128                                     out_trade_no,
129                                     description,
130                                     total_fee,
131                                     sp_openid,
132            ),
133            Self::Alipay(e) => e.pay(channel,
134                                     types,
135                                     sub_mchid,
136                                     out_trade_no,
137                                     description,
138                                     total_fee,
139                                     sp_openid,
140            ),
141            Pay::None => Err("No login data".to_owned()),
142            Pay::Ccbc(e) => e.pay(
143                channel,
144                types,
145                sub_mchid,
146                out_trade_no,
147                description,
148                total_fee,
149                sp_openid,
150            ),
151            Pay::Yrcc(e) => e.pay(
152                channel,
153                types,
154                sub_mchid,
155                out_trade_no,
156                description,
157                total_fee,
158                sp_openid,
159            )
160        }
161    }
162
163    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> {
164        match self {
165            Self::Wechat(e) => e.micropay(
166                channel,
167                auth_code,
168                sub_mchid,
169                out_trade_no,
170                description,
171                total_fee,
172                org_openid,
173                ip,
174            ),
175            Self::Alipay(e) => e.micropay(
176                channel,
177                auth_code,
178                sub_mchid,
179                out_trade_no,
180                description,
181                total_fee,
182                org_openid,
183                ip,
184            ),
185            Pay::Ccbc(e) => e.micropay(
186                channel,
187                auth_code,
188                sub_mchid,
189                out_trade_no,
190                description,
191                total_fee,
192                org_openid,
193                ip,
194            ),
195            Pay::None => Err("No login data".to_owned()),
196            &mut Pay::Yrcc(_) => todo!()
197        }
198    }
199
200    fn close(&mut self, out_trade_no: &str, sub_mchid: &str,channel:&str) -> Result<JsonValue, String> {
201        match self {
202            Self::Wechat(e) => e.close(
203                out_trade_no, sub_mchid,channel
204            ),
205            Self::Alipay(e) => e.close(
206                out_trade_no, sub_mchid,
207                channel
208            ),
209            Pay::Ccbc(e) => e.close(
210                out_trade_no, sub_mchid,channel
211            ),
212            Pay::None => Err("No login data".to_owned()),
213            &mut Pay::Yrcc(_) => todo!()
214        }
215    }
216
217    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
218        match self {
219            Self::Wechat(e) => e.pay_query(
220                out_trade_no,
221                sub_mchid,
222            ),
223            Self::Alipay(e) => e.pay_query(
224                out_trade_no,
225                sub_mchid,
226            ),
227            Self::Ccbc(e) => e.pay_query(
228                out_trade_no,
229                sub_mchid,
230            ),
231            Pay::None => Err("No login data".to_owned()),
232            &mut Pay::Yrcc(_) => todo!()
233        }
234    }
235    fn pay_micropay_query(&mut self, out_trade_no: &str, sub_mchid: &str,channel:&str) -> Result<JsonValue, String> {
236        match self {
237            Self::Wechat(e) => e.pay_micropay_query(
238                out_trade_no,
239                sub_mchid,
240                channel
241            ),
242            Self::Alipay(e) => e.pay_query(
243                out_trade_no,
244                sub_mchid
245            ),
246            Pay::Ccbc(e) => e.pay_micropay_query(
247                out_trade_no,
248                sub_mchid,
249                channel
250            ),
251            Pay::None => Err("No login data".to_owned()),
252            &mut Pay::Yrcc(_) => todo!()
253        }
254    }
255
256    fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
257        match self {
258            Self::Wechat(e) => e.pay_notify(
259                nonce,
260                ciphertext,
261                associated_data,
262            ),
263            Self::Alipay(e) => e.pay_notify(
264                nonce,
265                ciphertext,
266                associated_data,
267            ),
268            Pay::None => Err("No login data".to_owned()),
269            &mut Pay::Ccbc(_) | &mut Pay::Yrcc(_) => todo!()
270        }
271    }
272
273    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> {
274        match self {
275            Self::Wechat(e) => e.refund(
276                sub_mchid,
277                out_trade_no,
278                transaction_id,
279                out_refund_no,
280                amount,
281                total,
282                currency,
283            ),
284            Self::Alipay(e) => e.refund(
285                sub_mchid,
286                out_trade_no,
287                transaction_id,
288                out_refund_no,
289                amount,
290                total,
291                currency,
292            ),
293            Self::Ccbc(e) => e.refund(
294                sub_mchid,
295                out_trade_no,
296                transaction_id,
297                out_refund_no,
298                amount,
299                total,
300                currency,
301            ),
302            Pay::None => Err("No login data".to_owned()),
303            &mut Pay::Yrcc(_) => todo!()
304        }
305    }
306
307    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> {
308        match self {
309            Self::Wechat(e) => e.micropay_refund(
310                sub_mchid,
311                out_trade_no,
312                transaction_id,
313                out_refund_no,
314                amount,
315                total,
316                currency,
317                refund_text,
318            ),
319            Self::Alipay(e) => e.refund(
320                sub_mchid,
321                out_trade_no,
322                transaction_id,
323                out_refund_no,
324                amount,
325                total,
326                currency,
327            ),
328            Pay::None => Err("No login data".to_owned()),
329            &mut Pay::Ccbc(_) | &mut Pay::Yrcc(_) => todo!()
330        }
331    }
332
333    fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
334        match self {
335            Self::Wechat(e) => e.refund_notify(
336                nonce,
337                ciphertext,
338                associated_data,
339            ),
340            Self::Alipay(e) => e.refund_notify(
341                nonce,
342                ciphertext,
343                associated_data,
344            ),
345            Pay::None => Err("No login data".to_owned()),
346            &mut Pay::Ccbc(_) | &mut Pay::Yrcc(_) => todo!()
347        }
348    }
349
350    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
351        match self {
352            Self::Wechat(e) => e.refund_query(
353                trade_no,
354                out_refund_no,
355                sub_mchid,
356            ),
357            Self::Alipay(e) => e.refund_query(
358                trade_no,
359                out_refund_no,
360                sub_mchid,
361            ),
362            Pay::None => Err("No login data".to_owned()),
363            &mut Pay::Ccbc(_) | &mut Pay::Yrcc(_) => todo!()
364        }
365    }
366
367    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> {
368        match self {
369            Self::Wechat(e) => e.incoming(
370                business_code,
371                contact_info,
372                subject_info,
373                business_info,
374                settlement_info,
375                bank_account_info,
376            ),
377            Self::Alipay(e) => e.incoming(
378                business_code,
379                contact_info,
380                subject_info,
381                business_info,
382                settlement_info,
383                bank_account_info,
384            ),
385            Pay::None => Err("No incoming data".to_owned()),
386            &mut Pay::Ccbc(_) | &mut Pay::Yrcc(_) => todo!()
387        }
388    }
389}
390
391pub trait PayMode {
392    /// 检查账户是否通畅
393    fn check(&mut self) -> Result<bool, String>;
394    /// 获取商户号和状态
395    fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String>;
396    fn config(&mut self) -> JsonValue;
397    #[allow(clippy::too_many_arguments)]
398    /// 支付
399    /// * channel 渠道 wechat alipay
400    /// * out_trade_no 商户订单号
401    /// * sub_mchid 子商户号
402    /// * description 商品名称
403    /// * total_fee 支付金额
404    /// * notify_url 通知地址
405    /// * sp_openid 支付客户ID
406    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>;
407
408    #[allow(clippy::too_many_arguments)]
409    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>;
410    /// 关闭订单
411    fn close(&mut self, out_trade_no: &str, sub_mchid: &str,channel:&str) -> Result<JsonValue, String>;
412    /// 订单查询
413    /// * out_trade_no 商户订单号
414    /// * sub_mchid 子商户号
415    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
416    fn pay_micropay_query(&mut self, out_trade_no: &str, sub_mchid: &str,channel:&str) -> Result<JsonValue, String>;
417    /// 支付成功通知
418    fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String>;
419
420    #[allow(clippy::too_many_arguments)]
421    /// 订单退款
422    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>;
423    #[allow(clippy::too_many_arguments)]
424    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>;
425    /// 退款通知
426    fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String>;
427    /// 退款查询
428    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
429    /// 进件
430    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>;
431}
432
433/// 支付回调数据
434#[derive(Debug)]
435pub struct PayNotify {
436    /// 支付方式
437    trade_type: TradeType,
438    /// 商户订单号
439    out_trade_no: String,
440    /// 服务商商户号
441    sp_mchid: String,
442    /// 子商户号
443    sub_mchid: String,
444    /// 应用APPID
445    sp_appid: String,
446    /// 微信内部订单号
447    transaction_id: String,
448    /// 成功时间
449    success_time: i64,
450    /// 服务商用户ID
451    sp_openid: String,
452    /// 子商户用户ID
453    sub_openid: String,
454    /// 支付金额
455    total: f64,
456    /// 实际支付金额
457    payer_total: f64,
458    /// 币种
459    currency: String,
460    /// 实际支付币种
461    payer_currency: String,
462    /// 状态
463    trade_state: TradeState,
464}
465impl PayNotify {
466    pub fn json(&self) -> JsonValue {
467        object! {
468            "trade_type" => self.trade_type.to_string(),
469            "out_trade_no" => self.out_trade_no.to_string(),
470            "sp_mchid" => self.sp_mchid.to_string(),
471            "sub_mchid" => self.sub_mchid.to_string(),
472            "sp_appid" => self.sp_appid.to_string(),
473            "transaction_id" => self.transaction_id.to_string(),
474            "success_time" => self.success_time,
475            "sp_openid" => self.sp_openid.to_string(),
476            "sub_openid" => self.sub_openid.to_string(),
477            "total" => self.total,
478            "payer_total" => self.payer_total,
479            "currency" => self.currency.clone(),
480            "payer_currency" => self.payer_currency.clone(),
481            "trade_state" => self.trade_state.to_string(),
482        }
483    }
484    pub fn success_time(datetime: &str) -> i64 {
485        if datetime.is_empty() {
486            return 0;
487        }
488        let datetime = DateTime::parse_from_rfc3339(datetime).unwrap();
489        datetime.timestamp()
490    }
491    pub fn alipay_time(datetime: &str) -> i64 {
492        if datetime.is_empty() {
493            return 0;
494        }
495        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
496        t.and_utc().timestamp()
497    }
498    pub fn datetime_to_timestamp(datetime: &str, fmt: &str) -> i64 {
499        let t = NaiveDateTime::parse_from_str(datetime, fmt).unwrap();
500        let tz = FixedOffset::east_opt(Local::now().offset().local_minus_utc()).unwrap();
501        t.and_local_timezone(tz).unwrap().timestamp()
502    }
503}
504#[derive(Debug)]
505pub enum TradeType {
506    /// 小程序与JSAPI
507    JSAPI,
508    MICROPAY,
509    None,
510}
511impl TradeType {
512    fn from(code: &str) -> TradeType {
513        match code {
514            "JSAPI" => TradeType::JSAPI,
515            "MICROPAY" => TradeType::MICROPAY,
516            _ => TradeType::None
517        }
518    }
519    fn to_string(&self) -> &'static str {
520        match self {
521            TradeType::JSAPI => "JSAPI",
522            TradeType::MICROPAY => "MICROPAY",
523            TradeType::None => ""
524        }
525    }
526}
527#[derive(Debug)]
528pub enum TradeState {
529    /// 支付成功
530    SUCCESS,
531    /// 转入退款
532    REFUND,
533    /// 未支付
534    NOTPAY,
535    /// 已关闭
536    CLOSED,
537    /// 已撤销(仅付款码支付会返回)
538    REVOKED,
539    /// 用户支付中(仅付款码支付会返回)
540    USERPAYING,
541    /// 支付失败(仅付款码支付会返回)
542    PAYERROR,
543    None,
544}
545impl TradeState {
546    fn from(code: &str) -> TradeState {
547        match code {
548            "SUCCESS" | "TRADE_SUCCESS" | "成功" => TradeState::SUCCESS,
549            "REFUND" | "已全额退款" | "已部分退款" => TradeState::REFUND,
550            "NOTPAY" | "WAIT_BUYER_PAY" => TradeState::NOTPAY,
551            "CLOSED" | "TRADE_CLOSED" => TradeState::CLOSED,
552            "REVOKED" => TradeState::REVOKED,
553            "USERPAYING" | "待银行确认" => TradeState::USERPAYING,
554            "PAYERROR" | "TRADE_FINISHED" | "失败" => TradeState::PAYERROR,
555            _ => TradeState::None
556        }
557    }
558
559    fn to_string(&self) -> &'static str {
560        match self {
561            TradeState::SUCCESS => "已支付",
562            TradeState::REFUND => "已退款",
563            TradeState::NOTPAY => "待支付",
564            TradeState::CLOSED => "已关闭",
565            TradeState::REVOKED => "已关闭",
566            TradeState::USERPAYING => "待支付",
567            TradeState::PAYERROR => "支付失败",
568            TradeState::None => "待支付"
569        }
570    }
571}
572
573#[derive(Debug)]
574pub enum RefundStatus {
575    /// 退款成功
576    SUCCESS,
577    /// 退款关闭
578    CLOSED,
579    /// 退款处理中
580    PROCESSING,
581    /// 退款异常,手动处理此笔退款
582    ABNORMAL,
583    None,
584}
585impl RefundStatus {
586    fn from(code: &str) -> RefundStatus {
587        match code {
588            "SUCCESS" | "Y" | "REFUND_SUCCESS" => RefundStatus::SUCCESS,
589            "CLOSED" => RefundStatus::CLOSED,
590            "PROCESSING" | "N" => RefundStatus::PROCESSING,
591            "ABNORMAL" => RefundStatus::ABNORMAL,
592            _ => RefundStatus::None
593        }
594    }
595    fn to_string(&self) -> &'static str {
596        match self {
597            RefundStatus::SUCCESS => "已退款",
598            RefundStatus::None => "退款中",
599            RefundStatus::CLOSED => "已关闭",
600            RefundStatus::PROCESSING => "退款中",
601            RefundStatus::ABNORMAL => "退款异常"
602        }
603    }
604}
605/// 退款回调数据
606#[derive(Debug)]
607pub struct RefundNotify {
608    /// 商户订单号
609    out_trade_no: String,
610    refund_no: String,
611    /// 服务商商户号
612    sp_mchid: String,
613    /// 子商户号
614    sub_mchid: String,
615    /// 微信内部订单号
616    transaction_id: String,
617    /// 退款订单号
618    refund_id: String,
619    /// 成功时间
620    success_time: i64,
621    /// 支付金额
622    total: f64,
623    /// 退款金额
624    refund: f64,
625    /// 实际支付金额
626    payer_total: f64,
627    /// 实际退款金额
628    payer_refund: f64,
629    /// 状态
630    status: RefundStatus,
631}
632
633impl RefundNotify {
634    pub fn json(&self) -> JsonValue {
635        object! {
636            "out_trade_no" => self.out_trade_no.clone(),
637            "sp_mchid" => self.sp_mchid.clone(),
638            "sub_mchid" => self.sub_mchid.clone(),
639            "transaction_id" => self.transaction_id.clone(),
640            "success_time" => self.success_time,
641            "total" => self.total,
642            "refund" => self.refund,
643            "payer_total" => self.payer_total,
644            "payer_refund" => self.payer_refund,
645            "status" => self.status.to_string(),
646            "refund_no"=>self.refund_no.clone(),
647            "refund_id"=>self.refund_id.clone()
648        }
649    }
650}
651
652#[derive(Debug)]
653pub enum Types {
654    /// JS支付
655    Jsapi,
656    /// 扫码支付
657    Native,
658    /// H5页面
659    H5,
660    /// 小程序
661    MiniJsapi,
662    /// App
663    App,
664    /// 付款码
665    Micropay,
666}
667impl Types {
668    pub fn str(self) -> &'static str {
669        match self {
670            Types::Jsapi => "jsapi",
671            Types::Native => "native",
672            Types::H5 => "h5",
673            Types::MiniJsapi => "minijsapi",
674            Types::App => "app",
675            Types::Micropay => "micropay"
676        }
677    }
678    pub fn from(name: &str) -> Self {
679        match name {
680            "jsapi" => Types::Jsapi,
681            "native" => Types::Native,
682            "h5" => Types::H5,
683            "minijsapi" => Types::MiniJsapi,
684            "app" => Types::App,
685            "micropay" => Types::Micropay,
686            _ => Types::Jsapi
687        }
688    }
689}