zoukankan      html  css  js  c++  java
  • 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);
    };
  • 相关阅读:
    Length of Last Word
    Remove Duplicates from Sorted Array II
    Sum Root to Leaf Numbers
    Valid Parentheses
    Set Matrix Zeroes
    Symmetric Tree
    Unique Binary Search Trees
    110Balanced Binary Tree
    Match:Blue Jeans(POJ 3080)
    Match:Seek the Name, Seek the Fame(POJ 2752)
  • 原文地址:https://www.cnblogs.com/w-s-l123/p/13278694.html
Copyright © 2011-2022 走看看