wechat_minapp/qr/
minapp_code.rs

1//! 微信小程序小程序码生成模块
2//!
3//! 该模块提供了生成微信小程序小程序码的功能,支持多种类型的小程序码和自定义参数。
4//!
5//! # 主要功能
6//!
7//! - 生成小程序页面小程序码
8//! - 支持自定义尺寸、颜色、透明度等参数
9//! - 支持不同环境版本(开发版、体验版、正式版)
10//! - 链式参数构建器模式
11//!
12//! # 快速开始
13//!
14//! ```no_run
15//! use wechat_minapp::client::WechatMinapp;
16//! use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
17//!
18//! #[tokio::main]
19//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
20//!     // 初始化客户端
21//!     let app_id = "your_app_id";
22//!     let secret = "your_app_secret";
23//!     let client = WechatMinapp::new(app_id, secret);
24//!     let qr = Qr::new(client);
25//!
26//!     // 构建小程序码参数
27//!     let args = QrCodeArgs::builder()
28//!         .path("pages/index/index")
29//!         .width(300)
30//!         .env_version(MinappEnvVersion::Release)
31//!         .build()?;
32//!
33//!     // 生成小程序码
34//!     let qr_code = qr.qr_code(args).await?;
35//!     
36//!     // 获取小程序码图片数据
37//!     let buffer = qr_code.buffer();
38//!     println!("生成的小程序码大小: {} bytes", buffer.len());
39//!
40//!     // 可以将 buffer 保存为文件或直接返回给前端
41//!     // std::fs::write("qrcode.png", buffer)?;
42//!     
43//!     Ok(())
44//! }
45//! ```
46//!
47//! # 参数说明
48//!
49//! - `path`: 小程序页面路径,必填,最大长度 1024 字符
50//! - `width`: 小程序码宽度,单位 px,最小 280px,最大 1280px
51//! - `auto_color`: 是否自动配置线条颜色
52//! - `line_color`: 自定义线条颜色,RGB 格式
53//! - `is_hyaline`: 是否透明背景
54//! - `env_version`: 环境版本,默认为正式版
55//!
56//! # 注意事项
57//!
58//! - 生成的小程序码永不过期,数量不限
59//! - 接口只能生成已发布的小程序的小程序码
60//! - 支持带参数路径,如 `pages/index/index?param=value`
61//! - 小程序码大小限制为 128KB,请合理设置 width 参数
62//!
63//! # 示例
64//!
65//! ## 生成带颜色的小程序码
66//!
67//! ```no_run
68//! use wechat_minapp::client::WechatMinapp;
69//! use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
70//!
71//! #[tokio::main]
72//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
73//!     // 初始化客户端
74//!     let app_id = "your_app_id";
75//!     let secret = "your_app_secret";
76//!     let client = WechatMinapp::new(app_id, secret);
77//!     let qr = Qr::new(client);
78//!
79//!     let args = QrCodeArgs::builder()
80//!     .path("pages/detail/detail?id=123")
81//!     .width(400)
82//!     .line_color(Rgb::new(255, 0, 0)) // 红色线条
83//!     .with_is_hyaline() // 透明背景
84//!     .env_version(MinappEnvVersion::Develop)
85//!     .build()
86//!     .unwrap();
87//!     // 生成小程序码
88//!     let qr_code = qr.qr_code(args).await?;
89//!     
90//!     // 获取小程序码图片数据
91//!     let buffer = qr_code.buffer();
92//!     Ok(())
93//! }
94//! ```
95//!
96//! ## 生成简单小程序码
97//!
98//! ```no_run
99//! use wechat_minapp::client::WechatMinapp;
100//! use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
101//!
102//! #[tokio::main]
103//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
104//!     // 初始化客户端
105//!     let app_id = "your_app_id";
106//!     let secret = "your_app_secret";
107//!     let client = WechatMinapp::new(app_id, secret);
108//!     let qr = Qr::new(client);
109//!
110//!     let args = QrCodeArgs::builder()
111//!     .path("pages/index/index")
112//!     .build()
113//!     .unwrap();
114//!     // 生成小程序码
115//!     let qr_code = qr.qr_code(args).await?;
116//!     
117//!     // 获取小程序码图片数据
118//!     let buffer = qr_code.buffer();
119//!     Ok(())
120//! }
121//! ```
122//!
123//! # 错误处理
124//!
125//! 小程序码生成可能遇到以下错误:
126//!
127//! - 参数验证错误(路径为空或过长)
128//! - 认证错误(access_token 无效)
129//! - 网络错误
130//! - 微信 API 返回错误
131//!
132//! 建议在生产环境中妥善处理这些错误。
133
134use super::Qr;
135use crate::{
136    Result, constants,
137    error::Error::{self, InternalServer},
138    new_type::PagePath,
139    utils::build_request,
140};
141use http::Method;
142use serde::{Deserialize, Serialize};
143use tracing::debug;
144
145/// 二维码图片数据
146///
147/// 包含生成的二维码图片的二进制数据,通常是 PNG 格式。
148///
149/// # 示例
150///
151/// ```no_run
152/// use wechat_minapp::client::WechatMinappSDK;
153/// use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
154///
155/// #[tokio::main]
156/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
157///     // 初始化客户端
158///     let app_id = "your_app_id";
159///     let secret = "your_app_secret";
160///     let client = WechatMinappSDK::new(app_id, secret);
161///     let qr = Qr::new(client);
162///
163///     let args = QrCodeArgs::builder()
164///     .path("pages/index/index")
165///     .build()
166///     .unwrap();
167///     // 生成小程序码
168///     let qr_code = qr.qr_code(args).await?;
169///     
170///     // 获取小程序码图片数据
171///     let buffer = qr_code.buffer();
172///     Ok(())
173/// }
174/// ```
175#[derive(Debug, Serialize, Deserialize, Clone)]
176pub struct QrCode {
177    pub buffer: Vec<u8>,
178}
179
180impl QrCode {
181    /// 获取二维码图片的二进制数据
182    ///
183    /// 返回的字节向量通常是 PNG 格式的图片数据,可以直接写入文件或返回给 HTTP 响应。
184    ///
185    /// # 返回
186    ///
187    /// 二维码图片的二进制数据引用
188    pub fn buffer(&self) -> &Vec<u8> {
189        &self.buffer
190    }
191}
192
193/// 二维码生成参数
194///
195/// 用于配置二维码的生成选项,通过 [`QrCodeArgs::builder()`] 方法创建。
196#[derive(Debug, Deserialize, Serialize)]
197pub struct QrCodeArgs {
198    path: String,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    width: Option<i16>,
201    #[serde(skip_serializing_if = "Option::is_none")]
202    auto_color: Option<bool>,
203    #[serde(skip_serializing_if = "Option::is_none")]
204    line_color: Option<Rgb>,
205    #[serde(skip_serializing_if = "Option::is_none")]
206    is_hyaline: Option<bool>,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    env_version: Option<MinappEnvVersion>,
209}
210
211/// 二维码参数构建器
212///
213/// 提供链式调用的方式构建二维码参数,确保参数的正确性。
214///
215/// # 示例
216///
217/// ```
218/// use wechat_minapp::qr::{QrCodeArgs, Rgb, MinappEnvVersion};
219///
220/// let args = QrCodeArgs::builder()
221///     .path("pages/index/index")
222///     .width(300)
223///     .with_auto_color()
224///     .line_color(Rgb::new(255, 0, 0))
225///     .with_is_hyaline()
226///     .env_version(MinappEnvVersion::Release)
227///     .build()
228///     .unwrap();
229/// ```
230#[derive(Debug, Deserialize)]
231pub struct QrCodeArgBuilder {
232    path: Option<String>,
233    width: Option<i16>,
234    auto_color: Option<bool>,
235    line_color: Option<Rgb>,
236    is_hyaline: Option<bool>,
237    env_version: Option<MinappEnvVersion>,
238}
239
240// RGB 颜色值
241///
242/// 用于自定义二维码线条颜色。
243///
244/// # 示例
245///
246/// ```
247/// use wechat_minapp::qr::Rgb;
248///
249/// let red = Rgb::new(255, 0, 0);      // 红色
250/// let green = Rgb::new(0, 255, 0);    // 绿色
251/// let blue = Rgb::new(0, 0, 255);     // 蓝色
252/// let black = Rgb::new(0, 0, 0);      // 黑色
253/// ```
254#[derive(Debug, Deserialize, Clone, Serialize)]
255pub struct Rgb {
256    r: i16,
257    g: i16,
258    b: i16,
259}
260
261impl Rgb {
262    /// 创建新的 RGB 颜色
263    ///
264    /// # 参数
265    ///
266    /// - `r`: 红色分量 (0-255)
267    /// - `g`: 绿色分量 (0-255)
268    /// - `b`: 蓝色分量 (0-255)
269    ///
270    /// # 返回
271    ///
272    /// 新的 Rgb 实例
273    pub fn new(r: i16, g: i16, b: i16) -> Self {
274        Rgb { r, g, b }
275    }
276}
277
278impl QrCodeArgs {
279    pub fn builder() -> QrCodeArgBuilder {
280        QrCodeArgBuilder::new()
281    }
282
283    pub fn path(&self) -> String {
284        self.path.clone()
285    }
286
287    pub fn width(&self) -> Option<i16> {
288        self.width
289    }
290
291    pub fn auto_color(&self) -> Option<bool> {
292        self.auto_color
293    }
294
295    pub fn line_color(&self) -> Option<Rgb> {
296        self.line_color.clone()
297    }
298
299    pub fn is_hyaline(&self) -> Option<bool> {
300        self.is_hyaline
301    }
302
303    pub fn env_version(&self) -> Option<MinappEnvVersion> {
304        self.env_version.clone()
305    }
306}
307
308impl Default for QrCodeArgBuilder {
309    fn default() -> Self {
310        Self::new()
311    }
312}
313
314/// 小程序环境版本
315///
316/// 指定二维码生成的环境版本,不同环境版本对应不同的小程序实例。
317#[derive(Debug, Clone, Serialize, Deserialize)]
318#[serde(rename_all = "lowercase")]
319pub enum MinappEnvVersion {
320    /// 开发版,用于开发环境
321    Release,
322    /// 体验版,用于测试环境
323    Trial,
324    /// 正式版,用于生产环境
325    Develop,
326}
327
328impl From<MinappEnvVersion> for String {
329    fn from(value: MinappEnvVersion) -> Self {
330        match value {
331            MinappEnvVersion::Develop => "develop".to_string(),
332            MinappEnvVersion::Release => "release".to_string(),
333            MinappEnvVersion::Trial => "trial".to_string(),
334        }
335    }
336}
337
338impl QrCodeArgBuilder {
339    pub fn new() -> Self {
340        QrCodeArgBuilder {
341            path: None,
342            width: None,
343            auto_color: None,
344            line_color: None,
345            is_hyaline: None,
346            env_version: None,
347        }
348    }
349
350    pub fn path(mut self, path: impl Into<String>) -> Self {
351        self.path = Some(path.into());
352        self
353    }
354
355    pub fn width(mut self, width: i16) -> Self {
356        self.width = Some(width);
357        self
358    }
359
360    pub fn with_auto_color(mut self) -> Self {
361        self.auto_color = Some(true);
362        self
363    }
364
365    pub fn line_color(mut self, color: Rgb) -> Self {
366        self.line_color = Some(color);
367        self
368    }
369
370    pub fn with_is_hyaline(mut self) -> Self {
371        self.is_hyaline = Some(true);
372        self
373    }
374
375    pub fn env_version(mut self, version: MinappEnvVersion) -> Self {
376        self.env_version = Some(version);
377        self
378    }
379
380    pub fn build(self) -> Result<QrCodeArgs> {
381        let path = self.path.map_or_else(
382            || {
383                Err(Error::InvalidParameter(
384                    "小程序页面路径不能为空".to_string(),
385                ))
386            },
387            |v| {
388                let valid_path = PagePath::try_from(v)?;
389                Ok(valid_path.to_string())
390            },
391        )?;
392
393        if self.auto_color.is_some() && self.line_color.is_some() {
394            return Err(Error::InvalidParameter(
395                "auto_color 为 true 时,line_color 不能设置".to_string(),
396            ));
397        }
398
399        Ok(QrCodeArgs {
400            path,
401            width: self.width,
402            auto_color: self.auto_color,
403            line_color: self.line_color,
404            is_hyaline: self.is_hyaline,
405            env_version: self.env_version,
406        })
407    }
408}
409
410impl Qr {
411    /// 生成小程序二维码
412    ///
413    /// 调用微信小程序二维码生成接口,返回包含二维码图片数据的 [`QrCode`] 对象。
414    ///
415    /// # 参数
416    ///
417    /// - `args`: 二维码生成参数
418    ///
419    /// # 返回
420    ///
421    /// 成功返回 `Ok(QrCode)`,失败返回错误信息。
422    ///
423    /// # 示例
424    ///
425    /// ```no_run
426    /// use wechat_minapp::client::WechatMinappSDK;
427    /// use wechat_minapp::qr::{QrCodeArgs,Qr, MinappEnvVersion};
428    ///
429    /// #[tokio::main]
430    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
431    ///     // 初始化客户端
432    ///     let app_id = "your_app_id";
433    ///     let secret = "your_app_secret";
434    ///     let client = WechatMinappSDK::new(app_id, secret);
435    ///     let qr = Qr::new(client);
436    ///
437    ///     // 构建小程序码参数
438    ///     let args = QrCodeArgs::builder()
439    ///         .path("pages/index/index")
440    ///         .width(300)
441    ///         .env_version(MinappEnvVersion::Release)
442    ///         .build()?;
443    ///
444    ///     // 生成小程序码
445    ///     let qr_code = qr.qr_code(args).await?;
446    ///     
447    ///     // 获取小程序码图片数据
448    ///     let buffer = qr_code.buffer();
449    ///     println!("生成的小程序码大小: {} bytes", buffer.len());
450    ///
451    ///     // 可以将 buffer 保存为文件或直接返回给前端
452    ///     // std::fs::write("qrcode.png", buffer)?;
453    ///     
454    ///     Ok(())
455    /// }
456    /// ```
457    ///
458    /// # 错误
459    ///
460    /// - 网络错误
461    /// - 认证错误(access_token 无效)
462    /// - 微信 API 返回错误
463    /// - 参数序列化错误
464    pub async fn qr_code(&self, args: QrCodeArgs) -> Result<QrCode> {
465        debug!("get qr code args {:?}", &args);
466
467        let query = serde_json::json!({
468            "access_token":self.client.token().await?
469        });
470
471        let body = serde_json::to_value(QrCodeArgs {
472            path: args.path,
473            width: args.width,
474            auto_color: args.auto_color,
475            line_color: args.line_color,
476            is_hyaline: args.is_hyaline,
477            env_version: args.env_version,
478        })?;
479
480        let request = build_request(
481            constants::QR_CODE_ENDPOINT,
482            Method::POST,
483            None,
484            Some(query),
485            Some(body),
486        )?;
487
488        let client = &self.client.client;
489
490        let response = client.execute(request).await?;
491
492        debug!("response: {:#?}", response);
493
494        if response.status().is_success() {
495            Ok(QrCode {
496                buffer: response.into_body(),
497            })
498        } else {
499            let (_parts, body) = response.into_parts();
500            let message = String::from_utf8_lossy(&body).to_string();
501            Err(InternalServer(message))
502        }
503    }
504}