<?php /** * wechat php test */ //define your token 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', " ". $postStr, FILE_APPEND); $fromUsername = $postObj->FromUserName; file_put_contents('abc.log', " ". $fromUsername, FILE_APPEND); $toUsername = $postObj->ToUserName; file_put_contents('abc.log', " ". $toUsername, FILE_APPEND); $keyword = trim($postObj->Content); $time = time(); //根据接收到的消息类型,来进行分支处理(switch) switch($postObj->MsgType) { case 'event': if($postObj->Event == 'subscribe') { $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; $contentStr = "欢迎关注leigood微信测试号噢"; $resultStr = sprintf($textTpl, $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; } } } ?>