PHP實現微信公眾平臺開發---提升篇(access_token存session)
阿新 • • 發佈:2019-01-28
- cURL簡單採集
- 初始化 cURL $c = curl_init()
- 設定cURL
- 設定URL curl_setopt($c , CURLOPT_URL, ‘’)
- 以檔案流返回 curl_setopt($c , CURLOPT_RETURNTRANSFER,true) ;
- 執行採集 $output = curl_exec($c)
- 關閉 curl_close($c)
- 微信互動資訊的SDK (一些常用功能的封裝)
特性
- 便捷 經常用到的方法寫到SDK 其他專案直接引入SDK 呼叫方法
- 可重複利用性
- 實現 把常用的 回覆純文字|單圖文|多圖文封裝
- 第三方API在微信中實現
- 呼叫免費天氣API 通過cURL返回json型別天氣資訊
- 自定義選單
簡介
- 最多包含3個一級選單 每個一級選單最多5個二級選單
- 一級選單最多4個漢字 二級可以有多個 超出省略號(...)代替
- 測試時 取消關注再次關注看效果
多種型別按鈕
- click: 點選推送事件
- view:跳轉URL
...
測試賬號功能
- 未認證的個人號 沒有許可權呼叫 自定義選單介面等高階介面
- 訂閱號主體需要是企業 提供企業名稱 營業執照註冊號 認證才可以使用高階介面
準備幹活
- 封裝cURL (get|post)
- 將access_token 存session甚至超時時間
- 自定義選單
- 刪除選單
自定義選單推送
- 接收訊息
- MsgType 訊息型別,event
- Event 事件型別,CLICK
- EventKey 事件KEY值,與自定義選單介面中KEY值對應
- 回覆的時候
- strtolower($postObj->MsgType) == 'event'
- strtolower($postObj->Event) == 'click'
- strtolower($postObj->EventKey) == 'XXX' 自定義選單時 key
<?php namespace app\index\controller; class Index { public function indexBak() { $signature = $_GET['signature'] ; $timestamp = $_GET['timestamp'] ; $nonce = $_GET['nonce'] ; $echostr = $_GET['echostr'] ; $token = 'XXXXXXXXXXXXXX' ; $arr = array($token,$timestamp,$nonce) ; //自然排序 sort($arr) ; //拆成字串 加密 $str = sha1(implode($arr)) ; /* 第一次配置個人伺服器時候 為新伺服器會傳遞引數$echostr 與個人伺服器建立連線之後 不會傳遞該引數 */ if($str == $signature && $echostr) { echo $echostr ; die ; }/*else { $this->indexBak() ; }*/ } /* 關注 |取消關注 subscribe|unsubscribe */ public function index() { //獲取使用者資訊 xml資料包 $data = file_get_contents("php://input") ; file_put_contents('data.txt', $data) ; //xml格式資料轉換成物件 $postObj = simplexml_load_string($data,'SimpleXMLElement',LIBXML_NOCDATA) ; $toUser = $postObj->FromUserName ; $fromUser = $postObj->ToUserName ; $time = time() ; //如果訊息型別是 event (取消)關注事件 if(strtolower($postObj->MsgType) == 'event') { //如果 事件型別,subscribe(訂閱) 推送文字資訊 if(strtolower($postObj->Event) == 'subscribe') { $type = 'text' ; $content = "歡迎加入XXX,從今天起,我們將攜手共進,建議添加個人微信:dongling_shisan,經常會有霸王餐、試吃券、吃貨聚會等福利哦! 回覆 1 檢視熱門菜品, 回覆 2 跳轉到CSDN檢視相關資料,回覆 3 看片, 回覆 5 看大片, ... " ; //拼接 響應資料包模板 %s字串型別佔位 sprintf() $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>" ; //變數 依次替換字串型別%s佔位 $info = sprintf($template,$toUser,$fromUser,$time,$type,$content) ; echo $info ; }else if(strtolower($postObj->Event) == 'click'){ if(strtolower($postObj->EventKey) == 'tuijiancai') { $title1 = "推薦菜品類" ; $description1 = "半神半聖亦半仙 全儒全道是全賢 腦中真書藏萬卷 掌握文武半邊天" ; //圖片連結 網路地址 $picurl = "https://img4.mukewang.com/szimg/5aaa55850001a3ef10800600.jpg" ; //點選圖文跳轉的連結 $url = "http://www.baidu.com" ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item></Articles></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$title1,$description1,$picurl,$url) ; echo $info ; } if(strtolower($postObj->EventKey) == 'yuanchuangshuangwen1'){ $title1 = "原創文章" ; $description1 = "半神半聖亦半仙 全儒全道是全賢 腦中真書藏萬卷 掌握文武半邊天" ; //圖片連結 網路地址 $picurl = "https://img4.mukewang.com/szimg/5aaa55850001a3ef10800600.jpg" ; //點選圖文跳轉的連結 $url = "http://www.baidu.com" ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>5</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item></Articles></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url) ; echo $info ; } if(strtolower($postObj->EventKey) == 'yuanchuangshuangwen2'){ $title1 = "原創文章" ; $description1 = "半神半聖亦半仙 全儒全道是全賢 腦中真書藏萬卷 掌握文武半邊天" ; //圖片連結 網路地址 $picurl = "https://img4.mukewang.com/szimg/5aaa55850001a3ef10800600.jpg" ; //點選圖文跳轉的連結 $url = "http://www.baidu.com" ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>5</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item></Articles></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url) ; echo $info ; } }else{ $type = 'text' ; $content = "世事如棋 乾坤莫測 笑盡英雄啊" ; //拼接 響應資料包模板 %s字串型別佔位 sprintf() $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>" ; //變數 依次替換字串型別%s佔位 $info = sprintf($template,$toUser,$fromUser,$time,$type,$content) ; echo $info ; } }else if(strtolower($postObj->MsgType) == 'text'){ $content = $postObj->Content ;//使用者傳送的內容 原樣返回 switch ($content) { case '1': $str = "猴頭, 燕窩 ,鯊魚翅" ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$str) ; echo $info ; break; //帶超連結的純文字 點選文字跳轉 case '2': $str = '<a href="https://blog.csdn.net/donglingjiu/article/details/81014313">檢視資料</a>' ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$str) ; echo $info ; break; case '3': /* <xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[fromUser] ]></FromUserName><CreateTime>12345678</CreateTime><MsgType>< ![CDATA[news] ]></MsgType><ArticleCount>2</ArticleCount><Articles><item><Title>< ![CDATA[title1] ]></Title> <Description>< ![CDATA[description1] ]></Description><PicUrl>< ![CDATA[picurl] ]></PicUrl><Url>< ![CDATA[url] ]></Url></item><item><Title>< ![CDATA[title] ]></Title><Description>< ![CDATA[description] ]></Description><PicUrl>< ![CDATA[picurl] ]></PicUrl><Url>< ![CDATA[url] ]></Url></item></Articles></xml> */ $title1 = "XXX圖文1" ; $description1 = "半神半聖亦半仙 全儒全道是全賢 腦中真書藏萬卷 掌握文武半邊天" ; //圖片連結 網路地址 $picurl = "https://img4.mukewang.com/szimg/5aaa55850001a3ef10800600.jpg" ; //點選圖文跳轉的連結 $url = "http://www.baidu.com" ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item></Articles></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$title1,$description1,$picurl,$url) ; echo $info ; break ; case '4': $title1 = "XXX圖文1" ; $description1 = "半神半聖亦半仙 全儒全道是全賢 腦中真書藏萬卷 掌握文武半邊天" ; //圖片連結 網路地址 $picurl = "https://img4.mukewang.com/szimg/5aaa55850001a3ef10800600.jpg" ; //點選圖文跳轉的連結 $url = "http://www.baidu.com" ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>5</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item><item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item></Articles></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url,$title1,$description1,$picurl,$url) ; echo $info ; break ; default : $str = '遠看山有色 近停水無聲 春去花還在 人來鳥不驚 '; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$str) ; echo $info ; break ; } }else{ $str = '春眠不覺曉 '.'MediaId:'.$postObj->MediaId.' ThumbMediaId:'.$postObj->ThumbMediaId.' MsgId:'.$postObj->MsgId ; $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>" ; $info = sprintf($template,$toUser,$fromUser,$time,$str) ; echo $info ; } } /* cURL簡單的採集 */ public function httpcURL() { //初始化 $curl = curl_init() ; //設定url $url = "https://www.imooc.com/" ; curl_setopt($curl, CURLOPT_URL, $url) ; curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1) ;//檔案流形式返回 //採集 $output = curl_exec($curl) ; //關閉cURL curl_close($curl) ; //echo $output ; file_put_contents('data.html', $output) ; } /* cURL獲取access_token */ public function getAccessToken() { $appID = 'XXXXX' ; $appSecret = 'XXXXXXXXXXX' ; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appID."&secret=".$appSecret ; //初始化 cURL $curl = curl_init() ; //設定引數 curl_setopt($curl, CURLOPT_URL, $url) ; curl_setopt($curl,CURLOPT_RETURNTRANSFER,true) ; //採集資料 $output = curl_exec($curl) ; //關閉 curl_close($curl) ; if(curl_errno($curl)) { var_dump(curl_errno($curl)) ; } //採集回來的json格式轉換成陣列 $arr = json_decode($output,true) ; dump($arr) ; } /* 獲取微信伺服器IP地址 做安全性驗證 防止非微信伺服器請求 */ public function getWxServerIp() { //上述獲取的access_token $access_token = '12_pA2wc_Mi44MY7LFSZSHsmka5Yg8wWP_WSkEXyWEMW0NjumZkrtVJ-vq1WxJU5kZGAhvFe08NdcK6h07QgDMkslx9r6wO7d61E4RV0Q4kw6ARv0DAqiucmpMmVzXlJqiXp2oYRjo2ceISjqa2UPLfADAFAW' ; $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$access_token ; //初始化 cURL $ch = curl_init() ; //設定引數 curl_setopt($ch, CURLOPT_URL, $url) ; curl_setopt($ch,CURLOPT_RETURNTRANSFER,true) ; //採集資料 $output = curl_exec($ch) ; //關閉 curl_close($ch) ; /* if(curl_errno($ch)) { var_dump(curl_errno($ch)) ; }*/ //採集回來的json格式轉換成陣列 $arr = json_decode($output,true) ; dump($arr) ; $str = '' ; foreach ($arr as $key => $value) { $str .= implode($value,'||') ; } dump($str) ; file_put_contents('data.txt', $str) ; } /* 返回當前天氣 */ public function getWether() { //初始化 $curl = curl_init() ; //設定url $url = "http://wthrcdn.etouch.cn/weather_mini?city=".urlencode("深圳") ; echo $url ; curl_setopt($curl, CURLOPT_URL, $url) ; curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1) ;//檔案流形式返回 //採集 $output = curl_exec($curl) ; //關閉cURL curl_close($curl) ; // echo $output ; $arr = json_decode($output,true) ; var_dump($arr) ; } /* cURL可能是get|post $url 介面URL string $type 請求型別 string $res 返回資料型別 string $arr post請求引數 string */ public function http_curl($url,$type='get',$res='json',$arr='') { //初始化 $curl = curl_init() ; //設定curl引數 curl_setopt($curl, CURLOPT_URL, $url) ; curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1) ;//檔案流形式返回 if($type == 'post') { curl_setopt($curl, CURLOPT_POST, true) ; curl_setopt($curl, CURLOPT_POSTFIELDS, $arr) ; } //採集 $output = curl_exec($curl) ; //關閉cURL curl_close($curl) ; if($res == 'json') { /*if(curl_errno($curl)) { //請求失敗 返回錯誤資訊 return curl_error($curl) ; }else{ //請求成功 返回陣列格式 return json_decode($output,true) ; }*/ return json_decode($output,true) ; } } /* 將access_token存到session中 設定過期時間 */ public function getSessionAccessToken() { // 如果 session中存有 access_token 並且未超過有效期 使用session中的access_token if(session('access_token') && session('expire_time') > time()) { return session('access_token') ; }else{ //第一次獲取 或者已經超時 重新獲取access_token $appID = 'XXXXXX' ; $appSecret = 'XXXXXXXXXX' ; //get請求方式 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appID."&secret=".$appSecret ; $res = $this->http_curl($url,'get','json') ; $access_token = $res['access_token'] ; //將獲取到的access_token存到session 設定過期時間 session('access_token',$access_token) ; session('expire_time',time() + 7000 ) ; // SESSION['access_token'] = $access_token ; // SESSION['expire_time'] = time() + 7000 ; return $access_token ; } } /* 自定義選單 */ public function definedItem() { header("content-type:text/html;charset=utf-8") ; //介面 post請求 $access_token = $this->getSessionAccessToken() ; $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token ; //自定義選單資料 $data = array() ; $data["button"] = array( array( 'name'=>"今天吃啥", 'sub_button'=>array( array( "type"=>"click", "name"=>"推薦菜品", "key"=>"tuijiancai" ) , array( "type"=>"view", "name"=>"美團一下", "url"=>"http://i.meituan.com" ) , array( "type"=>"view", "name"=>"餓了嗎來一份", "url"=>"https://h5.ele.me" ) , array( "type"=>"scancode_push", "name"=>"掃碼推送", /* 草料二維碼 生成靜態二維碼 掃碼之後跳轉 二維碼 api http://qr.liantu.com/api.php?text= 頁面引用<img src="http://qr.liantu.com/api.php?text=x"/>進行引用 text=可以是連線 http://www.baidu.com 可以是文字等 */ "key"=>"saomatuisong" ) ) ) , array( 'name'=>"原創專欄", 'sub_button'=>array( array( "type"=>"scancode_waitmsg", "name"=>"掃碼帶提示", "key"=>"saomadaitishi" ) , array( "type"=>"pic_sysphoto", "name"=>"系統拍照發圖", "key"=>"xitongpaizhaofatu" ) , array( "type"=>"click", "name"=>"原創爽文1", "key"=>"yuanchuangshuangwen1" ) , array( "type"=>"click", "name"=>"原創爽文2", "key"=>"yuanchuangshuangwen2" ) , array( "type"=>"pic_photo_or_album", "name"=>"拍照或者相簿發圖", "key"=>"paizhaohuozhexiangce" ) ) ) , array( 'name'=>"聯絡我們", 'sub_button'=>array( array( "type"=>"pic_weixin", "name"=>"微信相簿發圖", "key"=>"weixinxiangcefatu" ) , array( "type"=>"location_select", "name"=>"傳送位置", "key"=>"fasongweizhi" ) , ) ) ) ; //漢字不轉義 $postJson = json_encode($data,JSON_UNESCAPED_UNICODE) ; //cURL post請求 $res = $this->http_curl($url,'post','json',$postJson) ; var_dump($res) ; } /* 刪除自定義選單 */ public function clearItem() { //獲取access_token $access_token = $this->getSessionAccessToken() ; //get請求 $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$access_token ; //cURL $res = $this->http_curl($url,'get','json') ; var_dump($res) ; } }