php实现微信公众号创建自定义菜单功能的实例代码

目的

创建自定义菜单,实现菜单事件。

首先获取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"}

总结

以上所述是小编给大家介绍的php实现微信公众号创建自定义菜单功能的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对安科网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关推荐