业务场景
适用于:在其它页面悬浮二维码,用户点击后在当前页面展示二维码,监听是否被扫,接收消息消费了多少钱,五秒后重新展示乘车码,用户可关闭二维码展示栏,继续浏览页面。
1.在app.js中开启websocket,并暴露接收消息的方法
onLaunch: function(options) {const that = thisthat.websocket()},//开启建链websocket() {const that = this;that.globalData.SocketTask = wx.connectSocket({url: 'wss:///szt-traffic/ws',success: res => {console.log('连接', res);},fail: err => {console.log('出现错误啦!!' + err);wx.showToast({title: '网络异常!',})}})that.globalData.SocketTask.onOpen((e) => {console.log('连接成功!');that.globalData.SocketTask.send({ data: JSON.stringify({ 'Websocket-Userid': 'traffic-consumeNotice-' + userId }) });count = 0; // 清零重连统计数据that.heartbeat(that.globalData.SocketTask); // 发送心跳包});that.globalData.SocketTask.onClose((e) => {console.log(e);console.log('连接已关闭!');that.reconnect()});that.globalData.SocketTask.onError((e) => {console.log(e);console.log('连接出错!');that.reconnect()});},heartbeat(ws) {timer && clearInterval(timer);timer = setInterval(() => {if (ws.readyState === 3) {ws.close();}ws.send({ data: JSON.stringify({ 'Websocket-Userid': 'traffic-consumeNotice-' + userId }) });}, 30000)},reconnect(ws) {count++;if (count > 2) {wx.showToast({ title: '语音播报服务连接失败,请刷新后重试!', icon: "none" });return}console.log('开始重连');setTimeout(function () {global.ws = connect();}, 1000)},
2.封装接收消息的工具类socket_code.js
var e = require("./trade.js"),t = require("./token.js"),r = require("./request.js"),a = getApp();var TimeCode;const SocketTask = a.globalData.SocketTask;module.exports = {//申、生码changeCode: function (qrcode) {r.request(url, {}, "GET").then((e) => {console.log(e)if (e.statusCode == 200 && e.data.returncode === "00") {getCurrentPages()[getCurrentPages().length - 1].setData({ code: e.data.qrcode, money: Number(e.data.money / 100).toFixed(2)});qrcode.makeCode(e.data.qrcode);wx.setStorageSync("qrCode", e.data.qrcode)refresh(qrcode)} else if (e.statusCode == 200 && e.data.returncode === "02") {getCurrentPages()[getCurrentPages().length - 1].setData({ code: '余额不足,请充值', money: Number(e.data.money / 100).toFixed(2) });} else if (e.statusCode == 200 && e.data.returncode === "01") {getCurrentPages()[getCurrentPages().length - 1].setData({ code: e.data.error });} else { getCurrentPages()[getCurrentPages().length - 1].setData({ code: '请求失败' });}})},//每隔五分钟刷新一次二维码refresh: function (qrcode){TimeCode = setInterval(function () {changeCode(qrcode);}, 300000)},//清除定时器clearCode: function (qrcode){clearInterval(TimeCode)},//接收websocket信息getMessage:function(){SocketTask.onMessage((e) => {console.log('接收消息')console.log(e)var obj = JSON.parse(e.data)if (obj.returncode == "00") {console.log('收到消息')if (wx.getStorageSync('qrcode') == obj.qrcode) {console.log("重复发送")} else {wx.setStorageSync('qrcode', obj.qrcode)getCurrentPages()[getCurrentPages().length - 1].setData({ show: false, basefare: Number(obj.basefare / 100).toFixed(2), transamt: Number(obj.transamt / 100).toFixed(2), discountprice: Number(obj.discountprice / 100).toFixed(2) })setTimeout(function () {getCurrentPages()[getCurrentPages().length - 1].setData({ show: true })getCurrentPages()[getCurrentPages().length - 1].changeCode(qrcode)}, 8000)}}});}, };
3.在其它js页面生码并监听、接收消息
在js页面引入生码js,接收websocket的js
var QRCode = require('../../utils/qrcode.js');var notice = require("../../utils/socket_code.js");var qrcode = new QRCode('canvas', {//注意id唯一width: 250,height: 250,colorDark: "#000000",colorLight: "#ffffff",correctLevel: QRCode.CorrectLevel.H,});Page({data: {show: true,codeShow: false,},onShow: function () {notice.getMessage()},modalClose: function() {var ts = thists.setData({codeShow: false})},changeCode: function() {var ts = thists.setData({codeShow: true})notice.changeCode(qrcode)},})
wxml页面
<!-- 展示乘车码 --><view class="code_mode" bindtap="changeCode"><image src="../../img/code.png" class="code"></image><view class="code_text">去乘车</view></view><!-- 弹窗 --><view wx:if="{{codeShow}}" class="modal"><view class="mask"></view><image src="../../img/close.png" class="modal_close" bindtap="modalClose"></image><canvas wx:if='{{show}}' class='canvas' canvas-id='canvasRecharge'></canvas><view wx:if='{{!show}}' class='suc'><view style='padding: 60rpx 0;'>扫码成功</view><view style='margin-top: 20rpx;'>¥{{transamt}}</view><view style='margin-top: 30rpx;font-size:30rpx;'>正常消费:¥{{basefare}}</view><view style='margin-top: 20rpx;font-size:30rpx;color:#FF9800'>优惠金额:¥{{discountprice}}</view></view></view>
wxss样式
.code_mode{width: 110rpx;height: 130rpx;text-align: center;position: fixed;bottom: 100rpx;right: 20rpx;background-color: #eee;}.code{width: 80rpx;height: 80rpx; margin-top: 6rpx;}.code_text{font-size: 22rpx;color: rgb(0, 153, 255);text-align: center;text-decoration:underline;}.modal{position: fixed;top: 0;left: 0;z-index: 100;width: 100vw;height: 100vh;}.modal_close{width: 50rpx;height: 50rpx;display: flex;float: right;}.mask {position: absolute;top: 0;left: 0;width: 100vw;height: 100vh;background: rgba(0, 0, 0, 0.5);z-index: -1;}.canvas{width: 250px;height: 250px; margin: 320rpx auto; line-height: 250rpx;}.suc {width: 230px;height: 230px;background-color: #fff;margin: 320rpx auto;font-size: 36rpx;text-align: center;}
如果觉得《微信小程序:监听二维码是否被使用 开启全局websocket 在其它页面接收消息》对你有帮助,请点赞、收藏,并留下你的观点哦!