作者:興xing0_0,來自原文地址
由于項目需求,需要獲取小程序頁面的帶有參數(shù)的二維碼。好,那就看文檔搞吧。
之前都是寫前端,沒有寫過后臺的東西,這次難得有機會組長讓我試一試試用node來寫,那就寫吧。
1、首頁獲取token,發(fā)送request請求,用get的方式,在url后面加上小程序的grant_type,appid,secret,就順利拿到token了,注意,這個token是有有效時間的,小程序的是7200秒,也就是2個小時,每天獲取的次數(shù)有限,需要有個中控服務(wù)器定時獲取token,由于我的業(yè)務(wù)量小,就沒有對token進行保存了,每次都是重新獲取。
2、獲取完token之后,再發(fā)送請求獲取二維碼,坑的是,微信沒有告訴我們獲取的是二進制流,之前一直是寫前端的代碼,對流沒有概念,百度之,谷歌之,折騰了兩天,終于搞定。還遇到了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;
-
//請求二維碼的參數(shù)
-
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請求數(shù)據(jù)出錯');
-
}
-
}
-
}
-
module.exports = createQrcode;//暴露對象,調(diào)用create方法既可以創(chuàng)建二維碼
|