uniapp实现微信小程序的登录流程(包括微信授权和手机号授权)
2020-02-18 本文已影响0人
欢欢小天使K
怎么使用uniapp实现微信小程序的微信授权和手机号授权呢?
效果如下:
屏幕快照 2020-02-18 下午4.43.53.png
首先配置微信小程序的AppID,如果不配置AppID,就会在uni.login()的返回结果中获得mock值。
打开根目录下的manifest.json > 微信小程序配置 > 填写微信小程序AppID
login/login.js代码 :
import AppConfig from '../../config.js'
import api from '@/common/vmeitime-http/'
const WxAuth = require('@/common/WxAuth');
export default {
data() {
return {
process: {
step: 1, //1:需要微信授权;2:需要手机号授权
user: 0, //微信 0:未授权;1:已授权
phone: 0 //手机号 0:未授权;1:已授权
},
}
},
onLoad() {
// #ifdef MP-WEIXIN
WxAuth.onLogin();
// #endif
},
methods: {
/**
* 微信授权 uni.getUserInfo
*/
handleGetUserInfo(e) {
let {
errMsg,
iv,
encryptedData
} = e.detail;
let frUserId = uni.getStorageSync('fr_user_id') || '', // 从哪个用户分享过来的
taskId = uni.getStorageSync('task_id') || 1,
inviteType = uni.getStorageSync('invite_type') || ''; // 邀请的用户类型
if (errMsg == 'getUserInfo:ok') { // 同意授权
uni.hideLoading()
// 检查登录态是否过期。
WxAuth.checkSession().then(code => {
//code, iv, encryptedData 传给服务器解析,得到用户信息
let data = {
code,
iv,
encryptedData,
frUserId,
taskId,
inviteType: inviteType,
loginType: 'WXMA'
}
return api.login(data)
}).then(result => {
//result: userInfo、token
if (result.data.statusCode == 200) {
if (result.data.code == 200) {
//临时登录凭证 code 只能使用一次,故刷新code;
WxAuth.onLogin();
//更新用户信息
let token = result.data.data.token;
let userInfo = result.data.data;
let memberDays = userInfo.user.memberDays;
let is_vip = memberDays ? (new Date(memberDays.replace(/-/g, "\/")) - new Date() > 0 ? true : false) : false;
let userInfoNew = { ...userInfo.user,
is_vip
};
uni.setStorageSync('token', token);
uni.setStorageSync('userInfo', userInfoNew);
uni.showToast({
title: '授权成功!'
});
if (userInfo.user.mobile) {
this.process.user = 1;
this.process.step = 1;
uni.hideLoading()
setTimeout(function() {
uni.navigateBack({
delta: 1
});
}, 1000);
} else {
this.process.user = 1;
this.process.step = 2;
uni.hideLoading()
}
} else {
console.log("获取用户信息: 老用户")
}
} else {
console.log("获取用户信息失败")
}
}).catch(console.log)
} else {
// 拒绝授权
uni.showToast({
title: '授权失败!',
icon: 'none'
});
}
},
/**
* 手机号授权
* @param {*} e
*/
getPhoneNumber(e) {
let {
errMsg,
iv,
encryptedData
} = e.detail;
let token = uni.getStorageSync('token') || '';
if (errMsg == "getPhoneNumber:ok") { // 同意授权
uni.hideLoading()
// 检查登录态是否过期。
WxAuth.checkSession().then(code => {
//code, iv, encryptedData 传给服务器解析,得到手机号信息
const data = {
code,
iv,
encryptedData
};
// token
api.wxmobile(data)
.then(res => {
uni.showToast({
title: '授权成功!'
});
this.process.phone = 1;
uni.hideLoading();
setTimeout(function() {
uni.navigateBack({
delta: 1 //上一级页面
});
}, 1000);
}).catch(err => {
console.log(err)
});
}).catch(console.log)
} else {
// 拒绝手机号授权
uni.showToast({
title: '手机号授权失败!',
icon: 'none'
});
}
},
// 暂不登录
handNotLogin() {
uni.navigateBack();
}
}
}
@/common/WxAuth代码 :
/**
* 检查登录态是否过期
*/
function checkSession() {
return new Promise((resolve, reject) => {
wx.checkSession({
success(res) {
//session_key 未过期,并且在本生命周期一直有效
let code = uni.getStorageSync('code') || '';
// TODO:code==‘’
resolve(code);
},
fail: async (err) => {
// session_key 已经失效,需要重新执行登录流程
let code = await onLogin();
reject(code);
}
})
})
}
/**
* 调用接口获取登录凭证(code)
*/
function onLogin() {
return new Promise((resolve, reject) => {
uni.login({
provider: 'weixin',
success: function(res) {
if (res.errMsg == "login:ok") {
uni.setStorageSync('code', res.code);
resolve(res.code);
} else {
reject(res);
}
},
fail: function(err) {
reject(res);
}
});
})
}
module.exports = {
checkSession,
onLogin
};