发布于 2017-05-10 13:04:25 | 295 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Node.JS入门教程,程序狗速度看过来!

Node.js 服务器端的JavaScript

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用


这篇文章主要介绍了nodejs获取微信小程序带参数二维码实现代码的相关资料,需要的朋友可以参考下

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方法既可以创建二维码 

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务