Home Backend Development PHP Tutorial Sharing methods for developing custom menus in PHP WeChat

Sharing methods for developing custom menus in PHP WeChat

Jun 01, 2018 pm 02:37 PM
php share customize

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"}]
  }
 ]
}
Copy after login

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[&#39;HTTP_USER_AGENT&#39;]);
  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>
Copy after login

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"}]
  }
 ]
}
Copy after login

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, &#39;SimpleXMLElement&#39;, 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;
  }
 }
?>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles