Skip to main content

wechat_mp_notify/
handler.rs

1//! 消息推送处理器
2
3use crate::config::{DataFormat, NotifyConfig};
4use crate::crypto::{
5    decrypt_message, encrypt_message, sha1_sign, verify_msg_signature, verify_url_signature,
6};
7use crate::error::{NotifyError, Result};
8use crate::message::{parse_plain_json, parse_plain_xml, IncomingMessage};
9use serde::Deserialize;
10use serde_json::json;
11
12/// URL 查询参数(GET 验证 / POST 推送共用)
13#[derive(Debug, Clone, Default)]
14pub struct NotifyQuery {
15    /// 明文模式签名
16    pub signature: Option<String>,
17    /// 时间戳
18    pub timestamp: Option<String>,
19    /// 随机串
20    pub nonce: Option<String>,
21    /// URL 验证用
22    pub echostr: Option<String>,
23    /// 安全模式消息签名
24    pub msg_signature: Option<String>,
25    /// 加密类型,aes
26    pub encrypt_type: Option<String>,
27    /// 用户 openid(可选)
28    pub openid: Option<String>,
29}
30
31impl NotifyQuery {
32    /// 是否为安全模式
33    pub fn is_safe_mode(&self) -> bool {
34        self.encrypt_type
35            .as_deref()
36            .map(|t| t.eq_ignore_ascii_case("aes"))
37            .unwrap_or(false)
38            || self.msg_signature.is_some()
39    }
40}
41
42/// 加密包体外壳(JSON)
43#[derive(Debug, Clone, Deserialize)]
44pub struct EncryptedEnvelope {
45    /// 密文
46    #[serde(rename = "Encrypt")]
47    pub encrypt: String,
48    #[serde(rename = "ToUserName", default)]
49    pub to_user_name: Option<String>,
50}
51
52/// 加密回包
53#[derive(Debug, Clone, serde::Serialize)]
54pub struct EncryptedReply {
55    #[serde(rename = "Encrypt")]
56    pub encrypt: String,
57    #[serde(rename = "MsgSignature")]
58    pub msg_signature: String,
59    #[serde(rename = "TimeStamp")]
60    pub time_stamp: i64,
61    #[serde(rename = "Nonce")]
62    pub nonce: String,
63}
64
65/// 消息推送处理器
66pub struct NotifyHandler {
67    config: NotifyConfig,
68}
69
70impl NotifyHandler {
71    /// 创建处理器
72    pub fn new(config: NotifyConfig) -> Self {
73        Self { config }
74    }
75
76    /// 配置引用
77    pub fn config(&self) -> &NotifyConfig {
78        &self.config
79    }
80
81    /// 处理 URL 验证 GET 请求,成功返回 echostr
82    pub fn verify_url(&self, query: &NotifyQuery) -> Result<String> {
83        let signature = query
84            .signature
85            .as_deref()
86            .ok_or_else(|| NotifyError::Format("缺少 signature".into()))?;
87        let timestamp = query
88            .timestamp
89            .as_deref()
90            .ok_or_else(|| NotifyError::Format("缺少 timestamp".into()))?;
91        let nonce = query
92            .nonce
93            .as_deref()
94            .ok_or_else(|| NotifyError::Format("缺少 nonce".into()))?;
95        let echostr = query
96            .echostr
97            .as_deref()
98            .ok_or_else(|| NotifyError::Format("缺少 echostr".into()))?;
99
100        if !verify_url_signature(&self.config.token, timestamp, nonce, signature) {
101            return Err(NotifyError::Signature);
102        }
103        Ok(echostr.to_string())
104    }
105
106    /// 解析 POST 推送包体,返回明文消息
107    pub fn parse_incoming(&self, query: &NotifyQuery, body: &str) -> Result<IncomingMessage> {
108        let plain = if query.is_safe_mode() {
109            self.decrypt_body(query, body)?
110        } else {
111            // 明文模式验签
112            let signature = query
113                .signature
114                .as_deref()
115                .ok_or_else(|| NotifyError::Format("缺少 signature".into()))?;
116            let timestamp = query
117                .timestamp
118                .as_deref()
119                .ok_or_else(|| NotifyError::Format("缺少 timestamp".into()))?;
120            let nonce = query
121                .nonce
122                .as_deref()
123                .ok_or_else(|| NotifyError::Format("缺少 nonce".into()))?;
124            if !verify_url_signature(&self.config.token, timestamp, nonce, signature) {
125                return Err(NotifyError::Signature);
126            }
127            body.to_string()
128        };
129
130        match self.config.data_format {
131            DataFormat::Json => parse_plain_json(&plain),
132            DataFormat::Xml => {
133                // 明文可能是 JSON(兼容)或 XML
134                let trimmed = plain.trim_start();
135                if trimmed.starts_with('{') {
136                    parse_plain_json(&plain)
137                } else {
138                    parse_plain_xml(&plain)
139                }
140            }
141        }
142    }
143
144    /// 仅解密得到明文字符串
145    pub fn decrypt_body(&self, query: &NotifyQuery, body: &str) -> Result<String> {
146        let encrypt = extract_encrypt(body, self.config.data_format)?;
147        let timestamp = query
148            .timestamp
149            .as_deref()
150            .ok_or_else(|| NotifyError::Format("缺少 timestamp".into()))?;
151        let nonce = query
152            .nonce
153            .as_deref()
154            .ok_or_else(|| NotifyError::Format("缺少 nonce".into()))?;
155        let msg_signature = query
156            .msg_signature
157            .as_deref()
158            .ok_or_else(|| NotifyError::Format("安全模式缺少 msg_signature".into()))?;
159
160        if !verify_msg_signature(
161            &self.config.token,
162            timestamp,
163            nonce,
164            &encrypt,
165            msg_signature,
166        ) {
167            return Err(NotifyError::Signature);
168        }
169
170        decrypt_message(&self.config, &encrypt)
171    }
172
173    /// 构造安全模式加密回包(JSON)
174    pub fn encrypt_reply(&self, plain: &str, timestamp: i64, nonce: &str) -> Result<EncryptedReply> {
175        let encrypt = encrypt_message(&self.config, plain)?;
176        let msg_signature = sha1_sign(&[
177            &self.config.token,
178            &timestamp.to_string(),
179            nonce,
180            &encrypt,
181        ]);
182        Ok(EncryptedReply {
183            encrypt,
184            msg_signature,
185            time_stamp: timestamp,
186            nonce: nonce.to_string(),
187        })
188    }
189
190    /// 成功应答:空串 / success(多数事件无需加密)
191    pub fn reply_success() -> &'static str {
192        "success"
193    }
194}
195
196fn extract_encrypt(body: &str, format: DataFormat) -> Result<String> {
197    let trimmed = body.trim_start();
198    if trimmed.starts_with('{') || matches!(format, DataFormat::Json) && trimmed.contains("Encrypt")
199    {
200        // 尝试 JSON
201        if let Ok(env) = serde_json::from_str::<EncryptedEnvelope>(body) {
202            return Ok(env.encrypt);
203        }
204        if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
205            if let Some(enc) = v.get("Encrypt").and_then(|x| x.as_str()) {
206                return Ok(enc.to_string());
207            }
208        }
209    }
210
211    // XML:<Encrypt><![CDATA[...]]></Encrypt> 或 <Encrypt>...</Encrypt>
212    if let Some(start) = body.find("<Encrypt>") {
213        let after = &body[start + "<Encrypt>".len()..];
214        let content = if let Some(rest) = after.strip_prefix("<![CDATA[") {
215            rest.split("]]>").next().unwrap_or("")
216        } else {
217            after.split("</Encrypt>").next().unwrap_or("").trim()
218        };
219        if !content.is_empty() {
220            return Ok(content.to_string());
221        }
222    }
223
224    Err(NotifyError::Format("无法从包体提取 Encrypt".into()))
225}
226
227/// 便捷:构造 JSON 成功应答字符串
228pub fn success_json() -> String {
229    json!({ "errcode": 0 }).to_string()
230}