情景:微信小程序的最后一页中间有一个自己的二维码,方便用户截图分享,如果知道域名和网页路径,是很容易生成一个二维码的,但是微信小程序没办法这样做。
微信小程序没有window.location,所以必须通过微信提供的方法来获取这个二维码,具体方法:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
这些操作都是需要后端去操作的,前端可以通过downloadFile方法来获取临时的二维码图片文件,然后再赋值给Image的src用来展示;或者通过canvas把它绘制出来。
注意:代码中接口必须是Get接口,imgInfo参数必须用encodeURIComponent方法处理一下,而且wx.downloadFile方法必须设置下载域名白名单才能在发布状态下调用成功。
下载域名白名单设置后,并不能立即使用,等待两三个小时也有可能。
...
this.getQrCode().then(res => {
if (!res) {
wx.hideLoading();
// wx.showToast({
// title: '二维码加载出错~',
// icon: 'none'
// })
this.setData({
downloadFileErr: true
});
return false
}
const ctx = wx.createCanvasContext('myCanvas');
ctx.save();
ctx.drawImage(
'../../images/share@2x.png',
0, 0,
750, 1624,
0, 0,
this.data.cvsSize.width, this.data.cvsSize.height
);
this.drawRect(ctx);
this.drawEwm(ctx, res.tempFilePath);
ctx.draw(false, function () {
wx.hideLoading({
success: (res) => {
wx.showToast({
title: '绘制完成',
})
},
})
});
})
},
...
getQrCode () {
var SessionResult = wx.getStorageSync('SessionResult') || {}
let imgInfo = {
channelNo: 'cy35',
scene: 'userId=' + SessionResult.userId + '&type=1',
width: 280
}
return new Promise((resolve, reject) => {
wx.showToast({
title: 'getQrCode...',
})
wx.downloadFile({
url: Ajax.preUrl + 'ky/createUnlimitedQr?imgInfo=' + encodeURIComponent(JSON.stringify(imgInfo)),
success (res) {
if (res.statusCode === 200) {
// console.log('downloadFile', res)
resolve(res)
} else {
wx.showToast({
title: 'success.' + res.statusCode,
})
resolve('');
}
},
fail (err) {
wx.showToast({
title: 'fail.' + err,
})
console.log('downloadFile failed.', err);
resolve('');
}
})
})
},
生成了二维码并附带了参数,那么扫码后在首页怎么获取这个传过来的参数呢?
scene: 'userId=' + SessionResult.userId + '&type=1'这部分代码就是二维码附带的参数,在进入页面index.js的onload方法里面,可以得到这个参数。
if(options.scene){
console.log('options.scene:', options)
let scene=decodeURIComponent(options.scene);
console.log('options.scene:', scene)
//&是我们定义的参数链接方式
let userId=scene.split("&")[0];
if (typeof userId === 'string' && userId.indexOf('=') > 0) {
userId = userId.split('=')[1]
}
}
options.scene结果打印:
{scene: "userId=2100&type=1"}
网友评论