当前位置: 首页 > 后端技术 > Node.js

node微信开发简单学习

时间:2023-04-04 01:32:37 Node.js

微信开发环境配置可参考微信公众平台。这篇文章需要结合项目使用,否则我会一头雾水。微信接入(1)填写服务器配置URL:URL是开发者接收微信消息和事件的接口URLToken:开发者可以任意填写,用于生成签名【详见验证有效性部分】]constconfig={wechat:{appID:'XXXXXX',//自己的appIDappSecret:'XXXXXXXXXX',//自己的appSecrettoken:'imoocwechatweidadepig',/*getAccessToken:function(){returnutil.readFileAsync(wechat_file)},saveAccessToken:function(data){data=JSON.stringify(data)returnutil.writeFileAsync(wechat_file,data)}*/}}letapp=newKoa()//opts==config.wechatapp.use(we(config.wechat))}(2)验证服务器地址合法性开发者提交信息后,微信服务器会向填写的URL地址发送GET请求,过去发送的GET请求包括签名、时间戳、nonce和echostr。开发者通过将token、timestamp、nonce按字典顺序拼接成字符串进行sha1加密,得到加密后的字符串,与签名进行比对,判断请求来自微信。如果相等,则原样返回echostr参数的内容,则进入成功。让token=opts.token,signature=this.query.signature,nonce=this.query.nonce,timestamp=this.query.timestamp,echostr=this.query.echostr让str=[token,timestamp,nonce].sort().join('')letsha=sha1(str)//访问成功if(sha===signature){this.body=echostr+'testuse'}else{this.body='wrong'}根据接口文档实现业务逻辑access_token凭证access_token是公众号全局唯一的接口调用凭证,公众号调用各个接口时都需要access_token,所以access_token非常重要。开发人员注意:凭证需要保持安全。access_token的存储必须至少预留512个字符。access_token的有效期目前是2小时(7200),需要定时刷新。重复获取会使上次获取的access_token失效。使用APPID和AppSecret调用此接口获取access_tokenhttpsRequest方法:GEThttps://api.weixin.qq.com/cgi...向此发送请求时,一般情况下微信会返回JSON数据:{"access_token":“ACCESS_TOKEN”,“expires_in”:7200}。access_token表示获取的证书,expires_in表示证书的有效时间。让appID=this.appIDletappSecret=this.appSecretleturl=api.accessToken+'&appid='+appID+'&secret='+appSecretreturnnewPromise(function(resolve,reject){request({url:url,json:true},(function(error,response,body){letdata=response.bodyletnow=(newDate().getTime())letexpires_in=now+(data.expires_in-20)*1000data.expires_in=expires_inresolve(data)}))})过程中的问题(1)程序逻辑不清晰(2)Promise的使用,resolve()的传递(3)request模块的错误使用