- 首先要明确授权登录的业务流程:微信官方文档中对授权登录已经解释的很清楚了,在这里再简单赘述下吧。
- 业务需求是:小程序在加载时,登录并获取用户信息。如果没有用户信息则跳转到引导或着登录页。
- 业务逻辑是:首先调用
wx.login函数获取code,然后向服务器发送请求,根据拿到的code换取登录凭证openId最后再根据openId查询绑定的用户信息。如果用户已存在则直接获取用户信息,否做跳转至引导页或登录页,获取到用户信息后将信息存到全局数据中便于调用,==> 登录完成。 - 但由于小程序存在分享页面等功能,用户打开不一定都是初始页面。小程序的onLaunch生命周期和页面onLoad生命周期函数是同时运行的,其中的请求也是异步的。可能会存在登录后但获取用户信息未完成,页面已经开始调用用户信息并请求数据,所以,页面要在登录函数中进行验证,如果小程序的加载函数先执行完成,页面就继续执行;如果页面先加载完成,则把请求数据的函数传入到
app.js中。当小程序加载函数完成后再调用。
在app.js中的onLaunch生命周期函数中, 当然页可以写在自定义的login登录页(需要手动登录时),根据个人情况看吧:
onLaunch: function () {
let that = this;
wx.showLoading({
title: "加载中...",
mask: true,
});
wx.login({
success: (res) => {
that.request(
"/sysLogin/loginPage/lodin",
{
jsCode: res.data,
},
(succRes) => {
wx.hideLoading();
if (succRes.statusCode == 200) {
if (succRes.data.code == 200) {
that.globalData.userInfo = succRes.data.payload.data;
that.globalData.id = succRes.data.payload.data.id;
that.globalData.openId = succRes.data.payload.openId;
let pages = getCurrentPages();
let currentPages = pages[pages.length - 1];
let url = currentPages.route;
if (url == "pages/guidance/guidance") {
wx.showToast({
icon: "none",
mask: true,
title: "登录成功, 请稍等...",
});
setTimeout(function () {
wx.switchTab({
url: "pages/index/index",
});
}, 2000);
} else {
wx.showToast({
title: "已登录",
icon: "none",
duration: 1500,
});
}
} else if ((succRes, data.code == 400)) {
let pages = getCurrentPages();
let currentPages = pages[pages.length - 1];
let url = currentPages.route;
if (url != "pages/guidance/guidance") {
wx.showModal({
title: "尚未登录平台,请先登录",
confirmText: "去登录",
showCancel: false,
success: function (res) {
if (res.confirm) {
wx.reLaunch({
url: "/pages/guidance/guidance",
});
}
},
});
}
}
} else {
wx.showModal({
title: "错误提示",
content: "连接服务器失败!请稍后再试",
showCancel: false,
});
}
that.globalData.sync_finish = true;
if (that.sync_finishCallback) {
that.sync_finishCallback(that.globalData.sync_finish);
}
},
(err) => {
wx.hideLoading();
wx.showModal({
title: "错误提示",
content: error,
showCancel: false,
});
that.globalData.sync_finish = true;
if (that.sync_finishCallback) {
that.sync_finishCallback(that.globalData.sync_finish);
}
}
);
},
});
}
globalData: {
openId: undefined,
id:undefined,
userInfo: undefined,
sync_finish: false,
},