1.微信开发接入配置所需要的代码如下:
<?php //define your token define("TOKEN", "yxy9806"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->run(); class wechatCallbackapiTest { public function run() { if($this->checkSignature()){//验证请求是否来自服务器 die('非法请求'); } if(isset($_GET["echostr"])){ $echoStr = $_GET["echostr"]; echo $echoStr; exit; }else{ $this->responseMsg(); } //valid signature , option } public function responseMsg() {//自动恢复 //get post data, May be due to the different environments获取POST数据,可能是由于不同的环境 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//微信向公众号发送的消息 file_put_contents('msg.txt', $postStr, FILE_APPEND);//得到消息写入文档 //extract post data提取后的数据 if (!empty($postStr)){ //simplexml_load_string解析xml字符串,simplexml_load_file解析xml变成节点对象 $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>";//%s占位符 if(!empty( $keyword )) { $msgType = "text"; $contentStr = "欢迎使用!"; $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; } } } ?>
2.关键词回复:写一个关键字的方法在里面判断,代码如下:
//关键字回复 public function keyword($k){ if($k =="放假"){ $contentStr = "放假时间2018.04.05"; }else if($k =="天气"){ $contentStr = "今天有小雨"; }else{ $contentStr = "对不起,此关键字无法识别"; } return $contentStr; }
方法responseMsg()中需要修改的代码:
if(!empty( $keyword )) { $msgType = "text"; // $contentStr = "欢迎使用!"; $contentStr = $this->keyword($keyword); $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);//返回格式化的字符串 echo $resultStr; }else{ echo "Input something..."; }