用户未授权过的情况下调用uni.getUesrInfo接口,不会出现授权弹窗
- 进入登录页判断是否已经授权登录过 在onReady生命周期通过api uni.login()在成功回调里获取code后调用后端登录授权接口判断是否已经登录过,登录过则传入code参数返回token,存入本地
onReady() {
// 获取微信code
uni.login({
success: (res) => {
if (res.code) {
// console.log('获取微信code')
apiLogin({
loginType: '3',
code: res.code
}).then(response => {
//判断是否等录如果已登陆,进入index
console.log('判断是否登录', response)
const data = response[1].data
console.log(data.code)
if (data.code === 200) {
// 保存token
uni.setStorageSync('token', data.data)
// 判断跳转页面方法
this.toOtherPage();
}
})
} else {
// 显示登陆页
this.isHide = true
}
}
})
},
methods:{
// 判断跳转页面方法
toOtherPage(){
if(this.enterpriseId){
// 被邀请进来完成企业认证的,跳转到企业认证页
uni.redirectTo({
url:'/pages/enterprise/enterprise?enterpriseId='+this.enterpriseId
})
} else if(this.uuid){
//从接受签署页面过来
uni.redirectTo({
url:'/pages/receiveContract/receiveContract?uuid='+this.uuid
})
}else {
this.toIndex();
}
}
}
2. 点击登录按钮 借助button组件绑定获取用户信息的方法,uni.getUserInfo()获取返回值iv和encrytedData,将其和code传参调用后端接口,返回token,存入本地
<button class='login-but' v-if="isTick" open-type="getUserInfo" @getuserinfo="wechatLogin"><text>微信用户快捷登录</text></button>
wechatLogin(res) {
console.log('微信授权登录', res.detail)
if (res.detail.userInfo) {
uni.showToast({
title: '授权成功'
})
} else {
// console.log('微信授权失败')
uni.showToast({
title: '授权失败,请同意授权',
icon: 'none'
})
return
}
let encryptedData = res.detail.encryptedData
let iv = res.detail.iv
// 获取code
uni.login({
success: (res) => {
console.log('获取code', res)
if (res.code) {
let code = res.code
apiLogin({
code: code,
loginType: '0',
encryptedData: encryptedData,
iv: iv
}).then(res => {
console.log('请求登录', res)
const data = res[1]['data'];
if (data.code === 200) {
// 保存token
uni.setStorageSync('token', data.data)
// 判断跳转页面方法
this.toOtherPage();
} else {
console.log('微信授权登录失败')
uni.showToast({
title: '微信授权登录失败',
icon: 'none'
})
return
}
});
} else {
uni.showModal({
title: '未获取到code'
})
return
}
}
})
}