chimes_utils/wechat/
mod.rs

1use std::fs::File;
2
3// use self::errors::WechatError;
4
5// 请求默认AGENT
6pub const WECHAT_DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3534.4 Safari/537.36";
7
8/// 微信接口域名
9pub const API_DOMAIN: &str = "https://api.weixin.qq.com";
10
11mod errors;
12mod message;
13mod token;
14
15pub use errors::*;
16pub use message::*;
17pub use token::*;
18pub type WechatResult<T> = Result<T, WechatError>;
19
20#[inline]
21pub fn json_decode(data: &str) -> WechatResult<serde_json::Value> {
22    let obj: serde_json::Value = match serde_json::from_str(data) {
23        Ok(decoded) => decoded,
24        Err(ref e) => {
25            return Err(WechatError::custom(-3, format!("Json decode error: {}", e)));
26        }
27    };
28    let dic = obj.as_object().unwrap();
29    let code = if dic.contains_key("errcode") {
30        "errcode"
31    } else {
32        "code"
33    };
34
35    let code = obj[code].as_i64().unwrap_or_default();
36    if code != 0 {
37        let msg: String = if dic.contains_key("msg") {
38            obj["msg"].to_string()
39        } else {
40            obj["errmsg"].to_string()
41        };
42        return Err(WechatError::custom(code as i32, msg));
43    }
44    println!("obj====={:?}", obj);
45    Ok(obj)
46}
47
48/// 微们接口平台类型
49// #[derive(Serialize, Deserialize, Debug, Clone)]
50#[derive(Debug, Clone)]
51pub enum PlatformType {
52    OfficialAccount, // 公众号
53    OpenPlatfrom,    // 开放平台
54    MiniProgram,     // 小程序
55}
56
57/// 微信sdk配置
58#[derive(Debug, Clone)]
59pub struct WechatConfig {
60    pub app_id: String,         // 应用id
61    pub offical_appid: String,  // 关联公众号的AppId,用这个来发送消息
62    pub secret: String,         // 密钥
63    pub token: String,          // token,在接口配置时填写的token,用于sigine验证
64    pub platform: PlatformType, // 配置的平台类型
65    // pub msg_type: MessageFormat,    // 消息格式
66    // pub encrypt_mode: EncryptMode   // 加密方式
67    pub mch_id: String,      //商户id
68    pub private_key: String, //商户证书私钥
69    pub certificate: String, //商户证书路径
70    pub secret_key: String,  //API 秘钥
71    pub notify_url: String,
72    pub refund_notify_url: String,
73}
74
75impl WechatConfig {
76    /// 设置配置
77    pub fn load(params: serde_json::Value) -> WechatResult<WechatConfig> {
78        let _conf = WechatConfig {
79            app_id: params["app-id"].as_str().unwrap_or_default().to_string(),
80            offical_appid: params["offical-appid"]
81                .as_str()
82                .unwrap_or_default()
83                .to_string(),
84            secret: params["secret"].as_str().unwrap_or_default().to_string(),
85            token: params["token"].as_str().unwrap_or_default().to_string(),
86            platform: PlatformType::MiniProgram,
87            mch_id: params["mch_id"].as_str().unwrap_or_default().to_string(),
88            private_key: params["private_key"]
89                .as_str()
90                .unwrap_or_default()
91                .to_string(),
92            certificate: params["certificate"]
93                .as_str()
94                .unwrap_or_default()
95                .to_string(),
96            secret_key: params["secret_key"]
97                .as_str()
98                .unwrap_or_default()
99                .to_string(),
100            notify_url: params["notify-url"]
101                .as_str()
102                .unwrap_or_default()
103                .to_string(),
104            refund_notify_url: if params["refund-notify-url"].as_str().is_none() {
105                params["notify-url"]
106                    .as_str()
107                    .unwrap_or_default()
108                    .to_string()
109            } else {
110                params["refund-notify-url"]
111                    .as_str()
112                    .unwrap_or_default()
113                    .to_string()
114            },
115        };
116        Ok(_conf)
117    }
118
119    /// 加载yml配置文件
120    pub fn load_yaml(conf_path: &str) -> WechatResult<WechatConfig> {
121        use yaml_rust::yaml;
122        // open file
123        let mut f = match File::open(conf_path) {
124            Ok(f) => f,
125            Err(e) => {
126                return Err(WechatError::custom(4004, format!("{}", e)));
127            }
128        };
129        let mut s = String::new();
130        use std::io::Read;
131        match f.read_to_string(&mut s) {
132            Ok(s) => s,
133            Err(e) => {
134                return Err(WechatError::custom(
135                    4004,
136                    format!("Error Reading file: {}", e),
137                ));
138            }
139        };
140        // f.read_to_string(&mut s).unwrap(); // read file content to s
141        // load string to yaml loader
142        // println!("Loaded {}", s);
143        let docs = yaml::YamlLoader::load_from_str(&s).unwrap();
144        // get first yaml hash doc
145        let _yaml_doc = &docs[0];
146        // get server value
147        // let server = yaml_doc["weapp"].clone();
148
149        Ok(WechatConfig::default())
150    }
151}
152
153/// 默认配置项
154impl Default for WechatConfig {
155    fn default() -> Self {
156        WechatConfig {
157            app_id: String::new(),
158            offical_appid: String::new(),
159            secret: String::new(),
160            token: String::new(),
161            platform: PlatformType::MiniProgram,
162            mch_id: "".to_string(),
163            private_key: "".to_string(),
164            certificate: "".to_string(),
165            secret_key: "".to_string(),
166            notify_url: "".to_string(),
167            refund_notify_url: "".to_string(),
168            // msg_type: MessageFormat::Json,
169            // encrypt_mode: EncryptMode::Plaintext
170        }
171    }
172}