wechat_mp_notify/
config.rs1use crate::error::{NotifyError, Result};
4use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8pub enum DataFormat {
9 #[default]
11 Json,
12 Xml,
14}
15
16#[derive(Clone)]
18pub struct NotifyConfig {
19 pub token: String,
21 pub encoding_aes_key: String,
23 pub app_id: String,
25 pub data_format: DataFormat,
27 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 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 pub fn with_data_format(mut self, format: DataFormat) -> Self {
64 self.data_format = format;
65 self
66 }
67
68 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
93pub(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}