Skip to content

Instantly share code, notes, and snippets.

@snsnsjsn
Created April 29, 2016 14:05
Show Gist options
  • Select an option

  • Save snsnsjsn/a5e91d8f3e33499b65026fdadb180b30 to your computer and use it in GitHub Desktop.

Select an option

Save snsnsjsn/a5e91d8f3e33499b65026fdadb180b30 to your computer and use it in GitHub Desktop.

Revisions

  1. snsnsjsn created this gist Apr 29, 2016.
    97 changes: 97 additions & 0 deletions new_file0
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,97 @@
    <?php
    /**
    * wechat php test
    */

    //define your token
    define("TOKEN", "weixin");
    $wechatObj = new wechatCallbackapiTest();
    //这里是第一次token获取后,就不需要再执行验证了,或者可以在获取token后,注释掉 $wechatObj->valid();这样就是对接好后不需要每次对暗号token
    if($_GET['echostr'])
    {
    $wechatObj->valid();
    }else{
    $wechatObj->responseMsg();
    }


    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 = "和电视咯大开大";
    $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;
    }
    }
    }

    ?>