微信小程序登录如何实现(微信小程序一键登录设计以及实现)
微信小程序登录如何实现(微信小程序一键登录设计以及实现)接受code 信息调用微信获取openidPage({ /** * 页面的初始数据 */ data: { openid: "" loginstate: "0" openid: "" userEntity: null terminal: "" osVersion: "" phoneNumber: "" showModal: false //定义登录弹窗 } //在页面加载的时候,判断缓存中是否有内容,如果有,存入到对应的字段里 onLoad: function () { var that = this; wx.getStorage({ key: '
流程图
页面原型
微信一键登录
绑定用户手机号码
前台代码
index.wxml
<button class='phone-text' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGotUserInfo">请登录</button>
<!--登录弹窗-->
<view class="modal-mask" catchtouchmove="preventTouchMove" wx:if="{{showModal}}"></view>
<view class="modal-dialog" wx:if="{{showModal}}">
<view class="modal-content">
<view><image src='../images/show.png' class='show'></image></view>
<view>绑定手机号</view>
<view>请先绑定手机号在进行此操作</view>
<button open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">
<image src='../images/showWx.png' class='iconWx'></image>微信用户一键绑定
</button>
</view>
</view>
index.js
Page({
/**
* 页面的初始数据
*/
data: {
openid: ""
loginstate: "0"
openid: ""
userEntity: null
terminal: ""
osVersion: ""
phoneNumber: ""
showModal: false //定义登录弹窗
}
//在页面加载的时候,判断缓存中是否有内容,如果有,存入到对应的字段里
onLoad: function () {
var that = this;
wx.getStorage({
key: 'openid'
success: function (res) {
that.setData({ openid: res.data });
}
fail: function (res) {
that.getcode();
}
});
wx.getStorage({
key: 'userEntity'
success: function (res) {
that.setData({ userEntity: res.data });
}
fail: function (res) {
console.log("fail1");
}
});
wx.getStorage({
key: 'loginstate'
success: function (res) {
that.setData({ loginstate: res.data });
} fail: function (res) {
console.log("fail2");
}
});
}
onGotUserInfo: function (e) {
var that = this;
if (e.detail.errMsg == "getUserInfo:ok") {
wx.setStorage({
key: "userinfo"
data: e.detail.userInfo
})
this.setData({ userInfo: e.detail.userInfo });
that.showDialogBtn();//调用一键获取手机号弹窗(自己写的)
}
}
// 显示一键获取手机号弹窗
showDialogBtn: function () {
this.setData({
showModal: true//修改弹窗状态为true,即显示
})
}
// 隐藏一键获取手机号弹窗
hideModal: function () {
this.setData({
showModal: false//修改弹窗状态为false 即隐藏
});
}
onshow: function (openid userInfo phoneNumber) {
var that = this;
wx.getSystemInfo({
success: function (res) {
that.setData({ terminal: res.model });
that.setData({ osVersion: res.system });
}
})
wx.request({
url: '登录接口'
method: 'POST'
header: {
'content-type': 'application/json' // 默认值
}
data: {
username: phoneNumber
parentuser: 'xudeihai'
wximg: userInfo.avatarUrl
nickname: userInfo.nickName
identity: ""
terminal: that.data.terminal
osVersion: that.data.system
logintype: "10" //微信登录
openid: that.data.openid
}
success(res) {
if (res.data.r == "T") {
that.setData({ userEntity: res.data.d });
wx.setStorage({
key: "userEntity"
data: res.data.d
})
that.setData({ loginstate: "1" });
wx.setStorage({
key: "loginstate"
data: "1"
})
wx.setStorage({
key: 'userinfo'
data: "1"
})
}
else {
return;
}
}
fail(res) {
console.log(res);
}
})
}
//绑定手机
getPhoneNumber: function (e) {
var that = this;
that.hideModal();
wx.checkSession({
success: function () {
wx.login({
success: res => {
wx.request({
url: '自己的登录接口' //仅为示例,并非真实的接口地址
data: {
account: '1514382701'
jscode: res.code
}
method: "POST"
header: {
'content-type': 'application/json' // 默认值
}
success(res) {
if (res.data.r == "T") {
wx.setStorage({
key: "openid"
data: res.data.openid
})
wx.setStorage({
key: "sessionkey"
data: res.data.sessionkey
})
wx.setStorageSync("sessionkey" res.data.sessionkey);
wx.request({
url: '自己的解密接口' //自己的解密地址
data: {
encryptedData: e.detail.encryptedData
iv: e.detail.iv
code: wx.getStorageSync("sessionkey")
}
method: "post"
header: {
'content-type': 'application/json'
}
success: function (res) {
if (res.data.r == "T") {
that.onshow(that.data.openid that.data.userInfo res.data.d.phoneNumber);//调用onshow方法,并传递三个参数
console.log("登录成功")
console.log(res.data.d.phoneNumber)//成功后打印微信手机号
}
else {
console.log(res);
}
}
})
}
}
})
}
})
}
fail: function () {
wx.login({
success: res => {
wx.request({
url: '自己的登录接口' //仅为示例,并非真实的接口地址
data: {
account: '1514382701'
jscode: res.code
}
method: "POST"
header: {
'content-type': 'application/json' // 默认值
}
success(res) {
if (res.data.r == "T") {
wx.setStorage({
key: "openid"
data: res.data.openid
})
wx.setStorage({
key: "sessionkey"
data: res.data.sessionkey
})
wx.request({
url: '自己的解密接口' //自己的解密地址
data: {
encryptedData: e.detail.encryptedData
iv: e.detail.iv
code: res.data.sessionkey
}
method: "post"
header: {
'content-type': 'application/json'
}
success: function (res) {
that.onshow(that.data.openid that.data.userInfo res.data.d.phoneNumber);//调用onshow方法,并传递三个参数
}
})
}
}
})
}
})
}
})
}
})
后台代码
接受code 信息调用微信获取openid
@ApiOperation("乘客微信一键登录")
@PostMapping("/customer/loginByWeixin")
public Result<JSONObject> loginByWeixin(@RequestParam(value = "code") String code HttpServletRequest request) {
Result<JSONObject> result = new Result<JSONObject>();
if (code == null) {
result.setMessage("code不能为空!");
result.setSuccess(false);
return result;
}
String sessionKey = null;
String openId = null;
try {
WxMaJscode2SessionResult wxMaJscode2SessionResult = this.wxService.getUserService().getSessionInfo(code);
sessionKey = wxMaJscode2SessionResult.getSessionKey();
openId = wxMaJscode2SessionResult.getOpenid();
} catch (Exception e) {
e.printStackTrace();
result.setMessage("微信登录 调用官方接口失败!" e.getMessage());
result.setSuccess(false);
return result;
}
if (sessionKey == null || openId == null) {
result.setMessage("微信登录 调用官方接口失败!");
result.setSuccess(false);
return result;
}
LeUser user = leUserService.getUserByOpenid(openId);
if (user == null) { //新用户注册
user = new LeUser();
user.setWeixinOpenid(openId);
user.setPasswd(openId);
user.setStatus(1);
user.setLastLoginTime(new Date());
leUserService.save(user);
}
HashMap<String String> wxsession = new HashMap<>();
wxsession.put("openid" openId);
wxsession.put("sessionkey" sessionKey);
//老用户登录
userInfo(user result);
return result;
}
绑定用户信息
@AutoLog(value = "乘客解密用户信息&绑定用户信息")
@ApiOperation(value = "乘客解密用户信息&绑定用户信息" notes = "乘客解密用户信息&绑定用户信息")
@PostMapping(value = "/customer/bindUserinfo")
public Result bindUserinfo(@RequestParam(value = "sessionKey") String sessionKey
@RequestParam(value = "encryptedData") String encryptedData
@RequestParam(value = "iv") String iv HttpServletRequest request) {
WxMaUserInfo userInfo = null;
try {
// 解密用户信息
userInfo = this.wxService.getUserService().getUserInfo(sessionKey encryptedData iv);
} catch (Exception e) {
e.printStackTrace();
return Result.error("解密用户信息失败!" e.getMessage());
}
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
String userId = sysUser.getId();
LeUser user = leUserService.getById(userId);
user.setNickname(userInfo.getNickName());
user.setUsername(userInfo.getNickName());
user.setAvatar(userInfo.getAvatarUrl());
user.setUsex(userInfo.getGender() == "女" ? 2 : 1);
leUserService.updateById(user);
return Result.OK(user);
}
绑定乘客信息
@AutoLog(value = "乘客解密用户手机号码&绑定用户手机号码")
@ApiOperation(value = "乘客解密用户手机号码&绑定用户手机号码" notes = "乘客解密用户手机号码&绑定用户手机号码")
@PostMapping(value = "/customer/bindUserphone")
public Result bindUserphone(@RequestParam(value = "sessionKey") String sessionKey
@RequestParam(value = "encryptedData") String encryptedData
@RequestParam(value = "iv") String iv HttpServletRequest request) {
WxMaPhoneNumberInfo phoneNumberInfo = null;
try {
// 解密用户信息
phoneNumberInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey encryptedData iv);
} catch (Exception e) {
e.printStackTrace();
return Result.error("解密用户信息失败!" e.getMessage());
}
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
String userId = sysUser.getId();
LeUser user = leUserService.getById(userId);
user.setMobile(phoneNumberInfo.getPhoneNumber());
leUserService.updateById(user);
return Result.OK(user);
}