服务端
- 使用
axios
发送 HTTP 请求 - 返回
base64
编码的字符串
import axios from 'axios'
const WECHAT_HOST = 'https://api.weixin.qq.com'
async function getwxacodeunlimit(accessToken: string, page: string, scene = '', width = 430): Promise<string> {
const { data }: { data: Buffer } = await axios.post(
`${WECHAT_HOST}/wxa/getwxacodeunlimit?access_token=${accessToken}`,
{
page,
scene,
width,
},
{
responseType: 'arraybuffer',
}
)
if (data.length < 200) {
const { errcode, errmsg } = JSON.parse(data.toString())
throw new WechatRequestError(JSON.stringify({ errcode, errmsg }))
} else {
return data.toString('base64')
}
}
因为微信接口 /wxa/getwxacodeunlimit
成功时返回的是 Buffer
,失败时返回 JSON
结构。所以这里我把返回数据统一当成 Buffer
来处理,当 data
的长度小于 200 时,就判断为获取失败。
小程序端
javascript 的代码:
// 请求服务端接口获取回来数据,{qrcodeBase64}
this.setData({ qrcodeBase64 })
wxml 的代码:
<image src="data:image/jpeg;base64,{{qrcodeBase64}}"/>
二维码就这样完美呈现啦。
结语
来回请求生成 qrcode
会耗费巨大时间,你们可以根据业务需求,把 qrcodeBase64
存起来或者转换成图片再存起来。