br_pay/
lib.rs

1use chrono::{DateTime, NaiveDateTime};
2use crate::wechat::Wechat;
3use json::{object, JsonValue};
4use crate::alipay::AliPay;
5
6pub mod alipay;
7pub mod wechat;
8
9#[derive(Clone)]
10pub enum Pay {
11    Wechat(Wechat),
12    Alipay(AliPay),
13    None,
14}
15
16impl Pay {
17    pub fn new(data: JsonValue) -> Self {
18        match data["mode"].as_str().unwrap_or("") {
19            "wechat" => Pay::Wechat(Wechat {
20                appid: data["appid"].to_string(),
21                sp_mchid: data["sp_mchid"].to_string(),
22                serial_no: data["serial_no"].to_string(),
23                app_private: data["app_private"].to_string(),
24                secret: data["secret"].to_string(),
25                apikey: data["apikey"].to_string(),
26                notify_url: data["notify_url"].to_string(),
27            }),
28            "alipay" => Pay::Alipay(AliPay {
29                appid: data["appid"].to_string(),
30                sp_mchid: data["sp_mchid"].to_string(),
31                app_private: data["app_private"].to_string(),
32                app_auth_token: data["app_auth_token"].as_str().unwrap_or("").to_string(),
33                content_encryp: data["content_encryp"].to_string(),
34                alipay_public_key: data["alipay_public_key"].to_string(),
35                notify_url: data["notify_url"].to_string(),
36            }),
37            _ => Pay::None
38        }
39    }
40}
41impl PayMode for Pay {
42    fn login(&mut self, code: &str) -> Result<JsonValue, String> {
43        match self {
44            Self::Wechat(e) => e.login(code),
45            Self::Alipay(e) => e.login(code),
46            Pay::None => Err("No login data".to_owned())
47        }
48    }
49
50    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
51        match self {
52            Self::Wechat(e) => e.pay_query(
53                out_trade_no,
54                sub_mchid,
55            ),
56            Self::Alipay(e) => e.pay_query(
57                out_trade_no,
58                sub_mchid,
59            ),
60            Pay::None => Err("No login data".to_owned())
61        }
62    }
63
64    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> {
65        match self {
66            Self::Wechat(e) => e.refund(
67                sub_mchid,
68                out_trade_no,
69                transaction_id,
70                out_refund_no,
71                amount,
72                total,
73                currency,
74            ),
75            Self::Alipay(e) => e.refund(
76                sub_mchid,
77                out_trade_no,
78                transaction_id,
79                out_refund_no,
80                amount,
81                total,
82                currency,
83            ),
84            Pay::None => Err("No login data".to_owned())
85        }
86    }
87
88    fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
89        match self {
90            Self::Wechat(e) => e.pay_notify(
91                nonce,
92                ciphertext,
93                associated_data,
94            ),
95            Self::Alipay(e) => e.pay_notify(
96                nonce,
97                ciphertext,
98                associated_data,
99            ),
100            Pay::None => Err("No login data".to_owned())
101        }
102    }
103
104    fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
105        match self {
106            Self::Wechat(e) => e.refund_notify(
107                nonce,
108                ciphertext,
109                associated_data,
110            ),
111            Self::Alipay(e) => e.refund_notify(
112                nonce,
113                ciphertext,
114                associated_data,
115            ),
116            Pay::None => Err("No login data".to_owned())
117        }
118    }
119
120    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
121        match self {
122            Self::Wechat(e) => e.refund_query(
123                trade_no,
124                out_refund_no,
125                sub_mchid,
126            ),
127            Self::Alipay(e) => e.refund_query(
128                trade_no,
129                out_refund_no,
130                sub_mchid,
131            ),
132            Pay::None => Err("No login data".to_owned())
133        }
134    }
135
136    fn auth(&mut self, code: &str) -> Result<JsonValue, String> {
137        match self {
138            Self::Wechat(e) => e.auth(code),
139            Self::Alipay(e) => e.auth(code),
140            Pay::None => Err("No login data".to_owned())
141        }
142    }
143
144    fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
145        match self {
146            Self::Wechat(e) => e.close(
147                out_trade_no, sub_mchid,
148            ),
149            Self::Alipay(e) => e.close(
150                out_trade_no, sub_mchid,
151            ),
152            Pay::None => Err("No login data".to_owned())
153        }
154    }
155
156    fn config(&mut self) -> JsonValue {
157        match self {
158            Self::Wechat(e) => object! {
159                sp_mchid:e.sp_mchid.clone(),
160                appid:e.appid.clone(),
161            },
162            Self::Alipay(e) => object! {
163                appid:e.appid.clone(),
164                sp_mchid:e.sp_mchid.clone()
165            },
166            Pay::None => object! {
167                appid:"",
168                sp_mchid:""
169            }
170        }
171    }
172
173    fn pay(&mut self, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String> {
174        match self {
175            Self::Wechat(e) => e.pay(
176                types,
177                sub_mchid,
178                out_trade_no,
179                description,
180                total_fee,
181                sp_openid,
182            ),
183            Self::Alipay(e) => e.pay(
184                types,
185                sub_mchid,
186                out_trade_no,
187                description,
188                total_fee,
189                sp_openid,
190            ),
191            Pay::None => Err("No login data".to_owned())
192        }
193    }
194
195    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String> {
196        match self {
197            Self::Wechat(e) => e.notify(data),
198            Self::Alipay(e) => e.notify(data),
199            Pay::None => Err("No login data".to_owned())
200        }
201    }
202}
203
204pub trait PayMode {
205    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String>;
206    fn config(&mut self) -> JsonValue;
207    fn login(&mut self, code: &str) -> Result<JsonValue, String>;
208    fn auth(&mut self, code: &str) -> Result<JsonValue, String>;
209
210    /// 支付
211    /// * out_trade_no 商户订单号
212    /// * sub_mchid 子商户号
213    /// * description 商品名称
214    /// * total_fee 支付金额
215    /// * notify_url 通知地址
216    /// * sp_openid 支付客户ID
217    fn pay(&mut self, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String>;
218    /// 关闭订单
219    fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
220    /// 订单查询
221    /// * out_trade_no 商户订单号
222    /// * sub_mchid 子商户号
223    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
224    /// 支付成功通知
225    fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String>;
226
227    #[allow(clippy::too_many_arguments)]
228    /// 订单退款
229    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>;
230    /// 退款通知
231    fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String>;
232    /// 退款查询
233    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
234}
235
236/// 支付回调数据
237#[derive(Debug)]
238pub struct PayNotify {
239    /// 支付方式
240    trade_type: TradeType,
241    /// 商户订单号
242    out_trade_no: String,
243    /// 服务商商户号
244    sp_mchid: String,
245    /// 子商户号
246    sub_mchid: String,
247    /// 应用APPID
248    sp_appid: String,
249    /// 微信内部订单号
250    transaction_id: String,
251    /// 成功时间
252    success_time: i64,
253    /// 服务商用户ID
254    sp_openid: String,
255    /// 子商户用户ID
256    sub_openid: String,
257    /// 支付金额
258    total: usize,
259    /// 实际支付金额
260    payer_total: usize,
261    /// 币种
262    currency: String,
263    /// 实际支付币种
264    payer_currency: String,
265    /// 状态
266    trade_state: TradeState,
267}
268impl PayNotify {
269    pub fn json(&self) -> JsonValue {
270        object! {
271            "trade_type" => self.trade_type.to_string(),
272            "out_trade_no" => self.out_trade_no.to_string(),
273            "sp_mchid" => self.sp_mchid.to_string(),
274            "sub_mchid" => self.sub_mchid.to_string(),
275            "sp_appid" => self.sp_appid.to_string(),
276            "transaction_id" => self.transaction_id.to_string(),
277            "success_time" => self.success_time,
278            "sp_openid" => self.sp_openid.to_string(),
279            "sub_openid" => self.sub_openid.to_string(),
280            "total" => self.total,
281            "payer_total" => self.payer_total,
282            "currency" => self.currency.clone(),
283            "payer_currency" => self.payer_currency.clone(),
284            "trade_state" => self.trade_state.to_string(),
285        }
286    }
287    pub fn success_time(datetime: &str) -> i64 {
288        if datetime.is_empty() {
289            return 0;
290        }
291        let datetime = DateTime::parse_from_rfc3339(datetime).unwrap();
292        datetime.timestamp()
293    }
294    pub fn alipay_time(datetime: &str) -> i64 {
295        if datetime.is_empty() {
296            return 0;
297        }
298        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
299        t.and_utc().timestamp()
300    }
301}
302#[derive(Debug)]
303pub enum TradeType {
304    /// 小程序与JSAPI
305    JSAPI,
306    None,
307}
308impl TradeType {
309    fn from(code: &str) -> TradeType {
310        match code {
311            "JSAPI" => TradeType::JSAPI,
312            _ => TradeType::None
313        }
314    }
315    fn to_string(&self) -> &'static str {
316        match self {
317            TradeType::JSAPI => "JSAPI",
318            TradeType::None => ""
319        }
320    }
321}
322#[derive(Debug)]
323pub enum TradeState {
324    /// 支付成功
325    SUCCESS,
326    /// 转入退款
327    REFUND,
328    /// 未支付
329    NOTPAY,
330    /// 已关闭
331    CLOSED,
332    /// 已撤销(仅付款码支付会返回)
333    REVOKED,
334    /// 用户支付中(仅付款码支付会返回)
335    USERPAYING,
336    /// 支付失败(仅付款码支付会返回)
337    PAYERROR,
338    None,
339}
340impl TradeState {
341    fn from(code: &str) -> TradeState {
342        match code {
343            "SUCCESS" | "TRADE_SUCCESS" => TradeState::SUCCESS,
344            "REFUND" => TradeState::REFUND,
345            "NOTPAY" | "WAIT_BUYER_PAY" => TradeState::NOTPAY,
346            "CLOSED" | "TRADE_CLOSED" => TradeState::CLOSED,
347            "REVOKED" => TradeState::REVOKED,
348            "USERPAYING" => TradeState::USERPAYING,
349            "PAYERROR" | "TRADE_FINISHED" => TradeState::PAYERROR,
350            _ => TradeState::None
351        }
352    }
353
354    fn to_string(&self) -> &'static str {
355        match self {
356            TradeState::SUCCESS => "已支付",
357            TradeState::REFUND => "已支付",
358            TradeState::NOTPAY => "待支付",
359            TradeState::CLOSED => "已关闭",
360            TradeState::REVOKED => "已关闭",
361            TradeState::USERPAYING => "待支付",
362            TradeState::PAYERROR => "支付失败",
363            TradeState::None => "待支付"
364        }
365    }
366}
367
368#[derive(Debug)]
369pub enum RefundStatus {
370    /// 退款成功
371    SUCCESS,
372    /// 退款关闭
373    CLOSED,
374    /// 退款处理中
375    PROCESSING,
376    /// 退款异常,手动处理此笔退款
377    ABNORMAL,
378    None,
379}
380impl RefundStatus {
381    fn from(code: &str) -> RefundStatus {
382        match code {
383            "SUCCESS" | "Y" | "REFUND_SUCCESS" => RefundStatus::SUCCESS,
384            "CLOSED" => RefundStatus::CLOSED,
385            "PROCESSING" | "N" => RefundStatus::PROCESSING,
386            "ABNORMAL" => RefundStatus::ABNORMAL,
387            _ => RefundStatus::None
388        }
389    }
390    fn to_string(&self) -> &'static str {
391        match self {
392            RefundStatus::SUCCESS => "已退款",
393            RefundStatus::None => "退款中",
394            RefundStatus::CLOSED => "已关闭",
395            RefundStatus::PROCESSING => "退款中",
396            RefundStatus::ABNORMAL => "退款异常"
397        }
398    }
399}
400/// 退款回调数据
401#[derive(Debug)]
402pub struct RefundNotify {
403    /// 商户订单号
404    out_trade_no: String,
405    refund_no: String,
406    /// 服务商商户号
407    sp_mchid: String,
408    /// 子商户号
409    sub_mchid: String,
410    /// 微信内部订单号
411    transaction_id: String,
412    /// 退款订单号
413    refund_id: String,
414    /// 成功时间
415    success_time: i64,
416    /// 支付金额
417    total: f64,
418    /// 退款金额
419    refund: f64,
420    /// 实际支付金额
421    payer_total: f64,
422    /// 实际退款金额
423    payer_refund: f64,
424    /// 状态
425    status: RefundStatus,
426}
427
428impl RefundNotify {
429    pub fn json(&self) -> JsonValue {
430        object! {
431            "out_trade_no" => self.out_trade_no.clone(),
432            "sp_mchid" => self.sp_mchid.clone(),
433            "sub_mchid" => self.sub_mchid.clone(),
434            "transaction_id" => self.transaction_id.clone(),
435            "success_time" => self.success_time,
436            "total" => self.total,
437            "refund" => self.refund,
438            "payer_total" => self.payer_total,
439            "payer_refund" => self.payer_refund,
440            "status" => self.status.to_string(),
441            "refund_no"=>self.refund_no.clone(),
442            "refund_id"=>self.refund_id.clone()
443        }
444    }
445}
446
447pub enum Types {
448    /// JS支付
449    Jsapi,
450    /// 扫码支付
451    Native,
452    /// H5页面
453    H5,
454    /// 小程序
455    MiniJsapi,
456    /// App
457    App,
458    /// 付款码
459    Micropay,
460}
461impl Types {
462    pub fn str(self) -> &'static str {
463        match self {
464            Types::Jsapi => "jsapi",
465            Types::Native => "native",
466            Types::H5 => "h5",
467            Types::MiniJsapi => "minijsapi",
468            Types::App => "app",
469            Types::Micropay => "micropay"
470        }
471    }
472    pub fn from(name: &str) -> Self {
473        match name {
474            "jsapi" => Types::Jsapi,
475            "native" => Types::Native,
476            "h5" => Types::H5,
477            "minijsapi" => Types::MiniJsapi,
478            "app" => Types::App,
479            "micropay" => Types::Micropay,
480            _ => Types::Jsapi
481        }
482    }
483}