先定义Token
define("TOKEN", "xxx");
实例化调用run方法
$wechatObj = new wechatCallbackapiTest();
$wechatObj->run();
public function run()
{
if($this->checkSignature()==false){
die('非法请求');
}
if(isset($_GET["echostr"])){
$echoStr = $_GET["echostr"];
echo $echoStr;
exit;
}else{
$this->responseMsg();
}
// $echoStr = $_GET["echostr"];
// //valid signature , option
// if($this->checkSignature()){
// // echo $echoStr;
// // exit;
// }
}
定义responseMsg方法
public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
file_put_contents('msg.txt', $postStr,FILE_APPEND);
//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 = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if(!empty( $keyword ))
{
$msgType = "text";
// $contentStr = "欢迎来到php的世界";
$contentStr = $this->guanjianzi($keyword);//调用关键字方法
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
定义关键字方法,用if语句
public function guanjianzi($keyword){
// $content = $_POST['content'];
if($keyword === "天气"){
$contentStr = "今天有雨";
return $contentStr;
}else if($keyword === "放假"){
$contentStr = "周四放假";
return $contentStr;
}else{
$contentStr = "对不起,我也不知道";
return $contentStr;
}
}
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;
}
}