目的
创建自定义菜单,实现菜单事件。
首先获取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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
<?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实现微信公众号创建自定义菜单功能的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
原文链接:https://segmentfault.com/a/1190000019436016