天天看點

微信公衆号伺服器配置--驗證token

1 登陸公衆号背景:https://mp.weixin.qq.com

2 滑鼠滑到最底部的《開發–基本配置》

微信公衆号伺服器配置--驗證token

3 填寫相關伺服器配置資訊:

微信公衆号伺服器配置--驗證token

這裡的token要跟伺服器的驗證檔案裡的token一緻。

4 寫一個驗證檔案放進伺服器,驗證token,看是否連接配接成功。附上驗證代碼:

<?php

/**
  * wechat php test
  */


//define your token

define("TOKEN", "wechat");

$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)){


                $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;

        }

    }

}


?>
           

5 如果點選送出之後,提示token驗證成功,說明已經成功了,如果失敗,檢視代碼是否正确,配置資訊是否正确,多送出幾次看看。

繼續閱讀