wechat_minapp/user/
credential.rs

1use super::User;
2use super::user_info::{UserBuilder, UserInfo};
3#[allow(deprecated)]
4use aes::{
5    Aes128,
6    cipher::{BlockDecryptMut, KeyIvInit, block_padding::Pkcs7, generic_array::GenericArray},
7};
8use base64::{Engine, engine::general_purpose::STANDARD};
9use cbc::Decryptor;
10use hex::encode;
11use hmac::{Hmac, Mac};
12use http::Method;
13use serde::{Deserialize, Serialize};
14use serde_json::from_slice;
15use sha2::Sha256;
16use tracing::{debug, instrument};
17
18use crate::utils::{RequestBuilder, ResponseExt};
19use crate::{Result, constants};
20
21type Aes128CbcDec = Decryptor<Aes128>;
22
23#[derive(Serialize, Deserialize, Clone)]
24pub struct Credential {
25    open_id: String,
26    session_key: String,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    union_id: Option<String>,
29}
30
31impl Credential {
32    pub fn open_id(&self) -> &str {
33        &self.open_id
34    }
35
36    pub fn session_key(&self) -> &str {
37        &self.session_key
38    }
39
40    pub fn union_id(&self) -> Option<&str> {
41        self.union_id.as_deref()
42    }
43
44    /// 解密用户数据,使用的是 AES-128-CBC 算法,数据采用PKCS#7填充。
45    /// https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
46    /// ```no_run
47    /// use wechat_minapp::client::WechatMinappSDK;
48    /// use wechat_minapp::user::{User, Contact};
49    ///
50    ///  #[tokio::main]
51    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
52    ///     let client = WechatMinappSDK::new("app_id", "secret");
53    ///     let user = User::new(client);
54    ///     let code = "0816abc123def456";
55    ///     let credential = user.login(code).await?;
56    ///     let info = credential.decrypt(&encrypted_data, &iv)?;
57    ///     println!("昵称: {}", info.nickname());
58    ///     println!("性别: {}", info.gender());
59    ///     println!("地区: {}-{}-{}", info.country(), info.province(), info.city());
60    ///     println!("头像: {}", info.avatar());
61    ///     println!("AppID: {}", info.app_id());
62    ///     println!("时间戳: {}", info.timestamp());
63    ///     
64    ///     Ok(())
65    /// }
66    /// ```
67    #[instrument(skip(self, encrypted_data, iv))]
68    pub fn decrypt(&self, encrypted_data: &str, iv: &str) -> Result<UserInfo> {
69        debug!("encrypted_data: {}", encrypted_data);
70        debug!("iv: {}", iv);
71
72        let key = STANDARD.decode(self.session_key.as_bytes())?;
73        let iv = STANDARD.decode(iv.as_bytes())?;
74        #[allow(deprecated)]
75        let decryptor = Aes128CbcDec::new(
76            &GenericArray::clone_from_slice(&key),
77            &GenericArray::clone_from_slice(&iv),
78        );
79
80        let encrypted_data = STANDARD.decode(encrypted_data.as_bytes())?;
81
82        let buffer = decryptor.decrypt_padded_vec_mut::<Pkcs7>(&encrypted_data)?;
83
84        let builder = from_slice::<UserBuilder>(&buffer)?;
85
86        debug!("user builder: {:#?}", builder);
87
88        Ok(builder.build())
89    }
90}
91
92impl std::fmt::Debug for Credential {
93    // 为了安全,不打印 session_key
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("Credential")
96            .field("open_id", &self.open_id)
97            .field("session_key", &"********")
98            .field("union_id", &self.union_id)
99            .finish()
100    }
101}
102
103type HmacSha256 = Hmac<Sha256>;
104
105impl User {
106    /// 检查登录态是否过期
107    /// [官方文档](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/checkSessionKey.html)
108    #[instrument(skip(self, session_key, open_id))]
109    pub async fn check_session_key(&self, session_key: &str, open_id: &str) -> Result<()> {
110        let mut mac = HmacSha256::new_from_slice(session_key.as_bytes())?;
111        mac.update(b"");
112        let hasher = mac.finalize();
113        let signature = encode(hasher.into_bytes());
114
115        let query = serde_json::json!({
116            "openid": open_id.to_string(),
117            "signature":signature,
118            "sig_method": "hmac_sha256".to_string()
119        });
120
121        let request = RequestBuilder::new(constants::CHECK_SESSION_KEY_END_POINT)
122            .query(query)
123            .method(Method::GET)
124            .build()?;
125
126        let client = &self.client.client;
127
128        let response = client.execute(request).await?;
129
130        debug!("response: {:#?}", response);
131        response.to_json::<()>()
132    }
133
134    /// 重置用户的 session_key
135    /// [官方文档](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/ResetUserSessionKey.html)
136    #[instrument(skip(self, open_id))]
137    pub async fn reset_session_key(&self, session_key: &str, open_id: &str) -> Result<Credential> {
138        let mut mac = HmacSha256::new_from_slice(session_key.as_bytes())?;
139        mac.update(b"");
140        let hasher = mac.finalize();
141        let signature = encode(hasher.into_bytes());
142
143        let query = serde_json::json!({
144            "access_token":self.client.token().await?,
145            "openid": open_id.to_string(),
146            "signature":signature,
147            "sig_method": "hmac_sha256".to_string()
148        });
149
150        let request = RequestBuilder::new(constants::RESET_SESSION_KEY_END_POINT)
151            .query(query)
152            .method(Method::GET)
153            .build()?;
154
155        let client = &self.client.client;
156        let response = client.execute(request).await?;
157        debug!("response: {:#?}", &response);
158
159        response.to_json::<Credential>()
160    }
161}