萬盛學電腦網

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

微信公眾平台自定義選單開發完整指南:建立、查詢、刪除與 Access Token 管理

核心流程

  1. 獲取 access_token(有效期 2 小時,需快取)
  2. 呼叫選單 API:建立/查詢/刪除
  3. 處理微信回調事件(點擊、跳轉)

Access Token 管理(關鍵基礎設施)

<?php
class WeChatAccessToken
{
    private string $appId;
    private string $appSecret;
    private string $cacheKey = 'wechat_access_token';
    private int $expireBuffer = 200; // 提前 200 秒刷新

    public function __construct(string $appId, string $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getToken(): string
    {
        // 1. 嘗試從快取取得(Redis/APCu/檔案)
        $cached = $this->getFromCache();
        if ($cached && $cached['expire'] > time() + $this->expireBuffer) {
            return $cached['token'];
        }

        // 2. 向微信請求新 Token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $response = $this->httpGet($url);
        $data = json_decode($response, true);

        if (empty($data['access_token']) || !empty($data['errcode'])) {
            throw new RuntimeException("Get access_token failed: " . ($data['errmsg'] ?? $response));
        }

        // 3. 存入快取
        $this->saveToCache($data['access_token'], $data['expires_in'] ?? 7200);
        return $data['access_token'];
    }

    private function getFromCache(): ?array
    {
        // Redis 範例
        if (extension_loaded('redis')) {
            $redis = new Redis();
            $redis->connect('127.0.0.1', 6379);
            $val = $redis->get($this->cacheKey);
            return $val ? json_decode($val, true) : null;
        }
        // 檔案快取備援
        $file = sys_get_temp_dir() . '/' . $this->cacheKey . '.json';
        if (file_exists($file)) {
            return json_decode(file_get_contents($file), true);
        }
        return null;
    }

    private function saveToCache(string $token, int $expiresIn): void
    {
        $data = ['token' => $token, 'expire' => time() + $expiresIn];
        if (extension_loaded('redis')) {
            $redis = new Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->setex($this->cacheKey, $expiresIn - $this->expireBuffer, json_encode($data));
        } else {
            file_put_contents(sys_get_temp_dir() . '/' . $this->cacheKey . '.json', json_encode($data));
        }
    }

    private function httpGet(string $url): string
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => false, // 生產環境請配置 CA 憑證
            CURLOPT_SSL_VERIFYHOST => false,
        ]);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new RuntimeException('cURL error: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
}
?>

自定義選單操作類

<?php
class WeChatMenu
{
    private WeChatAccessToken $tokenManager;

    public function __construct(WeChatAccessToken $tokenManager)
    {
        $this->tokenManager = $tokenManager;
    }

    private function apiUrl(string $action): string
    {
        return "https://api.weixin.qq.com/cgi-bin/menu/{$action}?access_token=" . $this->tokenManager->getToken();
    }

    private function httpPost(string $url, string $json): array
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $json,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $result = curl_exec($ch);
        if (curl_errno($ch)) throw new RuntimeException(curl_error($ch));
        curl_close($ch);
        return json_decode($result, true);
    }

    // 建立選單
    public function create(array $menuData): array
    {
        $json = json_encode($menuData, JSON_UNESCAPED_UNICODE);
        return $this->httpPost($this->apiUrl('create'), $json);
    }

    // 查詢選單
    public function get(): array
    {
        $ch = curl_init($this->apiUrl('get'));
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10]);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }

    // 刪除選單
    public function delete(): array
    {
        return $this->httpPost($this->apiUrl('delete'), '{}');
    }
}
?>

選單結構定義(符合微信規範)

<?php
$menu = [
    'button' => [
        [
            'type' => 'click',
            'name' => '今日歌曲',
            'key' => 'V1001_TODAY_MUSIC',
        ],
        [
            'name' => '菜單',
            'sub_button' => [
                [
                    'type' => 'view',
                    'name' => '搜尋',
                    'url' => 'https://www.soso.com/',
                ],
                [
                    'type' => 'view',
                    'name' => '視頻',
                    'url' => 'https://v.qq.com/',
                ],
                [
                    'type' => 'click',
                    'name' => '贊一下我們',
                    'key' => 'V1001_GOOD',
                ],
            ],
        ],
    ],
];

// 限制:
// - 一級選單最多 3 個
// - 二級選單最多 5 個
// - 名稱:一級 ≤ 16 字元,二級 ≤ 40 字元
// - type: click(點擊推事件) | view(跳轉 URL) | miniprogram(小程序) | scancode_push 等
?>

完整建立流程範例

<?php
require 'WeChatAccessToken.php';
require 'WeChatMenu.php';

$appId = 'YOUR_APP_ID';
$appSecret = 'YOUR_APP_SECRET';

$token = new WeChatAccessToken($appId, $appSecret);
$menu = new WeChatMenu($token);

try {
    $result = $menu->create($menu);
    if (isset($result['errcode']) && $result['errcode'] !== 0) {
        throw new Exception("Menu create failed: {$result['errmsg']} (errcode: {$result['errcode']})");
    }
    echo "選單建立成功!\n";
} catch (Throwable $e) {
    echo "錯誤: " . $e->getMessage() . "\n";
}
?>

事件處理:接收使用者點擊

<?php
// 回調入口
$postStr = file_get_contents('php://input');
$xml = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

$msgType = (string)$xml->MsgType;
$event = (string)$xml->Event;
$eventKey = (string)$xml->EventKey;
$fromUser = (string)$xml->FromUserName;
$toUser = (string)$xml->ToUserName;

if ($msgType === 'event' && $event === 'CLICK') {
    $reply = match ($eventKey) {
        'V1001_TODAY_MUSIC' => getTodayMusicReply($fromUser, $toUser),
        'V1001_GOOD' => getThankYouReply($fromUser, $toUser),
        default => getDefaultReply($fromUser, $toUser),
    };
    echo $reply;
    exit;
}

function getTodayMusicReply(string $to, string $from): string
{
    return <<


%d

1


<![CDATA[今日推薦:告白氣球]]>






XML;
}
?>

常見錯誤代碼對照

errcodeerrmsg原因與解決
40018invalid button name size按鈕名稱過長(一級≤16字、二級≤40字)
40018invalid sub_button name size子按鈕名稱過長
41001access_token missingToken 遺失/過期,需重新獲取
42001access_token expiredToken 過期,重新獲取
45009api freq out of limit調用頻率超限,需緩存 Token、降低調用頻率
46003menu size too large選單 JSON 過大(>2KB),精簡內容

最佳實踐清單

  • ✅ Access Token **集中管理、快取、自動刷新**,避免重複請求導致失效
  • ✅ 選單 JSON 使用 JSON_UNESCAPED_UNICODE 避免中文轉義
  • ✅ 建立/修改選單後,**查詢驗證** 是否生效
  • ✅ 開發環境用 ngrok 內網穿透測試回調
  • ✅ 生產環境啟用 CURLOPT_SSL_VERIFYPEER 並配置 CA 憑證
  • ✅ 選單結構存入資料庫/配置檔,支援動態管理、版本控制

微信選單是用戶進入服務的第一道門面,結構清晰、回應及時、錯誤處理完善,能顯著提升用戶留存與互動率。

copyright © 萬盛學電腦網 all rights reserved