微信公眾號文檔
文檔中驗證消息來自微信服務器,按照文檔來寫
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 );
if($tmpStr == $signature ){
return true;
}else{
return false;
}
}

image.png
微信文檔已說明,【按照原樣返回echostr參數(shù)】,所以例子中return true會一直接入失敗,這里改為
return $_GET["echostr"];或者echo $_GET["echostr"];exit;

image.png

image.png
laravel 關注/取消微信公眾號事件需要注意的是路由
Route::match(['get','post'], 'api/index', 'ApiController@checkSignature');
微信公眾號事件也是回調(diào)這個方法,只是用POST方式請求
// 驗證來自微信服務器
private function checkSignature(Request $request)
{
// 驗證消息來自微信服務器
if($request->method()=='GET'){
$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);
if($tmpStr == $signature && $_GET['echostr']){
echo $_GET['echostr'];
exit;
}else{
return false;
}
} elseif ($request->method()=='POST') {
// 事件處理 關注/取消事件等
$postArr = file_get_contents("php://input");
//獲取到xml數(shù)據(jù)后,處理消息類型,并設置回復消息內(nèi)容(回復就是直接打印xml數(shù)據(jù))
//數(shù)據(jù)格式
$arr = simplexml_load_string($postArr);
if(strtolower($arr->MsgType)=="event")
{
$toUser = $arr->ToUserName;
$foUser = $arr->FromUserName; // 用戶openid
$msgType = 'text';
$createTime = time();
$content = '歡迎關注我的微信公眾平臺';
if(strtolower($arr->Event)=="subscribe") {//訂閱
$temp = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
echo $temp;
}elseif (strtolower($arr->Event)=="unsubscribe"){ // 取消訂閱
echo '';
}
}
}
}