获取二维码,小程序
获取小程序二维码接口 https://developers.weixin.qq.com/miniprogram/dev/api/qrcode.html
我的代码如下
// 获取小程序指定页面的二维码
const axios = require('axios');
const fs = require('fs');
// 1.首先获取 access_token
const APPID = '小程序AppID';
const APPSECRET = '小程序AppSecret';
// 获取 accessToken
getToken()
.then(res => {
// 根据access_token 获取二维码
return getQRCode(res.access_token);
})
.then(data => {
if (data.errcode) {
console.error(data);
return;
}
// 此处如何将返回的数据流保存为图片???????????
console.log(data);
});
// 获取access_token
function getToken() {
return new Promise(function (resolve) {
axios
.get('https://api.weixin.qq.com/cgi-bin/token', {
params: {
grant_type: 'client_credential',
appid: APPID,
secret: APPSECRET
}
})
.then(response => response.data)
.then(function (data) {
resolve(data);
});
});
}
// 获取二维码
function getQRCode(access_token) {
const GET_WXACODE_UNLIMIT = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=`;
let params = {
scene: 'goodsId=123412',
page: 'pages/product/index',
width: 430,
auto_color: false,
line_color: { "r": "0", "g": "0", "b": "0" }
};
console.log(JSON.stringify(params));
return new Promise(function (resolve, reject) {
axios
.post(GET_WXACODE_UNLIMIT + access_token, params)
.then(response => response.data)
.then(function (data) {
resolve(data);
});
});
}
上述代码中 console.log(data); 的结果大致如下
请教各位大神,我如何把返回的数据流保存为图片?
5 回复
写入一个文件中
@peasonlee 我使用的是 fs.writeFile(‘a.png’, data) 最后这个 a.png 打不开,看不了
如果是想把二维码返回给前端,直接把data返回给GET路由就行
this.type = 'image/jpeg'
this.status = 200
this.body = data
app.get('/qrcode', async (req, res, next) => {
const type = req.query.type || 'item';
const id = req.query.id || 1;
try {
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`
const result = await axios.get(url);
const data = result.data;
const accessToken = data.access_token;
const qrUrl = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
const obj = {
scene: `${type}-${id}`,
page: 'pages/video/video'
};
const qrResult = await axios({
method: 'post',
responseType:'stream', // very very very very very very very very important
url: qrUrl,
data: obj
});
const qrData = qrResult.data;
qrData.pipe(fs.createWriteStream('./' + 1 + '.png'));
res.json({success: true});
} catch (e) {
next(e);
}
});
@tsq 正解。非常感谢!!!