您的位置:首页 > 移动开发 > 微信开发

nodejs获取微信小程序带参数二维码实现代码

2017-04-12 11:11 1186 查看

nodejs获取微信小程序带参数二维码实现代码

由于项目需求,需要获取小程序页面的带有参数的二维码。好,那就看文档搞吧。

之前都是写前端,没有写过后台的东西,这次难得有机会组长让我试一试试用node来写,那就写吧。

1、首页获取token,发送request请求,用get的方式,在url后面加上小程序的grant_type,appid,secret,就顺利拿到token了,注意,这个token是有有效时间的,小程序的是7200秒,也就是2个小时,每天获取的次数有限,需要有个中控服务器定时获取token,由于我的业务量小,就没有对token进行保存了,每次都是重新获取。

2、获取完token之后,再发送请求获取二维码,坑的是,微信没有告诉我们获取的是二进制流,之前一直是写前端的代码,对流没有概念,百度之,谷歌之,折腾了两天,终于搞定。还遇到了express的坑,用原来express的代码,死活生成不了二维码,新建一个express再生成二维码就没问题,莫名其妙的坑。

上代码:

var fs = require('fs');
var request = require('request');
var wx_conf = require('../../conf/wx_conf');//这里放了微信appid跟appSecret,文件没有引入进来,要用的时候,改一下吧。
var AccessToken = {
grant_type: 'client_credential',
appid: wx_conf.appId,
secret: wx_conf.appSecret
}
var wx_gettoken_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=' + AccessToken.grant_type + '&appid=' + AccessToken.appid + '&secret=' + AccessToken.secret;
//请求二维码的参数
var postData = {
path: "pages/index/index",
width: 430
}
var createQrcode = {
create: function() {
console.log('fn:create');
this.getToken();
},
//获取微信的token
getToken: function() {
console.log('fn:getToken');
var that = this;
new Promise((resolve, reject) => {
console.log('进入Promise方法了');
request({
method: 'GET',
url: wx_gettoken_url
}, function(err, res, body) {
if (res) {
resolve({
isSuccess: true,
data: JSON.parse(body)
});
} else {
console.log (err);
reject({
isSuccess: false,
data: err
});
}
})
}).then(proData => {
that.getQrcode(proData);
});
},
//生成二维码
getQrcode: function(proData) {
console.log ('fn:getQrcode');
if (proData.isSuccess) {
postData = JSON.stringify(postData);
request({
method: 'POST',
url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + proData.data.access_token,
body: postData
}).pipe(fs.createWriteStream('./public/images/index.png'));//路径自己定义吧
} else {
console.log('Promise请求数据出错');
}
}
}
module.exports = createQrcode;//暴露对象,调用create方法既可以创建二维码

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息