最近接触到微信公众号开发,首先就是爬这个关于自定义菜单的坑了,看了文档一段时间加上百度的总结了实现的方法
上代码,这里要说明我直接用了自己的access——token令牌,这个自己根据自己的令牌来实现。关于appid跟appsercet的获取就在这里不解释了,不会可以直接百度。下面是简单实现菜单的方法,自己可以封装一些很多的函数,详情参考微信开发文档即可。最后附上自己的图
//微信自定义菜单
header("Content-type: text/html; charset=utf-8");
//define("ACCESS_TOKEN", "5b9FZhqOXvEf2GthK76FF03kio0uUST9uqUT9L3mLli1qKdPp4dF7Ik0ZiKLGlWs4DQHMB-IveCgNvxEuDlMIrqloxrXa1IaYy5cGB3Gp9TvP_Yh-o1H-bi8Nq9BXE3JMAUbADACQK");`
function get_access_token() {
$appid = "你的微信公众号 appid";
$appsecret = "你的微信公众号 appsercet";
$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"];
return $access_token;
}
//创建菜单
function createMenu($data) {
$access_token = get_access_token();
var_dump($access_token);
if (!$access_token)
return;
$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":[
{
"name":"安全动态",
"sub_button":[
{
"type":"click",
"name":"一天一句",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"安全通知",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"重要通知",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"经验交流",
"key":"V1001_HELLO_WORLD"
},
{
"type":"click",
"name":"安全热点",
"key":"V1001_GOOD"
}]
},
{
"name":"小安微课堂",
"sub_button":[
{
"type":"click",
"name":"学习记录",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"安全学习",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"本质安全",
"key":"V1001_HELLO_WORLD"
},
{
"type":"click",
"name":"班组安全",
"key":"V1001_GOOD"
}]
},
{
"name":"测试评估",
"sub_button":[
{
"type":"click",
"name":"联系小安",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"投票活动",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"成绩查询",
"key":"V1001_GOOD"
},
{
"type":"click",
"name":"考试测评",
"key":"V1001_HELLO_WORLD"
},
{
"type":"click",
"name":"用户登录",
"key":"V1001_GOOD"
}]
}
]
}';
echo createMenu($data);
?>