目的
創建自定義菜單,實現菜單事件。
首先獲取Access_Token
接口:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
我用的是測試號,修改APPID和APPSECRET,然後瀏覽器訪問上面這個Url即可生成Access_Token
然後配置菜單的事件,caidan.php
<?php
header("Content-type: text/html; charset=utf-8");
define("ACCESS_TOKEN", "生成的Access_Token");
//創建菜單
function createMenu($data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".ACCESS_TOKEN);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);
if (curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $tmpInfo;
}
//獲取菜單
function getMenu(){
return file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".ACCESS_TOKEN);
}
//刪除菜單
function deleteMenu(){
return file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".ACCESS_TOKEN);
}
$data = '{
"button":[
{
"type":"click",
"name":"首頁",
"key":"home"
},
{
"type":"click",
"name":"簡介",
"key":"introduct"
},
{
"name":"菜單",
"sub_button":[
{
"type":"click",
"name":"hello word",
"key":"V1001_HELLO_WORLD"
},
{
"type":"click",
"name":"贊一下我們",
"key":"V1001_GOOD"
}]
}]
}';
echo createMenu($data);
瀏覽器訪問caidan.php
正確時的返回JSON數據包如下:
{"errcode":0,"errmsg":"ok"}
錯誤時的返回JSON數據包如下(示例爲無效菜單名長度):
{"errcode":40018,"errmsg":"invalid button name size"}
作者:TANKING
微信:face6009
網站:https://www.likeyunba.com