阅读 43

eggjs-对接微信公众号

 

验证Token

我们知道在微信开发时都需在公众开发配置中对Token验证一次,接下来谈谈验证的步骤

第一步确定验证URL

比如我的是https://www.jakehu.me/wechat,那么先对eggjs路由改造

1
2
3
4
5
// app/router.js

module.exports = app => {
app.router.get(‘/wechat‘, app.controller.wechat.index);
};
 

改造完路由后我们还必须对安全这块进行设置,屏蔽对路由/wechatcsrf验证
1
2
3
4
5
6
7
// config/config.default.js

config.security = {
csrf: {
ignore: ‘/wechat‘,
},
};
 

 

第二步编写验证Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// app/controller/wechat.js

async index () {
const query = this.ctx.request.query;
const signature = query.signature;
const timestamp = query.timestamp;
const nonce = query.nonce;
const echostr = query.echostr;
   if (await this.check(timestamp, nonce, signature, ‘token‘)) {
this.ctx.body = echostr;
} else {
this.ctx.body = ‘It is not from weixin‘;
}
}

async check (timestamp, nonce, signature, token) {
const tmp = [ token, timestamp, nonce ].sort().join(‘‘);
const currSign = crypto.createHash(‘sha1‘).update(tmp).digest(‘hex‘);
return (currSign === signature);
}
 

然后就可以在开发者配置进行验证就好了

注:上面代码中的token即为你在开发者配置页面中填写的token

接入开发

第一步安装必要组件

这里我们用到了co-wechat插件

1
npm i co-wechat -s
 

安装后对插件进行配置
1
2
3
4
5
6
7
// config/config.default.js

config.wechat = {
token: ‘token‘,
appid: ‘appid‘,
encodingAESKey: ‘encodingAESKey‘,
};
 

 

编写对接代码

首先是Controller的编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// app/controller/wechat.js

const wechat = require(‘co-wechat‘);
module.exports = app => {
class WechatController extends app.Controller { }

// 因为 Egg 需要用类的形式来组织,而 wechat 是通过 middleware 方法来生成中间件
WechatController.prototype.wechat = wechat({
token: ‘token‘,
appid: ‘appid‘,
encodingAESKey: ‘encodingAESKey‘,
}).middleware(async (message, ctx) => {
console.log(message);
return { type: ‘text‘, content: ‘Hello world!‘ };
});

return WechatController;
};
 

其次我们对路由再进行改造
1
2
3
4
5
// app/router.js

module.exports = app => {
app.router.post(‘/wechat‘, app.controller.wechat.wechat);
};

原文:https://www.cnblogs.com/w-s-l123/p/13278694.html

文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐