最近改造一个微信小程序项目:
原登录逻辑:直接获取用户信息(wx.getUserProfile)进行登录
改造后:用户登录前先获取用户手机号 判断时候注册过 再进行后续操作(这边主要介绍如何直接获取手机号)
实现逻辑
微信小程序页面代码(wxml)比较简单没什么好介绍的
<view class="container">
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" class="login-btn one"
type="warn">微信手机号码授权</button>
</view>
<view class="form-box">
<button type="primary" class="login-btn two" catch:tap="wxBack">暂不授权</button>
</view>
</view>
重点JS实现
var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var user = require('../../../utils/user.js');
var app = getApp();
Page({
data: {
sessionkey: '',
code: '',
openId: undefined,
unionId: undefined,
},
onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数
// 调用wx.login获取code 并调用后台获取sessionKey
var that = this;
//刷新sessionKey
wx.login({
success(res) {
that.setData({
code: res.code
})
//后台通过code获取openId和sessionkey方法
util.request(api.getSessionKey, {
code: res.code,
}, 'GET').then(res => {
//将返回值绑定到data中
that.setData({
openId: res.data.openId,
unionId: res.data.unionId,
sessionkey: res.data.sessionKey
})
})
}
})
},
onReady: function () {
},
onShow: function () {
// 页面显示
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
},
wxBack() {
wx.switchTab({
url: '/pages/positionList/positionList'
})
},
getPhoneNumber(e) {
let that = this;
//后台解密手机号方法
util.request(api.getPhoneNumber, {
sessionKey: that.data.sessionkey,
openId: that.data.openId,
unionId: that.data.unionId,
wxPhoneCiphertext: e.detail
}, 'POST').then(res => {
if (res.errno === 0) {
//已有账号 登录成功
//存储用户信息
wx.setStorageSync('userInfo', res.data.userInfo);
wx.setStorageSync('token', res.data.token);
wx.setStorageSync('tokenStatus', 1)
app.globalData.hasLogin = true;
wx.setStorageSync('isWxUser', 1);
wx.switchTab({
url: '/pages/recruitPerson/recruitPerson',
})
} else if (res.errno === 509) {
//没有账号进一步获取用户信息
that.getUserProfile();
}
})
},
getUserProfile() {
// An highlighted block
wx.showModal({
title: '温馨提示',
content: '点击确定获取微信头像及昵称',
success(res) {
if (res.confirm) {
wx.getUserProfile({
desc: "获取你的昵称、头像、地区及性别",
success: res => {
user.loginByWeixin(res.userInfo).then(res => {
app.globalData.hasLogin = true;
wx.setStorageSync('isWxUser', 1);
wx.switchTab({
url: '/pages/recruitPerson/recruitPerson',
})
}).catch((err) => {
app.globalData.hasLogin = false;
util.showErrorToast('微信登录失败');
});
},
fail: res => {
//拒绝授权
that.showErrorModal('您拒绝了请求');
return;
}
})
} else if (res.cancel) {
//拒绝授权 showErrorModal是自定义的提示
that.showErrorModal('您拒绝了请求');
return;
}
}
})
},
})