結合上文全局登錄校驗,實現微信受權登陸
官方手冊地址: https://uniapp.dcloud.io/api/plugins/login?id=getuserinfohtml
<script>
var loginRes;
export default {
onLoad:function(){
loginRes = this.checkLogin('../my/my', '2');
if(!loginRes){
return;
}
}
}
</script>
若是登錄過,則不發生跳轉,直接 return;,不然跳轉至 login.vue 並攜帶兩個參數(登錄成功後的跳轉界面、跳轉方式),完成登錄操做。vue
<script>
var _self;
export default {
data() {
return {
backpage:'',
backtype:''
};
},
onLoad:function(options){
_self = this;
// #ifdef APP-PLUS
uni.login({
success: (res) => {
// console.log(JSON.stringify(res))
// 第三方登錄
// res 對象格式
//{"code":"***",
//"authResult":{
//"openid":"***",
//"scope":"snsapi_userinfo",
//"refresh_token":"**",
//"code":"****",
//"unionid":"***",
//"access_token":"***",
//"expires_in":7200
//},
//"errMsg":"login:ok"}
uni.getUserInfo({
success: (info) => {
// console.log(JSON.stringify(info))
// info 對象格式
// {"errMsg":"getUserInfo:ok",
// "rawData":"...
// "userInfo":{
//"openId":"***",
//"nickName":"***",
//"gender":1,
// "city":"Xi'an",
// "province":"Shaanxi",
// "country":"China",
// "avatarUrl":"頭像",
// "unionId":"oU5Yyt_agt547zWyA0v0eLfFPqxo"
//},"signature":""}
// 與服務器交互將數據提交到服務端數據庫
uni.request({
url: _self.apiServer+'member&m=login',
method: 'POST',
header: {'content-type' : "application/x-www-form-urlencoded"},
data: {
openid: info.userInfo.openId,
name: info.userInfo.nickName,
face: info.userInfo.avatarUrl,
},
success: res => {
console.log(JSON.stringify(res))
res = res.data;
if(res.status == 'ok'){
uni.showToast({
title: '登錄成功',
mask: false,
duration: 1500
});
uni.setStorageSync('SUID' , res.data.u_id + '');
uni.setStorageSync('SRAND', res.data.u_random + '');
uni.setStorageSync('SNAME', res.data.u_name + '');
uni.setStorageSync('SFACE', res.data.u_face + '');
// 判斷跳轉方式
if(options.backtype == '1'){
uni.redirectTo({url:options.backpage});
}else{
uni.switchTab({url:options.backpage});
}
}else{
uni.showToast({title:res.data});
}
},
fail: () => {
console.log('登錄失敗')
},
complete: () => {}
});
},
fail: () => {
uni.showToast({title:"微信登陸受權失敗"});
}
})
},
fail: () => {
uni.showToast({title:"微信登陸受權失敗"});
}
})
// #endif
console.log(options)
}
}
</script>
主要涉及到2個方法:java
用於觸發第三方登錄,調起微信登錄,登錄成功後返回對象格式以下:數據庫
{
"code":"***",
"authResult":{
"openid":"***",
"scope":"snsapi_userinfo",
"refresh_token":"**",
"code":"****",
"unionid":"***",
"access_token":"***",
"expires_in":7200
},
"errMsg":"login:ok"
}
獲取用戶信息,經過上方的 uni.login 方法會獲得用戶 access_token,故 uni.getUserInfo 在此基礎上獲取用戶的 openid、userInfo(頭像、暱稱) 等信息。api
{
"errMsg":"getUserInfo:ok",
"rawData":"...
"userInfo":{
"openId":"***",
"nickName":"***",
"gender":1,
"city":"Xi'an",
"province":"Shaanxi",
"country":"China",
"avatarUrl":"頭像",
"unionId":"oU5xxxxxxxxxxeLfFPqxo"
},
"signature":""
}
此方法爲 uni-app 中用於網絡請求。詳細見官方手冊:https://uniapp.dcloud.io/api/request/request?id=request服務器
點擊 my.vue 將會觸發 微信登錄受權界面,以下:微信
登錄成功後,向遠程服務器發送一個保存用戶信息的請求網絡