大家都知道微信要想成為微信開發者,必須在微信公眾號后臺配置回調url,也就是開發者服務器url ,url代表開發者接收微信事件的地址,token由開發者隨意填寫,之前是已經開發好的,服務器配置也弄好了,可是過了兩個月發現在以同樣的方式接入,總是提示:"token驗證失敗",真實百思不得其解;
index-wechat.jpg
分析原因
(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驗證失?。?/p>
(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;
}
}