这篇文章主要介绍了node实现生成带参数的小程序二维码并保存到本地功能,涉及nodejs模块引用、接口调用、编码转换、图片生成等相关操作技巧,需要的朋友可以参考下。
首先第一步,我们需要从接口https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 获取access_token
然后从接口获取返回的图片 Buffer
POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
这里介绍几种方式展示获取小程序码
1. 第一种 图片+base64渲染方式
后端直接返回数据,前端使用image+base64渲染
相关代码如下:
async getAccessToken() { return new Promise(async resolve => { const appSecret = '你的appSecret'; const appId = '你的appId'; request .get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`) .end(async (err, res) => { if (err) console.log('err :>> ', err); const result = JSON.parse(res.text); if (result.access_token) { resolve(result.access_token); } }); }); } async createProcess(data) { return new Promise(async (resolve, reject) => { const accessToken = await this.getAccessToken(); const options = { url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`, method: 'POST', body: { scene: `phone=${data.phone}`, page: 'pages/index/index', }, json: true, encoding: null, }; aRequest(options, (error, response) => { // Do more stuff with 'body' here if (error) reject(error); // 处理响应,编码成base64 const type = response.headers['content-type']; const prefix = 'data:' + type + ';base64,'; const base64 = Buffer.from(response.body, 'binary').toString('base64'); const src = prefix + base64; resolve(src); }); }); } // 根据用户手机生成小程序二维码 async createWxQrcode(data) { return await this.createProcess(data); }
上面为Nestjs代码示例,其中aRequest为请求库request,然后返回给前端src就可以直接显示了。
2. 第二种 服务器图片地址
后端生成图片后返回服务器图片地址
需要的源代码:
https://github.com/eelaix/woyaocd
tools目录下,
qrcodemaker1.js B型二维码生成器
qrcodemaker2.js C型二维码生成器
3. 后端生成图片后上传文件云,类似oss,返回图片地址
这种方式大家可以自行尝试,大概思路和第二种差不多,只不过多了一步上传到第三方云平台。