ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 基础配置 ## 服务端安装think-weichat中间件 [https://github.com/akira-cn/think-wechat](https://github.com/akira-cn/think-wechat) ~~~ $ npm install think-wechat ~~~ ## 配置 middleware * 编辑 config/middleware.js ~~~js const path = require('path'); const wechat = require('think-wechat') const isDev = think.env === 'development'; module.exports = [ { handle: wechat, match: '/home/weixin', options: { token: 'weixin', appid: 'wxf23493b0cf5d0804', //encodingAESKey: '', //测试号不需要配置 checkSignature: true, // 可选,默认为true。由于微信公众平台接口调试工具在明文模式下不发送签名,所以如要使用该测试工具,请将其设置为false }, }, { handle: 'payload', options: { uploadDir: path.join(think.ROOT_PATH, 'runtime/data'), }, }, ]; ~~~ **注意**:think-wechat 必须要在 payload 中间件前面加载,它会代替 payload 处理微信发过来的 post 请求中的数据。 * 根据 match 配置,增加对应的 controller 和 action ## 登陆微信官方开发者中心,配置接口信息 请填写接口配置信息,此信息需要你有自己的服务器资源,填写的URL需要正确响应微信发送的Token验证,请阅读[消息接口使用指南](http://mp.weixin.qq.com/wiki/index.php?title=%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E6%8C%87%E5%8D%97)。 URL:[http://zengqingsong.oicp.net/home/weixin](http://zengqingsong.oicp.net/home/weixin) Token:weixin > 本地开发,可以使用花生壳做本地域名映射(微信公众号开发必须80端口,所以需要有公网的服务器,本地开发使用花生壳做代理) 支持的 action 包括:textAction、imageAction、voiceAction、videoAction、shortvideoAction、locationAction、linkAction、eventAction、deviceTextAction、deviceEventAction。 ## DEMO 增加控制器home/controller/weixin ``` const DEFULT_AUTO_REPLY = '功能正在开发中~'; const BaseController = require('./base.js'); module.exports = class extends BaseController { constructor(ctx) { super(ctx); } //支持的 action // 包括:textAction、imageAction、voiceAction、videoAction、shortvideoAction、locationAction、linkAction、eventAction、deviceTextAction、deviceEventAction。 // https://github.com/akira-cn/think-wechat https://github.com/node-webot/wechat //微信公众号控制器 /** * index action * @return {Promise} [] */ indexAction() { ///home/weixin/index?signature=6a8f855d69d080052142b85da4faafe149168a1d&echostr=7148202192707206511&timestamp=1558920224&nonce=418613906 // 验证开发者服务器 // 这里只是演示,所以没做签名校验,实际上应该要根据微信要求进行签名校验 const echostr = this.get('echostr'); return echostr; } textAction() { //发送文本消息 const {Content} = this.post(); //this.success('你发送给我的是:' + Content.trim()); this.success([ { title: '你来我家接我吧', description: '这是女神与高富帅之间的对话', picurl: 'http://nodeapi.cloudfoundry.com/qrcode.jpg', url: 'http://nodeapi.cloudfoundry.com/', }, ]); } eventAction() { const message = this.post(); this.success(JSON.stringify(message)); } __call() { this.success(DEFULT_AUTO_REPLY); } }; ```