async getAccessToken() {
return new Promise(async(resolve, reject) => {
const model = think.model('mp_weixin');
const sqlToken = await model.find();
const expTime = (new Date()).getTime() + 7200000;
if (!sqlToken.exp_time || (sqlToken.exp_time && parseInt(sqlToken.exp_time) < expTime)) {
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.weixin.appid}&secret=${config.weixin.secret}`;
const result = await request(url, { method: 'GET' });
if (result && result.statusCode === 200) {
const data = typeof result.body === 'string' ? JSON.parse(result.body) : result.body;
const params = { ...data, exp_time: expTime };
if (!sqlToken.id) {
model.add(params);
} else {
model.where({id: sqlToken.id}).update(params);
}
resolve(data);
}
} else {
resolve(sqlToken);
}
});
}
async getQrCode(goodsId, accessToken) {
return new Promise(async(resolve, reject) => {
const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
var postData = {
path: 'pages/goods/goods',
scene: encodeURI(`id=${goodsId}`),
width: 200,
is_hyaline: true
};
const result = await request(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify(postData)
});
if (result && result.statusCode === 200) {
resolve(result.body);
} else {
reject(result);
}
});
}
async qrcodePosterAction() {
const goodsId = this.get('goods_id');
const accesssToken = await this.getAccessToken();
const qrCode = await this.getQrCode(goodsId, accesssToken.access_token);
const qrcodeBuffer = Buffer.from(qrCode, 'base64');
console.log(qrcodeBuffer, qrcodeBuffer.length, '//////////qrcodeBuffer');
fs.writeFileSync(`${think.ROOT_PATH}/www/static/qrcode_${new Date().getTime()}.png`, qrcodeBuffer, (error) => {
console.log(error, '///////e');
});
}
二维码接口不一定返回图片,没做判断
这是think.js 做服务端 还请各位大佬解惑