[TOC] #### 1. 公眾號自動回復(fù) --- 安裝 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. 控制器調(diào)用邏輯層方法 --- ``` <?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 { /** * 自動回復(fù) * * @param string $token 令牌token */ public static function message(string $token) { // 獲取公眾號操作實例 $account = app(\app\lib\OfficialAccount::class); // 服務(wù)器配置接入驗證 $account->checkSignature($token); // 用戶發(fā)送的數(shù)據(jù)包數(shù)組 $account->app->server->push(function ($message) { switch ($message['MsgType']) { case 'text': return '收到文字消息'; break; default: return ''; break; } }); $response = $account->app->server->serve(); $response->send(); } /** * 接收用戶發(fā)送的數(shù)據(jù)包 * * @return array 數(shù)據(jù)包數(shù)組 */ // private static function getMessage(): array // { // // 用戶發(fā)送的xml數(shù)據(jù)包 // $xml = file_get_contents('php://input'); // // 將xml數(shù)據(jù)轉(zhuǎn)為對象 // $obj = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA); // // 將對象轉(zhuǎn)為json字符串,再轉(zhuǎn)回數(shù)組 // return json_decode(json_encode($obj), true); // } } ``` #### 4. EasyWechat 基礎(chǔ)類庫 --- ``` <?php namespace app\lib; use EasyWeChat\Factory; class OfficialAccount { /** * 初始化配置 */ public function __construct() { $config = [ 'app_id' => 'wx44afd321dc997xxx', 'secret' => '98b74d03ef0699753fe542274f508xxx', // 指定 API 調(diào)用返回結(jié)果的類型:array(default)/collection/object/raw/自定義類名 'response_type' => 'array', ]; $this->app = Factory::officialAccount($config); } // +----------------------------------------------------------- // | 公眾號自動回復(fù) // +----------------------------------------------------------- /** * 服務(wù)器配置接入驗證 * * @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('未設(shè)置消息推送token令牌'); if (empty($signature) || empty($tmpStr) || empty($nonce)) die('非法請求?。?!'); if ($tmpStr != $signature) die('簽名驗證錯誤'); isset($_GET['echostr']) ? die($_GET['echostr']) : ''; } } ```