您的位置:首页 > 移动开发 > 微信开发

微信token验证

2018-02-06 13:11 85 查看
在公共号基本配置里,填写服务器地址时要验证token,就把以下代码放在文件里,等验证通过后再删除

<?php

/**

  * wechat php test

  */

define('IN_ECS', true);

error_reporting(0);

require('../includes/init.php');

//define your token

define("TOKEN", "weixin");

$wechatObj = new wechatCallbackapiTest();

$wechatObj->valid();

class wechatCallbackapiTest

{

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

                $type = (string)$postObj->MsgType;

                $time = time();

                file_put_contents(dirname(__FILE__).'/award_4.php', $postObj); 

                $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, $from
4000
Username, $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;
}
}

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: