大家都知道微信要想成为微信开发者,必须在微信公众号后台配置回调url,也就是开发者服务器url ,url代表开发者接收微信事件的地址,token由开发者随意填写,之前是已经开发好的,服务器配置也弄好了,可是过了两个月发现在以同样的方式接入,总是提示:"token验证失败",真实百思不得其解;
分析原因
(1). 接入文件不能有BOM,(查看后没有BOM)
(2).在服务器端验证通过后,原样输出echoStr之前不能有任何输出,所有要关闭php的display_errors=off,(已确定设置)
(3).在服务器端验证通过后,写入文件,查看文件内容,(发现没有问题,输出true,说明通过服务器验证)
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 ){
//在这里将true写入文件
return true;
}else{
return false;
}
}
此时微信端依然报"token验证失败"
(4) 在网上找到微信官方接入demo
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
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 */
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}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;
}
}
}
?>
配置后请求该demo内容,微信提示"提交成功"(注意:在同一域名下)
(5) 最后分析,我们的接入文件是在thinkphp框架下的,不是直接访问的.php文件,最后解决办法是在echo $echoStr;之前ob_clean();
清空(擦掉)输出缓冲区解决;
public function valid($echoStr)
{
if($this->checkSignature())
{
ob_clean();//清空(擦掉)输出缓冲区解决,这一行很关键
echo $echoStr;//原路返回验证的随机字符串
exit;
}
}