Skip to main content

wechat_mp_notify/
config.rs

1//! 消息推送配置
2
3use crate::error::{NotifyError, Result};
4use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
5
6/// 推送数据格式
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8pub enum DataFormat {
9    /// JSON(小程序推荐)
10    #[default]
11    Json,
12    /// XML
13    Xml,
14}
15
16/// 消息推送配置(后台「消息推送」三项)
17#[derive(Clone)]
18pub struct NotifyConfig {
19    /// Token
20    pub token: String,
21    /// EncodingAESKey(43 字符,不含末尾 `=`)
22    pub encoding_aes_key: String,
23    /// 小程序 AppID(解密后校验)
24    pub app_id: String,
25    /// 数据格式
26    pub data_format: DataFormat,
27    /// 解码后的 32 字节 AESKey(内部使用)
28    pub(crate) aes_key: [u8; 32],
29}
30
31impl std::fmt::Debug for NotifyConfig {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("NotifyConfig")
34            .field("token", &"***")
35            .field("encoding_aes_key", &"***")
36            .field("app_id", &self.app_id)
37            .field("data_format", &self.data_format)
38            .finish()
39    }
40}
41
42impl NotifyConfig {
43    /// 创建配置
44    pub fn new(
45        token: impl Into<String>,
46        encoding_aes_key: impl Into<String>,
47        app_id: impl Into<String>,
48    ) -> Result<Self> {
49        let token = token.into();
50        let encoding_aes_key = encoding_aes_key.into();
51        let app_id = app_id.into();
52        let aes_key = decode_aes_key(&encoding_aes_key)?;
53        Ok(Self {
54            token,
55            encoding_aes_key,
56            app_id,
57            data_format: DataFormat::Json,
58            aes_key,
59        })
60    }
61
62    /// 设置数据格式
63    pub fn with_data_format(mut self, format: DataFormat) -> Self {
64        self.data_format = format;
65        self
66    }
67
68    /// 从环境变量加载
69    ///
70    /// - `WECHAT_MP_APP_ID`
71    /// - `WECHAT_MP_PUSH_TOKEN`
72    /// - `WECHAT_MP_PUSH_AES_KEY`
73    /// - `WECHAT_MP_PUSH_FORMAT`(可选:`json` / `xml`)
74    pub fn from_env() -> Result<Self> {
75        let app_id = env_required("WECHAT_MP_APP_ID")?;
76        let token = env_required("WECHAT_MP_PUSH_TOKEN")?;
77        let aes_key = env_required("WECHAT_MP_PUSH_AES_KEY")?;
78        let mut cfg = Self::new(token, aes_key, app_id)?;
79        if let Ok(fmt) = std::env::var("WECHAT_MP_PUSH_FORMAT") {
80            cfg = cfg.with_data_format(match fmt.to_ascii_lowercase().as_str() {
81                "xml" => DataFormat::Xml,
82                _ => DataFormat::Json,
83            });
84        }
85        Ok(cfg)
86    }
87}
88
89fn env_required(key: &str) -> Result<String> {
90    std::env::var(key).map_err(|_| NotifyError::Config(format!("缺少环境变量: {key}")))
91}
92
93/// EncodingAESKey → 32 字节 AESKey
94pub(crate) fn decode_aes_key(encoding_aes_key: &str) -> Result<[u8; 32]> {
95    let key = if encoding_aes_key.ends_with('=') {
96        encoding_aes_key.to_string()
97    } else {
98        format!("{encoding_aes_key}=")
99    };
100    let bytes = BASE64
101        .decode(key.as_bytes())
102        .map_err(|e| NotifyError::Config(format!("EncodingAESKey Base64 解码失败: {e}")))?;
103    if bytes.len() != 32 {
104        return Err(NotifyError::Config(format!(
105            "AESKey 长度应为 32 字节,实际 {}",
106            bytes.len()
107        )));
108    }
109    let mut arr = [0u8; 32];
110    arr.copy_from_slice(&bytes);
111    Ok(arr)
112}