Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

提供与微信小程序后端 API 交互的核心功能,包括用户登录、访问令牌管理等。

§功能特性

  • 用户登录凭证校验
  • 访问令牌自动管理(支持普通令牌和稳定版令牌)
  • 线程安全的令牌刷新机制
  • 内置 HTTP 客户端

§快速开始

use wechat_minapp::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化客户端
    let app_id = "your_app_id";
    let secret = "your_app_secret";
    let client = Client::new(app_id, secret);

    // 用户登录
    let code = "user_login_code_from_frontend";
    let credential = client.login(code).await?;
    println!("用户OpenID: {}", credential.openid());

    // 获取访问令牌
    let access_token = client.access_token().await?;
    println!("访问令牌: {}", access_token);

    Ok(())
}

§令牌管理

客户端自动管理访问令牌的生命周期:

  • 令牌过期前自动刷新
  • 多线程环境下的安全并发访问
  • 避免重复刷新(令牌锁机制)
  • 支持强制刷新选项

§线程安全

Client 实现了 SendSync,可以在多线程环境中安全使用。

Implementations§

Source§

impl Client

Source

pub fn new(app_id: &str, secret: &str) -> Self

创建新的微信小程序客户端

§参数
  • app_id: 小程序 AppID
  • secret: 小程序 AppSecret
§返回

新的 Client 实例

§示例
use wechat_minapp::Client;

let client = Client::new("wx1234567890abcdef", "your_app_secret_here");
Source

pub async fn login(&self, code: &str) -> Result<Credential>

用户登录凭证校验

通过微信前端获取的临时登录凭证 code,换取用户的唯一标识 OpenID 和会话密钥。

§参数
  • code: 微信前端通过 wx.login() 获取的临时登录凭证
§返回

成功返回 Ok(Credential),包含用户身份信息

§错误
  • 网络错误
  • 微信 API 返回错误
  • 响应解析错误
§示例
use wechat_minapp::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("app_id", "secret");
    let code = "0816abc123def456";
    let credential = client.login(code).await?;

    println!("用户OpenID: {}", credential.openid());
    println!("会话密钥: {}", credential.session_key());
     
    Ok(())
}
§API 文档

微信官方文档 - code2Session

Source

pub async fn access_token(&self) -> Result<String>

获取访问令牌

获取用于调用微信小程序接口的访问令牌。如果当前令牌已过期或即将过期,会自动刷新。

§返回

成功返回 Ok(String),包含有效的访问令牌

§错误
  • 网络错误
  • 微信 API 返回错误
  • 令牌刷新失败
§示例
use wechat_minapp::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("app_id", "secret");
    let access_token = client.access_token().await?;
     
    println!("访问令牌: {}", access_token);
    Ok(())
}
§注意
  • 令牌有效期为 2 小时
  • 客户端会自动管理令牌刷新,无需手动处理
  • 多线程环境下安全
Source

pub async fn stable_access_token( &self, force_refresh: impl Into<Option<bool>> + Clone + Send, ) -> Result<String>

获取稳定版访问令牌

获取稳定版的访问令牌,相比普通令牌有更长的有效期和更好的稳定性。

§参数
  • force_refresh: 是否强制刷新令牌
    • Some(true): 强制从微信服务器获取最新令牌
    • Some(false)None: 仅在令牌过期时刷新
§返回

成功返回 Ok(String),包含有效的稳定版访问令牌

§错误
  • 网络错误
  • 微信 API 返回错误
  • 令牌刷新失败
§示例
use wechat_minapp::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("app_id", "secret");
     
    // 仅在过期时刷新
    let token1 = client.stable_access_token(None).await?;
     
    // 强制刷新
    let token2 = client.stable_access_token(true).await?;
     
    Ok(())
}
§注意
  • 稳定版令牌有效期更长,推荐在生产环境使用
  • 强制刷新会忽略本地缓存,直接请求新令牌
Source§

impl Client

Source

pub async fn check_session_key( &self, session_key: &str, open_id: &str, ) -> Result<()>

检查登录态是否过期 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/checkSessionKey.html

Source

pub async fn reset_session_key( &self, session_key: &str, open_id: &str, ) -> Result<Credential>

重置用户的 session_key https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/ResetUserSessionKey.html

Source§

impl Client

Source

pub async fn qr_code(&self, args: QrCodeArgs) -> Result<QrCode>

生成小程序二维码

调用微信小程序二维码生成接口,返回包含二维码图片数据的 QrCode 对象。

§参数
  • args: 二维码生成参数
§返回

成功返回 Ok(QrCode),失败返回错误信息。

§示例
use wechat_minapp::{Client, QrCodeArgs};

let client = Client::new("app_id", "secret");
let args = QrCodeArgs::builder()
    .path("pages/index/index")
    .width(300)
    .build()?;
     
let qr_code = client.qr_code(args).await?;
println!("二维码生成成功,大小: {} bytes", qr_code.buffer().len());
§错误
  • 网络错误
  • 认证错误(access_token 无效)
  • 微信 API 返回错误
  • 参数序列化错误
Source§

impl Client

Source

pub async fn msg_sec_check(&self, args: &Args) -> Result<MsgSecCheckResult>

内容安全检测

§示例
use wechat_minapp::minapp_security::{Args, Scene};
use wechant_minapp::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app_id = "your app id";
    let secret = "your app secret";
     
    let client = Client::new(app_id, secret);
    let args = Args::builder()
        .content("需要检测的文本内容")
        .scene(Scene::Comment)
        .openid("user_openid")
        .build()?;
     
    let result = client.msg_sec_check(args).await?;
     
    if result.is_pass() {
        println!("内容安全,可以发布");
    } else if result.needs_review() {
        println!("内容需要人工审核");
    } else {
        println!("内容有风险,建议修改");
    }
     
    Ok(())
}
Source§

impl Client

Source

pub async fn get_contact( &self, code: &str, open_id: Option<&str>, ) -> Result<Contact>

获取用户手机号信息

通过前端获取的临时凭证 code 换取用户的手机号信息。

§参数
  • code: 前端通过 wx.getPhoneNumber 获取的临时凭证
  • open_id: 用户 OpenID(可选),如果提供可以提升安全性
§返回

成功返回 Ok(Contact),包含用户手机号信息

§错误
  • 网络错误
  • 微信 API 返回错误
  • 访问令牌无效或过期
§示例
use wechat_minapp::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("app_id", "secret");
     
    // 不提供 OpenID
    let contact1 = client.get_contact("phone_code_1", None).await?;
    println!("手机号: {}", contact1.phone_number());
     
    // 提供 OpenID 提升安全性
    let contact2 = client.get_contact("phone_code_2", Some("user_openid")).await?;
    println!("纯手机号: {}", contact2.pure_phone_number());
     
    Ok(())
}
§前端配合

前端需要调用 wx.getPhoneNumber 获取临时凭证:

wx.getPhoneNumber({
  success: (res) => {
    console.log(res.code); // 将这个 code 发送到后端
  },
  fail: (err) => {
    console.error(err);
  }
});
§API 文档

获取手机号

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,