最近在做一个项目兼容app和小程序
这里写一下这里面微信登陆的流程
- 这里有授权获取手机号弹窗 需用户手动点击按钮确认授权才行
<!-- 授权获取手机号弹窗 需用户手动点击按钮确认授权才行-->
<u-modal v-model="showSQ" title=" " :show-confirm-button='false'>
<button
style="background-color:#23C9A5;width: 500rpx;height: 80rpx;color: #FFFFFF;margin: 100rpx auto 150rpx;"
open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">确认授权获取手机号码</button>
</u-modal>
- 微信图标 点击微信图标触发goWX方法
<!-- 微信图标 点击微信图标触发goWX方法-->
<view style="display: flex;justify-content: center;">
<image @click="goWX()" src="../../static/icon_wx.png" mode="aspectFill" style="width: 70rpx;height: 70rpx;margin: 0 auto;"></image>
</view>
1. 点击goWx 判断当前环境是app还是微信
goWX() {
// #ifdef APP-PLUS
this.wx()
// #endif
// #ifndef APP-PLUS
this.authorization()
// #endif
},
2. app授权拿到openid --登陆
// app获取微信授权
wx() {
uni.login({
provider: 'weixin',
success: (loginRes) => {
console.log('loginRes', loginRes)
let openId = loginRes.authResult.openid
this.wxLogin(openId)
}
});
},
3. 小程序 授权 --手机号授权–走后端接口获取openid–登陆
// 小程序授权接口
authorization(){
wx.getUserProfile({
desc:'授权登录',
success:(info)=>{
console.log('获取用户信息成功',info);
uni.login({
provider: 'weixin',
success: (loginRes) => {
this.wxcode = loginRes.code
this.showSQ = true
// wx.getSetting({
// success(res) {
// console.log(res)
// return
// console.log('getPhoneNumbergetPhoneNumber', res.authSetting['scope.getPhoneNumber'])
// if (!res.authSetting['scope.getPhoneNumber']) { //没有授权过手机号
// that.showSQ = true
// } else {
// //授权过手机号直接调用登陆接口
// }
// }
// })
}
});
},fail:(info)=> {
// 获取失败的去引导用户授权
uni.showToast({
icon: 'none',
title: '您需要授权,才能获取您的信息!'
});
}
})
},
getPhoneNumber(e) {
if (e.detail.errMsg == 'getPhoneNumber:ok') {
wx.login({
provider: 'weixin',
success: (loginRes) => {
this.wxcode = loginRes.code
console.log('loginRes',loginRes)
let data = {
code: this.wxcode,
iv: e.detail.iv,
encryptedData: e.detail.encryptedData
}
console.log('a',data)
this.getOpenid(data)
}
})
}
},
// 未注册 uni.login
getOpenid(data) {
this.$u.api.wxxcxRegister(data).then(res => {
console.log('wxxcxRegister',res)
if (res.code == 200) {
console.log('res.result.openid',res.result.openid)
this.wxLogin(res.result.openId)
} else {
this.$u.toast(res.message)
}
})
},
4. 登陆
wxLogin(openId){
this.$u.api.wxCustomerLogin({openId}).then(res => {
console.log(res)
if (res.code == -101) {
this.$u.toast(res.code.message)
setTimeout(() => {
uni.navigateTo({
url: 'binding?openId=' + openId
})
}, 1000)
} else if (res.code == 200) {
this.$u.toast('登录成功!')
uni.setStorageSync('doorToDoor_id', res.result.id)
setTimeout(() => {
uni.switchTab({
url: '../index/index'
})
}, 1500)
} else {
this.$u.toast(res.message)
}
})
},