ECHO陈文
关注互联网技术开发与维护运营

PHP 微信公众号的基本配置token验证失败

刚接触微信公众平台开发的程序猿来说,一般都会遇到这样的问题,在微信公众号后台中设置基本配置时,提示“token验证失败”,其实微信官方也给出了“接入指南”,但是文章真的太长了,相信很多人都没耐心看完,小编也是其中一个,所以就直接网上解决方案,下面跟大家分享一下,验证代码如下(这个文件就是你填写回调地址的目标文件):

define("TOKEN", "这里填写你的token");
$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 (!emptyempty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<!--[CDATA[%s]]--><!--[CDATA[%s]]-->%s<!--[CDATA[%s]]--><!--[CDATA[%s]]-->0";
            if(!emptyempty( $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, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}
赞(0) 打赏
未经允许不得转载:芦苇派 » PHP 微信公众号的基本配置token验证失败

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏