当前位置: 移动技术网 > IT编程>开发语言>PHP > php实现微信公众号创建自定义菜单功能的实例代码

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

涿州翼德张,蒙阴租房,向井理和北川景子宣布结婚

目的

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

首先获取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实现微信公众号创建自定义菜单功能的实例代码,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网