实现步骤
使用微信接口API文档,官方文档看得不明白,不如上实例
- 获取
ACCESS_TOKEN(后台)
const axios = require('axios')
const appId = '你小程序的appId'
const appSecret = '你小程序的appSecret'
const res = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`)
const ACCESS_TOKEN = res.data.access_token
一切正常就能拿到token了,错误的话看一下返回的错误码API文档,核对一下入参
- 返回前端的代码
const token = await getToken();
const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`
const page = 'pages/person/person'
const scene = 'foobar'
const buffer = await request({
url,
method: 'post',
responseType: 'arraybuffer', // 要设置为arraybuffer,默认是json
data: {
scene,
page,
env_version: 'trial', // trial体验版,release正式版,develop开发版,其实无效
auto_color: false,
line_color: {
'r': '0',
'g': '0',
'b': '0'
},
is_hyaline: true
},
});
// const appId = process.env.appId
// const devUrl = `https://open.weixin.qq.com/sns/getexpappinfo?appid=${appId}&path=${encodeURIComponent(page)}.html?scene=${encodeURIComponent(scene)}`;
// 无法生成测试环境小程序码,可以用链接替代,要转为二维码,可以使用wxbarcode
// wxbarcode.qrcode('qrcode', devUrl, 420, 420);
ctx.type = 'image/jpeg';
ctx.body = buffer
- 小程序端处理代码
wx.request({
url: `${host}/getQrcode`,
responseType: 'arraybuffer', // 接口返回的是image/jpeg,接收要设置为arraybuffer
success: (res) => {
console.log('buffer type', typeof(res.data))
const base64 = wx.arrayBufferToBase64(res.data);
this.setData({ qrUrl: "data:image/png;base64," + base64 })
}
})
直接buffer返回前端有时候不如先在后端上传到cdn,返回链接给前端