一、自訂菜單概述
自訂菜單能夠協助公眾號豐富介面,讓使用者更好更快地理解公眾號的功能。開啟自訂菜單後,公眾號介面如圖所示:
二、申請自訂菜單
個人訂閱號使用微博認證、企業訂閱號通過微信認證;可以申請到自訂菜單資格
服務號預設有菜單許可權。
三、獲得AppId 和AppSecert
AppId和AppSecret在開發人員中心-開發人員ID中,可以找到。
四、獲得Access Token
用appid和appsecert獲得access token,介面為
https://api.weixin.qq.com/cgi-bi ... mp;secret=APPSECRET
程式實現如下
$appid = ""; $appsecret = ""; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $jsoninfo = json_decode($output, true); $access_token = $jsoninfo["access_token"];
你也可以直接在瀏覽器地址欄中,拼接出地址,執行後,獲得如下資料
複製代碼 代碼如下:
{"access_token":"N2L7KXa084WvelONYjkJ_traBMCCvy_UKmpUUzlrQ0EA2yNp3Iz6eSUrRG0bhaR_viswd50vDuPkY5nG43d1gbm-olT2KRMxOsVE08RfeD9lvK9lMguNG9kpIkKGZEjIf8Jv2m9fFhf8bnNa-yQH3g",
複製代碼 代碼如下:
"expires_in":7200}
參數說明如下
其中的
N2L7KXa084WvelONYjkJ_traBMCCvy_UKmpUUzlrQ0EA2yNp3Iz6eSUrRG0bhaR_viswd50vDuPkY5nG43d1gbm-olT2KRMxOsVE08RfeD9lvK9lMguNG9kpIkKGZEjIf8Jv2m9fFhf8bnNa-yQH3g
就是access token。
或者使用官方的介面調試工具,地址為:
https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95&form=%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95%E5%88%9B%E5%BB%BA%E6%8E%A5%E5%8F%A3%20/menu/create
使用網頁調試工具調試自訂菜單介面
點擊檢查問題得,得到
這樣也獲得了access token
五、組織菜單內容
目前自訂菜單最多包括3個一級菜單,每個一級菜單最多包含5個二級菜單。一級菜單最多4個漢字,二級菜單最多7個漢字,多出來的部分將會以“...”代 替。請注意,建立自訂菜單後,由於微信用戶端緩衝,需要24小時微信用戶端才會展現出來。建議測試時可以嘗試取消追蹤公眾帳號後再次關注,則可以看到創 建後的效果。
目前自訂菜單介面可實現兩種類型按鈕,如下:
click:
使用者點擊click類型按鈕後,微信伺服器會通過訊息介面推送訊息類型為event 的結構給開發人員(參考訊息介面指南),並且帶上按鈕中開發人員填寫的key值,開發人員可以通過自訂的key值與使用者進行互動;
view:
使用者點擊view類型按鈕後,微信用戶端將會開啟開發人員在按鈕中填寫的url值 (即網頁連結),達到開啟網頁的目的,建議與網頁授權擷取使用者基本資料介面結合,獲得使用者的登入個人資訊。
介面調用請求說明
http請求方式:POST(請使用https協議) https://api.weixin.qq.com/cgi-bi ... _token=ACCESS_TOKEN
請求樣本
{ "button":[ { "type":"click", "name":"今日歌曲", "key":"V1001_TODAY_MUSIC" }, { "type":"click", "name":"歌手簡介", "key":"V1001_TODAY_SINGER" }, { "name":"菜單", "sub_button":[ { "type":"view", "name":"搜尋", "url":"http://www.soso.com/" }, { "type":"view", "name":"視頻", "url":"http://v.qq.com/" }, { "type":"click", "name":"贊一下我們", "key":"V1001_GOOD" }] }] }
參數說明
返回結果
正確時的返回JSON資料包如下:
{"errcode":0,"errmsg":"ok"}
錯誤時的返回JSON資料包如下(樣本為無效菜單名長度):
{"errcode":40018,"errmsg":"invalid button name size"}
六、提交菜單內容給伺服器
菜單的JSON結構為
{"button": [{"name":"天氣預報","sub_button":[{"type":"click","name":"北京天氣","key":"天氣北 京"}, {"type":"click","name":"上海天氣","key":"天氣上海"}, {"type":"click","name":" 廣州天氣","key":"天氣廣州"},{"type":"click","name":"深圳天氣","key":"天氣深圳"}, {"type":"view","name":"本地天氣","url":"http://m.hao123.com/a/tianqi"}]}, {"name":"方倍工作室","sub_button":[{"type":"click","name":"公司簡 介","key":"company"}, {"type":"click","name":"趣味遊戲","key":"遊戲"}, {"type":"click","name":"講個笑話","key":"笑話"}]}]}
將以下代碼儲存為menu.php,並且在瀏覽器中運行該檔案(比如 http://127.0.0.1/menu.php),將直接向微信伺服器提交菜單
php $access_token = ""; $jsonmenu = '{ "button":[ { "name":"天氣預報", "sub_button":[ { "type":"click", "name":"北京天氣", "key":"天氣北京" }, { "type":"click", "name":"上海天氣", "key":"天氣上海" }, { "type":"click", "name":"廣州天氣", "key":"天氣廣州" }, { "type":"click", "name":"深圳天氣", "key":"天氣深圳" }, { "type":"view", "name":"本地天氣", "url":"http://m.hao123.com/a/tianqi" }] }, { "name":"瑞雪", "sub_button":[ { "type":"click", "name":"公司簡介", "key":"company" }, { "type":"click", "name":"趣味遊戲", "key":"遊戲" }, { "type":"click", "name":"講個笑話", "key":"笑話" }] }] }'; $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token; $result = https_request($url, $jsonmenu); var_dump($result); 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; }?>
或者使用官方的調試介面 使用網頁調試工具調試該介面
提交成功後,重新關注後即可看到菜單。菜單效果類似如下:
七、響應菜單點擊事件
在訊息介面中處理event事件,其中的click代表菜單點擊,通過響應菜單結構中的key值回應訊息,view事件無須響應,將直接跳轉過去
define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); if (!isset($_GET['echostr'])) { $wechatObj->responseMsg(); }else{ $wechatObj->valid(); } class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } public function responseMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $RX_TYPE = trim($postObj->MsgType); switch ($RX_TYPE) { case "text": $resultStr = $this->receiveText($postObj); break; case "event": $resultStr = $this->receiveEvent($postObj); break; default: $resultStr = ""; break; } echo $resultStr; }else { echo ""; exit; } } private function receiveText($object) { $funcFlag = 0; $contentStr = "你發送的內容為:".$object->Content; $resultStr = $this->transmitText($object, $contentStr, $funcFlag); return $resultStr; } private function receiveEvent($object) { $contentStr = ""; switch ($object->Event) { case "subscribe": $contentStr = "歡迎洋洋部落格"; case "unsubscribe": break; case "CLICK": switch ($object->EventKey) { case "company": $contentStr[] = array("Title" =>"公司簡介", "Description" =>"洋洋的部落格", "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"weixin://addfriend/pondbaystudio"); break; default: $contentStr[] = array("Title" =>"預設菜單回複", "Description" =>"您正在使用的是<span style="font-family: Arial, Helvetica, sans-serif;">洋洋的部落格</span><span style="font-family: Arial, Helvetica, sans-serif;">", </span> "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"weixin://addfriend/pondbaystudio"); break; } break; default: break; } if (is_array($contentStr)){ $resultStr = $this->transmitNews($object, $contentStr); }else{ $resultStr = $this->transmitText($object, $contentStr); } return $resultStr; } private function transmitText($object, $content, $funcFlag = 0) { $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>%d</FuncFlag> </xml>"; $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $funcFlag); return $resultStr; } private function transmitNews($object, $arr_item, $funcFlag = 0) { //首條標題28字,其他標題39字 if(!is_array($arr_item)) return; $itemTpl = " <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> "; $item_str = ""; foreach ($arr_item as $item) $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']); $newsTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[news]]></MsgType> <Content><![CDATA[]]></Content> <ArticleCount>%s</ArticleCount> <Articles> $item_str</Articles> <FuncFlag>%s</FuncFlag> </xml>"; $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag); return $resultStr; } } ?>
八、菜單中擷取OpenID
由於菜單中只能填寫固定的url地址,對於想要菜單中擷取使用者的OpenID的情況,可以使用OAuth2.0授權的方式來實現。
URL中填寫的地址為一個固定的回調地址。原理方法可以參考 微信公眾平台開發(99) 自訂菜單擷取OpenID
<?php /* 洋洋的部落格 */ define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); if (isset($_GET['echostr'])) { $wechatObj->valid(); }else{ $wechatObj->responseMsg(); } class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ header('content-type:text'); echo $echoStr; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } public function responseMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; if($keyword == "?" || $keyword == "?") { $msgType = "text"; $contentStr = '目前時間是:'.date("Y-m-d H:i:s",time()); $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } }else{ echo ""; exit; } } } ?>
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。