js 生成二维码_实践生成带参数的小程序码

cde99ceb119ae306d2e3daa506e390f0.png

这篇文章主要介绍了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,返回图片地址

这种方式大家可以自行尝试,大概思路和第二种差不多,只不过多了一步上传到第三方云平台。

03d815e78771fa493f97b3bd19bf8a53.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值