最近看了下 mp 的官方文檔越寫越晦澀了,模模糊糊的不知道想講明什麼,連最近本的消息接入 demo 都沒了
如今雖然 sdk 很多 傻瓜式接入很友善 但多了解下明面的有利無弊
function checkSignature($token)
{
if (!isset($_GET["signature"]) || !isset($_GET["timestamp"]) || !isset($_GET["nonce"])) {
return false;
}
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$tmp_arr = array($timestamp, $nonce, $token);
sort($tmp_arr, SORT_STRING);
$tmp_str = implode($tmp_arr);
$signature_local = sha1($tmp_str);
if ($signature == $signature_local) {
return true;
} else {
return false;
}
}
// 與公衆平台約定的 token
CONST TOKEN = "big_cat";
// 接入開發者模式時 mp 發送的 echostr 的 GET 請求驗證伺服器是否合法
// signature=xxx&echostr=xxx×tamp=xxx&nonce=xxx
// 成功接入後 後續的 wx 消息都會以 POST 請求的方式以如下的 url 發送資料
// signature=xxx×tamp=xxx&nonce=xxx&openid=xxx
// 任何情況下都應首先驗證消息的合法性
if (checkSignature(TOKEN) === true) {
if (isset($_GET['echostr'])) { // wechat 開啟開發者模式接入時的認證
echo $_GET['echostr'];
} else {
$data_raw = file_get_contents("php://input");
//message_handler($data)
file_put_contents('wechat.log', $data_raw . PHP_EOL, FILE_APPEND);
}
}
驗證消息請求的合法性
公衆平台發起任何請求都會攜帶 signature timestamp nonce 三個 query string params
如果有 echostr 說明為開發者模式接入驗證
否則為開發者模式接入後微信公衆平台轉發的使用者消息或事件
任何情況下都要校驗消息的合法性