开发前提,注册小程序获取appid和secret
小程序端添加授权按钮
<button class="weui-btn" type="primary" bindtap="showTopTips" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button>
绑定授权事件
bindGetUserInfo: function (res) {
app.login(function(){
console.log("授权登录回调")
wx.navigateBack({
})
});
}
调用后台登录接口
login: function(callback) {
var that = this;
wx.login({
success: function(res) {
wx.request({
url: that.globalData.domain + '/api/wechat/user/login',
data: {
code: res.code
},
success: function(res) {
if (res.data.code == 1) {
that.globalData.sessionKey = res.data.sessionKey; //暂时,不应该在网络传输
// 去注册
that.registerUser(callback);
return;
}
if (res.data.code != 0) {
// 登录错误
wx.hideLoading();
wx.showModal({
title: '提示',
content: '无法登录,请重试',
showCancel: false
})
return;
}
that.globalData.token = res.data.token;
that.globalData.userInfo = res.data.userInfo;
callback();
}
})
}
})
},
registerUser: function(callback) {
var that = this;
wx.login({
success: function(res) {
var code = res.code; // 微信登录接口返回的 code 参数,下面注册接口需要用到
wx.getUserInfo({
success: function(res) {
var iv = res.iv;
var encryptedData = res.encryptedData;
var rawData = res.rawData;
var signature = res.signature;
// 下面开始调用注册接口
wx.request({
url: that.globalData.domain + '/api/wechat/user/register',
data: {
code: code,
encryptedData: encryptedData,
iv: iv,
rawData: rawData,
signature: signature,
sessionKey: that.globalData.sessionKey
}, // 设置请求的 参数
success: (res) => {
if (res.data.code == 0) {
wx.hideLoading();
that.login(callback);
} else {
// 登录错误
wx.hideLoading();
wx.showModal({
title: '提示',
content: '无法登录,请重试',
showCancel: false
})
}
}
})
},
fail: function(res) {
console.log(res)
}
})
}
})
},
后台接口由于封装了下看不出来具体请求,实际上是调用微信接口如下来换取openid 微信昵称等信息
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
/**
* 登陆接口
*/
@AuthIgnore
@GetMapping("login")
public R login(String code) {
if (StringUtils.isBlank(code)) {
return R.error("empty jscode");
}
try {
WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
this.logger.info(session.getSessionKey());
this.logger.info(session.getOpenid());
//查询用户信息
UserEntity user = userService.queryByOpenid(session.getOpenid());
if(user == null) {
String sessionKey = session.getSessionKey();
return R.error(1, "未注册").put("sessionKey", sessionKey);
}
//生成token
Map<String, Object> map = tokenService.createToken(user.getId());
map.put("userInfo", user);
return R.ok(map);
} catch (WxErrorException e) {
this.logger.error(e.getMessage(), e);
return R.error();
}
}