index.php的代码如下
<?php /** * wechat php test */ //define your token require_once "common.php"; define("TOKEN", "twgdh"); $wechatObj = new wechatCallbackapiTest(); //当接入成功后,请注销这句话,否则,会反复验证。 //$wechatObj->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"]; //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 */ // 使用simplexml技术对xml进行解析 // libxml_disable_entity_loader(true), 是从安全性考虑,为了防止xml外部注入, //只对xml内部实体内容进行解析 libxml_disable_entity_loader(true); //加载 postStr 字符串 $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA); file_put_contents(‘abc.log‘, "\r\n\r\n". $postStr, FILE_APPEND); $fromUsername = $postObj->FromUserName; file_put_contents(‘abc.log‘, "\r\n\r\n". $fromUsername, FILE_APPEND); $toUsername = $postObj->ToUserName; file_put_contents(‘abc.log‘, "\r\n\r\n". $toUsername, FILE_APPEND); $keyword = trim($postObj->Content); $time = time(); //根据接收到的消息类型,来进行分支处理(switch) switch($postObj->MsgType) { case ‘event‘: if($postObj->Event == ‘subscribe‘) { global $tmp_arr; $contentStr = "欢迎关注leigood微信测试号噢"; $resultStr = sprintf($tmp_arr[‘text‘], $fromUsername, $toUsername, $time, $contentStr); echo $resultStr; } break; case ‘text‘: global $tmp_arr; $contentStr = ‘hello,‘.$keyword; $resultStr = sprintf($tmp_arr[‘text‘], $fromUsername, $toUsername, $time, $contentStr); echo $resultStr; break; } }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; } } } ?>
因为模版重用性比较高所以我们来定义一个模版,common.php,代码如下:
<?php $tmp_arr = array( ‘text‘ => "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>" );
这样功能即可实现了,但是为了让代码的安全性更高一点我们可以用到大文本方法来编辑模版性息,代码如下:
<?php $tmp_arr = array( ‘text‘ => <<<XML <xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml> XML );
这两种方法都是可以正常使用的,但推荐用第二种方法安全性高一些,因为他可以防注入