目的
創建自定義菜單,實現菜單事件。
首先獲取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