if($keyword=="你好"){ $contentStr = "hello";}elseif($keyword=="苏州"){ $contentStr = "上有天堂,下有苏杭";}else{ $contentStr = "感谢您关注【卓锦苏州】 微信号:zhuojinsz";}如果用户发送"你好",则回复"hello",如果用户发送"苏州",则回复"上有天堂,下有苏杭",其他信息,则回复你的欢迎词。
<?php/** * wechat php test *///define your tokendefine("TOKEN", "zhuojin");$wechatObj = new wechatCallbackapiTest();$wechatObj->responseMsg();//$wechatObj->valid();class wechatCallbackapiTest{/*public function valid(){$echoStr = $_GET["echostr"];//valid signature , optionif($this->checkSignature()){echo $echoStr;exit;}}*/public function responseMsg(){//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);$RX_TYPE = trim($postObj->MsgType);switch($RX_TYPE){case "text":$resultStr = $this->handleText($postObj);break;case "event":$resultStr = $this->handleEvent($postObj);break;default:$resultStr = "Unknow msg type: ".$RX_TYPE;break;}echo $resultStr;}else {echo "";exit;}}public function handleText($postObj){$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";if($keyword=="你好"){$contentStr = "hello";}elseif($keyword=="苏州"){$contentStr = "上有天堂,下有苏杭";}else{$contentStr = "感谢您关注【卓锦苏州】 微信号:zhuojinsz";}$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);echo $resultStr;}else{echo "Input something...";}}public function handleEvent($object){$contentStr = "";switch ($object->Event){case "subscribe":$contentStr = "感谢您关注【卓锦苏州】"." "."微信号:zhuojinsz"." "."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"." "."目前平台功能如下:"." "."【1】 查天气,如输入:苏州天气"." "."【2】 查公交,如输入:苏州公交178"." "."【3】 翻译,如输入:翻译I love you"." "."【4】 苏州信息查询,如输入:苏州观前街"." "."更多内容,敬请期待...";break;default :$contentStr = "Unknow Event: ".$object->Event;break;}$resultStr = $this->responseText($object, $contentStr);return $resultStr;}public function responseText($object, $content, $flag=0){$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>%d</FuncFlag></xml>";$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);return $resultStr;}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;}}}?>四、测试
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。