egg公众号开发

新建项目

$ npm i egg-init -g
$ egg-init wechat_public_number_demo --type=simple
$ cd wechat_public_number_demo
$ npm i
$ npm run dev
$ open localhost:7001

接入公众号

由于配置的URL必须要域名,为了实现本地开发,本人采用Sunny-Ngrok进行端口映射,具体用法请自行百度。
**注意:**端口若不为80,则无法配置成功。
config/config.default.js

config.wechat_config = {
  token: 'wechat_public_number_demo',
};

router.js

router.get('/wechat', controller.home.fromWechat);

controller/home.js

const crypto = require('crypto');

async fromWechat() {
  const token = this.ctx.app.config.wechat_config.token;
  const query = this.ctx.query;
  const timestamp = query.timestamp;
  const nonce = query.nonce;
  const signature = query.signature;
  const echostr = query.echostr;
  const str = [ token, timestamp, nonce ].sort().join('');
  const hash = crypto.createHash('sha1');
  hash.update(str);
  const sha = hash.digest('hex');
  if (sha === signature) {
    this.ctx.body = echostr;
  }
}

package.json

"dev": "egg-bin dev --port=80",

获取access_token

config/config.default.js

appId: 'wx230f799414023398',
appSecret: '27118b180d47a9b11c094a03cea63a74',
getAccessTokenUrl: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET',

schedule/access_token.js

'use strict';

const Subscription = require('egg').Subscription;

class UpdateCache extends Subscription {
  static get schedule() {
    return {
      interval: '2h',
      type: 'all',
    };
  }

  async subscribe() {
    const config = this.ctx.app.config.wechat_config;
    const url = config.getAccessTokenUrl.replace('APPID', config.appId).replace('APPSECRET', config.appSecret);
    const res = await this.ctx.curl(url, {
      dataType: 'json',
    });
    console.log(res.data.access_token);
    this.ctx.app.access_token = res.data.access_token;
  }
}

module.exports = UpdateCache;

app.js

'use strict';

module.exports = app => {
  app.beforeStart(async () => {
    await app.runSchedule('access_token');
  });
};

自定义菜单

由于egg内置了安全插件,请求会报错,暂时的解决方案是关闭csrf检查。
config.default.js

postCreateMenuUrl: 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN',

config.security = {
  csrf: {
    enable: false,
  },
};

app.js

const menu
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值