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!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
