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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::api::r#trait::{WechatApi, WechatContext};
use crate::error::WechatError;

#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize)]
pub struct QrcodeOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_color: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_color: Option<LineColor>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_hyaline: Option<bool>,
}

impl QrcodeOptions {
    pub fn new() -> Self {
        Self {
            path: None,
            width: None,
            auto_color: None,
            line_color: None,
            is_hyaline: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct UnlimitQrcodeOptions {
    pub scene: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_color: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_color: Option<LineColor>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_hyaline: Option<bool>,
}

impl UnlimitQrcodeOptions {
    pub fn new(scene: impl Into<String>) -> Self {
        Self {
            scene: scene.into(),
            page: None,
            width: None,
            auto_color: None,
            line_color: None,
            is_hyaline: None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct UrlSchemeExpire {
    #[serde(rename = "type")]
    pub expire_type: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_time: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_interval: Option<i64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct UrlSchemeOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire: Option<UrlSchemeExpire>,
}

#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
pub struct UrlSchemeResponse {
    pub openlink: String,
    #[serde(default)]
    pub errcode: i32,
    #[serde(default)]
    pub errmsg: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct UrlLinkOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_type: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_time: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expire_interval: Option<i64>,
}

#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
pub struct UrlLinkResponse {
    pub link: String,
    #[serde(default)]
    pub errcode: i32,
    #[serde(default)]
    pub errmsg: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ShortLinkOptions {
    pub page_url: String,
}

#[non_exhaustive]
#[derive(Debug, Clone, Deserialize)]
pub struct ShortLinkResponse {
    pub link: String,
    #[serde(default)]
    pub errcode: i32,
    #[serde(default)]
    pub errmsg: String,
}

/// WeChat Mini Program QR code and URL link API
///
/// Provides methods for generating Mini Program codes, QR codes,
/// URL schemes, URL links, and short links.
pub struct QrcodeApi {
    context: Arc<WechatContext>,
}

impl QrcodeApi {
    pub fn new(context: Arc<WechatContext>) -> Self {
        Self { context }
    }

    /// Generate a Mini Program code (limited usage, up to 100,000 codes).
    ///
    /// POST /wxa/getwxacode
    pub async fn get_wxa_code(&self, options: QrcodeOptions) -> Result<Vec<u8>, WechatError> {
        self.get_image_bytes("/wxa/getwxacode", &options).await
    }

    /// Generate an unlimited Mini Program code (no usage limit).
    ///
    /// POST /wxa/getwxacodeunlimit
    pub async fn get_wxa_code_unlimit(
        &self,
        options: UnlimitQrcodeOptions,
    ) -> Result<Vec<u8>, WechatError> {
        self.get_image_bytes("/wxa/getwxacodeunlimit", &options)
            .await
    }

    /// Create a Mini Program QR code for a given page path.
    ///
    /// POST /cgi-bin/wxaapp/createwxaqrcode
    pub async fn create_qrcode(
        &self,
        path: &str,
        width: Option<u32>,
    ) -> Result<Vec<u8>, WechatError> {
        #[derive(Serialize)]
        struct Request {
            path: String,
            #[serde(skip_serializing_if = "Option::is_none")]
            width: Option<u32>,
        }

        let request = Request {
            path: path.to_string(),
            width,
        };
        self.get_image_bytes("/cgi-bin/wxaapp/createwxaqrcode", &request)
            .await
    }

    /// Generate a URL Scheme for opening the Mini Program.
    ///
    /// POST /wxa/generatescheme
    pub async fn generate_url_scheme(
        &self,
        options: UrlSchemeOptions,
    ) -> Result<String, WechatError> {
        let response: UrlSchemeResponse = self
            .context
            .authed_post("/wxa/generatescheme", &options)
            .await?;

        WechatError::check_api(response.errcode, &response.errmsg)?;

        Ok(response.openlink)
    }

    /// Generate a URL Link for opening the Mini Program.
    ///
    /// POST /wxa/generate_urllink
    pub async fn generate_url_link(&self, options: UrlLinkOptions) -> Result<String, WechatError> {
        let response: UrlLinkResponse = self
            .context
            .authed_post("/wxa/generate_urllink", &options)
            .await?;

        WechatError::check_api(response.errcode, &response.errmsg)?;

        Ok(response.link)
    }

    /// Generate a short link for the Mini Program.
    ///
    /// POST /wxa/genwxashortlink
    pub async fn generate_short_link(
        &self,
        options: ShortLinkOptions,
    ) -> Result<String, WechatError> {
        let response: ShortLinkResponse = self
            .context
            .authed_post("/wxa/genwxashortlink", &options)
            .await?;

        WechatError::check_api(response.errcode, &response.errmsg)?;

        Ok(response.link)
    }

    /// Query details of an existing URL Scheme
    ///
    /// POST /wxa/queryscheme?access_token=ACCESS_TOKEN
    pub async fn query_scheme(&self, scheme: &str) -> Result<QuerySchemeResponse, WechatError> {
        #[derive(Serialize)]
        struct Request {
            scheme: String,
        }

        let body = Request {
            scheme: scheme.to_string(),
        };
        let response: QuerySchemeResponse =
            self.context.authed_post("/wxa/queryscheme", &body).await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    /// Query details of an existing URL Link
    ///
    /// POST /wxa/query_urllink?access_token=ACCESS_TOKEN
    pub async fn query_url_link(
        &self,
        url_link: &str,
    ) -> Result<QueryUrlLinkResponse, WechatError> {
        #[derive(Serialize)]
        struct Request {
            url_link: String,
        }

        let body = Request {
            url_link: url_link.to_string(),
        };
        let response: QueryUrlLinkResponse = self
            .context
            .authed_post("/wxa/query_urllink", &body)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    /// Generate an NFC Scheme for opening the Mini Program via NFC
    ///
    /// POST /wxa/generatenfcscheme?access_token=ACCESS_TOKEN
    pub async fn generate_nfc_scheme(
        &self,
        options: NfcSchemeOptions,
    ) -> Result<NfcSchemeResponse, WechatError> {
        let response: NfcSchemeResponse = self
            .context
            .authed_post("/wxa/generatenfcscheme", &options)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    async fn get_image_bytes<T: Serialize>(
        &self,
        endpoint: &str,
        body: &T,
    ) -> Result<Vec<u8>, WechatError> {
        let response = self.context.authed_post_raw(endpoint, body).await?;
        if let Err(error) = response.error_for_status_ref() {
            return Err(error.into());
        }

        let bytes = response.bytes().await?;
        if let Some((code, message)) = parse_api_error_from_json_bytes(&bytes) {
            return Err(WechatError::Api { code, message });
        }
        Ok(bytes.to_vec())
    }
}

impl WechatApi for QrcodeApi {
    fn api_name(&self) -> &'static str {
        "qrcode"
    }

    fn context(&self) -> &WechatContext {
        &self.context
    }
}

fn parse_api_error_from_json_bytes(bytes: &[u8]) -> Option<(i32, String)> {
    let value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
    let raw_code = value.get("errcode")?.as_i64()?;
    if raw_code == 0 {
        return None;
    }

    let code = i32::try_from(raw_code).unwrap_or_else(|_| {
        if raw_code.is_negative() {
            i32::MIN
        } else {
            i32::MAX
        }
    });
    let message = value
        .get("errmsg")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown error")
        .to_string();
    Some((code, message))
}

/// Scheme info from queryScheme
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SchemeInfo {
    #[serde(default)]
    pub appid: String,
    #[serde(default)]
    pub path: String,
    #[serde(default)]
    pub query: String,
    #[serde(default)]
    pub create_time: i64,
    #[serde(default)]
    pub expire_time: i64,
    #[serde(default)]
    pub env_version: String,
}

/// Scheme quota info
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SchemeQuota {
    #[serde(default)]
    pub long_time_used: i64,
    #[serde(default)]
    pub long_time_limit: i64,
}

/// Response from queryScheme
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct QuerySchemeResponse {
    #[serde(default)]
    pub scheme_info: SchemeInfo,
    #[serde(default)]
    pub scheme_quota: SchemeQuota,
    #[serde(default)]
    pub(crate) errcode: i32,
    #[serde(default)]
    pub(crate) errmsg: String,
}

/// URL Link info from queryUrlLink
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct UrlLinkInfo {
    #[serde(default)]
    pub appid: String,
    #[serde(default)]
    pub path: String,
    #[serde(default)]
    pub query: String,
    #[serde(default)]
    pub create_time: i64,
    #[serde(default)]
    pub expire_time: i64,
    #[serde(default)]
    pub env_version: String,
}

/// URL Link quota info
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct UrlLinkQuota {
    #[serde(default)]
    pub long_time_used: i64,
    #[serde(default)]
    pub long_time_limit: i64,
}

/// Response from queryUrlLink
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct QueryUrlLinkResponse {
    #[serde(default)]
    pub url_link_info: UrlLinkInfo,
    #[serde(default)]
    pub url_link_quota: UrlLinkQuota,
    #[serde(default)]
    pub(crate) errcode: i32,
    #[serde(default)]
    pub(crate) errmsg: String,
}

/// Jump target for NFC Scheme
#[derive(Debug, Clone, Serialize)]
pub struct NfcSchemeJumpWxa {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env_version: Option<String>,
}

/// Options for generating NFC Scheme
#[derive(Debug, Clone, Serialize)]
pub struct NfcSchemeOptions {
    pub jump_wxa: NfcSchemeJumpWxa,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sn: Option<String>,
}

/// Response from generateNFCScheme
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NfcSchemeResponse {
    #[serde(default)]
    pub openlink: String,
    #[serde(default)]
    pub(crate) errcode: i32,
    #[serde(default)]
    pub(crate) errmsg: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_qrcode_options_defaults() {
        let mut options = QrcodeOptions::new();
        options.path = Some("/pages/index".to_string());
        assert!(options.path.is_some());
    }

    #[test]
    fn test_line_color() {
        let color = LineColor { r: 0, g: 0, b: 0 };
        assert_eq!(color.r, 0);
    }

    #[test]
    fn test_unlimit_options() {
        let options = UnlimitQrcodeOptions {
            scene: "abc".to_string(),
            page: Some("/pages/index".to_string()),
            width: Some(430),
            auto_color: None,
            line_color: None,
            is_hyaline: None,
        };
        assert_eq!(options.scene, "abc");
    }

    #[test]
    fn test_query_scheme_response_parse() {
        let json = r#"{
            "scheme_info": {
                "appid": "wx1234567890abcdef",
                "path": "/pages/index",
                "query": "id=123",
                "create_time": 1700000000,
                "expire_time": 1700100000,
                "env_version": "release"
            },
            "scheme_quota": {
                "long_time_used": 5,
                "long_time_limit": 100
            },
            "errcode": 0,
            "errmsg": "ok"
        }"#;
        let response: QuerySchemeResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.scheme_info.appid, "wx1234567890abcdef");
        assert_eq!(response.scheme_info.path, "/pages/index");
        assert_eq!(response.scheme_quota.long_time_used, 5);
        assert_eq!(response.errcode, 0);
    }

    #[test]
    fn test_query_url_link_response_parse() {
        let json = r#"{
            "url_link_info": {
                "appid": "wx1234567890abcdef",
                "path": "/pages/index",
                "query": "",
                "create_time": 1700000000,
                "expire_time": 1700100000,
                "env_version": "release"
            },
            "url_link_quota": {
                "long_time_used": 2,
                "long_time_limit": 100
            },
            "errcode": 0,
            "errmsg": "ok"
        }"#;
        let response: QueryUrlLinkResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.url_link_info.appid, "wx1234567890abcdef");
        assert_eq!(response.url_link_quota.long_time_used, 2);
    }

    #[test]
    fn test_nfc_scheme_response_parse() {
        let json =
            r#"{"openlink": "weixin://dl/business/?t=NFC123", "errcode": 0, "errmsg": "ok"}"#;
        let response: NfcSchemeResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.openlink, "weixin://dl/business/?t=NFC123");
        assert_eq!(response.errcode, 0);
    }

    #[test]
    fn test_query_scheme_response_defaults() {
        let json = r#"{"errcode": 0, "errmsg": "ok"}"#;
        let response: QuerySchemeResponse = serde_json::from_str(json).unwrap();
        assert!(response.scheme_info.appid.is_empty());
        assert_eq!(response.scheme_quota.long_time_used, 0);
    }
}