isValid() && $this->validateSignature($token)) { // 如果验证通过,返回echostr给微信服务器 return $_GET['echostr']; } // 设置调试模式 $this->debug = $debug; // 解析微信发送的XML数据 $xml = (array) simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA); // 将XML数据转换为数组,并转换所有键为小写 $this->request = array_change_key_case($xml, CASE_LOWER); } // 私有方法isValid,用于检查是否是微信服务器的验证请求 private function isValid() { // 检查是否存在echostr参数,该参数在微信服务器验证时存在 return isset($_GET['echostr']); } // 私有方法validateSignature,用于验证签名 private function validateSignature($token) { // 获取微信服务器发送的signature、timestamp、nonce参数 $signature = $_GET['signature']; $timestamp = $_GET['timestamp']; $nonce = $_GET['nonce']; // 将token、timestamp、nonce组合并排序 $signatureArray = array($token, $timestamp, $nonce); sort($signatureArray, SORT_STRING); // 计算签名并比较 return sha1(implode($signatureArray)) == $signature; } // 受保护的方法getRequest,用于获取请求参数 protected function getRequest($param = FALSE) { // 如果没有指定参数,则返回所有请求参数 if ($param === FALSE) { return $this->request; } // 将参数名转为小写 $param = strtolower($param); // 如果请求参数存在,则返回该参数的值 if (isset($this->request[$param])) { return $this->request[$param]; } // 如果请求参数不存在,则返回NULL return NULL; } // 公共方法run,用于处理微信请求 public function run() { // 根据请求类型分发处理 return WechatRequest::switchType($this->request); } // 公共方法checkSignature,用于检查签名 public function checkSignature() { // 获取微信服务器发送的signature、timestamp、nonce参数 $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; // 获取配置中的token $token = WECHAT_TOKEN; // 将token、timestamp、nonce组合并排序 $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); // 将组合后的字符串转为sha1签名 $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); // 比较计算出的签名和微信服务器发送的签名 if( $tmpStr == $signature ){ // 如果签名匹配,返回echostr给微信服务器 echo $_GET['echostr']; return true; }else{ // 如果签名不匹配,返回false return false; } } }