最近接触到微信生成小程序码的项目,依照小程序开发文档依葫芦画瓢,发现腾讯给我们留了一个大坑。
官方接口返回给我们的小程序码是图片数据流ArrayBuffer,然后它这个wx.arrayBufferToBase64(ArrayBuffer arrayBuffer)接口就这么不能用了,法克。
几经折腾,终于可以正常实现生成小程序码了,不说废话,上代码
//首先利用官方接口获取小程序码图片流数据(access_token要先拿到)
wx.request({
url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='+access_token,
method: 'POST',
responseType: 'arraybuffer',
data: {
scene: 'id=1',//你的参数
page: 'pages/index/index',
check_path:false,
env_version:'trial',
width: 200,
is_hyaline: true
},
header: {
'content-type': 'application/json'
},
//success: function (res)
success:(res)=> {
// 现在拿到的是小程序码二进制流数据buffer,将buffer写入临时文件路径,然后绑定到页面的data属性
console.log(res.data);
let buffer=res.data;
let fileMananger=wx.getFileSystemManager();
let filePath=wx.env.USER_DATA_PATH+'/qr.jpeg';
console.log(filePath);
fileMananger.writeFile({
filePath:filePath,
encoding:"binary",
data:buffer,
success:(res)=>{
console.log(res);
console.log(filePath);
this.setData({
qrcodeUrl:filePath
})
},
fail: function (err) {
console.log(err);
}
})
这样一来我就在前端就可以生成了,看效果