Brylew
V2EX  ›  Node.js

Node.js 实现微信 Token 验证

  •  
  •   Brylew · Sep 6, 2015 · 4503 views
    This topic created in 3914 days ago, the information mentioned may be changed or developed.

    通过原生 Node.js 实现微信 Token 验证。

    //引入必要包
    var http = require ('http'),
        url = require ('url'),
        crypto = require ('crypto');
    
    //创建服务器
    http.createServer (function (req, res ) {
        res.writeHead (200, {
            'Content-Type': 'text/html; charset=UTF-8'
        });
    
        // 参数转 sha1 的一系列处理
        var query = url.parse (req.url, true ).query,
            token = 'YOUR TOKEN',
            array = [token, query.timestamp, query.nonce],
            key = array.sort ().join (''),
            sha1 = crypto.createHash ('sha1').update (key ).digest ('hex');
        // sha1 处理结束
    
        if (sha1 == query.signature ) {
            res.write (query.echostr ); // 返回 echostr 实现验证
        } else {
            res.write ('Error, Token verification failed.'); // 返回错误信息
        }
        res.end ();
    }).listen ('62002'); // 监听端口,通过 Apache 或者 Nginx 转发,微信只支持 80 端口。
    

    这个是新人贴。:)

    4 replies    2015-09-07 00:24:52 +08:00
    zonghua
        1
    zonghua  
       Sep 6, 2015 via iPhone
    咦,我记得验证是需要两步的,还要一个链表翻转
    lsongdev
        2
    lsongdev  
       Sep 6, 2015 via iPhone
    Brylew
        3
    Brylew  
    OP
       Sep 7, 2015
    @zonghua 这只适用于初始化验证,没有进一步进行扩展封装。
    Brylew
        4
    Brylew  
    OP
       Sep 7, 2015
    @song940 看着像一款非常 nice 的一个 package
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5452 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 87ms · UTC 05:47 · PVG 13:47 · LAX 22:47 · JFK 01:47
    ♥ Do have faith in what you're doing.