• 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);
    };
  • 相关阅读:
    电子公文传输系统-个人贡献
    电子公文传输系统团队项目 冲刺总结
    2020课程设计——个人报告
    2020课程设计——小组报告
    电子公文传输系统团队项目 描述设计
    OpenSSL中的dgst、dh、dhparam、enc命令使用说明
    用OpenSSL搭建的CA配置tomcat,部署https网站
    2020课程设计——第三周进展
    myod-系统调用版本
    20181312 2020-2021-1 《信息安全系统设计与实现(上)》用myod实现Linux下od -tx -tc功能
  • 原文地址:https://www.cnblogs.com/w-s-l123/p/13278694.html
Copyright © 2020-2023  润新知