br-pay 0.0.29

This is an pay
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use chrono::{DateTime, NaiveDateTime};
use crate::wechat::Wechat;
use json::{object, JsonValue};
use crate::alipay::AliPay;

pub mod alipay;
pub mod wechat;

#[derive(Clone)]
pub enum Pay {
    Wechat(Wechat),
    Alipay(AliPay),
    None,
}

impl Pay {
    pub fn new(data: JsonValue) -> Self {
        match data["mode"].as_str().unwrap_or("") {
            "wechat" => Pay::Wechat(Wechat {
                appid: data["appid"].to_string(),
                sp_mchid: data["sp_mchid"].to_string(),
                serial_no: data["serial_no"].to_string(),
                app_private: data["app_private"].to_string(),
                secret: data["secret"].to_string(),
                apikey: data["apikey"].to_string(),
                notify_url: data["notify_url"].to_string(),
            }),
            "alipay" => Pay::Alipay(AliPay {
                appid: data["appid"].to_string(),
                sp_mchid: data["sp_mchid"].to_string(),
                app_private: data["app_private"].to_string(),
                app_auth_token: data["app_auth_token"].as_str().unwrap_or("").to_string(),
                content_encryp: data["content_encryp"].to_string(),
                alipay_public_key: data["alipay_public_key"].to_string(),
                notify_url: data["notify_url"].to_string(),
            }),
            _ => Pay::None
        }
    }
}
impl PayMode for Pay {
    fn login(&mut self, code: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.login(code),
            Self::Alipay(e) => e.login(code),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.pay_query(
                out_trade_no,
                sub_mchid,
            ),
            Self::Alipay(e) => e.pay_query(
                out_trade_no,
                sub_mchid,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    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> {
        match self {
            Self::Wechat(e) => e.refund(
                sub_mchid,
                out_trade_no,
                transaction_id,
                out_refund_no,
                amount,
                total,
                currency,
            ),
            Self::Alipay(e) => e.refund(
                sub_mchid,
                out_trade_no,
                transaction_id,
                out_refund_no,
                amount,
                total,
                currency,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.pay_notify(
                nonce,
                ciphertext,
                associated_data,
            ),
            Self::Alipay(e) => e.pay_notify(
                nonce,
                ciphertext,
                associated_data,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.refund_notify(
                nonce,
                ciphertext,
                associated_data,
            ),
            Self::Alipay(e) => e.refund_notify(
                nonce,
                ciphertext,
                associated_data,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.refund_query(
                trade_no,
                out_refund_no,
                sub_mchid,
            ),
            Self::Alipay(e) => e.refund_query(
                trade_no,
                out_refund_no,
                sub_mchid,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn auth(&mut self, code: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.auth(code),
            Self::Alipay(e) => e.auth(code),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.close(
                out_trade_no, sub_mchid,
            ),
            Self::Alipay(e) => e.close(
                out_trade_no, sub_mchid,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn config(&mut self) -> JsonValue {
        match self {
            Self::Wechat(e) => object! {
                sp_mchid:e.sp_mchid.clone(),
                appid:e.appid.clone(),
            },
            Self::Alipay(e) => object! {
                appid:e.appid.clone(),
                sp_mchid:e.sp_mchid.clone()
            },
            Pay::None => object! {
                appid:"",
                sp_mchid:""
            }
        }
    }

    fn pay(&mut self, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.pay(
                types,
                sub_mchid,
                out_trade_no,
                description,
                total_fee,
                sp_openid,
            ),
            Self::Alipay(e) => e.pay(
                types,
                sub_mchid,
                out_trade_no,
                description,
                total_fee,
                sp_openid,
            ),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.notify(data),
            Self::Alipay(e) => e.notify(data),
            Pay::None => Err("No login data".to_owned())
        }
    }

    fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String> {
        match self {
            Self::Wechat(e) => e.get_sub_mchid(sub_mchid),
            Self::Alipay(e) => e.get_sub_mchid(sub_mchid),
            Pay::None => Err("No login data".to_owned())
        }
    }
}

pub trait PayMode {
    /// 获取商户号和状态
    fn get_sub_mchid(&mut self, sub_mchid: &str) -> Result<JsonValue, String>;
    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String>;
    fn config(&mut self) -> JsonValue;
    fn login(&mut self, code: &str) -> Result<JsonValue, String>;
    fn auth(&mut self, code: &str) -> Result<JsonValue, String>;

    /// 支付
    /// * out_trade_no 商户订单号
    /// * sub_mchid 子商户号
    /// * description 商品名称
    /// * total_fee 支付金额
    /// * notify_url 通知地址
    /// * sp_openid 支付客户ID
    fn pay(&mut self, types: Types, sub_mchid: &str, out_trade_no: &str, description: &str, total_fee: f64, sp_openid: &str) -> Result<JsonValue, String>;
    /// 关闭订单
    fn close(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
    /// 订单查询
    /// * out_trade_no 商户订单号
    /// * sub_mchid 子商户号
    fn pay_query(&mut self, out_trade_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
    /// 支付成功通知
    fn pay_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String>;

    #[allow(clippy::too_many_arguments)]
    /// 订单退款
    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>;
    /// 退款通知
    fn refund_notify(&mut self, nonce: &str, ciphertext: &str, associated_data: &str) -> Result<JsonValue, String>;
    /// 退款查询
    fn refund_query(&mut self, trade_no: &str, out_refund_no: &str, sub_mchid: &str) -> Result<JsonValue, String>;
}

/// 支付回调数据
#[derive(Debug)]
pub struct PayNotify {
    /// 支付方式
    trade_type: TradeType,
    /// 商户订单号
    out_trade_no: String,
    /// 服务商商户号
    sp_mchid: String,
    /// 子商户号
    sub_mchid: String,
    /// 应用APPID
    sp_appid: String,
    /// 微信内部订单号
    transaction_id: String,
    /// 成功时间
    success_time: i64,
    /// 服务商用户ID
    sp_openid: String,
    /// 子商户用户ID
    sub_openid: String,
    /// 支付金额
    total: usize,
    /// 实际支付金额
    payer_total: usize,
    /// 币种
    currency: String,
    /// 实际支付币种
    payer_currency: String,
    /// 状态
    trade_state: TradeState,
}
impl PayNotify {
    pub fn json(&self) -> JsonValue {
        object! {
            "trade_type" => self.trade_type.to_string(),
            "out_trade_no" => self.out_trade_no.to_string(),
            "sp_mchid" => self.sp_mchid.to_string(),
            "sub_mchid" => self.sub_mchid.to_string(),
            "sp_appid" => self.sp_appid.to_string(),
            "transaction_id" => self.transaction_id.to_string(),
            "success_time" => self.success_time,
            "sp_openid" => self.sp_openid.to_string(),
            "sub_openid" => self.sub_openid.to_string(),
            "total" => self.total,
            "payer_total" => self.payer_total,
            "currency" => self.currency.clone(),
            "payer_currency" => self.payer_currency.clone(),
            "trade_state" => self.trade_state.to_string(),
        }
    }
    pub fn success_time(datetime: &str) -> i64 {
        if datetime.is_empty() {
            return 0;
        }
        let datetime = DateTime::parse_from_rfc3339(datetime).unwrap();
        datetime.timestamp()
    }
    pub fn alipay_time(datetime: &str) -> i64 {
        if datetime.is_empty() {
            return 0;
        }
        let t = NaiveDateTime::parse_from_str(datetime, "%Y-%m-%d %H:%M:%S").unwrap();
        t.and_utc().timestamp()
    }
}
#[derive(Debug)]
pub enum TradeType {
    /// 小程序与JSAPI
    JSAPI,
    None,
}
impl TradeType {
    fn from(code: &str) -> TradeType {
        match code {
            "JSAPI" => TradeType::JSAPI,
            _ => TradeType::None
        }
    }
    fn to_string(&self) -> &'static str {
        match self {
            TradeType::JSAPI => "JSAPI",
            TradeType::None => ""
        }
    }
}
#[derive(Debug)]
pub enum TradeState {
    /// 支付成功
    SUCCESS,
    /// 转入退款
    REFUND,
    /// 未支付
    NOTPAY,
    /// 已关闭
    CLOSED,
    /// 已撤销(仅付款码支付会返回)
    REVOKED,
    /// 用户支付中(仅付款码支付会返回)
    USERPAYING,
    /// 支付失败(仅付款码支付会返回)
    PAYERROR,
    None,
}
impl TradeState {
    fn from(code: &str) -> TradeState {
        match code {
            "SUCCESS" | "TRADE_SUCCESS" => TradeState::SUCCESS,
            "REFUND" => TradeState::REFUND,
            "NOTPAY" | "WAIT_BUYER_PAY" => TradeState::NOTPAY,
            "CLOSED" | "TRADE_CLOSED" => TradeState::CLOSED,
            "REVOKED" => TradeState::REVOKED,
            "USERPAYING" => TradeState::USERPAYING,
            "PAYERROR" | "TRADE_FINISHED" => TradeState::PAYERROR,
            _ => TradeState::None
        }
    }

    fn to_string(&self) -> &'static str {
        match self {
            TradeState::SUCCESS => "已支付",
            TradeState::REFUND => "已支付",
            TradeState::NOTPAY => "待支付",
            TradeState::CLOSED => "已关闭",
            TradeState::REVOKED => "已关闭",
            TradeState::USERPAYING => "待支付",
            TradeState::PAYERROR => "支付失败",
            TradeState::None => "待支付"
        }
    }
}

#[derive(Debug)]
pub enum RefundStatus {
    /// 退款成功
    SUCCESS,
    /// 退款关闭
    CLOSED,
    /// 退款处理中
    PROCESSING,
    /// 退款异常,手动处理此笔退款
    ABNORMAL,
    None,
}
impl RefundStatus {
    fn from(code: &str) -> RefundStatus {
        match code {
            "SUCCESS" | "Y" | "REFUND_SUCCESS" => RefundStatus::SUCCESS,
            "CLOSED" => RefundStatus::CLOSED,
            "PROCESSING" | "N" => RefundStatus::PROCESSING,
            "ABNORMAL" => RefundStatus::ABNORMAL,
            _ => RefundStatus::None
        }
    }
    fn to_string(&self) -> &'static str {
        match self {
            RefundStatus::SUCCESS => "已退款",
            RefundStatus::None => "退款中",
            RefundStatus::CLOSED => "已关闭",
            RefundStatus::PROCESSING => "退款中",
            RefundStatus::ABNORMAL => "退款异常"
        }
    }
}
/// 退款回调数据
#[derive(Debug)]
pub struct RefundNotify {
    /// 商户订单号
    out_trade_no: String,
    refund_no: String,
    /// 服务商商户号
    sp_mchid: String,
    /// 子商户号
    sub_mchid: String,
    /// 微信内部订单号
    transaction_id: String,
    /// 退款订单号
    refund_id: String,
    /// 成功时间
    success_time: i64,
    /// 支付金额
    total: f64,
    /// 退款金额
    refund: f64,
    /// 实际支付金额
    payer_total: f64,
    /// 实际退款金额
    payer_refund: f64,
    /// 状态
    status: RefundStatus,
}

impl RefundNotify {
    pub fn json(&self) -> JsonValue {
        object! {
            "out_trade_no" => self.out_trade_no.clone(),
            "sp_mchid" => self.sp_mchid.clone(),
            "sub_mchid" => self.sub_mchid.clone(),
            "transaction_id" => self.transaction_id.clone(),
            "success_time" => self.success_time,
            "total" => self.total,
            "refund" => self.refund,
            "payer_total" => self.payer_total,
            "payer_refund" => self.payer_refund,
            "status" => self.status.to_string(),
            "refund_no"=>self.refund_no.clone(),
            "refund_id"=>self.refund_id.clone()
        }
    }
}

pub enum Types {
    /// JS支付
    Jsapi,
    /// 扫码支付
    Native,
    /// H5页面
    H5,
    /// 小程序
    MiniJsapi,
    /// App
    App,
    /// 付款码
    Micropay,
}
impl Types {
    pub fn str(self) -> &'static str {
        match self {
            Types::Jsapi => "jsapi",
            Types::Native => "native",
            Types::H5 => "h5",
            Types::MiniJsapi => "minijsapi",
            Types::App => "app",
            Types::Micropay => "micropay"
        }
    }
    pub fn from(name: &str) -> Self {
        match name {
            "jsapi" => Types::Jsapi,
            "native" => Types::Native,
            "h5" => Types::H5,
            "minijsapi" => Types::MiniJsapi,
            "app" => Types::App,
            "micropay" => Types::Micropay,
            _ => Types::Jsapi
        }
    }
}