需求:用户A进入小程序生成一个二维码,用户B用手机扫用户A的二维码,扫码成功后用户B需要等待用户A进行确认授权,用户A确认授权后,用户B的页面出现用户A的二维码的信息。
解决方案:1、轮询方式;2、websocket长连接方式(有些浏览器不兼容websocket)
一、轮询方式
流程图
具体实现
亮码者生成二维码后,增加轮询调用查询码状态接口
//小程序端轮询查看码状态
client() {
var _this = this;
var code = this.$route.query.code;
axios
.get("/personal/info/codeStatus?code=" + code)
.then(function (response) {
console.log(response.data.data);
setTimeout(function () {
if (response.data.data == 1) {//状态为1说明还没有被扫描
_this.client();
} else {
axios
.get("/personal/info/doScan?code=" + code)
.then(function (response) {
console.log(response.data.data);
})
.catch(function (error) {
console.log(error);
});
}
}, 1500);
})
.catch(function (error) {
console.log(error);
});
},
扫码者扫码之后也增加轮询调用查询码状态接口
//扫码端轮询查看码状态
server() {
var _this = this;
var code = this.$route.query.code;
axios
.get("/personal/info/codeStatus?code=" + code)
.then(function (response) {
console.log(response.data.data);
setTimeout(function () {
if (response.data.data == 2) {//状态为2说明小程序端还没有确认
_this.server();
} else if (response.data.data == 1) {//扫码
axios
.get("/personal/info/doScan?code=" + code)
.then(function (response) {
console.log(response.data.data);
})
.catch(function (error) {
console.log(error);
});
} else {
//调用查询码信息接口,展示数据
}
}, 1500);
})
.catch(function (error) {
console.log(error);
});
},
生成码接口
@CrossOrigin(origins ="*") //解决跨域问题,可以用全局配置
@ApiOperation(value = "用户亮码")
@PostMapping("/createCode")
public String createCode(@RequestBody CreateCodeVo createCodeVo) throws IOException {
if (ObjectUtils.allNotNull(createCodeVo)) {
String encrypt = AESUtil.encrypt(String.valueOf(createCodeVo.getUserId()));
System.out.println(encrypt);
final BufferedImage bufferedImage = QRCodeUtil.createCodeWithLogo("http://192.168.1.104:8080/#/?code="+encrypt, "", -1, -1, -1);
if (bufferedImage != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
byte[] bytes = baos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
String pngBase64 = encoder.encodeBuffer(bytes);
baos.close();
pngBase64 = pngBase64.replaceAll("\n", <