微信公众号认证 express 代码

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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值