This article mainly introduces the development of custom menus in PHP WeChat in detail, which has certain reference value. Interested friends can refer to it
Currently, the custom menu of WeChat service accounts includes up to 3 Each first-level menu contains up to 5 second-level menus. The first-level menu can contain up to 4 Chinese characters, and the second-level menu can contain up to 7 Chinese characters. The extra parts will be replaced by "...". Please note that after creating a custom menu, it will take 24 hours for the WeChat client to display it due to WeChat client caching. It is recommended that when testing, you can try to unfollow the public account and follow it again, and you can see the effect after creation.
Currently, the custom menu interface can implement two types of buttons, as follows:
click: After the user clicks the click type button, the WeChat server will send the message through the message interface Push the message type event structure to the developer (refer to the Message Interface Guide), and bring the key value filled in by the developer in the button. The developer can interact with the user through the customized key value;
view:
After the user clicks the view type button, the WeChat client will open the url value (i.e. web link) filled in by the developer in the button to achieve the purpose of opening the web page. It is recommended to match the web page Authorize to obtain the user's basic information interface and obtain the user's login personal information.
Interface call request descriptionhttp request method: POST (please use https protocol) https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
Request example (please use UTF-8 encoding for JSON data)
{ "button":[ {"type":"click","name":"我的信息","sub_button":[ {"type":"click","name":"拇指查询","key":"BUTTON_1"}, {"type":"click","name":"拇指请假","key":"BUTTON_2"}, {"type":"view","name":"工号绑定","url":"http://XXXXXXXXXXXXXXXXX"}] }, {"type":"click","name":"业务流程","key":"BUTTON_3"}, {"name":"员工建议","sub_button":[ {"type":"view","name":"思想火花","url":"http://XXXXXXXXXXXXXXXXXX"}, {"type":"view","name":"奖品兑换","url":"http://XXXXXXXXXXXXXXXXXX"}, {"type":"click","name":"赞一下我们","key":"BUTTON_ZAN"}] } ] }
Parameter description
Return result
Return JSON data when correct The package is as follows:
{"errcode":0,"errmsg":"ok"}
The returned JSON data package in case of error is as follows (an example is invalid menu name length):
{"errcode":40018 ,"errmsg":"invalid button name size"}
The following is sample code (PHP).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="author" content="Chris Mao" /> </head> <body> <?php $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $output = curl_exec($ch); curl_close($ch); if (empty($output)) { var_dump($output); exit; } $result = json_decode($output); $token = $result->access_token; //创建菜单 $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$token"; $jsonData = file_get_contents("menu.json"); $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $output = curl_exec($ch); curl_close($ch); var_dump($output); ?> </body> </html>
menu.json
{ "button":[ {"type":"click","name":"我的信息","sub_button":[ {"type":"click","name":"拇指查询","key":"BUTTON_1"}, {"type":"click","name":"拇指请假","key":"BUTTON_2"}, {"type":"view","name":"工号绑定","url":"http://XXXXXXXXXXXXXXXXX"}] }, {"type":"click","name":"业务流程","key":"BUTTON_3"}, {"name":"员工建议","sub_button":[ {"type":"view","name":"思想火花","url":"http://XXXXXXXXXXXXXXXXXX"}, {"type":"view","name":"奖品兑换","url":"http://XXXXXXXXXXXXXXXXXX"}, {"type":"click","name":"赞一下我们","key":"BUTTON_ZAN"}] } ] }
Respond to custom menu events
$wechatObj = new wechatCallbackAPI(); if (isset($_GET["echostr"])) { $wechatObj->valid(); } else { $wechatObj->responseMsg(); } class wechatCallbackAPI { private $token = "WEIXIN"; private $appId = "APPID"; private $appSecret = "APPSECRET"; private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $tmpArr = array($this->token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if($tmpStr == $signature) { return true; } else { return false; } } private function getAccessToken() { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $ch = curl_init($url); $curl_setopt($ch, CURLOPT_HEADER, 0); $curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $curl_setopt($ch, CURLOPT_POST, 0); $curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); $curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $output = curl_exec($ch); curl_close($ch); if (empty($output)) { return ""; } $result = json_decode($result); return $result->access_token; } public function valid() { $echoStr = $_GET["echostr"]; //valid signature, option if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (empty($postStr)){ echo ""; exit; } //extract post data $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $time = time(); //文本消息模板 $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; switch (strtolower(trim($postObj->MsgType))) { case "text": //文本消息 $keyword = trim($postObj->Content); if(!empty($keyword)) { $msgType = "text"; $contentStr = "$fromUsername, 您发送了文本信息: $keyword "; if (strtolower($keyword) == "time") { $contentStr = date("Y-m-d H:i:s", $time); } $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); } else { $resultStr = "Input something..."; } break; case "image": //图片消息 $msgType = "text"; $contentStr = "$fromUsername, 您发送了图片信息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "voice": //声音消息 $msgType = "text"; $contentStr = "$fromUsername, 您发送了声音信息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "video": //视频消息 $msgType = "text"; $contentStr = "$fromUsername, 您发送了视频信息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "location": //位置消息 $msgType = "text"; $contentStr = "$fromUsername, 您发送了位置信息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "link": //链接消息 $msgType = "text"; $contentStr = "$fromUsername, 您发送了链接信息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "event": //事件 switch (strtolower(trim($postObj->Event))) { case "subscribe": //关注事件 $msgType = "text"; $contentStr = "欢迎您关注XXXXXXX"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "unsubscribe": //取消关注事件 break; case "scan": //用户已关注时扫描二维码事件 $msgType = "text"; $contentStr = "$fromUsername, 您扫描了二维码"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "location": //上传地理位置事件 $msgType = "text"; $contentStr = "$fromUsername, 您上传地理位置"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); break; case "click": //自定义菜单事件 $msgType = "text"; $contentStr = "$fromUsername, 您点击了自定义菜单 $postObj->EventKey "; if ("BUTTON_ZAN" == $postObj->EventKey) { $contentStr = "感谢您的赞,我们会继续提供更优质的服务。"; } $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); ; break; default: $resultStr = ""; } break; default: $resultStr = ""; } echo $resultStr; } } ?>
Custom menu query
Use the interface to create custom After creating the menu, developers can also use the interface to query the structure of the custom menu.
Request instructions
http request method: GET
https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN
Return instructions
Corresponding to the creation interface, the correct Json return result is:
Copy code The code is as follows:
{"menu":{"button":[{"name":"My information","sub_button":[ {"type":"click","name":"Thumb query","key":"BUTTON_1","sub_button":[]},{"type":"click","name":"Thumb leave ","key":"BUTTON_2","sub_button":[]},{"type":"view","name":"Work ID Binding","url":"http:\/\/XXXXXXXX ","sub_button":[]}]},{"type":"click","name":"Business Process","key":"BUTTON_3","sub_button":[]},{"name" :"Employee Suggestions","sub_button":[{"type":"view","name":"Idea Spark","url":"http:\/\/XXXXXXXX","sub_button":[]} ,{"type":"view","name":"Prize Redemption","url":"http:\/\/XXXXXXXX","sub_button":[]},{"type":"click", "name":"Like us","key":"BUTTON_ZAN","sub_button":[]}]}]}}
Custom menu deletion
After using the interface to create a custom menu, developers can also use the interface to delete the currently used custom menu.
Request description
http request method: GET
https://api.weixin.qq.com/cgi-bin/menu/delete ?access_token=ACCESS_TOKEN
Return description
Corresponds to the creation interface, the correct Json return result:
{"errcode":0,"errmsg" :"ok"}
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHP array addition operation and the difference from array_merge
##Usage of call_user_func_array callback function in PHP
Notes on how PHP uses the curl function to send Post requests
The above is the detailed content of Sharing methods for developing custom menus in PHP WeChat. For more information, please follow other related articles on the PHP Chinese website!

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
