php实现微信公众号创建自定义菜单功能的实例代码
程序员文章站
2022-08-27 22:12:12
目的
创建自定义菜单,实现菜单事件。
首先获取access_token
接口:
https://api.weixin.qq.com/cgi-bin/token...
目的
创建自定义菜单,实现菜单事件。
首先获取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实现微信公众号创建自定义菜单功能的实例代码,希望对大家有所帮助