Get authorization
When using in the applet plug-in, you need to call after obtaining user authorization in the user information function page.
Because WeChat officially modified the getUserInfo interface, it is not possible to pop up the authorization window as soon as you enter the WeChat applet. You can only use type= in the button. getUserInfo to trigger. Official connection
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
WXML part
<button class="button" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">
授权登录
</button>
JS part
bindGetUserInfo(e) {
if (e.detail.userInfo == undefined) {
console.log("用户已取消授权");
} else {
console.log("用户授权成功!");
}
}
open-type type
getUserInfo to obtain user information
bindGetUserInfo bind callback function
The click effect is as follows
Login process
js events can be actively triggered by users or can be written into life cycle functions
// 获取用户信息
wx.getUserInfo({
// 成功回调
success: function (res) {
console.log(res.userInfo)
// 直接调用登录接口
wx.login({
// 超时时间设置
timeout:10000,
// 使用async await 代替 .then
success: async (result)=>{
// URL 为登录的接口 功能为 自动注册登录
let {
data} = await request("URL",{
// 是否自动注册
autoReg:true,
// wx.login() 返还的 code
code:result.code,
})
// 全局变量保存token
app.globalData.token = data.data.token
// 跳转至主页或会员页面
wx.switchTab({
url: 'url',
})
},
// 登录失败提示
fail: ()=>{
console.log('请求失败!可再次尝试');
},
});
}
})
Determine whether the user is authorized
// 获取用户授权信息
wx.getSetting({
// 执行成功
success: resData => {
// 用户授权
if (resData.authSetting['scope.userInfo']) {
// 获取用户信息
wx.getUserInfo({
success: res => {
// 登录 更新信息
wx.login({
timeout: 10000,
success: async (result) => {
let {
data
} = await request("user/wxapp/login", {
code: result.code,
})
// 更新 token
this.globalData.token= data.data.token;
},
fail: () => {
},
});
}
})
} else {
console.log("未授权");
// 跳转至授权页
wx.redirectTo({
url: '../../package/pages/authorize/authorize',
})
}
}
})