萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

微信公眾平台接入 2048 遊戲:開源嵌入、回調處理與圖文回覆完整實作

架構設計

  1. **遊戲託管**:2048 開源碼部署在 HTTPS 域名下(微信要求 HTTPS)
  2. **事件回調**:用戶關注/發送關鍵字 → 微信推送 XML → 我方解析回覆
  3. **圖文回覆**:關鍵字「2048」觸發圖文消息,含遊戲連結

完整回調處理器

<?php
// wechat.php - 微信回調入口
define('TOKEN', 'your_token_here'); // 微信後台配置一致

$wechat = new WeChatCallback();
if (isset($_GET['echostr'])) {
    $wechat->valid(); // 驗證簽名
} else {
    $wechat->responseMsg(); // 處理業務消息
}

class WeChatCallback
{
    public function valid(): void
    {
        $signature = $_GET['signature'] ?? '';
        $timestamp = $_GET['timestamp'] ?? '';
        $nonce = $_GET['nonce'] ?? '';
        $echostr = $_GET['echostr'] ?? '';

        $tmpArr = [TOKEN, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING);
        $tmpStr = sha1(implode($tmpArr));

        if ($tmpStr === $signature) {
            echo $echostr;
        } else {
            echo 'Invalid signature';
        }
        exit;
    }

    public function responseMsg(): void
    {
        $postStr = file_get_contents('php://input');
        if (empty($postStr)) {
            echo '';
            exit;
        }

        libxml_disable_entity_loader(true); // 防 XXE
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if (!$postObj) {
            echo '';
            exit;
        }

        $msgType = trim($postObj->MsgType);
        $fromUser = trim($postObj->FromUserName);
        $toUser = trim($postObj->ToUserName);

        $reply = '';
        switch ($msgType) {
            case 'event':
                $reply = $this->handleEvent($postObj, $fromUser, $toUser);
                break;
            case 'text':
                $reply = $this->handleText($postObj, $fromUser, $toUser);
                break;
            case 'image':
            case 'voice':
            case 'video':
                $reply = $this->handleMedia($postObj, $fromUser, $toUser);
                break;
            default:
                $reply = $this->defaultReply($fromUser, $toUser);
        }

        echo $reply;
    }

    private function handleEvent(SimpleXMLElement $obj, string $from, string $to): string
    {
        $event = trim($obj->Event);
        $content = '';

        switch ($event) {
            case 'subscribe':
                $content = "歡迎關注方倍工作室!\n回覆「2048」開始遊戲\n回覆「幫助」查看更多功能";
                break;
            case 'unsubscribe':
                // 用戶取消關注,可記錄日誌
                return '';
            case 'CLICK':
                // 自定義選單點擊事件
                $key = trim($obj->EventKey);
                $content = $this->handleMenuClick($key, $from, $to);
                break;
            case 'VIEW':
                // 跳轉鏈接,無需回覆
                return '';
        }

        return $this->textReply($from, $to, $content);
    }

    private function handleText(SimpleXMLElement $obj, string $from, string $to): string
    {
        $keyword = trim($obj->Content);
        
        if (stripos($keyword, '2048') !== false) {
            return $this->gameNewsReply($from, $to);
        }

        if (stripos($keyword, '幫助') !== false || stripos($keyword, 'help') !== false) {
            return $this->textReply($from, $to, "可用指令:\n2048 - 開始遊戲\n幫助 - 顯示此訊息");
        }

        return $this->defaultReply($from, $to);
    }

    private function handleMenuClick(string $key, string $from, string $to): string
    {
        return match ($key) {
            'V1001_TODAY_MUSIC' => $this->textReply($from, $to, '今日推薦:告白氣球 - 周杰倫'),
            'V1001_GOOD' => $this->textReply($from, $to, '謝謝您的讚!❤️'),
            default => $this->defaultReply($from, $to),
        };
    }

    private function gameNewsReply(string $from, string $to): string
    {
        $gameUrl = 'https://your-domain.com/2048/'; // 必須 HTTPS
        $articles = [
            [
                'Title' => '2048 數字遊戲',
                'Description' => '經典 2048 遊戲,滑動合並相同數字,挑戰 2048!支援手機觸控操作。',
                'PicUrl' => 'https://your-domain.com/assets/2048-cover.jpg',
                'Url' => $gameUrl,
            ],
        ];
        return $this->newsReply($from, $to, $articles);
    }

    private function textReply(string $from, string $to, string $content): string
    {
        $template = <<


%d



XML;
        return sprintf($template, $from, $to, time(), $content);
    }

    private function newsReply(string $from, string $to, array $articles): string
    {
        $itemTpl = <<
<![CDATA[%s]]>




XML;

        $itemsXml = '';
        foreach ($articles as $art) {
            $itemsXml .= sprintf($itemTpl, $art['Title'], $art['Description'], $art['PicUrl'], $art['Url']);
        }

        $template = <<


%d

%d

%s


XML;

        return sprintf($template, $from, $to, time(), count($articles), $itemsXml);
    }

    private function defaultReply(string $from, string $to): string
    {
        return $this->textReply($from, $to, '收到您的訊息,回覆「2048」玩遊戲,回覆「幫助」查看功能。');
    }
}
?>

2048 遊戲部署說明

  1. 從 官方 GitHub 下載源碼
  2. 部署至 HTTPS 網站目錄(如 `/var/www/2048/`)
  3. 確保 `index.html` 可直接訪問,靜態資源路徑正確
  4. 微信後台配置「業務域名」包含遊戲域名
  5. 若需分享功能,需配置 JS-SDK 安全域名並注入簽名

進階:遊戲狀態同步(選做)

<?php
// 簡易分數排行榜 API
// POST /api/2048/score  {openid, score}
// GET  /api/2048/rank?limit=10

// 需配合微信網頁授權獲取 openid
// 前端調用 wx.login -> code -> 後端換取 openid -> 儲存分數
?>

安全性檢查清單

  • ✅ 驗證簽名(`valid()`)防止偽造請求
  • ✅ `libxml_disable_entity_loader(true)` 防 XXE 攻擊
  • ✅ 回覆內容 CDATA 包裹,防 XML 注入
  • ✅ 遊戲域名 HTTPS、配置業務域名、JS-SDK 域名
  • ✅ 限流:同一用戶 1 分鐘最多 5 次請求
  • ✅ 敏感操作(刪除選單等)需管理員驗證

測試工具

  • 微信公眾平台測試賬號(無需認證即可測試)
  • ngrok 內網穿透:`ngrok http 80` 獲取 HTTPS 回調地址
  • Postman 模擬 XML POST 測試

接入微信公眾平台的關鍵在於:簽名驗證正確、XML 解析安全、回覆格式標準、HTTPS 域名合規。2048 遊戲作為輕量級 HTML5 遊戲,極適合作為粉絲互動的入門專案。

copyright © 萬盛學電腦網 all rights reserved