1. 程式人生 > >微信公眾平臺開發者模式的啟用並自動回覆

微信公眾平臺開發者模式的啟用並自動回覆

首先,什麼是開發者模式?

開發者模式,就是先驗證你的伺服器地址,驗證完成之後,使用者一旦給微信公眾號發訊息,微信的就會把微信使用者的訊息轉發到這個地址上。你的伺服器接到資料後,然後你自己設計一套程式,輸出一個結果,再由微信伺服器返回給使用者。

個人學習開發建議使用測試號 

登入後,在介面配置資訊中填寫剛才生成的URL地址和Token.

URL地址就是二級域名地址。

Token在程式中固定為 weixin

填寫好提交,提示配置成功!

如果提示“token驗證失敗”,多重次幾次。

<?php

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

class wechatCallbackapiTest
{
	public function run(){
        if($this->checkSignature() == false){
            die("非法請求");
        }
        if(isset($_GET["echostr"])){
            $echoStr = $_GET["echostr"];
            echo $echoStr;
            exit;
        }else{
            $this->responseMsg();
        }
    }

    public function responseMsg(){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		// $postStr = file_get_contents("php://input");
		file_put_contents('msg.txt',$postStr, FILE_APPEND);
		
      	//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 = "你好!";
                	// $contentStr = "hi!";
                	$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;
		}
	}
}

?>