valid(); } $wechatObj->responseMsg(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $postStr = file_get_contents("php://input"); file_put_contents("./demo.txt",date("Y-m-d H:i:s")." ".json_encode($postStr).PHP_EOL,FILE_APPEND); //extract post data if (!empty($postStr)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $type=$postObj->MsgType; $event=""; if ($type =='event'){ $event=$postObj->Event; } $time = time(); $textTpl = " %s "; if(!empty( $keyword ) || $event =="subscribe") { $msgType = "text"; if ($event == "subscribe"){ $contentStr = "欢迎关注,此号可以自由聊天^_^"; }else{ if (strpos($keyword,"主人") !== false){ $contentStr="我的主人是宇宙无敌超级大帅哥--人称陌帅"; }else{ $contentStr = $this->simsimiHttp($keyword); } } $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } }else { echo ""; exit; } } private function checkSignature() { // you must define TOKEN by yourself if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); } $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } private function simsimiHttp($msg){ $url="http://www.xiaodoubi.com/simsimiapi.php?msg=".$msg; $res = file_get_contents($url); file_put_contents("./demo.txt",date("Y-m-d H:i:s")." ".$res.PHP_EOL,FILE_APPEND); if (strpos($res,"xiaodouqqcom") !== false){ $res="无法回答,请不要发一下奇怪的问题或字符😒"; } return $res; } } ?>