var rp = require(request-promise);
const fs = require(fs);
var stream = require(stream);
// 请求微信access_token
rp(https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret)
.then(function(resultValue) {
console.log("请求 success:" + resultValue)
console.log(JSON.parse(resultValue).access_token)
// 请求小程序码
var http = require("http"),
data = {
// 小程序码参数
"page": "pages/CardDetail/CardDetail",
"width": 300,
"scene": "id=W6MIjlJhFW5Pec-Y",
};
data = JSON.stringify(data);
var options = {
method: "POST",
host: "api.weixin.qq.com",
path: "/wxa/getwxacodeunlimit?access_token=" + JSON.parse(resultValue).access_token,
headers: {
"Content-Type": "application/json",
"Content-Length": data.length
}
};
var req = http.request(options, function (res) {
res.setEncoding("binary");
var imgData = ;
res.on(data, function (chunk) {
imgData += chunk;
});
res.on("end", function () {
// 将返回的图片数据转化成uploadFile方法fileContent参数所需的文件流形式,且本地输出数据正常,可以试着用此方法执行uploadFile进行获取小程序码,作者采用了方法二
var bufferStream = new stream.PassThrough();
bufferStream.end(new Buffer(imgData));
console.log(uploadFile方法fileContent参数所需的文件流----)
console.log(bufferStream)
// Sublime Text可以运行输出到本地,且可以打开二维码
// 本地存放路径
var path = public/+ Date.now() +.png;
fs.writeFile(path, imgData, "binary", function (err) {
if (err) {
console.log("down fail");
}
console.log("down success");
});
});
});
req.write(data);
req.end();
})
.catch(function(err) {});