pub struct User {
pub client: WechatMinappSDK,
}Fields§
§client: WechatMinappSDKImplementations§
Source§impl User
impl User
Sourcepub async fn login(&self, code: &str) -> Result<Credential>
pub async fn login(&self, code: &str) -> Result<Credential>
用户登录凭证校验
通过微信前端获取的临时登录凭证 code,换取用户的唯一标识 OpenID 和会话密钥。
§参数
code: 微信前端通过wx.login()获取的临时登录凭证
§返回
成功返回 Ok(Credential),包含用户身份信息
§错误
- 网络错误
- 微信 API 返回错误
- 响应解析错误
§示例
use wechat_minapp::client::WechatMinappSDK;
use wechat_minapp::user::{User, Contact};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = WechatMinappSDK::new("app_id", "secret");
let user = User::new(client);
let code = "0816abc123def456";
let credential = user.login(code).await?;
println!("用户OpenID: {}", credential.open_id());
println!("会话密钥: {}", credential.session_key());
Ok(())
}§API 文档
Sourcepub async fn get_contact(
&self,
code: &str,
open_id: Option<&str>,
) -> Result<Contact>
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::WechatMinappSDK;
use wechat_minapp::user::{User, Contact};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = WechatMinappSDK::new("app_id", "secret");
let user = User::new(client);
let code = "0816abc123def456";
let contact = user.get_contact(code, None).await?;
println!("用户手机号: {}", contact.phone_number());
Ok(())
}§前端配合
前端需要调用 wx.getPhoneNumber 获取临时凭证:
wx.getPhoneNumber({
success: (res) => {
console.log(res.code); // 将这个 code 发送到后端
},
fail: (err) => {
console.error(err);
}
});§API 文档
Auto Trait Implementations§
impl Freeze for User
impl !RefUnwindSafe for User
impl Send for User
impl Sync for User
impl Unpin for User
impl UnsafeUnpin for User
impl !UnwindSafe for User
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more