access_token(有效期 2 小時,需快取)<?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
-
XML;
}
?>
| errcode | errmsg | 原因與解決 |
|---|---|---|
| 40018 | invalid button name size | 按鈕名稱過長(一級≤16字、二級≤40字) |
| 40018 | invalid sub_button name size | 子按鈕名稱過長 |
| 41001 | access_token missing | Token 遺失/過期,需重新獲取 |
| 42001 | access_token expired | Token 過期,重新獲取 |
| 45009 | api freq out of limit | 調用頻率超限,需緩存 Token、降低調用頻率 |
| 46003 | menu size too large | 選單 JSON 過大(>2KB),精簡內容 |
JSON_UNESCAPED_UNICODE 避免中文轉義ngrok 內網穿透測試回調CURLOPT_SSL_VERIFYPEER 並配置 CA 憑證微信選單是用戶進入服務的第一道門面,結構清晰、回應及時、錯誤處理完善,能顯著提升用戶留存與互動率。