小程序登录的两种方式
- 账号密码登录
- 获取小程序授权登录
账号密码登录
app.json页面顺序 先进入首页 有token就是首页 没有token时redirectTo登录页
{
"pages": [
"pages/sales/sales",
"pages/login/login",
],
app.js页面代码 页面装载时检查有没有token,有的话说明已经登录过了,拿一下缓存的用户信息否则跳转到登录页重新登录
接口封装 每次请求时去判断token,有的话,请求头带上token,否则跳转到登录页重新登录
用户登录方法,账号密码登录,成功以后token和用户信息都缓存起来
App({
globalData: {
dologin: false, //处于登录中
sessionKey: 'sess_jk',
userInfo: {
},
userToken: '',
token: '',
hasAuth: false,
siteBaseUrl: 'https://***',
},
token: null,
//启动
onLaunch: function () {
// 调用API从本地缓存中获取数据
var self = this,
token = self.getSession();
if (!token) {
wx.redirectTo({
url: '/pages/login/login',
})
console.log('重新登录');
} else {
let userInfo = JSON.parse(wx.getStorageSync('userInfo'))
let self=this;
self.globalData.userInfo= userInfo;
this.globalData.dologin = true;
}
},
//发起服务器请求
sendRequest: function (param) {
var self = this,
token = '',
data = param.data || {},
header = param.header || {
'content-type': 'application/json'
},
url = param.url,
requestUrl;
//如果参数里设置了token,直接使用
// if (!data.token) {
token = self.getSession();
if (!token) {
self.dologin = false
wx.redirectTo({
url: '/pages/login/login',
})
return;
//时间戳
var timestamp = Date.parse(new Date());
header['token'] = token
if (param.method) {
param.method = param.method.toUpperCase();
}
//实际请求地址
requestUrl = this.globalData.siteBaseUrl + param.url;
//开始请求
if (!param.hideLoading) {
wx.showLoading({
title: T_D.loading + '...',
});
}
wx.request({
url: requestUrl,
data: data,
method: param.method || 'GET',
header: header,
success: (res) => {
// console.log('request response from:' + param.url);
//api错误
if (res.statusCode && res.statusCode != 200) {
wx.showModal({
content: '' + res.errMsg
});
return;
}
if (res.data.code) {
//登录失效
if (res.data.code == '-1') {
wx.redirectTo({
url: '/pages/login/login',
})
return;
}
if (res.data.code != 10000) {
wx.showModal({
showCancel: false,
content: '' + res.data.msg
});
return;
}
} else {
wx.showModal({
showCancel: false,
content: T_D.error
});
return;
}
typeof param.success == 'function' && param.success(res.data);
},
//请求失败时执行
fail: (res) => {
wx.showModal({
content: T_D.failRequest + res.errMsg
})
typeof param.fail == 'function' && param.fail(res.data);
},
//完成请求,不管成功还是失败都执行
complete: (res) => {
wx.hideLoading();
typeof param.complete == 'function' && param.complete(res.data);
return;
}
});
},
//用户登录
login: function (passwd, phone) {
var self = this;
//设置登录中
self.globalData.dologin = true;
// 判断是否已在我的页面 授权登录,有则登录,没有则跳转至「我的」
if (!this.globalData.dologin) {
console.log('已登录');
wx.switchTab({
url: '/pages/sales/sales'
})
return;
}
let data = {
passwd: passwd,
telephone: phone
}
wx.request({
url: 'https://****',
data: data,
method: 'GET',
header: {
'content-type': 'application/json'
},
success: (res) => {
//api错误
if (res.statusCode && res.statusCode != 200) {
wx.showModal({
content: '' + res.errMsg
});
return;
}
//返回结果code判断,0=成功,1=错误,-1=未登录
if (res.data.code) {
if (res.data.code != 10000) {
wx.showModal({
showCancel: false,
content: '' + res.data.msg
});
return;
} else {
self.setSession(res.data.data.userToken);
self.globalData.dologin = true;
self.globalData.userInfo.id = res.data.data.user;
wx.setStorageSync('userInfo', JSON.stringify(self.globalData.userInfo))
console.log(self.globalData)
wx.switchTab({
url: '/pages/sales/sales',
});
}
} else {
wx.showModal({
showCancel: false,
content: T_D.error
});
return;
}
},
//请求失败时执行
fail: (res) => {
wx.showModal({
content: T_D.failRequest + res.errMsg
})
},
//完成请求,不管成功还是失败都执行
complete: (res) => {
wx.hideLoading();
return;
}
});
},
//检查登录
checkLogin: function () {
if (!this.getSession()) {
this.login();
}
},
//当前页面
getCurPage: function () {
var pages = getCurrentPages();
return pages[pages.length - 1];
},
//页面初始化
initPage: function () {
console.log(this.getCurPage());
this.getCurPage().onLoad();
// this.getCurPage().get_machinenum();
},
//token sessin
getSession: function () {
return wx.getStorageSync('userToken') || null;
},
setSession: function (userToken) {
wx.setStorageSync('userToken', userToken);
},
clearSession: function () {
console.log('退出登录 清除数据');
wx.removeStorageSync('userToken');
},
})
登录页面代码
//表单提交
formSubmit: function (e) {
var self = this,
value = e.detail.value,
passwd = value.passwd,
telephone = value.telephone;
//表单验证
if (telephone == '') {
wx.showToast({
title: '请输入手机号',
icon: 'none'
})
return false;
}
if (telephone.length != 11) {
wx.showToast({
title: '手机号长度有误!',
icon: 'none'
})
return false;
}
var reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
if (!reg_tel.test(telephone)) {
wx.showToast({
title: '手机格式有误!',
icon: 'none'
})
return false;
}
if (passwd == '') {
wx.showToast({
title: '请输入密码',
icon: 'none'
})
return false;
}
app.globalData.hasAuth = true;
app.login(passwd, telephone);
}
获取小程序授权登录
获取用户头像昵称和用户手机号分为两个页面,两个按钮分别去获取信息
//获取用户信息授权的按钮
<button class="info-button" size="mini" bindgetuserinfo="getUserInfo" open-type="getUserInfo">获取授权</button>
//js部分 先调用this.getUserProfile()函数获取授权,然后点击按钮调用getUserInfo方法,获得用户信息后跳转到获取手机号的界面
Page({
data: {
result: null,
scopeButton: true,
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
canIUseGetUserProfile: false,
canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
this.getUserProfile()
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res)
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
app.globalData.userInfo = res.userInfo
console.log(app.globalData.userInfo)
}
})
},
getUserInfo(e) {
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
app.globalData.userInfo = e.detail.userInfo
app.globalData.result = e.detail
wx.redirectTo({
url: '../login/login',
})
},
})
获取手机号
//获取手机号按钮
<button class="{{flag?'hide':'show'}}" type="primary" lang="zh_CN" open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">立即授权登录</button>
//获取授权方法 先获取用户信息,如果没有,先调用登录接口登录, 拿到信息调用接口去做绑定,成功后跳转到首页。拒绝授权提示影响使用。
getPhoneNumber: function (e) { //点击获取手机号码按钮
var that = this;
that.data.lee
if (that.data.lee == '') {
wx.showToast({
icon: "none",
title: '请先点击获取用户信息',
})
return
} else {
wx.checkSession({
success: function (res) {
let token=wx.getStorageSync('token')
wx.request({
url: app.globalData.baseurl + "user/binding",
data: {
result: JSON.stringify(app.globalData.result),
token:token,
user: '',
phone: JSON.stringify(e.detail)
},
method: "POST",
success(e) {
console.log(e)
// console.log(e)
wx.switchTab({
url: "../index/index"
})
tui.toast('登陆成功!', 2000, 'success')
wx.setStorageSync('token', e.data.data.token)
}
})
var ency = e.detail.encryptedData;
var iv = e.detail.iv;
var sessionk = that.data.sessionKey;
if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
console.log('授权失败')
wx.showModal({
title: '警告',
content: '您点击了拒绝授权,部分功能无法使用!!!',
showCancel: false,
confirmText: '返回授权',
success: function (res) {
// 用户没有授权成功,不需要改变 isHide 的值
if (res.confirm) {
wx.setStorageSync('enws', '1');
// wx.switchTab({
// url: "../index/index"
// })
console.log('用户点击了“返回授权”');
};
}
}),
that.setData({
modalstatus: true,
});
} else {
// console.log('同意授权',this.data.userInfo)
let token=wx.getStorageSync('token')
wx.request({
url: app.globalData.baseurl + "user/binding",
data: {
result: JSON.stringify(app.globalData.result),
user: '',
token:token,
phone: JSON.stringify(e.detail)
},
method: "POST",
success(e) {
// console.log(e)
wx.switchTab({
url: "../index/index"
})
wx.showToast({
icon: "none",
title: '登陆成功!',
})
wx.setStorageSync('token', e.data.data.token)
}
})
}
},
fail: function () {
console.log("session_key 已经失效,需要重新执行登录流程");
app.my_login() //重新登录
}
});
}
}
在app.js的生命周期函数onlaunch中调用登录方法,通过登录方法拿到token和用户信息存起来,用户信息包括微信用户昵称,用户电话,openid等。
//app.js
App({
globalData: {
userInfo: null,
token: '',
baseurl: "https://****/",
},
/*
当小程序初始话完成,会触发onlaunch(全局只触发一次)
*/
onLaunch: function () {
// 登录
this.my_login()
},
my_login: function () {
let that = this
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: that.globalData.baseurl + "user/wxLogin",
data: {
"code": res.code
},
method: "POST",
success(e) {
wx.setStorageSync('token', e.data.data.token)
if (e.data.data.userInfo) {
wx.switchTab({
url: '../index/index',
})
}
that.globalData.userInfo = e.data.data.userInfo
}
})
}
})
},
})
app.json顺序
"pages": [
"pages/getuserInfo/getuserInfo",
"pages/login/login",
"pages/index/index",
],