整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          如何使用開發者服務器運維微信公眾號

          文章目錄

          很多人都有自己的服務器,特別是對于大學生而言,很多服務器公司都對學生有優惠,例如騰訊云只要1元每月: ,那么我們作為一名程序員,總想把一切掌控在自己手中,,那么如何使用我們開發者服務器去管理微信公眾號呢?這就是本文介紹的內容。

          本文介紹以下內容:

          1 如何把微信公眾號授權給開發者服務器 2 如何使用代碼把開發者服務器與微信服務器進行關聯

          
          /**
           * 微信公眾號開發-入門
           *
           * api
           */
          define("TOKEN",'we--xxxx');   //這里和你微信公眾號開放平臺上的tonken填寫一樣的即可
          $weixinApi=new WeixinApi();
          if(isset($_GET["echostr"])){
              $weixinApi->valid();
          }else{
              $weixinApi->responseMsg();
          }
          class WeixinApi{
              //驗證接口
              public function valid(){
                  $echoStr = $_GET["echostr"];//從微信用戶端獲取一個隨機字符賦予變量echostr
                  if($this->checkSignature()){
                      echo $echoStr;
                      exit;
                  }
              }
              //檢查簽名
              private function checkSignature(){
                  //1 接受微信服務器get請求發送過來的4個參數
                  $signature = $_GET["signature"];//從用戶端獲取簽名賦予變量signature
                  $timestamp = $_GET["timestamp"];//從用戶端獲取時間戳賦予變量timestamp
                  $nonce = $_GET["nonce"];    //從用戶端獲取隨機數賦予變量nonce
                  //2 加密和校驗請求
                  //2.1 將token、timestamp、nonce三個參數進行字典序排序
                  $tmpArr = array(TOKEN, $timestamp, $nonce);//簡歷數組變量tmpArr
                  sort($tmpArr, SORT_STRING);//新建排序
                  //2.2 將三個參數字符串拼接成一個字符串進行sha1加密
                  $tmpStr = implode($tmpArr);//數組轉字符串
                  $tmpStr = sha1($tmpStr);//shal加密
                  //2.3 開發者獲得加密后的字符串可與signature對比,標識該請求來源于微信
                  if ($tmpStr == $signature) {
                      return true;
                  } else {
                      return false;
                  }
              }
              //回復消息
              public function responseMsg(){
                  //3 以下代碼接受消息
                  //3.1 接受微信服務器發送過來的原生的POST的數據包
          //        $postData = $GLOBALS["HTTP_RAW_POST_DATA"];
                  $postData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] :file_get_contents("php://input");
                  //3.2 處理數據包
                  $xmlObj = simplexml_load_string($postData, "SimpleXMLElement", LIBXML_NOCDATA);
                  $msgType = $xmlObj->MsgType;
                  //4 根據消息類型進行業務處理
                  switch ($msgType) {
                      //接受事件消息
                      case 'event':
                          $this->disposeEvent($xmlObj);
                          break;
                      //接受文本消息
                      case 'text':
                          $this->disposeText($xmlObj);
                          break;
                      //接受圖片消息
                      case 'image':
                          $this->disposeImage($xmlObj);
                          break;
                  }
              }
              //處理接收的事件消息
              private function disposeEvent($xmlObj){
                  switch ($xmlObj->Event){
                      case 'subscribe'://訂閱事件
                          $this->sendText('歡迎您的訂閱');
                          break;
                      case 'unsubscribe'://取消訂閱事件
                          $this->sendText('good-bye');//該消息用戶其實是看不到的,取消訂閱事件一般用來清除數據庫記錄
                          break;
                  }
              }
              //處理接收的文本消息
              private function disposeText($xmlObj){
                  $text=trim($xmlObj->Content);
                  //包含關鍵字都不做處理
                  if (!(
                      strstr($text,'違規')    //這里對違規的關鍵字做排除,不予理睬
                  )){
                      switch ($text){
                          case '你好':
                              $this->sendText($xmlObj,'Hi 我是開發者服務器');
                              break;
                          case 'new':
                              $newsArr=array(
                                  array(
                                      "title"=>"看到這條消息,你可以買彩票了",
                                      "description"=>"本公眾號有許多小彩蛋,歡迎您的探索。",
                                      "picUrl"=>"http://img.mp.itc.cn/upload/20170610/03d69e8df0524b8cb59fd16dc2fec989.jpg",
                                      "url"=>"http://www.baidu.com"
                                  )
                              );
                              $this->sendNews($xmlObj,$newsArr);
                              break;
                          default:
                              $this->tuling123($xmlObj,trim($xmlObj->Content));   //圖靈機器人
                      }
                  }
          
              }
              //處理接收的圖片消息
              private function disposeImage($xmlObj){    //一般情況下,不會去處理用戶發送的圖片
                  $this->sendImage($xmlObj,$xmlObj->PicUrl,$xmlObj->MediaId);
              }
              //發送文本的方法
              private function sendText($xmlObj,$content){
                  $replyTextMsg="
                                  
                                  
                                  %s
                                  
                                  
                              ";
                  echo sprintf($replyTextMsg,$xmlObj->FromUserName,$xmlObj->ToUserName,time(),$content);
              }
              //發送圖片的方法
              private function sendImage($xmlObj,$mediaId){
                  $replyImageMsg="
                                  
                                  
                                  %s
                                  
                                  
                                      
                                  
                              ";
                  echo sprintf($replyImageMsg,$xmlObj->FromUserName,$xmlObj->ToUserName,time(),$mediaId);
              }
              //發送圖文的方法
              private function sendNews($xmlObj,$newsArr){
                  $newsTplHead = "
                                  
                                  
                                  %s
                                  
                                  %s
                                  ";
                  $newsTplBody = "
                                  <![CDATA[%s]]> 
                                  
                                  
                                  
                              ";
                  $newsTplFoot = "
                              %s
                          ";
                  $replyNewsMsg = sprintf($newsTplHead, $xmlObj->FromUserName, $xmlObj->ToUserName, time(),count($newsArr));
                  foreach($newsArr as $key => $value){
                      $replyNewsMsg .= sprintf($newsTplBody, $value['title'], $value['description'], $value['picUrl'], $value['url']);
                  }
                  $replyNewsMsg  .= sprintf($newsTplFoot, 0);
                  echo $replyNewsMsg;
              }
              public function tuling123($xmlObj,$message){//這是是使用圖靈機器人
                  $tuTonken='2d8aaa17141c443----xxx---fsa';   //請去圖靈網http://www.tuling123.com/自己申請一個tonken
                  $tuUrl='http://www.tuling123.com/openapi/api?key='.$tuTonken.'&info='.$message.'&userid='.$xmlObj->FromUserName;
                  $tuData='{  
                      "key": "'.$tuTonken.'", 
                      "info": "'.$message.'",
                      "userid": "'.$xmlObj->FromUserName.'" 
                      }';
                  $results = $this->htts_request($tuUrl,$tuData);
          //        print_r($results);
                  if ($results['code']==100000){
                      $text=$results['text'];
                      $this->sendText($xmlObj,$text);
                  }else{
                      $this->sendText($xmlObj,'有問題,請輸入“幫助”');
                  }
              }
              //https請求(get和post)
              private function htts_request($url,$data=array()){
                  //1 初始化curl
                  $ch=curl_init();
                  //2 設置傳輸選項
                  curl_setopt($ch,CURLOPT_URL,$url);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//把頁面以文件流的形式返回
                  if (!empty($data)) {
                      curl_setopt($ch, CURLOPT_POST, true); //設置為 POST 請求
                      curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //設置POST的請求數據
                  }
                  //3 執行curl請求
                  $outopt=curl_exec($ch);
                  $outoptArr=json_decode($outopt,true);
                  //4 關閉curl
                  curl_close($ch);
                  return $outoptArr;
              }
          }
          ?>
          

          //獲取access_token
              private function getAccessToken(){
                  //獲取微信接口憑證
                  $appid="wxb4----xxx";//請在第一章第5小節的圖片中看
                  $appsecret="21d---xxx";//請在第一章第5小節的圖片中看
                  $data=json_decode(file_get_contents('./access_token.json'));
                  if ($data->expires_time <time()){
                      $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
                      $outoptArr=$this->htts_request($url,array(),false);
                      $access_token=$outoptArr['access_token'];
                      if (!empty($access_token)){
          
                          //把access_token寫入文件
                          $data->access_token=$outoptArr['access_token'];
                          $data->expires_time=time()+7000;
                          $fp=fopen('access_token.json','w');
                          fwrite($fp,json_encode($data));
                          fclose($fp);
                      }else{
                          echo '請求access_token錯誤';
                      }
                  }else{
                      $access_token=$data->access_token;
                  }
          //        echo $access_token;
                  return $access_token;
              }
          //實現自定義菜單
              public function menu_create(){
                  $access_token=$this->getAccessToken();
                  $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
                  $data='{
          		"button": [
          			{
          				"type": "click",
          				"name": "java",
          				"key": "learn_java"
          			},
          			{
          				"name":"chengxu",
          				"sub_button":[
          				{
          					"type": "view",
          					"name": "CSDN",
          					"url": "http://blog.csdn.net/tiandixuanwuliang/"
          				},
          				{
          					"type": "view",
          					"name": "Github",
          					"url": "https://github.com/wllfengshu/"
          				},
          				{
          					"type": "view",
          					"name": "jianshu",
          					"url": "https://www.jianshu.com/users/4d12e03d0a5f/timeline/"
          				},
          				{
          					"type": "view",
          					"name": "kaifazhe",
          					"url": "https://toutiao.io/u/431066/"
          				},
          				{
          					"type": "view",
          					"name": "yuyan",
          					"url": "http://www.baidu.com"
          				}]
          			},
          			{
          				"name":"jiaoliu",
          				"sub_button":[
          				{
          					"type": "view",
          					"name": "shuji",
          					"url": "http://blog.csdn.net/tiandixuanwuliang/"
          				},
          				{
          					"type": "view",
          					"name": "ziyuan",
          					"url": "https://github.com/wllfengshu/"
          				},
          				{
          					"type": "view",
          					"name": "sucai",
          					"url": "https://www.jianshu.com/users/4d12e03d0a5f/timeline/"
          				},
          				{
          					"type": "view",
          					"name": "daxuesheng",
          					"url": "https://toutiao.io/u/431066/"
          				},
          				{
          					"type": "click",
          					"name": "zuozhe",
          					"key": "about_author"
          				}]
          			}
          		]
          	}';
                  echo $url." / ".$data;
                  $outoptArr=$this->htts_request($url,json_decode($data,true),true);
                  echo '***';
                  print_r($outoptArr);
              }
          

              //網頁授權-base型
              public function snsapi_base($redirect_uri){
                  //以下是測試賬號
                  $appid="wxb4----xxx";//請在第一章第5小節的圖片中看
                  $appsecret="21da56-----xxx";//請在第一章第5小節的圖片中看
                  //準備scope
                  $snsapi_base_url="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=SCOPE&state=123#wechat_redirect";
                  $code=$_GET['code'];
                  //獲取code
                  if (!isset($code)){
                      header("Location:{$snsapi_base_url}");
                  }
                  //獲取access_token
                  $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
                  return $this->htts_request($url);
              }
          


          主站蜘蛛池模板: 国产一区三区三区| 精品国产一区二区三区香蕉| 精品一区二区三区波多野结衣 | 日本香蕉一区二区三区| 国产伦精品一区二区三区视频猫咪 | 国产婷婷色一区二区三区| 激情综合丝袜美女一区二区| 亚洲AV成人一区二区三区在线看| 国产一区二区三区免费观在线| 国产一区二区三区福利| 亚洲AV无码片一区二区三区| 国产主播福利一区二区| 无码国产精品一区二区免费16| 中文字幕一区二区人妻性色 | 国产一区二区在线视频播放| 精品一区高潮喷吹在线播放| 色欲AV蜜臀一区二区三区| 免费av一区二区三区| 国产一区二区三区91| 国产主播一区二区| 无码aⅴ精品一区二区三区浪潮| 国产一区二区三区在线2021| 激情综合一区二区三区| 在线观看午夜亚洲一区| 国产裸体歌舞一区二区| 一区二区三区国产精品| 人妻体内射精一区二区三区| 亚洲va乱码一区二区三区| 亚洲一区二区三区高清| 国产短视频精品一区二区三区| 国产精品亚洲一区二区麻豆 | 久99精品视频在线观看婷亚洲片国产一区一级在线 | 国产一区二区不卡老阿姨| 在线免费观看一区二区三区| 国产成人AV区一区二区三| 538国产精品一区二区在线| 色妞AV永久一区二区国产AV| 中文字幕在线一区二区在线 | 中文字幕日韩人妻不卡一区| 国产精品伦一区二区三级视频| 麻豆一区二区三区精品视频 |