uniapp微信授权登录 原理自己百度 先看效果,然后直接上代码
效果图
下面是代码:
登录按钮
<button @click="login()" open-type="getUserInfo" style="position: absolute;left:2%;top:79vh;border-radius:50%;width:118rpx;height:118rpx;background:url(https://img.alicdn.com/imgextra/i1/2200876587254/O1CN01qw7YDa23SNgXTgMsF_!!2200876587254.png) no-repeat;background-size:100% 100%;z-index:9999;"></button>
登录方法login
login:function(){
this.token = uni.getStorageSync('token');
if(unils.stringIsEmpty(this.content)){
let that = this;
var p = unils.authLogin();
p.then((loginResult)=>{
if(loginResult['code']){
that.token = loginResult['token'];
that.showUpload = true;
} else {
}
})
}
},
封装方法:
const authLogin = function (){
return new Promise(function(resolve, reject) {
let token = uni.getStorageSync('token');
if(stringIsEmpty(token)){
uni.getUserProfile({//getUserProfile接口只能是用户点击才能调用
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (ress) => {
let userObject = ress.userInfo;
uni.login({
success: (resss) => {
if(resss.errMsg == "login:ok"){
console.log(userObject);
let code = resss.code;
uni.request({
// header: {
// 'content-type': 'application/x-www-form-urlencoded'
// },
url:"你的接口地址",
method: 'POST',//接口类型
data: {
'code':code,
'avatar_url':userObject.avatarUrl,
'city':userObject.city,
'province':userObject.province,
'gender':userObject.gender,
'nick_name':userObject.nickName
}, //接口需要的数据
success: function(ressss) {
console.log(ressss);
if (ressss.data.code == 1) {
uni.setStorageSync('token', ressss.data.data.token);
uni.setStorageSync('uid', ressss.data.data.uid);
uni.setStorageSync('gender', userObject.gender);
uni.setStorageSync('avatar', userObject.avatarUrl);
uni.setStorageSync('nickname', userObject.nickName);
console.log(ressss.data.data.token);
var loginResult = new Array();
loginResult['code'] = true;
loginResult['token'] = ressss.data.data.token;
loginResult['uid'] = ressss.data.data.uid;
loginResult['gender'] = ressss.data.data.gender;
loginResult['avatar'] = ressss.data.data.avatarUrl;
loginResult['nickname'] = ressss.data.data.nickName;
resolve(loginResult);
// that.login(res.data); //将接口返回的数据保存在全局变量中.
//登录成功跳转首页或者你想跳转的地方...
//注意:如果时导航页 请用uni.switchTab
// 其他页面建议使用uni.reLaunch
} else {
uni.showToast({
title: '授权登录失败,请联系管理员!',
mask: true,
icon: 'none'
})
var loginResult = new Array();
loginResult['code'] = false;
resolve(loginResult);
}
}
})
}
}
})
},
fail: (ress) => {
uni.showToast({
title: '为了更好的体验,需要授权登录!',
mask: true,
icon: 'none'
})
var loginResult = new Array();
loginResult['code'] = false;
resolve(loginResult);
}
})
} else {
console.log('客户端判断已经登录');
var loginResult = new Array();
loginResult['code'] = true;
loginResult['token'] = uni.getStorageSync('token');
loginResult['uid'] = uni.getStorageSync('uid');
loginResult['gender'] = uni.getStorageSync('gender');
loginResult['avatar'] = uni.getStorageSync('avatar');
loginResult['nickname'] = uni.getStorageSync('nickName');
resolve(loginResult);
}
}).catch((e) => {
console.log(e)
});
}
点击下载demo