Sharing methods for developing custom menus in PHP WeChat
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
