1.創(chuàng)建login.js文件(也可以將該文件用作混入文件,使用更加方便)
主要用于存放登錄所需要的方法
**getUserProfile 獲取用戶頭像昵稱獲取規(guī)則已調(diào)整,參考小程序用戶頭像昵稱獲取規(guī)則調(diào)整公告
2.獲取用戶信息,頭像名稱等
//事件名,通過(guò)點(diǎn)擊事件執(zhí)行該方法
getUserProfile() {
uni.getUserProfile({
desc: '展示用戶信息',
success: res => {
console.log(res);
//見(jiàn)下方微信登錄方法
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
//此處為后臺(tái)接口提供的驗(yàn)證是否為新用戶
this.api.judgeAccount({
code: res.code
}).then(res => {
console.log(res);
//老用戶直接登錄成功進(jìn)入首頁(yè)
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
});
// 新用戶提供綁定微信,并執(zhí)行后續(xù)的手機(jī)號(hào)注冊(cè)業(yè)務(wù)邏輯
} 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(() => {
//執(zhí)行手機(jī)號(hào)注冊(cè)方法
}, 1500)
}
})
}
})
}
});
},
4.手機(jī)號(hào)注冊(cè)登錄(部分項(xiàng)目場(chǎng)景可能不需要,直接微信登錄即可)
//此處方法通過(guò)uniapp提供的html寫(xiě)法
//<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,
}
//后臺(tái)接口提供的獲取手機(jī)號(hào)碼,此時(shí)手機(jī)號(hào)是加密狀態(tài)
this.api.initWxLogin(params).then(res => {
console.log("key", res);
//后臺(tái)接口提供通過(guò)獲取的手機(jī)號(hào)碼key值解析為正常的手機(jī)號(hào)
this.api.decodeUserInfo({
...paramss,
sessionKey: res.data.msg
}).then(resd => {
uni.setStorageSync("phone", resd.data.data)
uni.login({
provider: 'weixin',
success: res => {
uni.request({
//后臺(tái)提供注冊(cè)接口
url: this.api.baseUrl +
'/commodity/driverUser/registerWechatAccount/'+res.code,
//請(qǐng)求參數(shù)后端定義的,各有不同,僅供參考
data: {
nickName: uni.getStorageSync('nickname'),
avatar: uni.getStorageSync('avatar'),
phone: uni.getStorageSync("phone"),
linkId: uni.getStorageSync("senceStoreId"),
invitationUserId: uni.getStorageSync('shareUserId')
},
method: 'POST',
//注冊(cè)成功并自動(dòng)登錄
success: res1 => {
//這里可以把獲取到的關(guān)鍵數(shù)據(jù)進(jìn)行本地存儲(chǔ)等
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("綁定狀態(tài)已過(guò)期,請(qǐng)重新綁定微信")
uni.clearStorageSync();
}
})
});
} else {
this.tui.toast('已拒絕登錄')
}
},
*該登錄邏輯可能根據(jù)不同場(chǎng)景邏輯代碼有所不同,僅供參考