oo10 / bs-weixin

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Node.js的微信公众号开发

使用nodejs+express进行微信开发

环境

  • node.js 最新版本
  • redis 最新版本
  • express.js 4.x

安装

//install
$npm install

修改微信信息:config.js

exports.WX = {
    TOKEN: "xxxxxx",
    APPID: "xxxxxx",
    APPSECRET: "xxxxxx"
};

修改成自己申请的公众号的token和appid和appsecret即可。

//start
$npm start

启动的端口为8888,在bin\www文件修改,访问

http://localhost:8888/weixin/index.html

有结果说明成功。

###外网映射

下载ngrock,官方有配置使用说明。再次访问映射外网的地址测试验证:

http://外网域名/weixin/index.html

##开发步骤

开发模式接入

  • 第一步:填写服务器配置

按照官方文档完成配置《接入指南》

URL地址填写上面:http://外网域名/weixin/index.html

  • 第二步:验证服务器地址的有效性

routes目录下的weixin.js"/index\.html"路由函数中:

if(this.req.method === "GET"){
    var signature = this.get("signature");
    var timestamp = this.get("timestamp");
    var nonce = this.get("nonce");
    var echostr = this.get("echostr");

    if(WeiXinUtil.checkSignature(signature, timestamp, nonce)){
        this.res.end(echostr);
    }else{
        this.res.end("hello");
    }
}

验证有效性的请求为GET请求,该请求由微信服务器请求,所以放在GET中处理。

微信服务器向我们的服务发送了四个参数:signaturetimestampnonceechostr,我们需要对signature进行验证,验证方法在

WeiXinUtil.checkSignature

函数中,

/**
 * 验证signature
 * @param signature
 * @param timestamp
 * @param nonce
 * @returns {boolean}
 */
checkSignature: function(signature, timestamp, nonce){
    var arr = [token, timestamp, nonce];
    arr.sort();

    var content = arr.join("");
    return sha1(content) === signature;
}

sha1为npm的sha1

最终将echostr返回给微信服务器

About


Languages

Language:JavaScript 61.8%Language:HTML 29.0%Language:CSS 9.2%Language:Batchfile 0.0%