Swoole coroutines have evolved to 4.0 and now support all PHP functions. It can be used directly in the production environment. Swoole coroutine is a technique that speeds up by reducing I/O congestion, statistical coroutine scheduling reduces I/O congestion and lets your program fly. Wechat public number management, small program management, this kind of program for IO operation is quite frequent. So using Swoole coroutines can greatly increase the accountability and speed of programs.

Install EasySwoole

EasySwoole is a particularly good project. It is difficult for Swoole beginners to read documents directly and understand them, but learning to use them through EasySwoole and then deepening their understanding of Swoole is a good way to quickly understand coroutine technology. EasySwoole provides many teaching videos and cases, which are very helpful for beginners.

Easyswoole /easyswoole PHP vendor/bin/easyswoole install PHP composer require easyswoole/easyswoole PHP vendor/bin/easyswoole installCopy the code

2. Install the wechat SDK

EasySwoole has a special wechat SDK that can be installed directly

# # to install the Sdk composer require easyswoole/wechat WeChat Sdk demo address: https://github.com/RunsTp/EasySwooleWeChatDemoCopy the code

3. Sign up for wechat services

The registration service is a bit awkward for beginners to understand. In fact, EasySwoole’s way is easy to understand, it is code in memory. What is code in memory? The most popular Laravel program code is written in the file store, the program will execute the code in the program each time, EasySwoole is to store the code in memory, after running the code will always be stored in memory. Laravel When you modify the code in the file your program will automatically execute the new code. EasySwoole changes the code in the file. Programs that are executing do not change and need to be restarted to get the new code. We can also find that Laravel’s memory consumption is relatively small and CPU beats are relatively large. In EasySwoole, the CPU does not move much, but the memory consumption is relatively large when running.

Here is the service registration in easysWooleEvent.php:

SQL > select * from 'db'; SQL > select * from 'db'; SQL > select * from 'db'; $weChatList = Config::getInstance()->getConf('GONG_ZHONG_HAO'); If (count($weChatList)>0){foreach ($weChatList as $key => $value) {$temp = WeChatManager::getInstance()->weChat($value['appId']); #WeChatManager is an object manager for quickly retrieving public id objects. $weChat = $temp->officialAccount()->server(); $weChat = $temp->officialAccount()->server(); Logger::getInstance()->console('debug', false); $weChat->onMessage() ->set(RequestConst::MSG_TYPE_TEXT, Function (RequestMsg $RequestMsg) {# TextMessageHandler monitoring class return TextMessageHandler: : handle ($RequestMsg); }); // Different from regular messages, the event class uses the onEvent method to register the processing mechanism. $subscribe ->onSubscribe(function (RequestMsg $RequestMsg){#EventMessageHandler EventMessageHandler::subscribe($requestMsg); }); $weChat->onEvent() ->set(RequestConst::DEFAULT_ON_EVENT,function (RequestMsg $RequestMsg){ # EventMessageHandler monitoring class return EventMessageHandler: : handle ($requestMsg); }); }}Copy the code

4. Create a wechat management control

Wechat management control is actually referred to WeChatManager class. Of course, if you only need to manage a public number, actually do not use this class. But since you’re a programmer, don’t underestimate your power. Figure out how to configure the public number this is still very simple for you.

Here is the main code in the class:

Class WeChatManager {// Use Singleton; Private $weChatList = []; private $weChatList = []; Private function register(string $appId): WeChat { $weChatList = Config::getInstance()->getConf('GONG_ZHONG_HAO'); $configArray = false; foreach ($weChatList as $key => $value) { if($appId == $value['appId']){ $configArray = [ 'appId' => $value['appId'], 'appSecret' => $value['appSecret'], 'token' => $value['token'], 'AesKey' => $value['AesKey'], ]; } } if(! $configArray){throw new RuntimeException(' public id does not exist.'); } $weChatConfig = new \EasySwoole\WeChat\Config(); $weChatConfig->setTempDir(Config::getInstance() ->getConf('TEMP_DIR')); $weChatConfig->officialAccount($configArray); $weChat = new WeChat($weChatConfig); $this->weChatList[$appId] = $weChat; return $weChat; Public function weChat(string $appId): WeChat { if (isset($this->weChatList[$appId])) { return $this->weChatList[$appId]; }else{ return $this->register($appId); }}}Copy the code

5. Create wechat interactive interface

After service registration and management controls are completed, it can only be said that the system can use SDK to process wechat messages. But as we all know, we need two interfaces to communicate with wechat.

$routeCollector->get('/token/{appId}', '/WeChat/Index/token'); $routeCollector->post('/token/{appId}', '/WeChat/Index/message');Copy the code

There are two interfaces in the route: GET and POST. One is message validation and the other is data interaction.

Data verification:

Public function token() {// Create AccessCheck Bean object $accessCheckBean = new AccessCheck($this->request()->getRequestParam()); $weChat = WeChatManager::getInstance() ->weChat($this->request()->getRequestParam('appId')); $verify = $weChat->officialAccount() ->server() ->accessCheck($accessCheckBean); If ($verify) {// Respond to Code 200 as per wechat convention and print the calculated value in the Body $this->response()->withStatus(Status::CODE_OK); $this->response()->write($accessCheckBean->getEchostr()); $this->response()->end(); }Copy the code

Data interaction:

Public function message() {$accessCheckBean = new AccessCheck($this->request()->getRequestParam()); $weChat = WeChatManager::getInstance() ->weChat($this->request()->getRequestParam('appId')); $rawContent = $this->request() ->getBody(); $XML = $WeChat -> Server (); $XML = $WeChat ->officialAccount(); ->parserRequest($rawContent); } $Throwable (Throwable $Throwable) {// TODO: Logger::getInstance() ->log('DEBUG -f ',Logger::LOG_LEVEL_INFO,'DEBUG'); } $this->response()->withStatus(Status::CODE_OK); $this->response()->write($XML ?? 'success'); }Copy the code

6. Business logic processing class (monitoring class)

The token function is used to verify the authenticity of wechat third-party server, and the main interaction is still in the message function. At this time a complete wechat tripartite management cycle has been built. The message is sent from the wechat server to the message function by request. The registered service is returned to the monitoring class. All you have to do is edit the monitor class for data processing and callback.

Below add first concern: EventMessageHandler: : subscribe ($requestMsg);

public static function subscribe(RequestMsg $requestMsg) { $openid = $requestMsg->getFromUserName(); Logger::getInstance()->console('---subscribe---', false); $reply = new Text(); $reply->setContent(self::$return); $user = WechatModel::create() ->where('openid',$openid) ->get(); if(! $user){ WechatModel::create()->data([ 'openid'=>$openid, 'keyword'=>uniqid(), 'update_time'=>time(), 'create_time'=>time() ], false)->save(); } return $reply; }Copy the code

7. Docking test

Will be third party entrance into the public’s own server address: https://127.23.132.89/token/ {appId} and then look to see your own data tables