站長資訊網
        最全最豐富的資訊網站

        php如何進行微信公眾號開發

        php如何進行微信公眾號開發

        php如何進行微信公眾號開發

        1、配置相關服務器

        (1) 如下,把自己的服務器ip白名單配置上;

        (2) 開始配置令牌,配置令牌時先需要把現成的代碼放到自己的服務器上面,代碼里面包含自己的設置的令牌號碼,這樣才可以配置成功。

        注意:下面這個代碼在配置好后,即可從服務器上面刪除代碼或者把index.php改一個名字。

        url必須是完整的url,比如 http://118.78.176.74/weixin/index.php

        php如何進行微信公眾號開發

        php如何進行微信公眾號開發

        <?php /**  * wechat php test  * update time: 20141008  */  //define your token //下面的即是你設置的token令牌  define("TOKEN", "zj123456"); $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 (!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 = "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;         } else {             return false;         }     } }

        2、配置ok后,接下來就可以實現相關的微信公眾號相關功能,比如說自動回復機器人。

        代碼包含3部分,當然,自動回復機器人,下面的代碼有些用不到。

        (1) 、index.php

        <?php  define("APPID","xxxxxxx"); define("APPSECRET","xxxxxx"); define("TOKEN","zj123456");  require("./wechat.inc.php"); $wechat = new WeChat(APPID,APPSECRET,TOKEN); $wechat->responseMsg(); ?>

        (2)、wechat.inc.php

        <?php  class WeChat {     private $_appid;     private $_appsecret;     private $_token;      public function __construct($appid, $appsecret, $token)     {         $this->_appid = $appid;         $this->_appsecret = $appsecret;         $this->_token = $token;     }      /**      *_request():發出請求      *@curl:訪問的URL      *@https:安全訪問協議      *@method:請求的方式,默認為get      *@data:post方式請求時上傳的數據      **/     private function _request($curl, $https = true, $method = 'get', $data = null, $headers = null)     {         $ch = curl_init(); //初始化         curl_setopt($ch, CURLOPT_URL, $curl); //設置訪問的URL         // curl_setopt($ch, CURLOPT_HEADER, false); //設置不需要頭信息         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只獲取頁面內容,但不輸出         if ($https) {             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服務器認證             curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客戶端認證         }         if ($method == 'post') {             curl_setopt($ch, CURLOPT_POST, true); //設置請求是POST方式             curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //設置POST請求的數據         }         $str = curl_exec($ch); //執行訪問,返回結果         curl_close($ch); //關閉curl,釋放資源         return $str;     }      /**      *_getAccesstoken():獲取access token      **/     private function _getAccesstoken()     {         $file = './accesstoken'; //用于保存access token         if (file_exists($file)) { //判斷文件是否存在             $content = file_get_contents($file); //獲取文件內容             $content = json_decode($content); //json解碼             if (time() - filemtime($file) < $content->expires_in) //判斷文件是否過期             {                 return $content->access_token;             } //返回access token         }         $content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->_appid . "&secret=" . $this->_appsecret); //獲取access token的json對象         file_put_contents($file, $content); //保存json對象到指定文件         $content = json_decode($content); //進行json解碼         return $content->access_token; //返回access token     }      /**      *_getTicket():獲取ticket,用于以后換取二維碼      *@expires_secords:二維碼有效期(秒)      *@type :二維碼類型(臨時或永久)      *@scene:場景編號      **/     public function _getTicket($expires_secords = 604800, $type = "temp", $scene = 1)     {         if ($type == "temp") { //臨時二維碼的處理             $data = '{"expire_seconds":' . $expires_secords . ', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //臨時二維碼生成所需提交數據             return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //發出請求并獲得ticket         } else { //永久二維碼的處理             $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene . '}}}'; //永久二維碼生成所需提交數據             return $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->_getAccesstoken(), true, "post", $data, ''); //發出請求并獲得ticket         }     }      /**      *_getQRCode():獲取二維碼      *@expires_secords:二維碼有效期(秒)      *@type:二維碼類型      *@scene:場景編號      **/     public function _getQRCode($expires_secords, $type, $scene)     {         $content = json_decode($this->_getTicket($expires_secords, $type, $scene)); //發出請求并獲得ticket的json對象         $ticket = $content->ticket; //獲取ticket         $image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket)         ); //發出請求獲得二維碼圖像         //$file = "./".$type.$scene.".jpg";// 可以將生成的二維碼保存到本地,便于使用         //file_put_contents($file, $image);//保存二維碼         return $image;     }     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"]; //獲得用戶發送信息         $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);         switch ($postObj->MsgType) {             case 'event':                 $this->_doEvent($postObj);                 break;             case 'text':                 $this->_doText($postObj);                 break;             case 'image':                 $this->_doImage($postObj);                 break;             case 'voice':                 $this->_doVoice($postObj);                 break;             case 'video':                 $this->_doVideo($postObj);                 break;             case 'location':                 $this->_doLocation($postObj);                 break;             default:exit;         }     }      private function _doEvent($postObj)     { //事件處理         switch ($postObj->Event) {             case 'subscribe': //訂閱                 $this->_doSubscribe($postObj);                 break;             case 'unsubscribe': //取消訂閱                 $this->_doUnsubscribe($postObj);                 break;             default:;         }     }      private function _doSubscribe($postObj)     {         $tpltext = '<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>';         $access_token = $this->_getAccesstoken();         $userInfo = $this->getUserinfo($access_token, $postObj->FromUserName);         $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '歡迎您關注' . 'Geroge Zhang' . '的世界!');         //還可以保存用戶的信息到數據庫         echo $str;      }      private function _doUnsubscribe($postObj)     {         ; //把用戶的信息從數據庫中刪除     }      private function _doText($postObj)     {         $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)) {             // $data_add = "question=" . $keyword;             // $appcode = "2fd264cdc7914b308e51ab986f73fb86";             // $headers = array();             // array_push($headers, "Authorization:APPCODE " . $appcode);             // $contentStr = $this->_request("http://jisuznwd.market.alicloudapi.com/iqa/query?question=" . $data_add, false, "GET", '', $headers);             $data_add = urlencode($keyword);             $contentStr = $this->_request("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" . $data_add, false, "GET", '', '');             $contentStr = json_decode($contentStr, true);             if ($contentStr['result'] == 0) {                 $contentStr = $contentStr['content'];             }             if ($keyword == "hello") {                 $contentStr = "你好";             }              if ($keyword == "PHP") {                 $contentStr = "最流行的網頁編程語言!";             }              if ($keyword == "JAVA") {                 $contentStr = "較流行的網頁編程語言!";             }              $msgType = "text";             $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);             echo $resultStr;         }         exit;     }      private function _doImage($postObj)     {         $tpltext = '<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>';         $str = sprintf($tpltext, $postObj->FromUserName, $postObj->ToUserName, time(), '您發送的圖片在' . $postObj->PicUrl . "。");         echo $str;     }      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;         } else {             return false;         }     }      /**      * 獲取用戶昵稱      * @param access_token  前面函數_getAccesstoken已經實現      * @param openid 即FromUserName這個參數      * url $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';      * return userInfo      */     public function getUserinfo($access_token, $openid)     {         $urlid = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';         $userInfo = $this->_request($urlid);         return $userInfo;     } }

        注意:想要獲取用戶信息必須是認證過了的訂閱號或者服務號!

        綜上,把如上三個文件,放到你的配置的服務器上面,即可實現自動回復機器人功能。

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 在线观看亚洲精品福利片| 亚洲欧洲精品成人久久奇米网| 日韩午夜高清福利片在线观看欧美亚洲精品suv | 日本精品卡一卡2卡3卡四卡| 亚洲第一极品精品无码久久| 久热精品视频第一页| 欧美国产日韩精品| 国产精品区免费视频| 一本一道久久a久久精品综合| 国产精品 视频一区 二区三区| 华人亚洲欧美精品国产| 国产精品原创巨作av女教师| 亚洲第一区精品观看| 久久精品18| 国产精品亚洲产品一区二区三区 | 国产午夜精品一区二区三区不卡| 九九精品免视看国产成人| HEYZO无码综合国产精品227| 人人妻人人澡人人爽人人精品97| 夜夜高潮夜夜爽国产伦精品| 免费精品久久久久久中文字幕| 精品精品国产理论在线观看| 国产成人精品a视频一区| 91精品国产高清久久久久久国产嫩草 | 精品水蜜桃久久久久久久| 国产精品成人无码久久久久久| 亚洲国产精品久久久久婷婷老年| 国产精品久久毛片完整版| 久久国产乱子伦精品免费强| 久久线看观看精品香蕉国产| 久久99精品国产一区二区三区| 9久久9久久精品| 久久99精品国产99久久6男男| 久久免费精品一区二区| 成人一区二区三区精品| 成人国产精品日本在线观看 | 亚洲性日韩精品一区二区三区| 亚洲乱码日产精品a级毛片久久| 少妇亚洲免费精品| 亚洲AV乱码久久精品蜜桃| 国产精品网站在线观看免费传媒 |