静默授权获取 OpenID
wx.login()
获取临时 code
(5分钟有效),传给后端。code + AppSecret
请求微信接口,换取 openid
和 session_key
。主动授权获取用户详情(头像、昵称等)
组件。bindgetuserinfo
事件,返回加密数据 encryptedData
和初始向量 iv
。wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userInfo']) {
// 已授权,直接调用 wx.getUserInfo
} else {
// 显示授权按钮
}
}
});
<button wx:if="{{!isAuth}}" open-type="getUserInfo" bindgetuserinfo="onAuth">授权登录button>
// JS
onAuth(e) {
if (e.detail.userInfo) {
// 用户同意授权
const { encryptedData, iv } = e.detail;
// 发送给后端解密
} else {
// 用户拒绝,提示引导重新授权
}
}
关键:用 session_key
解密 encryptedData
!
public String wxDecrypt(String encryptedData, String sessionKey, String iv) {
byte[] encData = Base64.decode(encryptedData);
byte[] ivData = Base64.decode(iv);
byte[] key = Base64.decode(sessionKey);
// AES-128-CBC 解密
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(ivData));
return new String(cipher.doFinal(encData), "UTF-8");
}
避坑:
session_key
可能过期(需重新 wx.login
获取)。session_key
不匹配或 Base64 解码错误!目标:用户信息全局共享,避免重复请求。
// store.js
import { observable, action } from 'mobx-miniprogram';
export const store = observable({
userInfo: {},
setUserInfo: action(function(info) {
this.userInfo = info;
wx.setStorageSync('user', JSON.stringify(info)); // 持久化
}),
// 从缓存初始化
initUser() {
const cache = wx.getStorageSync('user');
if (cache) this.userInfo = JSON.parse(cache);
}
});
使用场景:
用户拒绝授权怎么办?
wx.openSetting()
。UnionID 如何获取?
code
换 session_key
时,微信自动返回 unionid
(无需用户授权)!为何不推荐首页强制授权?
openid
建立用户体系。BadPaddingException
)。代码全开源:[Github 链接] | 更多实战案例点我主页
#微信小程序 #用户授权 #前端开发 #实战教程