var express = require('express');
var router = express.Router();
const crypto = require('crypto');
/* GET home page. */
router.get('/wechat/hello', function (req, res, next) {
res.render('index', {title: 'hello Wechat'});
});
const token = 'lK67K01kkC3X8Te2EN6d0qkd7s9RBRf9';
const handleWechatRequst = function (req, res, next) {
const {signature, timestamp, nonce, echostr}= req.query;
if (!signature || !timestamp || !nonce) {
return res.send('invalid request');
}
if ('POST' === req.method) {
console.log('handleWechatRequst.post:', {body: req.body, query: req.query});
}
if ('GET' === req.method) {
console.log('handleWechatRequst.get:', {body: req.body});
if (!echostr) {
return res.send('invalid request');
}
}
const params = [token, timestamp, nonce];
params.sort();
const hash = crypto.createHash('sha1');
const sign = hash.update(params.join('')).digest('hex');
if (signature === sign) {
console.log('~~~~~~~~~~~~~~~~~~~1');
if ('GET' === req.method) {
console.log('~~~~~~~~~~~~~~~~~~~2');
res.send(echostr ? echostr : 'invaid sign');
} else {
console.log('~~~~~~~~~~~~~~~~~~~3');
const tousername = req.body.xml.tousername[0].toString();
const fromusername = req.body.xml.fromusername[0].toString();
const createtime = Math.round(Date.now() / 1000);
const msgtype = req.body.xml.msgtype[0].toString();
const content = req.body.xml.content[0].toString();
const msgid = req.body.xml.msgid[0].toString();
console.log('~~~~~~~~~~~~~~~~~~~4');
console.log(tousername);
console.log(fromusername);
console.log(createtime);
console.log(msgid);
const response = `<xml>
<ToUserName> <![CDATA[${fromusername}]]> </ToUserName>
<FromUserName> <![CDATA[${tousername}]]> </FromUserName>
<CreateTime >${createtime}</CreateTime>
<MsgType> <![CDATA[${msgtype}]]> </MsgType>
<Content> <![CDATA[${content}]]> </Content>
</xml>`;
res.set('Content-Type', 'text/xml');
res.send(response);
}
} else {
res.send('invaid sign');
}
};
router.get('/api/wechat', handleWechatRequst);
router.post('/api/wechat', handleWechatRequst);
module.exports = router;
微信公众号认证 express 代码
最新推荐文章于 2020-09-29 11:01:13 发布