PHP微信公衆號開發之自動回覆

先把源碼類發出來php

<?php
/**
 本身封裝 微信 開發api
*/
header('Content-type: text/html; charset=utf-8');#設置頭信息
class zhphpWeixinApi{
      //定義屬性
      private $userPostData; #微信反饋給平臺的數據集
      private $fromUserName; #發微信用戶姓名
      private $toUserName; #接受微信用戶姓名
      private $keyword; #接受用戶發的微信信息
      private $createTime; #建立時間
      private $requestId;#獲取接收消息編號
      private $msgType; #用戶發的微信的類型

      
      public $token; #api token
      private $appid;#開發者 id
      private $appSecret;# 開發者的應用密鑰
      
      private $access_token;#微信平臺返回的access_token
      private $expires_in=0;#權限的期限
      
      public  $weixinConfig=array();#微信全局配置
      public  $debug=false;
      private $saveFilePath; //緩存文件保存路徑

      public  $oauthAccessToken; ##第三方網頁受權accecctoken
      public  $oauthOpenId;##受權後的用戶id
      
      /**
        $wx_msgType爲數組,能夠依據帳號的權限補充
      */
      private  $wx_msgType=array(
        'text',#文本消息內容類型
        'image',#圖片消息內容類型
        'voice',#語音消息內容類型
        'video',#視頻消息內容類型
        'link',#連接消息內容類型
        'location',#本地地理位置消息內容類型
        'event',#事件消息內容類型
        'subscribe',#是否爲普通關注事件
        'unsubscribe',#是否爲取消關注事件
        'music',#音樂消息內容類型
        'news',#新聞消息內容
        );
        
        /**
          配置文件
           $config=array(
            'token'=>'',
            'appid'=>'開發者 id ',
            'appSecret'=>'應用密鑰'
            )
       */
       public function setConfig($config){
            if( ! empty( $config ) ){
                $this->weixinConfig=$config;
            }elseif( empty($config) && ! empty($this->weixinConfig) ){
                $config=$this->weixinConfig;
            }
                 #配置參數屬性,這裏使用 isset進行了判斷,目的是爲後續程序判斷提供數據
                 $this->token=isset($config['token'])?$config['token']:null;
                 $this->appid=isset($config['appid'])?$config['appid']:null;
                 $this->appSecret=isset($config['appSecret'])?$config['appSecret']:null;
        }
        /**
         獲取config
        */
        public function getConfig(){
            return $this->weixinConfig;
        }
       /**
         檢驗 token
       */
      public function  validToken(){
          if(empty($this->token)){  //若是 不存在 token  就拋出異常
             return false;
            }else{
                if($this->checkSignature()){//檢查簽名,簽名經過以後,就須要處理用戶請求的數據
                   return  true;
                }else{
                    return  false;
                }
            }
       }
      /**
        檢查簽名
      */
      private function checkSignature(){
           try{ # try{.....}catch{.....} 捕捉語句異常
             $signature = isset($_GET["signature"])?$_GET["signature"]:null;//判斷騰訊微信返回的參數 是否存在 
             $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:null;//若是存在 就返回 不然 就 返回 null
             $nonce = isset($_GET["nonce"])?$_GET["nonce"]:null;
              ######下面的代碼是--微信官方提供代碼
             $tmpArr = array($this->token, $timestamp, $nonce);
             sort($tmpArr, SORT_STRING);
             $tmpStr = implode( $tmpArr );
             $tmpStr = sha1( $tmpStr );
             if( $tmpStr == $signature ){
                 return true;
             }else{
                 return false;
            }
            ######上面的代碼是--微信官方提供代碼  
           }catch(Exception $e){
               echo $e->getMessage();
               exit();
           }
    }
     /**
       處理用戶的請求
     */
     private function handleUserRequest(){
         if(isset($_GET['echostr'])){ //騰訊微信官方返回的字符串  若是是存在 echostr 變量 就代表 是微信的返回 咱們直接輸出就能夠了
               $echoStr = $_GET["echostr"];
               echo $echoStr;
               exit;
          }else{//不然 就是用戶本身回覆 的
             $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//用戶全部的回覆,騰訊微信都是放在這個變量的
              if (!empty($postStr)){
                 libxml_disable_entity_loader(true); //因爲微信返回的數據 都是以xml 的格式,因此須要將xml 格式數據轉換成 對象操做
                   $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                 $this->fromUserName=$postObj->FromUserName; //獲得發送者 姓名  通常爲微信人的帳號
                 $this->toUserName=$postObj->ToUserName;//獲得 接受者的 姓名  獲取請求中的收信人OpenId,通常爲公衆帳號自身
                 $this->msgType=trim($postObj->MsgType); //獲得 用戶發的數據的類型
                 $this->keyword=addslashes(trim($postObj->Content));//獲得 發送者 發送的內容
                 $this->createTime=date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);//當前的時間,咱們這裏是服務器的時間
                 $this->requestId=$postObj->MsgId;//MsgId  獲取接收消息編號
                 $this->userPostData=$postObj;
                //$this->responseMessage('text','返回:'.$this->msgType);
            }
          }
      }
      /**
        獲取用戶的數據對象集
      */
      public function getUserPostData(){
          return $this->userPostData;
      }
      /**
       檢查類型 方法
        依據不一樣的數據類型調用不一樣的模板
        判斷一下 微信反饋回來的數據類型 是否存在於 wx_msgType 數組中
     */
     private function isWeixinMsgType(){
         if(in_array($this->msgType,$this->wx_msgType)){
                 return true;
            }else{
                  return false;
            }
       }
     
    
      /**
        文本會話
      */
     private function textMessage($callData){
            if(is_null($callData)){
               return 'null';
            }
             $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>5</FuncFlag>
                    </xml>";
             if(is_string($callData)){
                 $resultStr = sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'text',$callData);            
             }else if(is_array($callData)){
                 $content='';
                 foreach($callData as $key => $value){
                     $content.=$value;
                    }
                 $resultStr= sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'text',$content);
             }
             return $resultStr;
     }
     /**
       圖片會話
     */
     private function imageMessage($callData){
         if(is_null($callData)){
               return 'null';
            }
         $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                      <Image>
                       <MediaId><![CDATA[%s]]></MediaId>
                      </Image>
                  </xml>";
         $resultStr = sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'image', $callData); 
         return $resultStr;
    }
     /**
      語音會話
     */
     private function voiceMessage($callData){
          if(is_null($callData)){
               return 'null';
            }
        $textTpl = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[%s]]></MsgType>
            <Voice>
              <MediaId><![CDATA[%s]]></MediaId>
            </Voice>
        </xml>";
      $resultStr = sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'voice',$callData['MediaId']);
       return $resultStr;
     }
     /**
      視頻會話
     */
     private function videoMessage($callData){
         if(is_null($callData)){
               return 'null';
            }
        $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        </Video>
        </xml>";
        $resultStr = sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'video',$callData['MediaId'],$callData['ThumbMediaId'],$callData['Title'],$callData['Description']);
        return $resultStr;
     }
     /**
      音樂會話
     */
     private function musicMessage($callData){ //依據文本 直接調用
          if(is_null($callData)){
               return 'null';
            }
        $textTpl = '<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
        </Music>
        </xml>';
        $resultStr = sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'music',$callData['Title'],$callData['Description'],$callData['MusicUrl'],$callData['HQMusicUrl']);
        return $resultStr;
     }
     /**
       回覆圖文消息
       $items 必須是數組 必須是二維數組
         $items=array(
             array('Title'=>'','Description'=>'','PicUrl'=>'','Url'=>'')
         
         )
     */
     private function newsMessage($items){
         if(is_null($items)){
               return 'null';
            }
        //##公共部分 圖文公共部分
         $textTpl = '<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <ArticleCount>%d</ArticleCount>
        <Articles>%s</Articles>
        </xml>';
       //##新聞列表部分模板
        $itemTpl = '<item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
        </item>';
         $articles = '';
         $count=0;
        if(is_array($items)){
             $level=$this->arrayLevel($items);//判斷數組的維度
             if($level == 1){ //是一維數組的狀況下
               $articles= sprintf($itemTpl, $items['Title'], $items['Description'], $items['PicUrl'], $items['Url']); 
               $count=1;
             }else{
                foreach($items as $key=>$item){
                 if(is_array($item)){
                       $articles.= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
                    }
                 }
               }
               $count=count($items);
             }
             $resultStr = sprintf($textTpl,$this->fromUserName,$this->toUserName,$this->createTime,'news',$count, $articles);
             return $resultStr;
     }
    
     /**
      debug調試
     */
     public function debug($data){
         echo '<pre>';
          print_r($data);
         echo '</pre>';
      }
           /**
        獲得數組的維度
      */
  private function arrayLevel($vDim){
    if(!is_array($vDim)){
        return 0; 
     }else{ 
         $max1 = 0; 
             foreach($vDim as $item1){ 
                $t1 = $this->arrayLevel($item1); 
                if( $t1 > $max1) {
                    $max1 = $t1; 
                }
             } 
        return $max1 + 1; 
       } 
  }
       
      /**
        訂閱號須要初始化
      */
      public function  weixinBaseApiMessage($args=array()){
               $this->setConfig($args);
               //檢查配置文件
               if(empty($this->weixinConfig)){
                  return false;
                }
                $this->handleUserRequest(); //處理用戶 請求
                return true;
        }
        public function weixinHighApiMessage($args=array()){
               $this->setConfig($args);
            //檢查配置文件
               if(empty($this->weixinConfig)){
                   return false;
                }
                return true;
                
        }
      /**
        經過同的類型調用不一樣的微信模板
         回覆微信內容信息
          $wxmsgType 參數是 數據類型 微信規定的類型
          $callData  參數是  數據庫查詢出來的數據或者指定數據
           小機器人 被動回覆 
     */
     public function responseMessage($wxmsgType,$callData=''){
            // if($this->isWeixinMsgType()){
                $method=$wxmsgType.'Message';//類型方法組裝
                $CallResultData=$this->$method($callData);//把程序的數據傳遞給模板,並返回數據格式
                if (!headers_sent()){//判斷是否有發送過頭信息,若是沒有就發送,並輸出內容
                 header('Content-Type: application/xml; charset=utf-8');
                 echo $CallResultData;
                 exit;
               } 
             //}
     }
      /**
       事件消息內容類型
      */
      public function responseEventMessage($message=''){
           $content = "";
           $event=$this->userPostData->Event;
           if($event == 'subscribe'){
               return  $content = $message;
           }elseif($event == 'unsubscribe'){
               return  $content = "取消關注";
           }elseif($event == 'scan' || $event=='SCAN'){
               return $this->getUserEventScanRequest();
           }elseif($event == 'click' || $event == 'CLICK'){
                switch ($this->userPostData->EventKey)
                {
                    case "company":
                        $content =$message.'爲你提供服務!';
                        break;
                    default:
                        $content =$this->getUsertEventClickRequest();//返回點擊的字符串
                        break;
                }
                return $content;
           }elseif($event == 'location' || $event=='LOCATION'){
                return $this->getUserLocationRequest();//本地地理位置分享後 返回x 、y座標,並返回經度和維度
           }elseif($event == 'view' || $event == 'VIEW'){
                return $this->userPostData->EventKey; //返回跳轉的連接
           }elseif($event == 'masssendjobfinish' || $event == 'MASSSENDJOBFINISH'){
               return $this->getUserMessageInfo();//返回會話的全部信息
           }else{
             return "receive a new event: ".$$this->userPostData->Event;  
           }
           return false;
        }
    
      
      /**
       獲取微信端 返回的數據類型
     */
     public function  getUserMsgType(){
         return strval($this->msgType);
     }
    
     /**
       獲取用戶發送信息的時間
     */
     public function getUserSendTime(){
        return $this->createTime;
     }
     /**
      獲取用戶的微信id
     */
     public function getUserWxId(){
         return  strval($this->fromUserName);
     }
     /**
      獲取到平臺的微信id
     */
     public function getPlatformId(){
         return strval($this->toUserName);
     }
      /**
       獲取用戶在客戶端返回的數據,文本數據
     */
     public function getUserTextRequest(){
         return  empty($this->keyword)?null:strval($this->keyword);
     }
     /**
       獲取接收消息編號,微信平臺接收的第幾條信息
     */
     public  function getUserRequestId(){
         return strval($this->requestId);
     }
     /**
      獲取圖片信息的內容
     */
     public function getUserImageRequest(){
         $image = array(); 
        $image['PicUrl'] = strval($this->userPostData->PicUrl);//圖片url地址
        $image['MediaId'] = strval($this->userPostData->MediaId);//圖片在微信公衆平臺下的id號
        return $image; 
     }
     /**
      獲取語音信息的內容
     */
     public function getUserVoiceRequest(){
        $voice = array();
        $voice['MediaId'] = $this->userPostData->MediaId;//語音ID
        $voice['Format'] = $this->userPostData->Format;//語音格式
        $voice['MsgId']=$this->userPostData->MsgId;//id
        if (isset($this->userPostData->Recognition) && !empty($this->userPostData->Recognition)){
         $voice['Recognition'] = $this->userPostData->Recognition;//語音的內容;;你剛纔說的是: xxxxxxxx
        }
        return $voice;
     }
     /**
      獲取視頻信息的內容
     */
     public function getUserVideoRequest(){
        $video = array();
        $video['MediaId'] =$this->userPostData->MediaId;
        $video['ThumbMediaId'] = $this->userPostData->ThumbMediaId;
        return $video;
     }
     /**
       獲取音樂消息內容
     */
     public function getUserMusicRequest(){
          $music=array();
          $music['Title'] =$this->userPostData->Title;//標題
          $music['Description']=$this->userPostData->Description;//簡介
          $music['MusicUrl']=$this->userPostData->MusicUrl;//音樂地址
          $music['HQMusicUrl']=$this->userPostData->HQMusicUrl;//高品質音樂地址
          return $music;
     }
     
     /**
      獲取本地地理位置信息內容
     */
      public function getUserLocationRequest(){
        $location = array();
        $location['Location_X'] = strval($this->userPostData->Location_X);//本地地理位置 x座標
        $location['Location_Y'] = strval($this->userPostData->Location_Y);//本地地理位置 Y 座標
        $location['Scale'] = strval($this->userPostData->Scale);//縮放級別爲
        $location['Label'] = strval($this->userPostData->Label);//位置爲
        $location['Latitude']=$this->userPostData->Latitude;//維度
        $location['Longitude']=$this->userPostData->Longitude;//經度
        return $location;  
      }
      /**
        獲取連接信息的內容
      */
      public function getUserLinkRequest(){ //數據以文本方式返回 在程序調用端 調用 text格式輸出
        $link = array();
        $link['Title'] = strval($this->userPostData->Title);//標題
        $link['Description'] = strval($this->userPostData->Description);//簡介
        $link['Url'] = strval($this->userPostData->Url);//連接地址
        return $link;  
      }
      /**
        二維碼掃描事件內容
      */
      public function getUserEventScanRequest(){
          $info = array();
          $info['EventKey'] = $this->userPostData->EventKey;
          $info['Ticket'] = $this->userPostData->Ticket;    
          $info['Scene_Id'] = str_replace('qrscene_', '', $this->userPostData->EventKey);
          return $info;
      }
      /**
        上報地理位置事件內容
      */
      public function getUserEventLocationRequest(){
          $location = array();
          $location['Latitude'] = $this->userPostData->Latitude;
          $location['Longitude'] =$this->userPostData->Longitude;
          return $location;
      }
      /**
        獲取菜單點擊事件內容
      */
      public function getUsertEventClickRequest(){
        return strval($this->userPostData->EventKey);
      }
      /**
        獲取微信會話狀態info
      */
        public function  getUserMessageInfo(){
            $info=array();
            $info['MsgID']=$this->userPostData->MsgID;//消息id
            $info['Status']=$this->userPostData->Status;//消息結果狀態
            $info['TotalCount']=$this->userPostData->TotalCount;//平臺的粉絲數量
            $info['FilterCount']=$this->userPostData->FilterCount;//過濾
            $info['SentCount']=$this->userPostData->SentCount;//發送成功信息
            $info['ErrorCount']=$this->userPostData->ErrorCount;//發送錯誤信息
            return $info;
        }
        /**
        向第三方請求數據,並返回結果
     */
    public  function relayPart3($url, $rawData){
       $headers = array("Content-Type: text/xml; charset=utf-8");
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
       $output = curl_exec($ch);
       curl_close($ch);
       return $output;
    }
    /**
    字節轉Emoji表情
    "中國:".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌:".$this->bytes_to_emoji(0x1F335);
    */
    public function bytes_to_emoji($cp){
        if ($cp > 0x10000){       # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x800){   # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x80){    # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else{                    # 1 byte
            return chr($cp);
        }
    }
      
    #############################################################高級接口################################
       /**
           微信api 接口地址
        */
       private  $weixinApiLinks = array(
            'message' => "https://api.weixin.qq.com/cgi-bin/message/custom/send?",##發送客服消息
            'group_create' => "https://api.weixin.qq.com/cgi-bin/groups/create?",##建立分組
            'group_get' => "https://api.weixin.qq.com/cgi-bin/groups/get?",##查詢分組
            'group_getid' => "https://api.weixin.qq.com/cgi-bin/groups/getid?",##查詢某個用戶在某個分組裏面
            'group_rename' => "https://api.weixin.qq.com/cgi-bin/groups/update?",##修改分組名
            'group_move' => "https://api.weixin.qq.com/cgi-bin/groups/members/update?",## 移動用戶分組
            'user_info' => "https://api.weixin.qq.com/cgi-bin/user/info?",###獲取用戶基本信息
            'user_get' => 'https://api.weixin.qq.com/cgi-bin/user/get?',##獲取關注者列表
            'menu_create' => 'https://api.weixin.qq.com/cgi-bin/menu/create?',##自定義菜單建立
            'menu_get' => 'https://api.weixin.qq.com/cgi-bin/menu/get?',##自定義菜單查詢
            'menu_delete' => 'https://api.weixin.qq.com/cgi-bin/menu/delete?',##自定義菜單刪除
            'qrcode' => 'https://api.weixin.qq.com/cgi-bin/qrcode/create?',##建立二維碼ticket
            'showqrcode' => 'https://mp.weixin.qq.com/cgi-bin/showqrcode?',##經過ticket換取二維碼
            'media_download' => 'http://file.api.weixin.qq.com/cgi-bin/media/get?',
            'media_upload' => 'http://file.api.weixin.qq.com/cgi-bin/media/upload?',##上傳媒體接口
            'oauth_code' => 'https://open.weixin.qq.com/connect/oauth2/authorize?',##微信oauth登錄獲取code
            'oauth_access_token' => 'https://api.weixin.qq.com/sns/oauth2/access_token?',##微信oauth登錄經過code換取網頁受權access_token
            'oauth_refresh' => 'https://api.weixin.qq.com/sns/oauth2/refresh_token?',##微信oauth登錄刷新access_token(若是須要)
            'oauth_userinfo' => 'https://api.weixin.qq.com/sns/userinfo?',##微信oauth登錄拉取用戶信息(需scope爲 snsapi_userinfo)
            'api_prefix'=>'https://api.weixin.qq.com/cgi-bin?',##請求api前綴
            'message_template'=>'https://api.weixin.qq.com/cgi-bin/message/template/send?',##模板發送消息接口
           'message_mass'=>'https://api.weixin.qq.com/cgi-bin/message/mass/send?',##羣發消息
           'upload_news'=>'https://api.weixin.qq.com/cgi-bin/media/uploadnews?',##上傳圖片素材
    );
      /**
        curl 數據提交
      */
    public function curl_post_https($url='', $postdata='',$options=FALSE){
        $curl = curl_init();// 啓動一個CURL會話
         curl_setopt($curl, CURLOPT_URL, $url);//要訪問的地址
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);//對認證證書來源的檢查
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);//從證書中檢查SSL加密算法是否存在
         curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);//模擬用戶使用的瀏覽器
         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);//使用自動跳轉
         curl_setopt($curl, CURLOPT_AUTOREFERER, 1);//自動設置Referer
         if(!empty($postdata)){
            curl_setopt($curl, CURLOPT_POST, 1);//發送一個常規的Post請求
             if(is_array($postdata)){
                curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($postdata,JSON_UNESCAPED_UNICODE));//Post提交的數據包  
             }else{
                curl_setopt($curl, CURLOPT_POSTFIELDS,$postdata);//Post提交的數據包 
             }
         }
        //curl_setopt($curl, CURLOPT_COOKIEFILE, './cookie.txt'); //讀取上面所儲存的Cookie信息
         // curl_setopt($curl, CURLOPT_TIMEOUT, 30);//設置超時限制防止死循環
          curl_setopt($curl, CURLOPT_HEADER, $options);//顯示返回的Header區域內容  能夠是這樣的字符串 "Content-Type: text/xml; charset=utf-8"
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//獲取的信息以文件流的形式返回
         $output = curl_exec($curl);//執行操做
         if(curl_errno($curl)){
              if($this->debug == true){
                   $errorInfo='Errno'.curl_error($curl);
                   $this->responseMessage('text',$errorInfo);//將錯誤返回給微信端
              }
        }
         curl_close($curl);//關鍵CURL會話
         return $output;//返回數據
   }
    /**
      本地緩存token
    */
     private function setFileCacheToken($cacheId,$data,$savePath='/'){
           $cache=array();
           $cache[$cacheId]=$data;
           $this->saveFilePath=$_SERVER['DOCUMENT_ROOT'].$savePath.'token.cache';
           file_exists($this->saveFilePath)?chmod($this->saveFilePath,0775):chmod($this->saveFilePath,0775);//給文件覆權限
           file_put_contents($this->saveFilePath,serialize($cache));
          
    }
     
     /**
       本地讀取緩存
     */
     private function getFileCacheToken($cacheId){
         $fileDataInfo=file_get_contents($_SERVER['DOCUMENT_ROOT'].'/token.cache');
         $token=unserialize($fileDataInfo);
          if(isset($token[$cacheId])){
              return $token[$cacheId];
          }
     }
   
   
      /**
         檢查高級接口權限 tokenc
        */
     public  function checkAccessToken(){
        if($this->appid && $this->appSecret){
             $access=$this->getFileCacheToken('access');
            if(isset($access['expires_in'])){
                 $this->expires_in= $access['expires_in'];
             }
             if( ( $this->expires_in  - time() ) <  0 ){//代表已通過期
                     $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appSecret}";
                     $access = json_decode($this->curl_post_https($url));
                     if(isset($access->access_token) && isset($access->expires_in)){
                      $this->access_token = $access->access_token;##獲得微信平臺返回獲得token
                      $this->expires_in=time()+$access->expires_in;##獲得微信平臺返回的過時時間
                      $this->setFileCacheToken('access',array('token'=>$this->access_token,'expires_in'=>$this->expires_in));##加入緩存access_token
                       return true;
                      }
                }else{
                     $access=$this->getFileCacheToken('access');
                     $this->access_token=$access['token'];
                     return true;
                }
          }
         return false;
    }
    /**
      獲取access_token
    */
    public function getAccessToken(){
        return strval($this->access_token);
    }
     /**
       獲得時間
     */
    public function getExpiresTime(){
       return $this->expires_in;
    }
    /**
      獲取用戶列表
       $next_openid 表示從第幾個開始,若是爲空 默認從第一個用戶開始拉取
    */
    public function getUserList($next_openid=null){
        $url=$this->weixinApiLinks['user_get']."access_token={$this->access_token}&next_openid={$next_openid}";
        $resultData=$this->curl_post_https($url);        
        return json_decode($resultData,true);
    }
    /**
     獲取用戶的詳細信息
    */
    public function getUserInfo($openid){
         $url=$this->weixinApiLinks['user_info']."access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
         $resultData=$this->curl_post_https($url);
         return json_decode($resultData,true);
    }
    /**
     建立用戶分組
    */
    public function createUsersGroup($groupName){
         $data = '{"group": {"name": "'.$groupName.'"}}';
         $url=$this->weixinApiLinks['group_create']."access_token=".$this->access_token;
         $resultData=$this->curl_post_https($url,$data);
         return json_decode($resultData,true);
    }
    /**
      移動用戶分組
    */
    public function moveUserGroup($toGroupid,$openid){
        $data = '{"openid":"'.$openid.'","to_groupid":'.$toGroupid.'}';
        $url=$this->weixinApiLinks['group_move']."access_token=".$this->access_token;
        $resultData=$this->curl_post_https($url,$data);
        return json_decode($resultData,true);
    }
    /**
      查詢全部分組
    */
    public function getUsersGroups(){
        $url=$this->weixinApiLinks['group_get']."access_token=".$this->access_token;
        $resultData=$this->curl_post_https($url);
        return json_decode($resultData,true);
    }
    /**
     查詢用戶所在分組
    */
    public function getUserGroup($openid){
        $data='{"openid":"'.$openid.'"}';
        $url=$this->weixinApiLinks['group_getid']."access_token=".$this->access_token;
        $resultData=$this->curl_post_https($url,$data);
        return json_decode($resultData,true);
    }
    /**
     修改分組名
    */
    public function updateUserGroup($groupId,$groupName){
        $data='{"group":{"id":'.$groupId.',"name":"'.$groupName.'"}}';
        $url=$this->weixinApiLinks['group_rename']."access_token=".$this->access_token;
        $resultData=$this->curl_post_https($url,$data);
        return json_decode($resultData,true);
    }
    /**
     生成二維碼
    */
    public function createQrcode($scene_id=0,$qrcodeType=1,$expire_seconds=1800){
          $scene_id=($scene_id == 0)?rand(1,9999):$scene_id;
          if($qrcodeType == 1){
              $action_name='QR_SCENE';##表示臨時二維碼
               $data='{"expire_seconds":'.$expire_seconds.',"action_name": "QR_SCENE","action_info":{"scene":{"scene_id": '.$scene_id.'}}}';
           }else{
              $action_name='QR_LIMIT_SCENE';
              $data='{"action_name": "QR_LIMIT_SCENE", "action_info":{"scene":{"scene_id": '.$scene_id.'}}}';
           }
           $url=$this->weixinApiLinks['qrcode']."access_token=".$this->access_token;
           $resultData=$this->curl_post_https($url,$data);
           $result=json_decode($resultData,true);
           return $this->weixinApiLinks['showqrcode']."ticket=".urlencode($result["ticket"]);
     }
     /**
      上傳多媒體文件
      type 分別有圖片(image)、語音(voice)、視頻(video)和縮略圖(thumb) 
     */
        public function uploadMedia($type, $file){
            $data=array("media"  => "@".dirname(__FILE__).'\\'.$file);
            $url=$this->weixinApiLinks['media_upload']."access_token=".$this->access_token."&type=".$type;
            $resultData=$this->curl_post_https($url, $data);
            return json_decode($resultData, true);
        }
        /**
        建立菜單
        */
        public function createMenu($menuListdata){
            $url =$this->weixinApiLinks['menu_create']."access_token=".$this->access_token;
            $resultData = $this->curl_post_https($url, $menuListdata);
            $callData=json_decode($resultData, true);
             if($callData['errcode'] > 0){#表示菜單建立失敗
                 return $callData;
             }
             return true;
        }
        /**
          查詢菜單
        */
        public function queryMenu(){
            $url = $this->weixinApiLinks['menu_get']."access_token=".$this->access_token;
            $resultData = $this->curl_post_https($url);
            return json_decode($resultData, true);
        }
        /**
         刪除菜單
        */
        public function deleteMenu(){
            $url = $this->weixinApiLinks['menu_delete']."access_token=".$this->access_token;
            $resultData = $this->curl_post_https($url);
            return json_decode($resultData, true);
        }
    /**
      給某我的發送文本內容
    */
    public function sendMessage($touser, $data, $msgType = 'text'){
             $message = array();
             $message['touser'] = $touser;
             $message['msgtype'] = $msgType;
             switch ($msgType){
                 case 'text':  $message['text']['content']=$data; break;
                 case 'image': $message['image']['media_id']=$data; break;
                 case 'voice': $message['voice']['media_id']=$data; break;
                 case 'video': 
                     $message['video']['media_id']=$data['media_id'];
                     $message['video']['thumb_media_id']=$data['thumb_media_id'];
                 break;
                 case 'music':  
                    $message['music']['title'] = $data['title'];// 音樂標題
                    $message['music']['description'] = $data['description'];// 音樂描述
                    $message['music']['musicurl'] = $data['musicurl'];// 音樂連接
                    $message['music']['hqmusicurl'] = $data['hqmusicurl'];// 高品質音樂連接,wifi環境優先使用該連接播放音樂
                    $message['music']['thumb_media_id'] = $data['title'];// 縮略圖的媒體ID
                 break;
                 case 'news':
                   $message['news']['articles'] = $data; // title、description、url、picurl
                   break;
             }
             $url=$this->weixinApiLinks['message']."access_token={$this->access_token}";
             $calldata=json_decode($this->curl_post_https($url,$message),true);
              if(!$calldata || $calldata['errcode'] > 0){
                  return false;
              }
              return true;
        }

    /**
     *  羣發
     * */

    public  function  sendMassMessage($sendType,$touser=array(),$data){
          $massArrayData=array();
          switch($sendType){
              case 'text':##文本
                  $massArrayData=array(
                      "touser"=>$touser,
                      "msgtype"=>'text',
                      "text"=>array('content'=>$data),
                  );
                  break;
              case 'news':##圖文
                  $massArrayData=array(
                      "touser"=>$touser,
                      "msgtype"=>'mpnews',
                      "mpnews"=>array('media_id'=>$data),
                  );
                  break;
              case 'voice':##語音
                  $massArrayData=array(
                      "touser"=>$touser,
                      "msgtype"=>'voice',
                      "voice"=>array('media_id'=>$data),
                  );
                  break;
              case 'image':##圖片
                  $massArrayData=array(
                      "touser"=>$touser,
                      "msgtype"=>'image',
                      "media_id"=>array('media_id'=>$data),
                  );
                  break;
              case 'wxcard': ##卡卷
                  $massArrayData=array(
                      "touser"=>$touser,
                      "msgtype"=>'wxcard',
                      "wxcard"=>array('card_id'=>$data),
                  );
                  break;
          }
         $url=$this->weixinApiLinks['message_mass']."access_token={$this->access_token}";
         $calldata=json_decode($this->curl_post_https($url,$massArrayData),true);
         return $calldata;
     }
    /**
     發送模板消息
     */    
     public function  sendTemplateMessage($touser,$template_id,$url,$topColor,$data){
         $templateData=array(
            'touser'=>$touser,
            'template_id'=>$template_id,
            'url'=>$url,
            'topcolor'=>$topColor,
            'data'=>$data,
          );
           $url=$this->weixinApiLinks['message_template']."access_token={$this->access_token}";
           $calldata=json_decode($this->curl_post_https($url,urldecode(json_encode($templateData))),true);
           return $calldata;
     }

    /**
     * @param $type
     * @param $filePath 文件根路徑
     */
    public  function  mediaUpload($type,$filePath){
        $url=$this->weixinApiLinks['media_upload']."access_token={$this->access_token}&type=".$type;
        $postData=array('media'=>'@'.$filePath);
        $calldata=json_decode($this->https_request($url,$postData),true);
        return $calldata;
    }

    /**
     * @param $data
     * @return mixed
     *   上傳圖片資源
     */
    public  function  newsUpload($data){
       $articles=array( 'articles'=>$data );
       $url=$this->weixinApiLinks['upload_news']."access_token={$this->access_token}";
       $calldata=json_decode($this->curl_post_https($url,$articles),true);
        return $calldata;
    }
    /**
     * 獲取微信受權連接
     *
     * @param string $redirect_uri 跳轉地址
     * @param mixed $state 參數
     */
    public function getOauthorizeUrl($redirect_uri = '', $state = '',$scope='snsapi_userinfo'){
        $redirect_uri = urlencode($redirect_uri);
        $state=empty($state)?'1':$state;
        $url=$this->weixinApiLinks['oauth_code']."appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
        return $url;
    }
    /**
     * 獲取受權token
     *
     * @param string $code 經過get_authorize_url獲取到的code
     */
    public function getOauthAccessToken(){
        $code = isset($_GET['code'])?$_GET['code']:'';
        if (!$code) return false;
        $url=$this->weixinApiLinks['oauth_access_token']."appid={$this->appid}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
        $token_data=json_decode($this->curl_post_https($url),true);
        $this->oauthAccessToken=$token_data['access_token'];
        return $token_data;
    }

    /**
     * 刷新access token並續期
     */
    public  function  getOauthRefreshToken($refresh_token){
        $url=$this->weixinApiLinks['oauth_refresh']."appid={$this->appid}&grant_type=refresh_token&refresh_token={$refresh_token}";
        $token_data=json_decode($this->curl_post_https($url),true);
        $this->oauthAccessToken=$token_data['access_token'];
        return $token_data;
    }
    /**
     * 獲取受權後的微信用戶信息
     *
     * @param string $access_token
     * @param string $open_id 用戶id
     */
    public function getOauthUserInfo($access_token='', $open_id = ''){
       $url=$this->weixinApiLinks['oauth_userinfo']."access_token={$access_token}&openid={$open_id}&lang=zh_CN";
       $info_data=json_decode($this->curl_post_https($url),true);
       return $info_data;
    }
    /**
     * 登出當前登錄用戶
     */
    public function logout($openid='',$uid=''){
        $url = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxlogout?redirect=1&type=1';
        $data=array('uin'=>$uid,'sid'=>$openid);
        $this->curl_post_https($url,$data);
        return true;
    }
    public  function https_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}

告知義務:
  1. api提供訂閱號基本服務以及公衆號經常使用服務;

  2. api如不能知足您的需求,請閱讀微信公衆平臺說明文檔

使用說明:
     header('Content-type: text/html; charset=utf-8');#設置頭信息
     require_once('zhphpWeixinApi.class.php');#加載微信接口類文件
     $zhwx=new zhphpWeixinApi();//實例化
     
    配置:
       第一種方式: 
       $zhwx->weixinConfig=array(
                            'token'=>'weixintest',
                            'appid'=>'wx7b4b6ad5c7bfaae1',
                            'appSecret'=>'faaa6a1e840fa40527934a293fabfbd1',
                            'myweixinId'=>'gh_746ed5c6a58b'
                            );
                            
        第二種方式:
        $configArr=array(
                'token'=>'weixintest',
                'appid'=>'wx7b4b6ad5c7bfaae1',
                'appSecret'=>'faaa6a1e840fa40527934a293fabfbd1',
                'myweixinId'=>'gh_746ed5c6a58b'
                );
        $zhwx->setConfig($configArr);
        
        第三種方式:
             $zhwx->weixinBaseApiMessage($configArr); ##訂閱號使用 

             $zhwx->weixinHighApiMessage($configArr);## 服務號使用
             
    官方建議使用 第二種方式         
        
        
    訂閱號基本功能調用
       $zhwx->weixinBaseApiMessage(); #訂閱號接口入口  返回 true  false
       
       
     下面是調用案例
    if($zhwx->weixinBaseApiMessage()){ //基本微信接口會話 必須
        $keyword=$zhwx->getUserTextRequest();//獲得用戶發的微信內容, 這裏能夠寫你的業務邏輯
        $msgtype=$zhwx->getUserMsgType();//獲得用戶發的微信數據類型, 這裏能夠寫你的業務邏輯
        $SendTime=$zhwx->getUserSendTime();//獲得用戶發送的時間
        $fromUserName=$zhwx->getUserWxId();//用戶微信id
        $pingtaiId=$zhwx->getPlatformId();//平臺微信id
        $requestId=$zhwx->getUserRequestId(); //獲取微信公衆平臺消息ID
        $userPostData=$zhwx->getUserPostData();//獲取用戶提交的post 數據對象集
    if( $msgtype == 'text' ){ //若是是文本類型
             if($keyword == 'news'){ //新聞類別請求
                $callData=array(
                      array('Title'=>'第一條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'http://t12.baidu.com/it/u=1040955509,77044968&fm=76','Url'=>'http://wxphptest1.applinzi.com/'),
                      array('Title'=>'第二條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'https://images0.cnblogs.com/blog2015/340216/201505/051316468603876.png','Url'=>'http://wxphptest1.applinzi.com/'),
                      array('Title'=>'第三條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'http://dimgcn2.s-msn.com/imageadapter/w60h60q85/stimgcn3.s-msn.com/msnportal/hp/2016/01/21/3e3ef7f07361b5211e2b155bb66fa6a9.jpg','Url'=>'http://wxphptest1.applinzi.com/'),
                 );
                $zhwx->responseMessage('news',$callData);
            }elseif($keyword == 'music'){ //音樂請求
               $music=array(
                 "Title"=>"最炫民族風",
                 "Description"=>"歌手:鳳凰傳奇",
                 "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3",
                 "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3"
                );
                $zhwx->responseMessage('music',$music); 
            }else{
                $callData='這是zhphp 官方對你的回覆:
                         你輸入的內容是'.$keyword.'
                         你發數據類型是:'.$msgtype.'
                         你發的數據時間是:'.$SendTime.'
                         你的微信ID是:'.$fromUserName.'
                         平臺的微信Id是:'.$pingtaiId.'
                         zhphp官方接收的ID是:'.$requestId;
                $zhwx->responseMessage('text',$callData);
            }
    }else if($msgtype == 'image'){ //若是是圖片類型
             $image=$zhwx->getUserImageRequest();//若是用戶發的是圖片信息,就去獲得用戶的圖形 信息
             $callData=$image['MediaId'];//mediaID 是微信公衆平臺返回的圖片的id,微信公衆平臺是依據該ID來調用用戶所發的圖片
             $zhwx->responseMessage('image',$callData);
            
        }else if($msgtype == 'voice'){ //若是是語音消息,用於語音交流
            $callData=$zhwx->getUserVoiceRequest(); //返回數組
            $zhwx->responseMessage('voice',$callData);
        }elseif($msgtype == 'event'){//事件,由系統自動檢驗類型
            $content='感謝你關注zhphp官方平臺';//給數據爲數據庫查詢出來的
            $callData=$zhwx->responseEventMessage($content);//把數據放進去,由系統自動檢驗類型,並返回字符串或者數組的結果
            $zhwx->responseMessage('text',$callData); //使用數據
        }else{
            $callData='這是zhphp 官方對你的回覆:
                       你發數據類型是:'.$msgtype.'
                       你發的數據時間是:'.$SendTime.'
                     zhphp官方接收的ID是:'.$requestId;
            $zhwx->responseMessage('text',$callData);
        }
    }
    ##########################################
    訂閱號提供基本接口
     validToken()       平臺與微信公衆號握手
     getAccessToken()   獲取accessToken
     getExpiresTime()   獲取accessToken 過時時間
     CheckAccessToken()  檢查高級接口權限
     bytes_to_emoji($cp) 字節轉表情
     getUserMessageInfo() 獲取用戶的全部會話狀態信息
     getUsertEventClickRequest() 獲取用戶點擊菜單信息
     getUserEventLocationRequest() 上報地理位置事件
     getUserEventScanRequest()  二維碼掃描類容
     getUserLinkRequest()       獲取用戶連接信息
     getUserLocationRequest()   獲取用戶本地位置信息
     getUserMusicRequest()      獲取音樂內容
     getUserVideoRequest()      獲取視頻內容
     getUserVoiceRequest()      獲取語音消息
     getUserImageRequest()      獲取圖片消息
     getUserRequestId()         返回微信平臺的當條微信id
     getUserTextRequest()       獲取用戶輸入的信息
     getPlatformId()             獲取當前平臺的id
     getUserWxId()                獲取當前用戶的id
     getUserSendTime()             獲取用戶發送微信的時間
     getUserMsgType()              獲取當前的會話類型
     isWeixinMsgType()             檢查用戶發的微信類型
     getUserPostData()             獲取用戶發送信息的數據對象集
     getConfig()                    獲取配置信息
     responseMessage($wxmsgType,$callData='')  微信平臺回覆用戶信息統一入口
    
    #####################################################
    服務號基本功能調用
      $zhwx->weixinHighApiMessage();  #服務號接口入口  返回 true  false
      $zhwx->CheckAccessToken();       #檢查access權限
      
      下面是調用案例
       if($zhwx->weixinHighApiMessage()){// 檢查配置統一入口
          if($zhwx->CheckAccessToken()){  //檢查accessToken 爲必須
          $arrayData=$zhwx->getUserList(); ##測試用戶列表
           echo '<pre>';
            rint_r($arrayData);
          echo '</pre>';*/
       }
     }
     
     ######################################################
     服務號提供的接口:
         getUserList($next_openid=null)  獲取用戶列表
         getUserInfo($openid)            獲取用戶詳細信息
         createUsersGroup($groupName)    建立分組
         moveUserGroup($toGroupid,$openid) 移動用戶到組
         getUsersGroups()                  獲取全部分組
         getUserGroup($openid)              獲取用戶所在的組
         updateUserGroup($groupId,$groupName) 修改組名
         createQrcode($scene_id,$qrcodeType=1,$expire_seconds=1800) 生成二維碼
         uploadMedia($type, $file)  上傳文件
         createMenu($menuListdata)   建立菜單
         queryMenu()                 查詢菜單
         deleteMenu()                刪除菜單
         sendMessage($touser, $data, $msgType = 'text') 主動某個用戶發送數據
         newsUpload($data) 上傳圖文素材 按接口規定 $data 必須是二維數組
         mediaUpload($type,$filePath)  上傳媒體文件 filePath 必須是文件絕對路徑
         sendTemplateMessage($touser,$template_id,$url,$topColor,$data) 發送模板消息 一般爲通知接口
         sendMassMessage($sendType,$touser=array(),$data)  羣發消息
    
    
    
header('Content-type: text/html; charset=utf-8');#設置頭信息
// 微信類 調用
require_once('zhphpWeixinApi.class.php');
echo 'helloword';
exit;
$zhwx=new zhphpWeixinApi();//實例化
$zhwx->weixinConfig=array('token'=>'weixintest','appid'=>'wx7b4b6ad5c7bfaae1','appSecret'=>'faaa6a1e840fa40527934a293fabfbd1','myweixinId'=>'gh_746ed5c6a58b');//參數配置
/*$configArr=array(
     'token'=>'weixintest',
     'appid'=>'wx7b4b6ad5c7bfaae1',
     'appSecret'=>'faaa6a1e840fa40527934a293fabfbd1',
     'myweixinId'=>'gh_746ed5c6a58b'
     );
 $zhwx->setConfig($configArr);
*/
 #################################應用程序邏輯#  訂閱號測試 start #####################################
    if($zhwx->weixinBaseApiMessage()){ //基本微信接口會話 必須
        $keyword=$zhwx->getUserTextRequest();//獲得用戶發的微信內容, 這裏能夠寫你的業務邏輯
        $msgtype=$zhwx->getUserMsgType();//獲得用戶發的微信數據類型, 這裏能夠寫你的業務邏輯
        $SendTime=$zhwx->getUserSendTime();//獲得用戶發送的時間
        $fromUserName=$zhwx->getUserWxId();//用戶微信id
        $pingtaiId=$zhwx->getPlatformId();//平臺微信id
        $requestId=$zhwx->getUserRequestId(); //獲取微信公衆平臺消息ID
        $userPostData=$zhwx->getUserPostData();//獲取用戶提交的post 數據對象集
    if( $msgtype == 'text' ){ //若是是文本類型
             if($keyword == 'news'){ //新聞類別請求
                $callData=array(
                      array('Title'=>'第一條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'http://t12.baidu.com/it/u=1040955509,77044968&fm=76','Url'=>'http://wxphptest1.applinzi.com/'),
                      array('Title'=>'第二條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'https://images0.cnblogs.com/blog2015/340216/201505/051316468603876.png','Url'=>'http://wxphptest1.applinzi.com/'),
                      array('Title'=>'第三條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'http://dimgcn2.s-msn.com/imageadapter/w60h60q85/stimgcn3.s-msn.com/msnportal/hp/2016/01/21/3e3ef7f07361b5211e2b155bb66fa6a9.jpg','Url'=>'http://wxphptest1.applinzi.com/'),
                 );
                $zhwx->responseMessage('news',$callData);
            }elseif($keyword == 'music'){ //音樂請求
               $music=array(
                 "Title"=>"最炫民族風",
                 "Description"=>"歌手:鳳凰傳奇",
                 "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3",
                 "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3"
                );
                $zhwx->responseMessage('music',$music); 
            }else{
                $callData='這是zhphp 官方對你的回覆:
                         你輸入的內容是'.$keyword.'
                         你發數據類型是:'.$msgtype.'
                         你發的數據時間是:'.$SendTime.'
                         你的微信ID是:'.$fromUserName.'
                         平臺的微信Id是:'.$pingtaiId.'
                         zhphp官方接收的ID是:'.$requestId;
                $zhwx->responseMessage('text',$callData);
            }
    }else if($msgtype == 'image'){ //若是是圖片類型
             $image=$zhwx->getUserImageRequest();//若是用戶發的是圖片信息,就去獲得用戶的圖形 信息
             $callData=$image['MediaId'];//mediaID 是微信公衆平臺返回的圖片的id,微信公衆平臺是依據該ID來調用用戶所發的圖片
             $zhwx->responseMessage('image',$callData);
            
        }else if($msgtype == 'voice'){ //若是是語音消息,用於語音交流
            $callData=$zhwx->getUserVoiceRequest(); //返回數組
            $zhwx->responseMessage('voice',$callData);
        }elseif($msgtype == 'video'){//視頻請求未測試成功
            $video=$zhwx->getUserVideoRequest();//獲得用戶視頻內容信息
            $callData['Title']='這是是視頻的標題';//參數爲必須
            $callData['Description']='這是視頻的簡介';//參數爲必須
            $callData['MediaId']=$video['MediaId'];//獲得數組中的其中的一個id
            $callData['ThumbMediaId']=$video['ThumbMediaId'];//視頻的縮略圖id
            $zhwx->responseMessage('video',$callData); //把數據傳遞到平臺接口 api 類 操做並返回數據給微信平臺
        }elseif($msgtype == 'link'){
            $link=$zhwx->getUserLinkRequest();
            $callData='這是zhphp 官方對你的回覆:
                     你輸入的內容是'.$keyword.'
                     你發數據類型是:'.$msgtype.'
                     你發的數據時間是:'.$SendTime.'
                    zhphp官方接收的ID是:'.$requestId;
           $zhwx->responseMessage('text',$callData);
       }elseif($msgtype == 'event'){//事件,由系統自動檢驗類型
            $content='感謝你關注zhphp官方平臺';//給數據爲數據庫查詢出來的
            $callData=$zhwx->responseEventMessage($content);//把數據放進去,由系統自動檢驗類型,並返回字符串或者數組的結果
            $zhwx->responseMessage('text',$callData); //使用數據
        }else{
            $callData='這是zhphp 官方對你的回覆:
                       你發數據類型是:'.$msgtype.'
                       你發的數據時間是:'.$SendTime.'
                     zhphp官方接收的ID是:'.$requestId;
            $zhwx->responseMessage('text',$callData);
        }
    }
 
###################################服務號測試 start ############
/*if($zhwx->weixinHighApiMessage()){// 檢查配置統一入口
$zhwx->checkAccessToken();
    //if($zhwx->checkAccessToken()){  //檢查accessToken 爲必須
      //$arrayData=$zhwx->getUserList(); ##測試用戶列表
       /*$openid='oQucos17KaXpwPfwp39FwzfzrfNA'; ###測試獲取我的信息
       $arrayData=$zhwx->getUserInfo($openid);
       echo '<pre>';
      print_r($arrayData);
      echo '</pre>';*/
      ###測試二維碼
      //$qrcodeImgsrc=$zhwx->createQrcode(100);
      //echo '<img src="'.$qrcodeImgsrc.'">';
      ###建立一個一級菜單  type 點擊類型  name 菜單名稱  key 菜單說明 
       /*$menuListData=array(
         'button'=>array(
            array('type'=>'click','name'=>'投票活動','key'=>'tphd',),
            array('type'=>'view','name'=>'查看結果','key'=>'ckjg','url'=>''),
           )
       );
       $list=$zhwx->createMenu($menuListData);
        var_dump($list);
      
 //}
}*/

###############################模板消息################
if($zhwx->weixinBaseApiMessage()){
    if($msgtype == 'text'){
        $location=urlencode($keyword);
        $url='http://api.map.baidu.com/telematics/v3/weather?location='.$location.'&output=json&ak=C845576f91f52f4e62bf8d9153644cb8';
        $jsonData=$zhwx->curl_post_https($url);
        $data=json_decode($jsonData,true);
        $weth=$data['results'][0];
      /*$content='你查詢的是:'.$weth['currentCity'].'的天氣狀況';
        $content.='pm2.5='.$weth['pm25'];
        $content.='今天的天氣是:'.$weth['weather_data'][0]['date'];
        $zhwx->responseMessage('text',$content);*/
        // $userlist=$zhwx->getUserList();
        // $zhwx->responseMessage('text',json_encode($userlist));
       $touser= $fromUserName;
        $tpl_id='eSYzsYE3rCupK8_boCnfMcayi0cUXwPB6W7Lrz4TrdA';
        $url='http://www.baidu.com/';
        $topcolor="#52654D";
        $wdata=array(
            'first'=>array('value'=>urlencode('歡迎使用天氣查詢系統'),'color'=>'#12581F'),
            'city'=>array('value'=>urlencode($weth['currentCity']),'color'=>'#56751F'),
            'pm'=>array('value'=>urlencode($weth['pm25']),'color'=>'#15751F'),
         );
        $zhwx->checkAccessToken();
        $cc=$zhwx->sendTemplateMessage($touser,$tpl_id,$url,$topcolor,$wdata);
    }
    }

###########################################新增羣發消息
<?php
header('Content-type: text/html; charset=utf-8');#設置頭信息
require_once('zhphpWeixinApi.class.php');
$zhwx=new zhphpWeixinApi();//實例化
$configArr=array(
     'token'=>'weixintest',
     'appid'=>'wx7b4b6ad5c7bfaae1',
     'appSecret'=>'faaa6a1e840fa40527934a293fabfbd1',
     'myweixinId'=>'gh_746ed5c6a58b'
     );
 $zhwx->setConfig($configArr);
 $zhwx->checkAccessToken();
 $userlist=$zhwx->getUserList();

if(isset($_POST['sub'])){
   $touser=$_POST['userOpenId'];
    //開始羣發
    $content='這是羣發的文本';
    $data= $zhwx->sendMassMessage('text',$touser,$content);
    echo '<pre>';
   print_r($data);
    echo '</pre>';
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>微信羣發信息</title>
     <style type="text/css">
         .userlistBox{
             width: 1000px;
             height: 300px;
             border: 1px solid  red;
         }
          td{ text-align: center; border: 1px solid black;}

     </style>
</head>
<body>

     <?php
      $userinfos=array();
       foreach($userlist['data'] as  $key=>$user){
            foreach($user as $kk=>$list){
                $userinfos[]=$zhwx->getUserInfo($list);
            }
        }
     ?>
     <form action="wx.php?act=send" method="post">
         <div class="userlistBox">
             <h2>請選擇用戶</h2>
             <table >
                 <tr>
                     <th style="width: 10%;">編號</th>
                     <th style="width: 15%;">關注事件類型</th>
                     <th style="width: 15%;">用戶姓名</th>
                     <th style="width: 10%;">性別</th>
                     <th style="width: 15%;">頭像</th>
                     <th style="width: 15%;">所在地</th>
                     <th style="width: 15%;">所在組</th>
                     <th style="width: 5%;">操做</th>
                 </tr>
                 <?php
                 foreach($userinfos  as $key=>$userinfo){
                     ?>
                     <tr>
                         <td><?php echo $key+1;?></td>
                         <td><?php
                             if($userinfo['subscribe'] == 1){
                                 echo '普通關注事件';
                             }
                             ?></td>
                         <td> <?php echo  $userinfo['nickname'];  ?></td>
                         <td> <?php echo  $userinfo['sex']==1?'男':'女';  ?></td>
                         <td>  <?php
                             if(empty($userinfo['headimgurl'])){
                                 echo '沒有頭像';
                             }else{
                                 echo '<img width="50px" height="50px" src="'.$userinfo['headimgurl'].'">';
                             }
                             ?></td>
                         <td><?php  echo $userinfo['country'].'-'.$userinfo['province'].'-'.$userinfo['city']; ?></td>
                         <td><?php
                             if($userinfo['groupid']  == 0){
                                 echo '沒有分組';
                             }else{
                                 echo '還有完善功能';
                             }
                             ?>
                         </td>
                         <td><input type="checkbox" value="<?php echo $userinfo['openid'];?>" name="userOpenId[]" id="m_<?php echo $key+1; ?>" /></td>
                     </tr>
                 <?php
                 }
                 ?>
             </table>
              <input type="submit" name="sub" value="發送" />
         </div>
    </form>
</body>
</html>
#######################################圖文發送案例調用
<?php
header('Content-type: text/html; charset=utf-8');#設置頭信息
require_once('dodiWeixinApi.class.php');
$zhwx=new dodiWeixinApi();//實例化
$configArr=array(
     'token'=>'weixintest',
     'appid'=>'wx7b4b6ad5c7bfaae1',
     'appSecret'=>'faaa6a1e840fa40527934a293fabfbd1',
     'myweixinId'=>'gh_746ed5c6a58b'
     );
 $zhwx->setConfig($configArr);##配置參數
 $zhwx->checkAccessToken();##檢查token
 $userlist=$zhwx->getUserList();##獲取用戶列表
 //var_dump($userlist);
 //$callData=$zhwx->mediaUpload('image','a.jpg');## 上傳圖片到微信  獲得 media id
//CQKrXGNiJWiKutD17CWhoqlqW_80IByyFpLWa-dnPzhl7jPpQFiBbXhsAQVwId-q
  $data=array(
        array(
            "thumb_media_id"=>"CQKrXGNiJWiKutD17CWhoqlqW_80IByyFpLWa-dnPzhl7jPpQFiBbXhsAQVwId-q",
            "author"=>"xxx",
            "title"=>"Happy Day",
            "content_source_url"=>"www.qq.com",
            "content"=>"<div style='width: 100%; height: 50px; background-color: red;'>文章內容</div>",
            "diges"=>"digest"
        ),
);
 //$aa=$zhwx->newsUpload($data);//上傳圖文素材[ media_id] => 2n32OjOIdP7jewG0d55bKvuJYcH6XpWTeg8ViHCfzHGgKBZxmE72s3T2LY-3Q8LO





if(isset($_POST['sub'])){
   $touser=$_POST['userOpenId'];
    //開始羣發
     $content='
     <div><img src="http://d005151912.0502.dodi.cn/a.jpg" style="width:100%; height:50px;"></div>
     <div> 這是商品說明</div>
     ';
     $content.='查看詳情: <a  href="http://msn.huanqiu.com/china/article/2016-01/8473360.html">國家統計局局長王保安涉嫌嚴重違紀被免職</a>';
   // $data= $zhwx->sendMassMessage('text',$touser,$content);
     $data=$zhwx->sendMassMessage('news',$touser,'2n32OjOIdP7jewG0d55bKvuJYcH6XpWTeg8ViHCfzHGgKBZxmE72s3T2LY-3Q8LO'); ##主動發送圖文消息
    echo '<pre>';
   print_r($data);
    echo '</pre>';
    exit;
}
?>
View Code

 

下面是個人寫法css

1.首先是個人文件結構html

2.文件偷偷打開來給你看看git

<?php
header('Content-type: text/html; charset=utf-8');#設置頭信息
require_once('weixinapi.php');#加載微信接口類文件
$zhwx=new zhphpWeixinApi();//實例化

$configArr=array(//本身修改
  'token'=>'----------------',
  'appid'=>'----------------------',
  'appSecret'=>'--------------------',
  'myweixinId'=>'--------------------'
);
$zhwx->setConfig($configArr);

if($zhwx->weixinBaseApiMessage()){ //基本微信接口會話 必須
    $keyword=$zhwx->getUserTextRequest();//獲得用戶發的微信內容, 這裏能夠寫你的業務邏輯
    $msgtype=$zhwx->getUserMsgType();//獲得用戶發的微信數據類型, 這裏能夠寫你的業務邏輯
    $SendTime=$zhwx->getUserSendTime();//獲得用戶發送的時間
    $fromUserName=$zhwx->getUserWxId();//用戶微信id
    $pingtaiId=$zhwx->getPlatformId();//平臺微信id
    $requestId=$zhwx->getUserRequestId(); //獲取微信公衆平臺消息ID
    $userPostData=$zhwx->getUserPostData();//獲取用戶提交的post 數據對象集
  if( $msgtype == 'text' ){ //若是是文本類型
       if($keyword == 'news'){ //新聞類別請求
        $callData=array(
            array('Title'=>'第一條新聞','Description'=>'第一條新聞的簡介','PicUrl'=>'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3246575267,854993829&fm=27&gp=0.jpg','Url'=>'https://mp.weixin.qq.com/s/ay8RRkElw2xUlffeDnhQLw'),
            array('Title'=>'第二條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'https://images0.cnblogs.com/blog2015/340216/201505/051316468603876.png','Url'=>'http://wxphptest1.applinzi.com/'),
            array('Title'=>'第三條新聞的標題','Description'=>'第一條新聞的簡介','PicUrl'=>'http://dimgcn2.s-msn.com/imageadapter/w60h60q85/stimgcn3.s-msn.com/msnportal/hp/2016/01/21/3e3ef7f07361b5211e2b155bb66fa6a9.jpg','Url'=>'http://wxphptest1.applinzi.com/'),
         );
        $zhwx->responseMessage('news',$callData);
      }elseif($keyword == 'music'){ //音樂請求
         $music=array(
         "Title"=>"安眠曲",
         "Description"=>"譚嗣同",
         "MusicUrl"=>"https://www.xiami.com/song/xN1kyHa331d?spm=a1z1s.3521865.23309997.51.kf2b5r"
         // ,"HQMusicUrl"=>"http://www.kugou.com/song/#hash=3339B5F7024EC2ABB8954C0CC4983548&album_id=548709"
        );
        $zhwx->responseMessage('music',$music); 
      }else{
        $callData='我輕輕的告訴你~
你輸入的內容是:'.$keyword.'
你發數據類型是:'.$msgtype.'
你發的數據時間是:'.$SendTime.'
------------------------------------------'.'
輸入 "news" "music"試試吧!';
        $zhwx->responseMessage('text',$callData);
      }
  }else if($msgtype == 'image'){ //若是是圖片類型
       $image=$zhwx->getUserImageRequest();//若是用戶發的是圖片信息,就去獲得用戶的圖形 信息
       $callData=$image['MediaId'];//mediaID 是微信公衆平臺返回的圖片的id,微信公衆平臺是依據該ID來調用用戶所發的圖片
       $zhwx->responseMessage('image',$callData);
      
    }else if($msgtype == 'voice'){ //若是是語音消息,用於語音交流
      $callData=$zhwx->getUserVoiceRequest(); //返回數組
      $zhwx->responseMessage('voice',$callData);
    }elseif($msgtype == 'event'){//事件,由系統自動檢驗類型
      $content='歡迎光臨━(*`∀´*)ノ亻'.'
      隨意輸入試試吧!';//給數據爲數據庫查詢出來的
      $callData=$zhwx->responseEventMessage($content);//把數據放進去,由系統自動檢驗類型,並返回字符串或者數組的結果
        $zhwx->responseMessage('text',$callData); //使用數據
    }else{
      $callData='我聽不清你在說什麼:
      你發數據類型是:'.$msgtype.'
      你發的數據時間是:'.$SendTime.'
      我接收的ID是:'.$requestId;
      $zhwx->responseMessage('text',$callData);
    }
  }
wei.php
weixinapi.php

源碼和weixinapi.php是不同的,後者刪減了部分,本身去對照。。web

 

基本就這樣了,能夠去公衆號上測試算法

相關文章
相關標籤/搜索