wechat-mp-sdk 0.3.0

WeChat Mini Program SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! WeChat SDK error types
//!
//! This module defines error types for the WeChat Mini Program SDK.
//!
//! ## Common WeChat API Error Codes
//!
//! - `-1`: System error
//! - `0`: Success
//! - `-1000`: Sign error
//! - `-1001`: Invalid parameter
//! - `-1002`: AppID error
//! - `-1003`: Access token error
//! - `-1004`: API frequency limit exceeded
//! - `-1005`: Permission denied
//! - `-1006`: API call failed
//! - `40001`: Invalid credential (access_token)
//! - `40002`: Invalid grant_type
//! - `40013`: Invalid appid
//! - `40125`: Invalid appsecret

use std::fmt;
use std::sync::Arc;
use thiserror::Error;

use crate::token::RETRYABLE_ERROR_CODES;

/// HTTP/transport error wrapper
///
/// Wraps either a reqwest HTTP error or a response decode error.
#[derive(Debug)]
pub enum HttpError {
    /// Reqwest HTTP client error
    Reqwest(Arc<reqwest::Error>),
    /// Response body decode error (valid JSON but doesn't match expected type)
    Decode(String),
}

impl fmt::Display for HttpError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HttpError::Reqwest(e) => write!(f, "{}", e),
            HttpError::Decode(msg) => write!(f, "Response decode error: {}", msg),
        }
    }
}

impl Clone for HttpError {
    fn clone(&self) -> Self {
        match self {
            HttpError::Reqwest(e) => HttpError::Reqwest(Arc::clone(e)),
            HttpError::Decode(msg) => HttpError::Decode(msg.clone()),
        }
    }
}

impl std::error::Error for HttpError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            HttpError::Reqwest(e) => Some(e.as_ref()),
            HttpError::Decode(_) => None,
        }
    }
}

impl From<reqwest::Error> for HttpError {
    fn from(e: reqwest::Error) -> Self {
        HttpError::Reqwest(Arc::new(e))
    }
}

impl HttpError {
    /// Returns true when this HTTP error represents a transient transport failure.
    pub fn is_transient(&self) -> bool {
        match self {
            HttpError::Reqwest(error) => match error.status() {
                Some(status) => status.is_server_error() || status.as_u16() == 429,
                None => true,
            },
            HttpError::Decode(_) => false,
        }
    }
}

/// WeChat SDK error types
///
/// # Variants
///
/// - `Http`: HTTP request/response errors
/// - `Json`: JSON serialization/deserialization errors
/// - `Api`: WeChat API returned an error
/// - `Token`: Access token related errors
/// - `Config`: Configuration errors
/// - `Signature`: Signature verification errors
/// - `Crypto`: Cryptography operation errors
/// - `InvalidAppId`: Invalid AppId format
/// - `InvalidOpenId`: Invalid OpenId format
/// - `InvalidAccessToken`: Invalid access token
/// - `InvalidAppSecret`: Invalid AppSecret
/// - `InvalidSessionKey`: Invalid SessionKey
/// - `InvalidUnionId`: Invalid UnionId
#[derive(Debug, Error)]
pub enum WechatError {
    /// HTTP request/response error (includes decode errors)
    #[error("{0}")]
    Http(HttpError),

    /// JSON serialization/deserialization error
    #[error("JSON serialization error: {0}")]
    Json(#[from] serde_json::Error),

    /// WeChat API returned an error
    ///
    /// # Fields
    /// - `code`: Error code returned by WeChat API
    /// - `message`: Error message from WeChat API
    #[error("WeChat API error (code={code}): {message}")]
    Api { code: i32, message: String },

    /// Access token related error
    #[error("Access token error: {0}")]
    Token(String),

    /// Configuration error
    #[error("Configuration error: {0}")]
    Config(String),

    /// Signature verification failed
    #[error("Signature verification failed: {0}")]
    Signature(String),

    /// Cryptography operation error
    #[error("Crypto operation error: {0}")]
    Crypto(String),

    /// Invalid AppId format
    ///
    /// AppId must start with 'wx' and be 18 characters long
    #[error("Invalid AppId: {0}")]
    InvalidAppId(String),

    /// Invalid OpenId format
    ///
    /// OpenId must be 20-40 characters
    #[error("Invalid OpenId: {0}")]
    InvalidOpenId(String),

    /// Invalid AccessToken
    #[error("Invalid AccessToken: {0}")]
    InvalidAccessToken(String),

    /// Invalid AppSecret
    #[error("Invalid AppSecret: {0}")]
    InvalidAppSecret(String),

    /// Invalid SessionKey
    #[error("Invalid SessionKey: {0}")]
    InvalidSessionKey(String),

    /// Invalid UnionId
    #[error("Invalid UnionId: {0}")]
    InvalidUnionId(String),
}

impl Clone for WechatError {
    fn clone(&self) -> Self {
        match self {
            WechatError::Http(e) => WechatError::Http(e.clone()),
            WechatError::Json(e) => WechatError::Json(serde_json::Error::io(std::io::Error::new(
                std::io::ErrorKind::Other,
                e.to_string(),
            ))),
            WechatError::Api { code, message } => WechatError::Api {
                code: *code,
                message: message.clone(),
            },
            WechatError::Token(msg) => WechatError::Token(msg.clone()),
            WechatError::Config(msg) => WechatError::Config(msg.clone()),
            WechatError::Signature(msg) => WechatError::Signature(msg.clone()),
            WechatError::Crypto(msg) => WechatError::Crypto(msg.clone()),
            WechatError::InvalidAppId(msg) => WechatError::InvalidAppId(msg.clone()),
            WechatError::InvalidOpenId(msg) => WechatError::InvalidOpenId(msg.clone()),
            WechatError::InvalidAccessToken(msg) => WechatError::InvalidAccessToken(msg.clone()),
            WechatError::InvalidAppSecret(msg) => WechatError::InvalidAppSecret(msg.clone()),
            WechatError::InvalidSessionKey(msg) => WechatError::InvalidSessionKey(msg.clone()),
            WechatError::InvalidUnionId(msg) => WechatError::InvalidUnionId(msg.clone()),
        }
    }
}

impl WechatError {
    /// Check WeChat API response errcode, return error if non-zero.
    pub(crate) fn check_api(errcode: i32, errmsg: &str) -> Result<(), WechatError> {
        if errcode != 0 {
            Err(WechatError::Api {
                code: errcode,
                message: errmsg.to_string(),
            })
        } else {
            Ok(())
        }
    }

    /// Returns true when this error is safe to retry.
    pub fn is_transient(&self) -> bool {
        match self {
            WechatError::Http(err) => err.is_transient(),
            WechatError::Api { code, .. } => RETRYABLE_ERROR_CODES.contains(code),
            _ => false,
        }
    }
}

impl From<reqwest::Error> for WechatError {
    fn from(e: reqwest::Error) -> Self {
        WechatError::Http(HttpError::Reqwest(Arc::new(e)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::token::RETRYABLE_ERROR_CODES;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn test_invalid_appid_error_message() {
        let err = WechatError::InvalidAppId("invalid".to_string());
        assert_eq!(err.to_string(), "Invalid AppId: invalid");
    }

    #[test]
    fn test_invalid_openid_error_message() {
        let err = WechatError::InvalidOpenId("short".to_string());
        assert_eq!(err.to_string(), "Invalid OpenId: short");
    }

    #[test]
    fn test_invalid_access_token_error_message() {
        let err = WechatError::InvalidAccessToken("".to_string());
        assert_eq!(err.to_string(), "Invalid AccessToken: ");
    }

    #[test]
    fn test_invalid_app_secret_error_message() {
        let err = WechatError::InvalidAppSecret("wrong".to_string());
        assert_eq!(err.to_string(), "Invalid AppSecret: wrong");
    }

    #[test]
    fn test_invalid_session_key_error_message() {
        let err = WechatError::InvalidSessionKey("invalid".to_string());
        assert_eq!(err.to_string(), "Invalid SessionKey: invalid");
    }

    #[test]
    fn test_invalid_union_id_error_message() {
        let err = WechatError::InvalidUnionId("".to_string());
        assert_eq!(err.to_string(), "Invalid UnionId: ");
    }

    #[test]
    fn test_check_api_success() {
        let result = WechatError::check_api(0, "success");
        assert!(result.is_ok());
    }

    #[test]
    fn test_check_api_error() {
        let result = WechatError::check_api(40013, "invalid appid");
        assert!(result.is_err());
        if let Err(WechatError::Api { code, message }) = result {
            assert_eq!(code, 40013);
            assert_eq!(message, "invalid appid");
        } else {
            panic!("Expected Api error");
        }
    }

    #[test]
    fn test_wechat_error_clone() {
        let err = WechatError::Api {
            code: 40013,
            message: "invalid appid".to_string(),
        };
        let cloned = err.clone();
        assert_eq!(format!("{}", err), format!("{}", cloned));

        let token_err = WechatError::Token("expired".to_string());
        let cloned_token = token_err.clone();
        assert_eq!(format!("{}", token_err), format!("{}", cloned_token));
    }

    #[test]
    fn test_http_error_clone() {
        let err = HttpError::Decode("bad json".to_string());
        let cloned = err.clone();
        assert_eq!(format!("{}", err), format!("{}", cloned));
    }

    #[test]
    fn test_http_error_source_chain() {
        use std::error::Error;

        let decode_err = HttpError::Decode("test".to_string());
        assert!(decode_err.source().is_none());
    }

    #[test]
    fn test_http_error_is_transient() {
        let reqwest_error = reqwest::Client::new().get("http://").build().unwrap_err();
        let reqwest_http_error = HttpError::Reqwest(Arc::new(reqwest_error));
        assert!(reqwest_http_error.is_transient());

        let decode_http_error = HttpError::Decode("bad json".to_string());
        assert!(!decode_http_error.is_transient());
    }

    #[test]
    fn test_wechat_error_is_transient_for_http_variants() {
        let reqwest_error = reqwest::Client::new().get("http://").build().unwrap_err();
        let transient_error = WechatError::Http(HttpError::Reqwest(Arc::new(reqwest_error)));
        assert!(transient_error.is_transient());

        let non_transient_error = WechatError::Http(HttpError::Decode("bad json".to_string()));
        assert!(!non_transient_error.is_transient());
    }

    #[tokio::test]
    async fn test_http_reqwest_status_503_is_transient() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/status-503"))
            .respond_with(ResponseTemplate::new(503))
            .mount(&mock_server)
            .await;

        let err = reqwest::Client::new()
            .get(format!("{}/status-503", mock_server.uri()))
            .send()
            .await
            .unwrap()
            .error_for_status()
            .unwrap_err();

        let http_error = HttpError::Reqwest(Arc::new(err));
        assert!(http_error.is_transient());
    }

    #[tokio::test]
    async fn test_http_reqwest_status_400_is_not_transient() {
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/status-400"))
            .respond_with(ResponseTemplate::new(400))
            .mount(&mock_server)
            .await;

        let err = reqwest::Client::new()
            .get(format!("{}/status-400", mock_server.uri()))
            .send()
            .await
            .unwrap()
            .error_for_status()
            .unwrap_err();

        let http_error = HttpError::Reqwest(Arc::new(err));
        assert!(!http_error.is_transient());
    }

    #[test]
    fn test_wechat_error_is_transient_for_api_and_all_other_variants() {
        for &code in RETRYABLE_ERROR_CODES {
            let retryable = WechatError::Api {
                code,
                message: "retryable".to_string(),
            };
            assert!(
                retryable.is_transient(),
                "code {} should be transient",
                code
            );
        }

        let non_retryable_api = WechatError::Api {
            code: 40013,
            message: "invalid appid".to_string(),
        };
        assert!(!non_retryable_api.is_transient());

        let json_error = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
        let non_transient_variants = [
            WechatError::Json(json_error),
            WechatError::Token("token".to_string()),
            WechatError::Config("config".to_string()),
            WechatError::Signature("sig".to_string()),
            WechatError::Crypto("crypto".to_string()),
            WechatError::InvalidAppId("appid".to_string()),
            WechatError::InvalidOpenId("openid".to_string()),
            WechatError::InvalidAccessToken("token".to_string()),
            WechatError::InvalidAppSecret("secret".to_string()),
            WechatError::InvalidSessionKey("session".to_string()),
            WechatError::InvalidUnionId("union".to_string()),
        ];

        for error in non_transient_variants {
            assert!(!error.is_transient());
        }
    }
}