1.创建login.js文件(也可以将该文件用作混入文件,使用更加方便)
主要用于存放登录所需要的方法
**getUserProfile 获取用户头像昵称获取规则已调整,参考小程序用户头像昵称获取规则调整公告
2.获取用户信息,头像名称等
//事件名,通过点击事件执行该方法
getUserProfile() {
uni.getUserProfile({
desc: '展示用户信息',
success: res => {
console.log(res);
//见下方微信登录方法
this.userLogin(res.userInfo);
},
fail: err => {
// err
this.tui.toast('获取用户信息失败')
}
});
},
3.微信登录
userLogin(userInfo) {
uni.login({
provider: 'weixin',
success: res => {
console.log(res);
uni.setStorageSync('nickname', userInfo.nickName);
uni.setStorageSync('avatar', userInfo.avatarUrl);
this.nickName = userInfo.nickName
this.avatar = userInfo.avatarUrl
//此处为后台接口提供的验证是否为新用户
this.api.judgeAccount({
code: res.code
}).then(res => {
console.log(res);
//老用户直接登录成功进入首页
if (res.data.data.isTrue == 2){
uni.setStorageSync("userId", res.data.data.cdDriverUser.driverUserId)
uni.switchTab({
url: "/pages/index/index"
})
uni.showToast({
title: '登录成功',
duration: 2000
});
// 新用户提供绑定微信,并执行后续的手机号注册业务逻辑
} else if (res.data.data.isTrue == 1) {
uni.login({
provider: 'weixin',
success: ress => {
console.log(ress);
uni.setStorageSync('code', ress.code);
this.tui.toast('绑定成功!');
setTimeout(() => {
//执行手机号注册方法
}, 1500)
}
})
}
})
}
});
},
4.手机号注册登录(部分项目场景可能不需要,直接微信登录即可)
//此处方法通过uniapp提供的html写法
//<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="login">去绑定</button>
getPhoneNumber(e) {
console.log(e);
if (e.detail.errMsg == "getPhoneNumber:ok") {
const params = {
code: uni.getStorageSync('code'),
};
const paramss = {
encryptedData: e.detail.encryptedData,
iv: e.detail.iv,
}
//后台接口提供的获取手机号码,此时手机号是加密状态
this.api.initWxLogin(params).then(res => {
console.log("key", res);
//后台接口提供通过获取的手机号码key值解析为正常的手机号
this.api.decodeUserInfo({
...paramss,
sessionKey: res.data.msg
}).then(resd => {
uni.setStorageSync("phone", resd.data.data)
uni.login({
provider: 'weixin',
success: res => {
uni.request({
//后台提供注册接口
url: this.api.baseUrl +
'/commodity/driverUser/registerWechatAccount/'+res.code,
//请求参数后端定义的,各有不同,仅供参考
data: {
nickName: uni.getStorageSync('nickname'),
avatar: uni.getStorageSync('avatar'),
phone: uni.getStorageSync("phone"),
linkId: uni.getStorageSync("senceStoreId"),
invitationUserId: uni.getStorageSync('shareUserId')
},
method: 'POST',
//注册成功并自动登录
success: res1 => {
//这里可以把获取到的关键数据进行本地存储等
uni.switchTab({
url: "/pages/index/index"
})
uni.showToast({
title: '登录成功',
duration: 2000
});
}
});
}
});
}).catch(err => {
console.log(err);
if (err.data.msg == "session_key:失败") {
this.tui.toast("绑定状态已过期,请重新绑定微信")
uni.clearStorageSync();
}
})
});
} else {
this.tui.toast('已拒绝登录')
}
},
*该登录逻辑可能根据不同场景逻辑代码有所不同,仅供参考