本教程假設讀者具備 PHP 基礎、MySQL 基本操作、HTTP/XML/JSON 基礎。以「方倍工作室」公眾號為例,手把手帶你完成:SAE 雲部署、開發模式啟用、基礎消息接口、PHP SDK 封裝、天氣查詢功能開發。

wechat-weather),將成二級域名 wechat-weather.sinaapp.com。

index.php(見下),壓縮為 index.zip 上傳。



<?php
/**
* 微信公眾平台驗證入口
* 方倍工作室 https://www.cnblogs.com/txw1958/
*/
define("TOKEN", "weixin");
$wechatObj = new WechatCallbackApiTest();
if (isset($_GET['echostr'])) {
// 首次驗證請求
$wechatObj->valid();
} else {
// 業務消息處理
$wechatObj->responseMsg();
}
class WechatCallbackApiTest {
public function valid() {
$echoStr = $_GET["echostr"];
if ($this->checkSignature()) {
echo $echoStr; // 原樣返回 echostr,驗證通過
exit;
}
}
private function checkSignature() {
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
return $tmpStr == $signature;
}
public function responseMsg() {
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)) {
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if ($keyword == "?" || $keyword == "?") {
$msgType = "text";
$contentStr = date("Y-m-d H:i:s", $time);
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
} else {
echo "";
exit;
}
}
}
?>



if (strpos($keyword, "天氣") === 0) {
$city = trim(substr($keyword, 2));
$weather = $this->getWeather($city);
$contentStr = $weather ? $weather : "查詢失敗,請檢查城市名";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, "text", $contentStr);
echo $resultStr;
}
private function getWeather($city) {
$key = "YOUR_API_KEY";
$url = "https://api.tianapi.com/tianqi/index?key=$key&city=" . urlencode($city);
$json = @file_get_contents($url);
if (!$json) return false;
$data = json_decode($json, true);
if ($data['code'] != 200) return false;
$w = $data['newslist'][0];
return "{$w['date']} {$w['week']}\n{$w['city']} 天氣:{$w['weather']}\n溫度:{$w['real']}°C\n風向:{$w['wind']}\n濕度:{$w['humidity']}%";
}
wechat-php-sdk、EasyWeChat(Laravel 首選),封裝簽名驗證、消息解析、客服接口、素材管理、支付等。| 現象 | 原因 | 解決 |
|---|---|---|
| 驗證失敗 | Token 不一致、URL 不可訪問、輸出多餘空白字符 | 核對 Token、瀏覽器直訪 URL、ob_clean() |
| 用戶收不到回復 | 超時(>5s)、XML 格式錯誤、未返回 echostr | 異步化、xml 輸出檢查、驗證邏輯正確 |
| SAE 部署 403/500 | 代碼語法錯誤、權限、缺少擴展 | 查看 SAE 日誌、啟用 display_errors |