JeecBoot微信扫码登录后台系统
一、前端页面
公共部分
1.1div展示二维码
<div class="qrcode" ref="qrCodeUrl"></div>
1.2依赖
//项目中安装依赖
npm install --save qrcodejs2
//页面中引入依赖
import QRCode from 'qrcodejs2'
1.3钩子函数
//初始化页面加载
mounted(){
this.createQrCode()
},
方法
2.1普通二维码
createQrCode(){
var qrcode = new QRCode(this.$refs.qrCodeUrl,{
//text:二维码内容,参数必填,否则生成不了二维码
text:"test",
width:100,
height:100,
colorDark:"#000000",
correctLevel:QRCode.CorrectLevel.H
});
},
2.2微信扫描登录二维码
微信测试号,扫码后,会提示Scope 参数错误或没有 Scope 权限
createQrCode(){
var qrcode = new QRCode(this.$refs.qrCodeUrl,{
text:"test",
width:100,
height:100,
colorDark:"#000000",
correctLevel:QRCode.CorrectLevel.H
});
const appId = "";
const redirectUrl = "";
const state = "";
const url = "https://open.weixin.qq.com/connect/qrconnect?appid=" +appId+ "&redirect_uri=" + redirectUrl+ "&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect";
qrcode.makeCode(url);
this.checkLoginStatus();
},
checkLoginStatus(){
const intervalId = setInterval(() => {
// 使用Ajax向后端获取二维码状态,检查用户是否已经登录
const ticket = '';
this.$http.post('/wxLogin/checkQRCode', {ticket}).then((response) => {
if (response.status === 200 && response.data.code === 0) {
clearInterval(intervalId);
// 用户已成功登录,跳转到主页
this.$router.push('/main');
}
}).catch((e) => {
console.log(e);
});
}, 3000);
},
二、后台代码
验证授权码或token的有效性
@RestController
@RequestMapping("/wxLogin")
public class WeChatLoginController {
@Autowired
private UserService userService;
@PostMapping("/checkQRCode")
public JSONObject checkQRCode(@RequestParam("ticket") String ticket){
JSONObject result = new JSONObject();
try {
// 调用微信API通过ticket获取二维码状态
String url = "https://api.weixin.qq.com/cgi-bin/login/qrcode?access_token=" + getAccessToken();
JSONObject param = new JSONObject();
param.put("ticket", ticket);
String response = HttpUtil.post(url, param.toString());
JSONObject jsonObject = JSON.parseObject(response);
int errcode = jsonObject.getIntValue("errcode");
if (errcode == 0) { // 获取二维码状态成功
int status = jsonObject.getIntValue("status");
if (status == 1) { // 用户已扫描二维码,等待用户确认登录
result.put("status", 1001);
result.put("ticket", jsonObject.getString("ticket"));
} else if (status == 2) { // 用户已确认登录,可以获取code或token了
String code = jsonObject.getString("user_code");
String openid = getUserOpenId(code);
User user = userService.getUserByOpenid(openid);
if (user != null) { // 验证通过,返回登录成功
result.put("status", 200);
} else { // 验证失败,返回登录失败
result.put("status", 300);
}
result.put("ticket", jsonObject.getString("ticket"));
} else { // 二维码失效或其他异常情况
result.put("status", 300);
}
} else {
result.put("status", 300);
}
} catch (Exception e) {
e.printStackTrace();
result.put("status", 300);
}
return result;
}
/**
* 根据授权码获取用户openid
*/
private String getUserOpenId(String code) throws Exception {
String url = "https://api.weixin.qq.com/sns/jscode2session" +
"?appid=" + ConfigConstant.WX_LOGIN_APPID +
"&secret=" + ConfigConstant.WX_LOGIN_SECRET +
"&js_code=" + code +
"&grant_type=authorization_code";
String response = HttpUtil.get(url);
JSONObject jsonObject = JSON.parseObject(response);
String openid = jsonObject.getString("openid");
if (openid == null) {
throw new Exception("Get openid failed!");
}
return openid;
}
/**
* 获取微信access token
*/
private String getAccessToken() throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/token" +
"?grant_type=client_credential" +
"&appid=" + ConfigConstant.WX_LOGIN_APPID +
"&secret=" + ConfigConstant.WX_LOGIN_SECRET;
String response = HttpUtil.get(url);
JSONObject jsonObject = JSON.parseObject(response);
String accessToken = jsonObject.getString("access_token");
if (accessToken == null) {
throw new Exception("Get access token failed!");
}
return accessToken;
}
}
一个在学习的开发者,勿喷,欢迎交流