Home >WeChat Applet >WeChat Development >How to use koa2 to build a WeChat third-party public platform

How to use koa2 to build a WeChat third-party public platform

php中世界最好的语言
php中世界最好的语言Original
2018-05-29 11:22:063330browse

This time I will show you how to use koa2 to build a WeChat third-party public platform. What are the precautions for using koa2 to build a WeChat third-party public platform. The following is a practical case, let's take a look.

Before writing, I want to talk about koa first. Compared with express, koa is much better in terms of execution process and components. koa itself does not provide too many extensions, but it is convenient to build extensions. It allows you to play freely and execute code in parallel like writing other languages. If promises free up cumbersome callbacks, then when writing web applications in koa, by combining different generators, you can avoid repeating cumbersome callback functions Nesting, and greatly improves the efficiency of error handling. koa does not bind any middleware in the kernel method. It only provides a lightweight and elegant function library, making it easy to write web applications. The natural asynchronous processing process of nodejs makes it very suitable for frequent transactions such as WeChat public accounts. Message interaction, coupled with pm2's multi-process management, can be said to have largely satisfied the message forwarding interaction of large accounts and the internal red envelope gameplay of public accounts.

When using koa2 to build a WeChat third-party public platform, the first thing to solve is how to obtain the XML stream returned by WeChat and how to return the corresponding XML body to WeChat.
Since koa itself is not a framework, so thanks to the many middlewares on the Internet, I built a framework similar to express. This framework has been open source. For details, please see my git address: https:// github.com/yxz1025/koa-lana, all WeChat messages are in this framework, please download it yourself!

Okay, first of all, let’s take a look at how to get the xml stream returned by WeChat:

======tool.js=====
//截获微信返回的xml流文件
const Promise = require('bluebird');
//普通post流转化为promise
var Tool = {
  convertPost: function(req) {
    let post_data = "";
    return new Promise(function(resolve, reject){
      req.on('data', function(chunk) {
        post_data += chunk;
      });
      req.on('end', function() {
        resolve(post_data);
      });
    });
  },
};
module.exports = Tool;
=====weichat.js======
//微信响应主体文件
const router = require('koa-router')();
const parseMessage = require('../common/parseMessage');
const config = require('../config');
const WXBizMsgCrypt = require('wechat-crypto');
const middleware = require('../model/middleware');
const validator = require('validator');
const Aes = require('../common/aes');
const Tool = require('../common/tool');
const cryptor = new WXBizMsgCrypt(config.component_config.token, config.component_config.key, config.component_config.component_appid);
//第三方授权路径 /:appid/callback  /wechat/100234/callback
router.post('/:appid/callback', async function(ctx, next) {
  let post_data = "";
  let req = ctx.req;
  post_data = await Tool.convertPost(req);
  let xml = parseMessage(post_data);
  let signature = cryptor.getSignature(ctx.query.timestamp, ctx.query.nonce, xml.encrypt);
  if (ctx.query.msg_signature != signature) {
    ctx.body = 'Auth failed!'; // 指纹码不匹配时返回错误信息,禁止后面的消息接受及发送
  }
  let message = middleware.decryptXml(xml);
  let appid = ctx.params.appid;
  message.appId = appid;
  //发送消息队列
  switch (message.msgType) {
    case 'text':
      //测试
      if (message.toUserName == "gh_3c884a361561") {
        if (message.content == "TESTCOMPONENT_MSG_TYPE_TEXT") {
          let text = middleware.text(message, message.content + "_callback");
          let reply = middleware.encryptXml(text);
          return ctx.body = reply;
        }
        let content = message.content;
        if (content.indexOf("QUERY_AUTH_CODE") != -1) {
          ctx.body = "";
          let code_li = content.split(":");
          await middleware.customSend(message.fromUserName, code_li[1]);
          return;
        }
      }
      let keywords = validator.trim(message.content).toLowerCase();
      let member_config = await middleware.getMemberConfig(message.toUserName, keywords);
      if (!member_config) {
        await middleware.sendMnsQuene(message);
        return ctx.body = "success";
      }else{
         //匹配成功
        message.packetsId = parseInt(member_config.hongbaoId);
        message.keywords = keywords;
        await middleware.sendMnsQuene(message);
        let data = {
          title: member_config.news_title || '点我领红包',
          description: member_config.description || '第一轮红包雨开始了,手快有,手慢无!',
          picurl: member_config.picurl || 'http://7xqomp.com2.z0.glb.qiniucdn.com/17269743.png'
        };
        let key = {
          fromUserName: message.fromUserName,
          toUserName: message.toUserName,
          keywords: keywords,
          appId: appid
        };
        key = JSON.stringify(key);
        key = Aes.encypt(key);
        key = Aes.base64_encode(key);
        //获取授权域名
        let auth_url = await middleware.packetDomain();
        data.url = "http://" + appid + "." + auth_url + "/redPackets/koulin?key=" + key;
        let news = middleware.news(message, [data]);
        let reply = middleware.encryptXml(news);
        ctx.body = reply; 
        return;       
      }
      break;
    case 'event':
      await middleware.sendMnsQuene(message);
      //测试专用
      if (message.toUserName == "gh_3c884a361561") {
        let text = middleware.text(message, message.event + "from_callback");
        let reply = middleware.encryptXml(text);
        ctx.body = reply;
        return;
      }
      break;
    default:
      await middleware.sendMnsQuene(message);
      ctx.body = "success";
      return;
  };
});
module.exports = router;

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related topics on the PHP Chinese website article!

Recommended reading:

How to operate Koa2 WeChat public account development and build a local development and debugging environment

How to operate Koa2 WeChat public account implementation Message management

The above is the detailed content of How to use koa2 to build a WeChat third-party public platform. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn