微信公众平台开发



邵淳华



准备活动


我们需要什么?




  • 一个可以部署应用的地方

  • 一个可以快速学习的工具




PaaS,免费,部署方便




JavaScript in server side

AppFog


  • 安装AF、上传本地应用
gem install af af loginaf update APP_NAME
  • 查看Log
  • af logs APP_NAME [--all]

    Be a developer


    1. 填写信息
      • URL
      • TOKEN
    2. 处理微信发送的信息
      • signature: 微信加密签名
      • timestamp: 时间戳
      • nonce: 随机数
      • echostr: 随机字符串

    验证信息


    1. token, timestamp, nonce三个参数进行字典序排序
    2. 将三个参数字符串拼接成一个字符串进行sha1加密
    3. 获得加密后的字符串,与signature比较

    in Node.js

     var isLegel = function (signature, timestamp, nonce) {    var TOKEN = 'tnwechattest';
        var arr = [TOKEN, timestamp, nonce];
        // 对三个参数进行字典序排序
        arr.sort();
        // sha1 加密
        var sha1 = crypto.createHash('sha1');
        var msg = arr[0] + arr[1] + arr[2];
        sha1.update(msg);
        msg = sha1.digest('hex');
        // 验证
        if(msg == signature) {
            console.log('验证成功');
            return true;
        } else {
            console.log('验证失败');
            return false;
        }};
     

    GET request

    http.createServer(function (req, res) {
        // 获取GET请求的参数     var url_params = url.parse(req.url, true);     var query = url_params.query;     res.writeHead(200, {'Content-Type': 'text/plain'});     if(isLegel(query.signature,  query.timestamp, query.nonce)) {         // 返回echostr         res.end(query.echostr);     } else {         //          res.end('Hello world\n');    } }).listen(process.env.VCAP_APP_PORT || 3000);
     make a demo

    use wechat


    wechat是一个微信公众平台消息接口服务中间件

    • 更方便与微信服务器通讯
    • 更多的关注业务逻辑
    • 社区支持

    Response Event


    微信公众平台现在支持的事件有三种:

    subscribe、unsubscribe、click(菜单)

     app.use('/', wechat(TOKEN, function(message, req, res) {     // ... }).event(function(message, req, res) {     // 关注事件     if(message.Event == 'subscribe') {         res.reply('感谢关注途牛旅游网!么么哒~');     } }));

    Reply message


     app.use('/', wechat(TOKEN, wechat.text(function(message, req, res) {     //      var input = (message.Content || '').trim();          if(input === '你好') {         res.reply('你也好!');     } else {         res.reply('听不懂!');     } }));

    Demo


    搜索:ituniu

    Screenshot

    Screenshot


    Else?


    • 等待回复
    • 自定义菜单
    • 做个「小黄鸡」?
      • 实例:豆瓣同城

     

    THX

    微信公众平台

    By fantasyshao

    微信公众平台

    微信公众平台开发

    • 7,292