时间:2021-07-01 10:21:17 帮助过:21人阅读
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 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 = ""; 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; } }} %s 0
记录日志,把获取合法返回的数据都记到日志里,看看成功和失败的日志区别来分析吧
你的验证参数字典排序不对
sort($tmpArr);改成sort($tmpArr, SORT_STRING);
补充一下:至于你有时成功,有时失败,是因为成功的数据正好是两种排序结果是一样的。
你的验证参数字典排序不对
sort($tmpArr);改成sort($tmpArr, SORT_STRING);