[TOC] #### 1. 公众号自动回复 --- 安装 easywechat 4.x扩展包 ```html composer require overtrue/wechat:~4.0 ``` 获取公众号操作对象 [https://easywechat.com/docs/4.x/official-account/index](https://easywechat.com/docs/4.x/official-account/index) #### 2. 控制器调用逻辑层方法 --- ``` <?php declare(strict_types=1); namespace app\controller; use app\logic\OfficialAccount; class Message { public function index() { $token = 'NBoqMdCbgoGNcXQSZBRSiIhyB'; OfficialAccount::message($token); } } ``` #### 3. 逻辑层 --- ``` <?php namespace app\logic; class OfficialAccount { /** * 自动回复 * * @param string $token 令牌token */ public static function message(string $token) { // 获取公众号操作实例 $account = app(\app\lib\OfficialAccount::class); // 服务器配置接入验证 $account->checkSignature($token); // 用户发送的数据包数组 $account->app->server->push(function ($message) { switch ($message['MsgType']) { case 'text': return '收到文字消息'; break; default: return ''; break; } }); $response = $account->app->server->serve(); $response->send(); } /** * 接收用户发送的数据包 * * @return array 数据包数组 */ // private static function getMessage(): array // { // // 用户发送的xml数据包 // $xml = file_get_contents('php://input'); // // 将xml数据转为对象 // $obj = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA); // // 将对象转为json字符串,再转回数组 // return json_decode(json_encode($obj), true); // } } ``` #### 4. EasyWechat 基础类库 --- ``` <?php namespace app\lib; use EasyWeChat\Factory; class OfficialAccount { /** * 初始化配置 */ public function __construct() { $config = [ 'app_id' => 'wx44afd321dc997xxx', 'secret' => '98b74d03ef0699753fe542274f508xxx', // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名 'response_type' => 'array', ]; $this->app = Factory::officialAccount($config); } // +----------------------------------------------------------- // | 公众号自动回复 // +----------------------------------------------------------- /** * 服务器配置接入验证 * * @param string $token 令牌(Token) */ public function checkSignature(string $token) { $nonce = $_GET["nonce"] ?? ''; $signature = $_GET["signature"] ?? ''; $timestamp = $_GET["timestamp"] ?? ''; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode('', $tmpArr); $tmpStr = trim(sha1($tmpStr)); if (empty($token)) die('未设置消息推送token令牌'); if (empty($signature) || empty($tmpStr) || empty($nonce)) die('非法请求!!!'); if ($tmpStr != $signature) die('签名验证错误'); isset($_GET['echostr']) ? die($_GET['echostr']) : ''; } } ```