#### 1. 小程序消息推送簡(jiǎn)介 --- 啟用小程序的消息推送后小程序收到的消息將推送至開(kāi)發(fā)者的設(shè)置的服務(wù)器地址 例如:用戶(hù)關(guān)注公眾號(hào)、用戶(hù)給小程序的客服會(huì)話(huà)發(fā)送消息 EasyWechat 3.x : [https://easywechat.com/docs/3.x/overview](https://easywechat.com/docs/3.x/overview) 更多內(nèi)容參考微信官方文檔:[https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html) #### 2. 開(kāi)啟小程序消息推送 --- **登錄小程序管理平臺(tái),找到 `開(kāi)發(fā)管理-開(kāi)發(fā)設(shè)置` 中的消息推送** ![](https://img.itqaq.com/art/content/db2dbd62c68cc76487afb3e6f9e69598.png) **消息加密方式設(shè)置為`明文模式`, 數(shù)據(jù)格式設(shè)置為 `JSON`** ![](https://img.itqaq.com/art/content/6b9a230bf09ae3cb5cca43f5caca13d5.png) #### 3. 小程序消息推送接入驗(yàn)證 --- **在小程序管理平臺(tái)設(shè)置消息推送配置時(shí),點(diǎn)擊 `提交` 可能會(huì)出現(xiàn): `Token校驗(yàn)失敗,請(qǐng)檢查確認(rèn)`** 原因分析:點(diǎn)擊`提交`,微信服務(wù)器會(huì)請(qǐng)求填寫(xiě)的 `URL(服務(wù)器地址)`,并攜帶一些參數(shù)進(jìn)行接入驗(yàn)證 我們需要接收傳遞的參數(shù)進(jìn)行加密,然后做簽名校驗(yàn),最后輸出 `echostr` 參數(shù)的值,這樣才能驗(yàn)證成功 ```php 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('非法請(qǐng)求?。?!'); if ($tmpStr != $signature) die('簽名驗(yàn)證錯(cuò)誤'); isset($_GET['echostr']) ? die($_GET['echostr']) : ''; } ``` #### 4. 客服會(huì)話(huà)自動(dòng)回復(fù) --- 文本消息 ```php $message = new \EasyWeChat\Message\Text(['content' => '未設(shè)置客服二維碼']); ``` 圖片消息 ```php $image = '';//本地圖片絕對(duì)路徑 $result = $app->material_temporary->uploadImage($image);// 上傳臨時(shí)素材 $message = new \EasyWeChat\Message\Image(['media_id' => $result['media_id']]); ``` ``` $token = ''; checkSignature($token); $message = json_decode(file_get_contents('php://input'), true); $app = \app\lib\EasyWechat::getInstance()->app; switch ($message['MsgType']) { case 'miniprogrampage': // 小程序卡片 $openid = $message['FromUserName']; // 自動(dòng)回復(fù)圖片 $image = getValue('kefu_qrcode'); if ($image) { // 上傳臨時(shí)素材 $result = $app->material_temporary->uploadImage($image); $content = new Image(['media_id' => $result['media_id']]); } else { $content = new Text(['content' => '未設(shè)置客服二維碼']); } // 發(fā)送消息 $app->staff->message($content)->to($openid)->send(); break; } $response = $app->server->serve(); $response->send(); ```