wechat-minapp 3.3.1

微信小程序服务端API SDK
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
//! 微信小程序小程序码生成模块
//!
//! 该模块提供了生成微信小程序小程序码的功能,支持多种类型的小程序码和自定义参数。
//!
//! # 主要功能
//!
//! - 生成小程序页面小程序码
//! - 支持自定义尺寸、颜色、透明度等参数
//! - 支持不同环境版本(开发版、体验版、正式版)
//! - 链式参数构建器模式
//!
//! # 快速开始
//!
//! ```no_run
//! use wechat_minapp::client::WechatMinapp;
//! use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // 初始化客户端
//!     let app_id = "your_app_id";
//!     let secret = "your_app_secret";
//!     let client = WechatMinapp::new(app_id, secret);
//!     let qr = Qr::new(client);
//!
//!     // 构建小程序码参数
//!     let args = QrCodeArgs::builder()
//!         .path("pages/index/index")
//!         .width(300)
//!         .env_version(MinappEnvVersion::Release)
//!         .build()?;
//!
//!     // 生成小程序码
//!     let qr_code = qr.qr_code(args).await?;
//!     
//!     // 获取小程序码图片数据
//!     let buffer = qr_code.buffer();
//!     println!("生成的小程序码大小: {} bytes", buffer.len());
//!
//!     // 可以将 buffer 保存为文件或直接返回给前端
//!     // std::fs::write("qrcode.png", buffer)?;
//!     
//!     Ok(())
//! }
//! ```
//!
//! # 参数说明
//!
//! - `path`: 小程序页面路径,必填,最大长度 1024 字符
//! - `width`: 小程序码宽度,单位 px,最小 280px,最大 1280px
//! - `auto_color`: 是否自动配置线条颜色
//! - `line_color`: 自定义线条颜色,RGB 格式
//! - `is_hyaline`: 是否透明背景
//! - `env_version`: 环境版本,默认为正式版
//!
//! # 注意事项
//!
//! - 生成的小程序码永不过期,数量不限
//! - 接口只能生成已发布的小程序的小程序码
//! - 支持带参数路径,如 `pages/index/index?param=value`
//! - 小程序码大小限制为 128KB,请合理设置 width 参数
//!
//! # 示例
//!
//! ## 生成带颜色的小程序码
//!
//! ```no_run
//! use wechat_minapp::client::WechatMinapp;
//! use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // 初始化客户端
//!     let app_id = "your_app_id";
//!     let secret = "your_app_secret";
//!     let client = WechatMinapp::new(app_id, secret);
//!     let qr = Qr::new(client);
//!
//!     let args = QrCodeArgs::builder()
//!     .path("pages/detail/detail?id=123")
//!     .width(400)
//!     .line_color(Rgb::new(255, 0, 0)) // 红色线条
//!     .with_is_hyaline() // 透明背景
//!     .env_version(MinappEnvVersion::Develop)
//!     .build()
//!     .unwrap();
//!     // 生成小程序码
//!     let qr_code = qr.qr_code(args).await?;
//!     
//!     // 获取小程序码图片数据
//!     let buffer = qr_code.buffer();
//!     Ok(())
//! }
//! ```
//!
//! ## 生成简单小程序码
//!
//! ```no_run
//! use wechat_minapp::client::WechatMinapp;
//! use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // 初始化客户端
//!     let app_id = "your_app_id";
//!     let secret = "your_app_secret";
//!     let client = WechatMinapp::new(app_id, secret);
//!     let qr = Qr::new(client);
//!
//!     let args = QrCodeArgs::builder()
//!     .path("pages/index/index")
//!     .build()
//!     .unwrap();
//!     // 生成小程序码
//!     let qr_code = qr.qr_code(args).await?;
//!     
//!     // 获取小程序码图片数据
//!     let buffer = qr_code.buffer();
//!     Ok(())
//! }
//! ```
//!
//! # 错误处理
//!
//! 小程序码生成可能遇到以下错误:
//!
//! - 参数验证错误(路径为空或过长)
//! - 认证错误(access_token 无效)
//! - 网络错误
//! - 微信 API 返回错误
//!
//! 建议在生产环境中妥善处理这些错误。

use super::Qr;
use crate::utils::{RequestBuilder, ResponseExt};
use crate::{Result, constants, error::Error, new_type::PagePath};
use serde::{Deserialize, Serialize};
use tracing::debug;

/// 二维码图片数据
///
/// 包含生成的二维码图片的二进制数据,通常是 PNG 格式。
///
/// # 示例
///
/// ```no_run
/// use wechat_minapp::client::WechatMinappSDK;
/// use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // 初始化客户端
///     let app_id = "your_app_id";
///     let secret = "your_app_secret";
///     let client = WechatMinappSDK::new(app_id, secret);
///     let qr = Qr::new(client);
///
///     let args = QrCodeArgs::builder()
///     .path("pages/index/index")
///     .build()
///     .unwrap();
///     // 生成小程序码
///     let qr_code = qr.qr_code(args).await?;
///     
///     // 获取小程序码图片数据
///     let buffer = qr_code.buffer();
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QrCode {
    pub buffer: Vec<u8>,
}

impl QrCode {
    /// 获取二维码图片的二进制数据
    ///
    /// 返回的字节向量通常是 PNG 格式的图片数据,可以直接写入文件或返回给 HTTP 响应。
    ///
    /// # 返回
    ///
    /// 二维码图片的二进制数据引用
    pub fn buffer(&self) -> &Vec<u8> {
        &self.buffer
    }
}

/// 二维码生成参数
///
/// 用于配置二维码的生成选项,通过 [`QrCodeArgs::builder()`] 方法创建。
#[derive(Debug, Deserialize, Serialize)]
pub struct QrCodeArgs {
    path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    width: Option<i16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    auto_color: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    line_color: Option<Rgb>,
    #[serde(skip_serializing_if = "Option::is_none")]
    is_hyaline: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    env_version: Option<MinappEnvVersion>,
}

/// 二维码参数构建器
///
/// 提供链式调用的方式构建二维码参数,确保参数的正确性。
///
/// # 示例
///
/// ```
/// use wechat_minapp::qr::{QrCodeArgs, Rgb, MinappEnvVersion};
///
/// let args = QrCodeArgs::builder()
///     .path("pages/index/index")
///     .width(300)
///     .with_auto_color()
///     .line_color(Rgb::new(255, 0, 0))
///     .with_is_hyaline()
///     .env_version(MinappEnvVersion::Release)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Deserialize)]
pub struct QrCodeArgBuilder {
    path: Option<String>,
    width: Option<i16>,
    auto_color: Option<bool>,
    line_color: Option<Rgb>,
    is_hyaline: Option<bool>,
    env_version: Option<MinappEnvVersion>,
}

// RGB 颜色值
///
/// 用于自定义二维码线条颜色。
///
/// # 示例
///
/// ```
/// use wechat_minapp::qr::Rgb;
///
/// let red = Rgb::new(255, 0, 0);      // 红色
/// let green = Rgb::new(0, 255, 0);    // 绿色
/// let blue = Rgb::new(0, 0, 255);     // 蓝色
/// let black = Rgb::new(0, 0, 0);      // 黑色
/// ```
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct Rgb {
    r: i16,
    g: i16,
    b: i16,
}

impl Rgb {
    /// 创建新的 RGB 颜色
    ///
    /// # 参数
    ///
    /// - `r`: 红色分量 (0-255)
    /// - `g`: 绿色分量 (0-255)
    /// - `b`: 蓝色分量 (0-255)
    ///
    /// # 返回
    ///
    /// 新的 Rgb 实例
    pub fn new(r: i16, g: i16, b: i16) -> Self {
        Rgb { r, g, b }
    }
}

impl QrCodeArgs {
    pub fn builder() -> QrCodeArgBuilder {
        QrCodeArgBuilder::new()
    }

    pub fn path(&self) -> String {
        self.path.clone()
    }

    pub fn width(&self) -> Option<i16> {
        self.width
    }

    pub fn auto_color(&self) -> Option<bool> {
        self.auto_color
    }

    pub fn line_color(&self) -> Option<Rgb> {
        self.line_color.clone()
    }

    pub fn is_hyaline(&self) -> Option<bool> {
        self.is_hyaline
    }

    pub fn env_version(&self) -> Option<MinappEnvVersion> {
        self.env_version.clone()
    }
}

impl Default for QrCodeArgBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// 小程序环境版本
///
/// 指定二维码生成的环境版本,不同环境版本对应不同的小程序实例。
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MinappEnvVersion {
    /// 开发版,用于开发环境
    Release,
    /// 体验版,用于测试环境
    Trial,
    /// 正式版,用于生产环境
    Develop,
}

impl From<MinappEnvVersion> for String {
    fn from(value: MinappEnvVersion) -> Self {
        match value {
            MinappEnvVersion::Develop => "develop".to_string(),
            MinappEnvVersion::Release => "release".to_string(),
            MinappEnvVersion::Trial => "trial".to_string(),
        }
    }
}

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

    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    pub fn width(mut self, width: i16) -> Self {
        self.width = Some(width);
        self
    }

    pub fn with_auto_color(mut self) -> Self {
        self.auto_color = Some(true);
        self
    }

    pub fn line_color(mut self, color: Rgb) -> Self {
        self.line_color = Some(color);
        self
    }

    pub fn with_is_hyaline(mut self) -> Self {
        self.is_hyaline = Some(true);
        self
    }

    pub fn env_version(mut self, version: MinappEnvVersion) -> Self {
        self.env_version = Some(version);
        self
    }

    pub fn build(self) -> Result<QrCodeArgs> {
        let path = self.path.map_or_else(
            || {
                Err(Error::InvalidParameter(
                    "小程序页面路径不能为空".to_string(),
                ))
            },
            |v| {
                let valid_path = PagePath::try_from(v)?;
                Ok(valid_path.to_string())
            },
        )?;

        if self.auto_color.is_some() && self.line_color.is_some() {
            return Err(Error::InvalidParameter(
                "auto_color 为 true 时,line_color 不能设置".to_string(),
            ));
        }

        Ok(QrCodeArgs {
            path,
            width: self.width,
            auto_color: self.auto_color,
            line_color: self.line_color,
            is_hyaline: self.is_hyaline,
            env_version: self.env_version,
        })
    }
}

impl Qr {
    /// 生成小程序二维码
    ///
    /// 调用微信小程序二维码生成接口,返回包含二维码图片数据的 [`QrCode`] 对象。
    ///
    /// # 参数
    ///
    /// - `args`: 二维码生成参数
    ///
    /// # 返回
    ///
    /// 成功返回 `Ok(QrCode)`,失败返回错误信息。
    ///
    /// # 示例
    ///
    /// ```no_run
    /// use wechat_minapp::client::WechatMinappSDK;
    /// use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     // 初始化客户端
    ///     let app_id = "your_app_id";
    ///     let secret = "your_app_secret";
    ///     let client = WechatMinappSDK::new(app_id, secret);
    ///     let qr = Qr::new(client);
    ///
    ///     // 构建小程序码参数
    ///     let args = QrCodeArgs::builder()
    ///         .path("pages/index/index")
    ///         .width(300)
    ///         .env_version(MinappEnvVersion::Release)
    ///         .build()?;
    ///
    ///     // 生成小程序码
    ///     let qr_code = qr.qr_code(args).await?;
    ///     
    ///     // 获取小程序码图片数据
    ///     let buffer = qr_code.buffer();
    ///     println!("生成的小程序码大小: {} bytes", buffer.len());
    ///
    ///     // 可以将 buffer 保存为文件或直接返回给前端
    ///     // std::fs::write("qrcode.png", buffer)?;
    ///     
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # 错误
    ///
    /// - 网络错误
    /// - 认证错误(access_token 无效)
    /// - 微信 API 返回错误
    /// - 参数序列化错误
    pub async fn qr_code(&self, args: QrCodeArgs) -> Result<QrCode> {
        debug!("get qr code args {:?}", &args);

        let query = serde_json::json!({
            "access_token":self.client.token().await?
        });

        let body = serde_json::to_value(QrCodeArgs {
            path: args.path,
            width: args.width,
            auto_color: args.auto_color,
            line_color: args.line_color,
            is_hyaline: args.is_hyaline,
            env_version: args.env_version,
        })?;

        let request = RequestBuilder::new(constants::QR_CODE_ENDPOINT)
            .query(query)
            .body(body)
            .build()?;

        let client = &self.client.client;

        let response = client.execute(request).await?;

        debug!("response: {:#?}", response);

        let buffer = response.to_raw()?;
        if buffer.len() > 2048 {
            return Ok(QrCode { buffer });
        }
        Err(Error::InternalServer(
            String::from_utf8_lossy(&buffer).to_string(),
        ))
    }
}