代碼直接用官方的例子來做小修改的
出現的問題是,部分訊息驗證不通過
例如我發送了一條資訊,如果驗證通過,回複歡迎資訊,如果驗證不通過,回複false關鍵詞
我發了5條資訊,有時候有兩條回複false,有時候有三條false。
為什麼會有驗證不通過的現象?
求大神指導
define("TOKEN", "token");$wechatObj = new wechatCallbackapiTest();//$wechatObj->valid();$wechatObj->run();class wechatCallbackapiTest{public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } public function run() { if($this->checkSignature()) { $this->responseMsg(); }else{ $this->responseMsg("false"); } } public function responseMsg($contentStr = "Welcome to wechat world!") {//get post data, May be due to the different environments$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post dataif (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "%s%s%s%s%s0"; if(!empty( $keyword )) { $msgType = "text"; //$contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } }else { echo ""; exit; } }private function checkSignature(){ $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN;$tmpArr = array($token, $timestamp, $nonce);sort($tmpArr);$tmpStr = implode( $tmpArr );$tmpStr = sha1( $tmpStr );if( $tmpStr == $signature ){return true;}else{return false;}}}
回複討論(解決方案)
記錄日誌,把擷取合法返回的資料都記到日誌裡,看看成功和失敗的日誌區別來分析吧
你的驗證參數字典排序不對
sort($tmpArr);改成sort($tmpArr, SORT_STRING);
補充一下:至於你有時成功,有時失敗,是因為成功的資料正好是兩種排序結果是一樣的。
你的驗證參數字典排序不對
sort($tmpArr);改成sort($tmpArr, SORT_STRING);
成了,感謝。
驗證方法直接複製官方的例子,我太相信他們了,坑啊