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

不言
發布: 2023-03-24 12:52:02
原創
3202 人瀏覽過

這篇文章介紹的內容是關於微信公眾平台開發者模式的啟用並自動回复,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

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

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

#個人學習發展建議使用測試號碼 

微信測試號碼位址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 

##登入後,在介面配置資訊中填入剛才產生的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(&#39;msg.txt&#39;,$postStr, FILE_APPEND);
		
      	//extract post data
		if (!empty($postStr)){
              	$postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, 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;
		}
	}
}

?>
登入後複製

相關推薦:

PHP微信開發之文字自動回覆

PHP微信開發之自動回覆


#

以上是微信公眾平台開發者模式的啟用並自動回复的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!