Skip to main content

br_alipay/
lib.rs

1use std::collections::HashMap;
2use json::{JsonValue};
3use crate::applet::Applet;
4use std::sync::{RwLock};
5use once_cell::sync::Lazy;
6use crate::config::{Channel, Config};
7use crate::isv::Isv;
8
9pub mod applet;
10pub mod config;
11mod isv;
12
13static ACCOUNT: Lazy<RwLock<HashMap<String, Config>>> = Lazy::new(|| {
14    RwLock::new(HashMap::new())
15});
16
17
18#[derive(Clone)]
19pub enum Alipay {
20    /// 小程序
21    Applet(Applet),
22    /// 第三方
23    Isv(Isv),
24    /// 网站
25    Web,
26    None,
27}
28
29impl Alipay {
30    pub fn new(config: Config) -> Self {
31        {
32            let mut data = ACCOUNT.write().unwrap();
33            if data.get(&config.appid.clone()).is_none() {
34                data.insert(config.appid.clone(), config.clone());
35            }
36        }
37        let t = ACCOUNT.read().unwrap();
38        let account = t.get(&config.appid).unwrap().clone();
39
40        match account.channel {
41            Channel::Applet => Alipay::Applet(Applet {
42                appid: account.appid,
43                app_private: account.app_private,
44                alipay_public_key: account.alipay_public_key,
45                app_auth_token: account.app_auth_token,
46            }),
47            Channel::Isv => Alipay::Isv(Isv {
48                appid: account.appid,
49                app_private: account.app_private,
50                alipay_public_key: account.alipay_public_key,
51                app_auth_token: account.app_auth_token,
52            }),
53            _ => Alipay::None,
54        }
55    }
56}
57impl AlipayMethod for Alipay {
58    fn check(&mut self) -> Result<bool, String> {
59        match self {
60            Self::Isv(e) => e.check(),
61            Self::Applet(e) => e.check(),
62            _ => Err("暂未开放".to_string()),
63        }
64    }
65
66
67    fn login(&mut self, code: &str) -> Result<JsonValue, String> {
68        match self {
69            Self::Applet(e) => e.login(code),
70            Self::Isv(e) => e.login(code),
71            _ => Err("暂未开通".to_string())
72        }
73    }
74
75    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String> {
76        match self {
77            Self::Isv(e) => e.notify(data),
78            Self::Applet(e) => e.notify(data),
79            _ => Err("暂未开放".to_string()),
80        }
81    }
82
83    fn auth(&mut self, code: &str) -> Result<JsonValue, String> {
84        match self {
85            Self::Isv(e) => e.auth(code),
86            Self::Applet(e) => e.auth(code),
87            _ => Err("暂未开放".to_string()),
88        }
89    }
90}
91pub trait AlipayMethod {
92    /// 服务状态检测
93    fn check(&mut self) -> Result<bool, String>;
94    /// 登录
95    fn login(&mut self, code: &str) -> Result<JsonValue, String>;
96    /// 异步通知
97    fn notify(&mut self, data: JsonValue) -> Result<JsonValue, String>;
98    /// 商家授权
99    fn auth(&mut self, code: &str) -> Result<JsonValue, String>;
100}