微信公眾平臺開發我們現在做得比較多了,下面給各位介紹的是一個入門級別的微信公眾平臺驗證基礎知識了,有興趣的和小編來看看。
開發微信的時候 需要驗證一下,在官方開發者中心哪里有可以下源代碼,登錄到 公眾帳號后 看到左邊的最下角有一個開發者中心點擊,然后填寫上你相對應的 Token 和 url 然后就可以驗證成功的話就可以開發了.
下載微信php驗證源代碼在 開發者中心 - 開發者文檔 - 接口消息 - 驗證消息真實 - 拉到最下面就php演示代碼.
下載好后代碼如下:
- <?php
- /**
- * wechat php test
- * update time: 20141008
- */
- //define your token
- define("TOKEN", "weixin");
- $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 (!emptyempty($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(!emptyempty( $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, SORT_STRING);
- $tmpStr = implode( $tmpArr );
- $tmpStr = sha1( $tmpStr );
- if( $tmpStr == $signature ){
- return true; //Vevb.com
- }else{
- return false;
- }
- }
- }
- ?>
TOKEN 修改為你自己想要的 然后在 開發者中心也要寫一樣的,在驗證的過程中 $wechatObj->valid(); 這段代碼不能去除這個是驗證,驗證成功后 我們就可以把 這段 $wechatObj->valid(); 這個注釋掉了,然后使用 $wechatObj->responseMsg(); 來進行測試
注意:在開發的時候需要把 $wechatObj->valid(); 給注釋掉,不然在手機測試的時候 會沒有顯示什么.
|
新聞熱點
疑難解答