当前位置: 代码迷 >> PHP >> 来技术论坛请问大神了,关于微信接口开发的
  详细解决方案

来技术论坛请问大神了,关于微信接口开发的

热度:102   发布时间:2016-04-28 18:37:27.0
来技术论坛请教大神了,关于微信接口开发的
代码直接用微信官方的例子来做小修改的
出现的问题是,部分消息验证不通过
例如我发送了一条信息,如果验证通过,回复欢迎信息,如果验证不通过,回复false关键词
我发了5条信息,有时候有两条回复false,有时候有三条false。
为什么会有验证不通过的现象?
求大神指导


define("TOKEN", "token");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->run();

class wechatCallbackapiTest
{
public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
         echo $echoStr;
         exit;
        }
    }
    
    public function run() {
     if($this->checkSignature()) {
     $this->responseMsg();
     }else{
     $this->responseMsg("false");
     }
    }

    public function responseMsg($contentStr = "Welcome to wechat world!")
    {
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

       //extract post data
if (!empty($postStr)){
                
               $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()
{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}


------解决方案--------------------
记录日志,把获取合法返回的数据都记到日志里,看看成功和失败的日志区别来分析吧
------解决方案--------------------
你的验证参数字典排序不对
sort($tmpArr);改成sort($tmpArr, SORT_STRING);
------解决方案--------------------
补充一下:至于你有时成功,有时失败,是因为成功的数据正好是两种排序结果是一样的。