思路很簡單:就是先獲取access_token,然后帶着一定規則的json數據參數請求創建菜單的接口。廢話不多講,直接上代碼。
class Wechat { public $APPID="wx******596"; public $APPSECRET="ad******0"; //獲取access_token public function index() { $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->APPID."&secret=".$this->APPSECRET; $date=postcurl($url); $access_token=$date['access_token']; return $access_token; } //拼接參數,帶着access_token請求創建菜單的接口 public function createmenu(){ $data='{ "button":[ { "type":"view", "name":"精選課程", "url":"https://w.url.cn/s/ASOsHnk" }, { "name":"優研優選", "sub_button":[ { "type":"click", "name":"院校&導師", "key":"SCHOOCL_TEACHER" }, { "type":"view", "name":"快速登錄", "url":"http://www.uyanuxuan.com/index.php" }, { "type":"view", "name":"導師計划", "url":"http://www.uyanuxuan.com/index.php/Home/About/xsjh.html" }] }, { "name":"我的", "sub_button":[ { "type":"click", "name":"聯系我們", "key":"CONTACTUS" }, { "type":"view", "name":"正版軟件", "url":"http://www.xmypage.com/model2_37685.html" }, { "type":"view", "name":"四六級沖刺", "url":"https://h5.youyinian.cn/" }] } ] }'; $access_token=$this->index(); $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token; $result=postcurl($url,$data); var_dump($result); }
備注:postcurl方法是提前寫好的php請求接口的方法。代碼如下:
//請求接口方法 function postcurl($url,$data = null){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); return $output=json_decode($output,true); }
public function getCurl($url) { $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); return $output; }
轉:https://blog.csdn.net/u013077250/article/details/79041303
自己也有寫:https://gitee.com/fps2tao/openweixin