微信开发环境配置
本篇文章需要配合项目食用,否则我会看的云里雾里的。
微信接入
(1)填写服务器配置
URL:URL是开发者用来接收微信消息和事件的接口URL
Token:开发者任意填写,用作生成签名【具体看验证有效性段落】
const config = { wechat: { appID: 'XXXXXX', // 自己的appID appSecret: 'XXXXXXXXXX', //自己的appSecret token: 'imoocwechatweidadepig', /* getAccessToken: function () { return util.readFileAsync(wechat_file) }, saveAccessToken: function (data) { data = JSON.stringify(data) return util.writeFileAsync(wechat_file, data) } */ }}let app = new Koa()// opts==config.wechatapp.use(we(config.wechat))}
(2)验证服务器地址的有效性
开发者提交信息后,微信服务器将发送GET请求到填写的URL地址上,发送过去的GET请求包括signature
、timestamp
、nonce
、echostr
。
token
、timestamp
、nonce
进行字典序排序然后拼接成字符串进行sha1加密,开发者获得加密后的字符串后与signature
对比,标识该请求来源于微信,如果相等,原样返回echostr
参数内容,接入成功。 let token = opts.token, signature = this.query.signature, nonce = this.query.nonce, timestamp = this.query.timestamp, echostr = this.query.echostr let str = [token, timestamp, nonce].sort().join('') let sha = sha1(str) // 接入成功 if(sha === signature) { this.body = echostr + '测试使用' } else { this.body = 'wrong' }
依据接口文档实现业务逻辑
access_token凭据
access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token,所以access_token是非常重要的。
开发者需要注意:
凭据需要进行妥善保存。
access_token的存储至少要保留512个字符空间。
access_token的有效期目前为2个小时(7200),需定时刷新。
重复获取将导致上次获取的access_token失效。
使用APPID和AppSecret调用本接口来获取access_token
https请求方式: GET
当发送请求到这个,正常情况下,微信会返回JSON数据:{"access_token":"ACCESS_TOKEN", "expires_in": 7200}。access_token表示获取到的凭证,expires_in表示凭证有效时间。
let appID = this.appIDlet appSecret = this.appSecretlet url = api.accessToken + '&appid=' + appID + '&secret=' + appSecretreturn new Promise(function (resolve, reject) { request({url: url, json: true},(function (error, response,body) { let data = response.body let now = (new Date().getTime()) let expires_in = now + (data.expires_in - 20) * 1000 data.expires_in = expires_in resolve(data) }))})
期间出现的问题
(1)程序的逻辑,没有搞通
(2)Promise的使用,resolve()的传递(3)request模块的错误使用