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

May 29, 2018 am 11:22 AM
koa2 build third party

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;
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
How to quickly build a statistical chart system under the Vue framework How to quickly build a statistical chart system under the Vue framework Aug 21, 2023 pm 05:48 PM

How to quickly build a statistical chart system under the Vue framework. In modern web applications, statistical charts are an essential component. As a popular front-end framework, Vue.js provides many convenient tools and components that can help us quickly build a statistical chart system. This article will introduce how to use the Vue framework and some plug-ins to build a simple statistical chart system. First, we need to prepare a Vue.js development environment, including installing Vue scaffolding and some related plug-ins. Execute the following command in the command line

PyCharm usage guide: Import third-party libraries with one click PyCharm usage guide: Import third-party libraries with one click Feb 21, 2024 am 10:33 AM

PyCharm is an integrated development environment that is widely welcomed by developers. It provides a wealth of functions and tools to make Python development more efficient and convenient. Among them, one-click import of third-party libraries is a very practical function of PyCharm, which can help developers quickly import the required external libraries and improve development efficiency. This article will introduce you to the usage guide of PyCharm's one-click import of third-party libraries, and provide specific code examples. 1. Open PyCharm First, open PyCharm and enter

Can buildings be built in the wild in Mistlock Kingdom? Can buildings be built in the wild in Mistlock Kingdom? Mar 07, 2024 pm 08:28 PM

Players can collect different materials to build buildings when playing in the Mistlock Kingdom. Many players want to know whether to build buildings in the wild. Buildings cannot be built in the wild in the Mistlock Kingdom. They must be within the scope of the altar. . Can buildings be built in the wild in Mistlock Kingdom? Answer: No. 1. Buildings cannot be built in the wild areas of the Mist Lock Kingdom. 2. The building must be built within the scope of the altar. 3. Players can place the Spirit Fire Altar by themselves, but once they leave the range, they will not be able to construct buildings. 4. We can also directly dig a hole in the mountain as our home, so we don’t need to consume building materials. 5. There is a comfort mechanism in the buildings built by players themselves, that is to say, the better the interior, the higher the comfort. 6. High comfort will bring attribute bonuses to players, such as

Quickly install PyTorch in PyCharm: an easy guide Quickly install PyTorch in PyCharm: an easy guide Feb 24, 2024 pm 09:54 PM

PyTorch Installation Guide: Quickly set up a development environment in PyCharm PyTorch is one of the most popular frameworks in the current field of deep learning. It has the characteristics of ease of use and flexibility, and is favored by developers. This article will introduce how to quickly set up the PyTorch development environment in PyCharm, so that you can start the development of deep learning projects. Step 1: Install PyTorch First, we need to install PyTorch. The installation of PyTorch usually needs to take into account the system environment

Best practices and precautions for building a web server under CentOS 7 Best practices and precautions for building a web server under CentOS 7 Aug 25, 2023 pm 11:33 PM

Best practices and precautions for building web servers under CentOS7 Introduction: In today's Internet era, web servers are one of the core components for building and hosting websites. CentOS7 is a powerful Linux distribution widely used in server environments. This article will explore the best practices and considerations for building a web server on CentOS7, and provide some code examples to help you better understand. 1. Install Apache HTTP server Apache is the most widely used w

Understand the installation status of third-party plug-ins for edge browsers Understand the installation status of third-party plug-ins for edge browsers Dec 23, 2023 pm 06:25 PM

The number of extension plug-ins on the edge browser is relatively small and it is difficult to meet the daily use of all users. At this time, third-party plug-ins need to be installed. So, can it be installed on the edge browser? Let’s take a look below. Can third-party plug-ins be installed in the edge browser? Answer: Yes. The new version of edge cannot quickly install plug-ins by dragging and dropping directly. When dragging the crx extension file to the developer page, edge will default to saving the file as a file, making it impossible to install it directly. 1. Move the file to the edge extension application folder and rename it to zip format, and unzip it. 2. The extended functions of the new version of Edge can be seen in the taskbar by clicking the three dots in the upper right corner. 3. Open "Developer Mode" on the extension page

What's the best way to set up a Douyin account? What is the five-piece account creation kit? What's the best way to set up a Douyin account? What is the five-piece account creation kit? Apr 02, 2024 am 09:52 AM

With the rapid development of mobile Internet, the short video application Douyin has become an indispensable part of people's daily lives. Having a popular Douyin account can not only attract the attention of fans, but also bring commercial value. So, how to set up the best Douyin account? 1. What is the best way to set up a Douyin account? 1. Clear positioning When creating a Douyin account, you must first clarify your positioning. Do you want to be a funny joker or a professional knowledge sharer? Clear positioning can help attract precise fans, thereby increasing the value of your account. 2. Account naming: A good account name can make fans remember you at a glance. The account name should be concise and clear, related to your positioning, and have a certain degree of creativity. Avoid using names that are too common to avoid confusion with others

How to build an account matrix? What are the functions of matrix construction? How to build an account matrix? What are the functions of matrix construction? Mar 23, 2024 pm 06:46 PM

In today's information-rich era, social media platforms have become the main way for people to obtain and share information. For individuals and enterprises, establishing an effective account network to achieve maximum dissemination of information and enhance influence has become an urgent challenge that needs to be solved. 1. How to build an account matrix? 1. Clarify the target audience. Before building an account matrix, the key is to clearly define the target audience and gain an in-depth understanding of their needs, interests, and consumption habits, so that a more targeted content strategy can be developed. 2. Choose the appropriate platform. According to the characteristics of the target group, choose the appropriate social media platform for layout. Currently, the mainstream social media platforms include Weibo, WeChat, Douyin, Kuaishou, etc. Each platform has its own unique user groups and communication characteristics, and the selection needs to be based on the actual situation.

See all articles