在接入微信公众平台前,需要验证第三方Token请求。
在验证Token的时候,微信会往url 发送 GET 请求,包含以下内容:signature
、timestamp
、nonce
、 echostr
。当服务器获取到数据后,会验证 signature
的正确性来保证数据是从微信发过来的。服务器验证代码如下:
private static function _chk($signature,$timestamp,$nonce,$token) { $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if( $tmpStr == $signature ){ return true; }else{ return false; } }
当返回 true
后,就需要打印出 echostr
的内容。微信获取到后就会提示接入成功了。
Token
验证完整代码
<?php define("TOKEN", "weixin"); $signature = @$_GET["signature"]; $timestamp = @$_GET["timestamp"]; $nonce = @$_GET["nonce"]; $echostr = @$_GET['echostr']; if($signature!=NULL && $timestamp!=NULL && $nonce!=NULL && $echostr!=NULL) { echo TOKEN_CHK::Token($echostr,$signature,$timestamp,$nonce,TOKEN); } /** * 用于验证Token的类 */ class TOKEN_CHK { /** * 核对令牌,确保信息发送来自微信 * * @access private * @param string $signature 微信加密签名 * @param string $timestamp 时间戳 * @param string $nonce 随机数 * @return void */ private static function _chk($signature,$timestamp,$nonce,$token) { $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if( $tmpStr == $signature ){ return true; }else{ return false; } } /** * 返回微信TOKEN验证结果 * * @access public * @param string $echostr 随机字符串,当确认是微信发送的数据就可以返回这个随机字符串 * @param string $signature 微信加密签名 * @param string $timestamp 时间戳 * @param string $nonce 随机数 * @return string */ public static function Token($echostr,$signature,$timestamp,$nonce,$token) { if(self::_chk($signature,$timestamp,$nonce,$token))return $echostr; else return false; } } ?>
扫描二维码可以测试一下功能