微信公眾帳號 服務號可以使用 自定義菜單功能。之前在創建菜單時一直失敗,原因是$data 格式一直沒有傳正確,後來終於解決了。這裡先記錄下 順便封裝了一個類,便於自定義菜單的管理。此類僅僅是自定義菜單的管理類,並未涉及微信自定義回復和菜單事件的代碼。
代碼如下
/** * @author LSH 2013-09-06 * * 微信自定義菜單的創建|查詢|取消 */ class weixinMenu { public static $appid = null; // 申請得到的appid public static $secret = null; // 申請得到的secret public static $getToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; public static $createMenu = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="; public static $selMenu ="https://api.weixin.qq.com/cgi-bin/menu/get?access_token="; public static $delMenu = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="; public static $opt = array( CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)', CURLOPT_FOLLOWLOCATION => 1, CURLOPT_AUTOREFERER =>1, CURLOPT_RETURNTRANSFER => true ); public $ACCESS_TOKEN = null; /** * 創建菜單 */ public function create() { $this->token(); $strMeau = '{ "button":[ { "type":"click", "name":"菜單左", "key":"V_MENU_LEFT" }, { "type":"click", "name":"菜單中", "key":"V_MENU_CENTER" }, { "type":"click", "name":"菜單右", "key":"V_MENU_RIGHT" }] }'; $ret = $this->HttpPost(self::$createMenu.$this->ACCESS_TOKEN,self::$opt, $strMeau); echo $ret; } /** * 查詢菜單 */ public function sel() { $this->token(); $ret = $this->HttpGet(self::$selMenu.$this->ACCESS_TOKEN,self::$opt); echo $ret; } /** * 取消菜單 */ public function del() { $this->token(); $ret = $this->HttpGet(self::$delMenu.$this->ACCESS_TOKEN,self::$opt); echo $ret; } /** * 獲取token */ private function token() { $tokenUrl = self::$getToken."&appid=".self::$appid."&secret=".self::$secret; $ret = $this->HttpGet($tokenUrl,self::$opt); $arrRet = json_decode($ret,true); $this->ACCESS_TOKEN = $arrRet['access_token']; } /** * POST 模式 * @param string $url post 的地址 * @param array $opt post 選項 * @param array $post_data post 數據 * @return mixed */ private function HttpPost($url, $opt = array(),$post_data) { $setopt = array( CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $post_data, ); if ( !empty($opt) ) { foreach ($opt as $key => $value) { $setopt[$key] = $value; } } $curl = curl_init($url); foreach ($setopt as $key => $value) { curl_setopt($curl, $key, $value ); } $responseText = curl_exec($curl); curl_close($curl); return $responseText; } /** * GET 方式 * @param stinrg $url GET 的url * @param array $opt GET 的選項 * @return mixed */ private function HttpGet($url, $opt = array()) { $setopt = array( CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url ); if ( !empty($opt) ) { foreach ($opt as $key => $value) { $setopt[$key] = $value; } } $curl = curl_init($url); foreach ($setopt as $key => $value) { curl_setopt($curl, $key, $value ); } $responseText = curl_exec($curl); curl_close($curl); return $responseText; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。