1. 程式人生 > 其它 >PHP微信公眾號開發之自動回覆

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; } ?>

下面是我的寫法
在這裡插入圖片描述
1.首先是我的檔案結構

2.檔案偷偷開啟來給你看看

<?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