비교적 완전한 위 챗 개발 php 코드

15971 단어 php위 챗 개발
본 논문 의 사례 는 여러분 에 게 위 챗 개발 phop 코드 를 공유 하 였 으 며,여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.

<?php
  //          
 
  class WeixinApi
  {
    private $appid;
    private $appsecret; 
 
    //          
    public function __construct($appid="",$appsecret="")
    {
      $this->appid = $appid;
      $this->appsecret = $appsecret;
    }
 
    //          
    public function valid()
    {
      if($this->checkSignature())
      {
        $echostr = $_GET['echostr'];//      
        return $echostr;
      }
      else
      {
        return "Error";
      }
    }
 
    //    
    private function checkSignature()
    {
      // 、       GET       4     
 
      $signature = $_GET['signature'];//      
 
      $timestamp = $_GET['timestamp'];//   
 
      $nonce = $_GET['nonce'];//   
 
      // 、  /    
      // 1.  token、timestamp、nonce           ;
      // bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )       
       
      $tmpArr = array(TOKEN,$timestamp,$nonce);//               
      sort($tmpArr,SORT_STRING);
 
      // 2.                   sha1  ;
      $tmpStr = implode($tmpArr); //         
 
      $signatureStr = sha1($tmpStr);
 
      // 3.              signature  。
      if($signatureStr == $signature)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
 
    //    
    public function responseMsg()
    {
      //         POST         ,   XML   
      $postData = $GLOBALS['HTTP_RAW_POST_DATA'];
 
      //  xml   
      $xmlObj = simplexml_load_string($postData,"SimpleXMLElement",LIBXML_NOCDATA);
 
      if(!$xmlObj)
      {
        echo "";
        exit;
      }
 
      //            
      $toUserName = $xmlObj->ToUserName;//      
      $fromUserName = $xmlObj->FromUserName;//       (openid)
      $msgType = $xmlObj->MsgType;//    
      switch ($msgType) {
        //      
        case 'text':
          //          
          $keyword = $this->receiveText($xmlObj); 
          //       
          switch($keyword)
          {
            case "w001":
            case "W001":
              return $this->replyText($xmlObj,"Hi~  ");
              break;
            case "w002":
            case "W002":
              return $this->replyText($xmlObj,"Hi~   ");
              break;
            case "  ":
              $key = "dee9ebc68fd5a61f67286063932afe56";
              return $this->replyNews($xmlObj,$this->joke_text($key));
              break;
            default:
              $key = "dee9ebc68fd5a61f67286063932afe56";
              return $this->replyNews($xmlObj,$this->joke_text($key));
              break;
          }    
          break;
        //      
        case 'image':
          return $this->receiveImage($xmlObj);
          break;
        //      
        case 'event':
          return $this->receiveEvent($xmlObj);
          break;
      }      
    }
 
    //      
    public function receiveEvent($obj)
    {
      //      
      $event = $obj->Event;
      switch ($event)
      {
        //    
        case 'subscribe':
          //      
          $newsArr = array(
                  array(
                    "Title"=>"         !",
                    "Description"=>"        ,        !",
                    "PicUrl"=>"http://jober.applinzi.com/news/img/news.png",
                    "Url"=>"http://jober.applinzi.com/news/index.php"
                  )                
                );
          //      
          return $this->replyNews($obj,$newsArr); 
          break;
        //      
        case 'unsubscribe':
          //         
          break;
        //       CLICK  
        case 'CLICK':
          $eventKey = $obj->EventKey;//    KEY ,         KEY   
          switch ($eventKey) 
          {
            case 'old':
   
              $weixinArr = $this->history("da675ebc6a0d72920dca3f676122a693");
              $weixinArr = array_slice($weixinArr, 0,5);
              $newsArr = array();
 
              foreach ($weixinArr as $item) 
              {
                $newsArr = array(array(
                          "Title" => $item['Description'],
                          "Description" => $item['Title'],
                          "PicUrl" => "http://1.jober.applinzi.com/news/img/2.jpg",
                          "Url" => "http://www.todayonhistory.com/"                          
                        ));
              }
              return $this->replyNews($obj,$newsArr);
              break;
          }
        break;
      }
    }
 
    //      
    public function receiveText($obj)
    {
      $content = trim($obj->Content);//       
      return $content;
    }
 
    //      
    public function receiveImage($obj)
    {
      $picUrl = $obj->PicUrl;//     
      $mediaId = $obj->MediaId;//      id
      return $this->replyImage($obj,$mediaId);
    }
 
    //      
    public function replyImage($obj,$mediaId)
    {
      $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[image]]></MsgType>
              <Image>
                <MediaId><![CDATA[%s]]></MediaId>
              </Image>
            </xml>";
      return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$mediaId);
           
    }
 
    //      
    public function replyText($obj,$content)
    {
      $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[text]]></MsgType>
              <Content><![CDATA[%s]]></Content>
            </xml>";
      return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$content);
    }
     
    //      
    public function replyNews($obj,$newsArr)
    {
      //         
      if(!is_array($newsArr))
      {
        return;
      }
      //           
      if(!$newsArr)
      {
        return;
      }
      $itemStr = "";
      //  item  
      $itemXml = "<item>
              <Title><![CDATA[%s]]></Title> 
              <Description><![CDATA[%s]]></Description>
              <PicUrl><![CDATA[%s]]></PicUrl>
              <Url><![CDATA[%s]]></Url>
            </item>";
      foreach($newsArr as $item)
      {
        $itemStr .= sprintf($itemXml,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
      }
      $replyXml = "<xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[news]]></MsgType>
              <ArticleCount>".count($newsArr)."</ArticleCount>
              <Articles>".$itemStr."</Articles>
            </xml>"; 
      return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time());     
    }
 
    //  https  (GET POST)
   
    protected function https_request($url,$data=null)
    {
      //1、   curl
      $ch = curl_init();
 
      //2、      
      curl_setopt($ch, CURLOPT_URL, $url);//   url  
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//               
       
      if(!empty($data))
      {
        curl_setopt($ch,CURLOPT_POST,1);//  POST  
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST     
      }
 
      //3、         
      $outopt = curl_exec($ch);
 
      // json       
      $outoptArr = json_decode($outopt,TRUE);
 
      //4、  curl
      curl_close($ch);
 
      //       $outopt json  ,       
      if(is_array($outoptArr))
      {  
        return $outoptArr;
      }
      else
      {
        return $outopt;
      }      
    }
 
    public function juhe_weixin($key,$type)
    {
      $url ="http://v.juhe.cn/toutiao/index?type={$type}&key={$key}";
      $result = $this->https_request($url);
      if($result['error_code'] == 0)
      {
        return $result['result']['data'];
      }
      else
      {
        return array();
      }
    }
 
    //    -      
    public function joke_text($key,$pagesize=10)
    {
      $url = "http://japi.juhe.cn/joke/img/text.from?key={$key}&pagesize={$pagesize}";
      $jokeArr = $this->https_request($url);
      $resultArr = $jokeArr['result']['data'];
      // $content = $resultArr[0]['content'];
      // return $this->replyText($xmlObj,$content);
       
      $newsArr = array();
      //            
      if($jokeArr['error_code'] == 0)
      {
        foreach($resultArr as $item)
        {
          $newsArr[] = array(
                "Title"=>$item['content'],
                "Description"=>$item['updatetime'],
                "PicUrl"=>$item['url'],
                "Url"=>$item['url']
              );
        }        
      }
      return $newsArr;
    }
 
 
    //    -        
       
    public function history($key)
    {
      $m = idate('m');
      $d = idate('d');
      $day = "{$m}/{$d}";
     
      $url = "http://v.juhe.cn/todayOnhistory/queryEvent.php?key={$key}&date={$day}";
      $historyArr = $this->https_request($url);
      $resultArr = $historyArr['result'];
      // $content = $resultArr['title'];
      // return $this->replyText($xmlObj,$content);
       
      $newsArr = array();
      //          
      if($jokeArr['error_code'] == 0)
      {
        foreach($resultArr as $item)
        {
          $newsArr[] = array(
                "Title"=>$item['title'],
                "Description"=>$item['date'],
                "PicUrl"=>"",
                "Url"=>""
              );
        }        
      }
      return $newsArr;
    }
 
    public function fund($key)
    {
 
      $url = "http://japi.juhe.cn/jingzhi/query.from?key={$key}";
      $fundArr = $this->https_request($url);
      $resultArr = $fundArr['result'];
      // $content = $resultArr['title'];
      // return $this->replyText($xmlObj,$content);
       
      $newsArr = array();
      //          
      if($jokeArr['error_code'] == 0)
      {
        foreach($resultArr as $item)
        {
          $newsArr[] = array(
                "Title"=>$item['day'],
                "Description"=>$item['title'],
                "PicUrl"=>"",
                "Url"=>"http://www.baidu.com"
              );
        }        
      }
      return $newsArr;
    }
 
    /**
      *               access_token   access_token
      *@return access_token string     
    **/
    public function getAccessToken()
    {
      //  memcache   access_token
      $access_token = $this->_memcache_get("access_token");
      //     access_token  
      if(!$access_token)
      {  
        //               access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        $outoptArr = $this->https_request($url);
        if(!isset($outoptArr['errcode']))
        {
          //memcache  access_token
          $this->_memcache_set("access_token",$outoptArr['access_token'],7000);
          return $outoptArr['access_token'];
        }
      }  
      return $access_token;
    }
 
    //   memcache
    private function _memcache_init()
    {
      $mmc = new Memcache;
      $ret = $mmc -> connect();
      if ($ret == false) 
      {
        return;
      } 
      return $mmc;
    }
 
    //  memcache
    private function _memcache_set($key,$value,$time=0)
    {
      $mmc = $this->_memcache_init();
      $mmc -> set($key,$value,0,$time);
    }
 
    //  memcahce
    private function _memcache_get($key)
    {
      $mmc = $this->_memcache_init(); 
      return $mmc -> get($key);  
    }
 
    //       
 
    public function menu_create($data)
    {
      $access_token = $this->getAccessToken();
      //           
      $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
      return $this->https_request($url,$data);
    }
 
    //       
    public function menu_delete()
    {
      $access_token = $this->getAccessToken();
      $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$access_token}";
      return $this->https_request($url);
    }
  }
?>
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기