wechat_mp_notify/
handler.rs1use 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#[derive(Debug, Clone, Default)]
14pub struct NotifyQuery {
15 pub signature: Option<String>,
17 pub timestamp: Option<String>,
19 pub nonce: Option<String>,
21 pub echostr: Option<String>,
23 pub msg_signature: Option<String>,
25 pub encrypt_type: Option<String>,
27 pub openid: Option<String>,
29}
30
31impl NotifyQuery {
32 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#[derive(Debug, Clone, Deserialize)]
44pub struct EncryptedEnvelope {
45 #[serde(rename = "Encrypt")]
47 pub encrypt: String,
48 #[serde(rename = "ToUserName", default)]
49 pub to_user_name: Option<String>,
50}
51
52#[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
65pub struct NotifyHandler {
67 config: NotifyConfig,
68}
69
70impl NotifyHandler {
71 pub fn new(config: NotifyConfig) -> Self {
73 Self { config }
74 }
75
76 pub fn config(&self) -> &NotifyConfig {
78 &self.config
79 }
80
81 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 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 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 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 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 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 ×tamp.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 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 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 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
227pub fn success_json() -> String {
229 json!({ "errcode": 0 }).to_string()
230}