<?php //封裝成一個微信介面類 class WeixinApi { private $appid; private $appsecret; //構造方法 初始化賦值 public function __construct($appid="",$appsecret="") { $this->appid = $appid; $this->appsecret = $appsecret; } //驗證伺服器位址有效性 public function valid() { if($this->checkSignature()) { $echostr = $_GET['echostr'];//隨機的字串 return $echostr; } else { return "Error"; } } //檢查簽名 private function checkSignature() { //一、接收微信伺服器GET方式提交過來的4個參數資料 $signature = $_GET['signature'];//微信加密簽名 $timestamp = $_GET['timestamp'];//時間戳記 $nonce = $_GET['nonce'];//隨機數 //二、加密/校正過程 // 1. 將token、timestamp、nonce三個參數進行字典序排序; // bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) 對數組排序 $tmpArr = array(TOKEN,$timestamp,$nonce);//將上面三個參數放到一個數組裡面 sort($tmpArr,SORT_STRING); // 2. 將三個參數字串拼接成一個字串進行sha1加密; $tmpStr = implode($tmpArr); //將數組轉化成字串 $signatureStr = sha1($tmpStr); // 3. 開發人員獲得加密後的字串與signature對比。 if($signatureStr == $signature) { return true; } else { return false; } } //響應訊息 public function responseMsg() { //接收微信伺服器發送POST請求到開發人員伺服器,攜帶的XML資料包 $postData = $GLOBALS['HTTP_RAW_POST_DATA']; //處理xml資料包 $xmlObj = simplexml_load_string($postData,"SimpleXMLElement",LIBXML_NOCDATA); if(!$xmlObj) { echo ""; exit; } //擷取接收訊息中的參數內容 $toUserName = $xmlObj->ToUserName;//開發人員微訊號 $fromUserName = $xmlObj->FromUserName;//發送方的微訊號(openid) $msgType = $xmlObj->MsgType;//訊息類型 switch ($msgType) { //接收簡訊 case 'text': //擷取簡訊的關鍵字 $keyword = $this->receiveText($xmlObj); //進行關鍵字回複 switch($keyword) { case "w001": case "W001": return $this->replyText($xmlObj,"Hi~你好"); break; case "w002": case "W002": return $this->replyText($xmlObj,"Hi~尷尬了"); break; case "笑話": $key = "dee9ebc68fd5a61f67286063932afe56"; return $this->replyNews($xmlObj,$this->joke_text($key)); break; default: $key = "dee9ebc68fd5a61f67286063932afe56"; return $this->replyNews($xmlObj,$this->joke_text($key)); break; } break; //接收圖片訊息 case 'image': return $this->receiveImage($xmlObj); break; //接收事件推送 case 'event': return $this->receiveEvent($xmlObj); break; } } //接收事件推送 public function receiveEvent($obj) { //接收事件類型 $event = $obj->Event; switch ($event) { //關注事件 case 'subscribe': //下發歡迎訊息 $newsArr = array( array( "Title"=>"做有價值的頭條資訊!", "Description"=>"把握價值頭條資訊,日常更加有談資呢!", "PicUrl"=>"http://jober.applinzi.com/news/img/news.png", "Url"=>"http://jober.applinzi.com/news/index.php" ) ); //回複圖文訊息 return $this->replyNews($obj,$newsArr); break; //取消追蹤事件 case 'unsubscribe': //帳號的解除綁定操作等等 break; //自訂菜單推送CLICK事件 case 'CLICK': $eventKey = $obj->EventKey;//擷取事件KEY值,與自訂菜單介面中KEY值對應 switch ($eventKey) { case 'old': $weixinArr = $this->history("da675ebc6a0d72920dca3f676122a693"); $weixinArr = array_slice($weixinArr, 0,5); $newsArr = array(); foreach ($weixinArr as $item) { $newsArr = array(array( "Title" => $item['Description'], "Description" => $item['Title'], "PicUrl" => "http://1.jober.applinzi.com/news/img/2.jpg", "Url" => "http://www.todayonhistory.com/" )); } return $this->replyNews($obj,$newsArr); break; } break; } } //接收簡訊 public function receiveText($obj) { $content = trim($obj->Content);//簡訊的內容 return $content; } //接收圖片訊息 public function receiveImage($obj) { $picUrl = $obj->PicUrl;//圖片的連結 $mediaId = $obj->MediaId;//圖片訊息媒體id return $this->replyImage($obj,$mediaId); } //回複圖片訊息 public function replyImage($obj,$mediaId) { $replyXml = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[image]]></MsgType> <Image> <MediaId><![CDATA[%s]]></MediaId> </Image> </xml>"; return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$mediaId); } //回複簡訊 public function replyText($obj,$content) { $replyXml = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$content); } //回複圖文訊息 public function replyNews($obj,$newsArr) { //判斷是否為數群組類型 if(!is_array($newsArr)) { return; } // 判斷數組是否為空白數組 if(!$newsArr) { return; } $itemStr = ""; //定義item模板 $itemXml = "<item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item>"; foreach($newsArr as $item) { $itemStr .= sprintf($itemXml,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']); } $replyXml = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>".count($newsArr)."</ArticleCount> <Articles>".$itemStr."</Articles> </xml>"; return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time()); } //封裝https請求(GET和POST) protected function https_request($url,$data=null) { //1、初始化curl $ch = curl_init(); //2、設定傳輸選項 curl_setopt($ch, CURLOPT_URL, $url);//請求的url地址 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//將請求的結果以檔案流的形式返回 if(!empty($data)) { curl_setopt($ch,CURLOPT_POST,1);//請求POST方式 curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST提交的內容 } //3、執行請求並處理結果 $outopt = curl_exec($ch); //把json資料轉化成數組 $outoptArr = json_decode($outopt,TRUE); //4、關閉curl curl_close($ch); //如果返回的結果$outopt是json資料,則需要判斷一下 if(is_array($outoptArr)) { return $outoptArr; } else { return $outopt; } } public function juhe_weixin($key,$type) { $url ="http://v.juhe.cn/toutiao/index?type={$type}&key={$key}"; $result = $this->https_request($url); if($result['error_code'] == 0) { return $result['result']['data']; } else { return array(); } } //彙總資料-擷取最新趣圖 public function joke_text($key,$pagesize=10) { $url = "http://japi.juhe.cn/joke/img/text.from?key={$key}&pagesize={$pagesize}"; $jokeArr = $this->https_request($url); $resultArr = $jokeArr['result']['data']; // $content = $resultArr[0]['content']; // return $this->replyText($xmlObj,$content); $newsArr = array(); //判斷笑話介面是否擷取資料 if($jokeArr['error_code'] == 0) { foreach($resultArr as $item) { $newsArr[] = array( "Title"=>$item['content'], "Description"=>$item['updatetime'], "PicUrl"=>$item['url'], "Url"=>$item['url'] ); } } return $newsArr; } //彙總資料-擷取曆史上的今天 public function history($key) { $m = idate('m'); $d = idate('d'); $day = "{$m}/{$d}"; $url = "http://v.juhe.cn/todayOnhistory/queryEvent.php?key={$key}&date={$day}"; $historyArr = $this->https_request($url); $resultArr = $historyArr['result']; // $content = $resultArr['title']; // return $this->replyText($xmlObj,$content); $newsArr = array(); //判斷介面是否擷取資料 if($jokeArr['error_code'] == 0) { foreach($resultArr as $item) { $newsArr[] = array( "Title"=>$item['title'], "Description"=>$item['date'], "PicUrl"=>"", "Url"=>"" ); } } return $newsArr; } public function fund($key) { $url = "http://japi.juhe.cn/jingzhi/query.from?key={$key}"; $fundArr = $this->https_request($url); $resultArr = $fundArr['result']; // $content = $resultArr['title']; // return $this->replyText($xmlObj,$content); $newsArr = array(); //判斷介面是否擷取資料 if($jokeArr['error_code'] == 0) { foreach($resultArr as $item) { $newsArr[] = array( "Title"=>$item['day'], "Description"=>$item['title'], "PicUrl"=>"", "Url"=>"http://www.baidu.com" ); } } return $newsArr; } /** *擷取基礎支援裡面的介面調用憑證access_token並緩衝access_token *@return access_token string 介面憑證 **/ public function getAccessToken() { //擷取memcache緩衝的access_token $access_token = $this->_memcache_get("access_token"); //如果緩衝的access_token失效 if(!$access_token) { //如果失效調用擷取介面憑證來擷取access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}"; $outoptArr = $this->https_request($url); if(!isset($outoptArr['errcode'])) { //memcache緩衝access_token $this->_memcache_set("access_token",$outoptArr['access_token'],7000); return $outoptArr['access_token']; } } return $access_token; } //初始化memcache private function _memcache_init() { $mmc = new Memcache; $ret = $mmc -> connect(); if ($ret == false) { return; } return $mmc; } //設定memcache private function _memcache_set($key,$value,$time=0) { $mmc = $this->_memcache_init(); $mmc -> set($key,$value,0,$time); } //擷取memcahce private function _memcache_get($key) { $mmc = $this->_memcache_init(); return $mmc -> get($key); } //自訂菜單建立 public function menu_create($data) { $access_token = $this->getAccessToken(); //自訂菜單建立介面地址 $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}"; return $this->https_request($url,$data); } //自訂菜單刪除 public function menu_delete() { $access_token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$access_token}"; return $this->https_request($url); } }?>