版权声明: https://blog.csdn.net/huangpb123/article/details/82527344
需求描述:商家用扫描枪扫用户条形码或二维码实现支付。
效果图:
说明:条形码和二维码都是通过 barcode.js 和 qrcode.js 插件由一串数字转换而成的,生成的图片就是 Canvas 图片。(插件下载地址见:我的 GitHub)
下面我总结一下整个实现流程:
1. 从后台获取要转换成条形码和二维码的一串数字 code
2. 用 barcode.js 和 qrcode.js 把数字分别转换成条形码和二维码并显示到页面上
wxml:
<view>
<canvas canvas-id="barcode" />
<view>{{codeStr}}</view>
<canvas canvas-id="qrcode" />
</view>
js:
// utils.js (封装 api)
import qrcode from './qrcode';
import barcode from './barcode';
// 把数字转换成条形码
function toBarcode (canvasId, code, width, height) {
barcode.code128(wx.createCanvasContext(canvasId), code, width, height);
}
// 把数字转换成二维码
function toQrcode (canvasId, code, width, height) {
qrcode.api.draw(code, {
ctx: wx.createCanvasContext(canvasId),
width,
height
})
}
export {
toBarcode,
toQrcode
}
// 使用 api
toBarcode('barcode', code, 680, 200);
toQrcode('qrcode', code, 420, 420);
const codeStr = `${code.slice(0, 4)}****${code.slice(20)}`;
3. 轮训请求后台,查看是否已被扫码(其实就是判断后台返回的 code 状态)
getStatus(code);
function getStatus (code) {
wx.request({
url: '',
method: 'GET',
data: {code},
success: (res) => {
if (res.isSuccess) {
// 支付成功后的操作
} else {
// 还未支付并且允许轮训的话就继续轮训
if (this.state.caninterval) {
setTimeout(() => {
getStatus(code);
}, 1000)
}
}
}
})
}
完整代码:
import { toBarcode, toQrcode } from '../utils';
Page({
data: {
canInterval: true, //判断能不能轮询
code: '', // 转换成条形码、二维码的数字
codeStr: ''
},
onLoad () {
wx.request({
url: '',
method: 'GET',
success: (res) => {
const { code } = res.data;
toBarcode('barcode', code , 680, 200);
toQrcode('qrcode', code, 420, 420);
const codeStr = `${code.slice(0, 4)}****${code.slice(20)}`;
this.setData({
code,
codeStr
})
this.getStatus(code);
}
})
},
onShow () {
const {code} = this.data;
this.setData({
canInterval: true
});
code && this.getStatus(code);
},
getStatus (code) {
wx.request({
url: '',
method: 'GET',
data: {code},
success: (res) => {
if (res.isSuccess) {
// 支付成功后的操作
} else {
// 还未支付并且允许轮训的话就继续轮训
if (this.state.canInterval) {
setTimeout(() => {
this.getStatus(code);
}, 1000)
}
}
}
})
},
onHide () {
this.setData({
canInterval: false
})
},
onUnload () {
this.setData({
canInterval: false
})
}
})