前景
昨晚在进行微信公众号的校验开发,echostr参数都能正常返回,可始终报token校验失败问题,网上一直找不到相关的错误指导,于是乎我来啦~~特此记录下,开发框架是 thinkPHP 6。
错误原因
echostr参数正常返回但是token验证失败的原因在于,response的content-type。
thinkphp 默认的字符串返回的 content-type是 text/html,但是微信那边接收的好像是text/plain;charset=utf-8,所以一直校验不过去。
最终源码记录
//微信公众号绑定域名校验
public function checkSignature()
{
$result = $this->validate($_GET, [
'signature' => 'require',
'timestamp' => 'require',
'nonce' => 'require',
'echostr' => 'require',
]);
if ($result) {
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$echostr = $_GET['echostr'];
$token = Config::get('my.WX_CHECK_TOKEN');
Log::info('微信请求了校验文件:' . json_encode($_GET));
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
Log::info('校验字符串为:' . $tmpStr);
//test
if ($tmpStr == $signature) {
Log::info('校验成功返回:' . $echostr);
return response($_GET['echostr'])->header([
'Content-Type' => 'text/plain;charset=utf-8'
]);
} else {
Log::info('校验失败!');
return response('false')->header([
'Content-Type' => 'text/plain;charset=utf-8'
]);
}
} else {
return $result;
}
}
加油~