Home WeChat Applet WeChat Development Detailed introduction to the creation and deletion of custom menus in WeChat public platform development

Detailed introduction to the creation and deletion of custom menus in WeChat public platform development

Mar 22, 2017 pm 04:45 PM
WeChat development

When creating menus, data is transmitted based on JSON, so JSON is used. Download the relevant package. Click to download:

There are instructions in the public platform development document:

Please note:

1. The custom menu includes up to 3 first-level menus, and each first-level menu contains up to 5 second-level menus.
2. 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 "...".
3. After creating a custom menu, due to WeChat client caching, it will take 24 hours for the WeChat client to display it. When testing, you can try to unfollow the public account and follow it again, and you can see the effect after creation.

The custom menu interface can implement multiple types of buttons, as follows:

1. Click: Click push event After the user clicks the click type button, the WeChat server will push the message through the message interface A structure of type event
is given to the developer (refer to the Message Interface Guide), with the key value filled in by the developer in the button. The developer can interact with the user by customizing the
key value;
2. View: Jump URL After the user clicks the view type button, the WeChat client will open the webpage URL filled in by the developer in the
button, which can be combined with the webpage authorization to obtain the user's basic information interface to obtain the user's basic information.
3. scancode_push: After the user clicks the button in the scan code push event, the WeChat client will activate the scan tool. After completing the scan code operation,
will display the scan result (if it is a URL, it will enter the URL), and The result of scanning the QR code will be sent to the developer, who can send messages.
4. scancode_waitmsg: Scan the code to push the event and pop up the "Message Receiving" prompt box. After the user clicks the button, the WeChat client will
launch the scan tool. After completing the code scanning operation, the result of the scan code will be displayed. Pass it to the developer, put away the scanning tool at the same time, and then pop up the "Message
Receiving" prompt box, and then you may receive a message from the developer.
5. pic_sysphoto: When the system pops up to take pictures and send pictures. After the user clicks the button, the WeChat client will call up the system camera. After completing the picture taking operation,
will send the taken photos to the developer and push the event to the developer. , and put away the system camera at the same time, and then you may receive a message from the developer.
6. pic_photo_or_album: After the user clicks the button to take a photo or send a picture to an album, the WeChat client will pop up a selector for the user to choose "take a photo" or "select from the mobile phone album". After the user selects, he will go through the other two processes.
7. pic_weixin: After the user clicks the button of the pop-up WeChat photo album sender, the WeChat client will call up the WeChat photo album. After completing the selection operation
, the selected photos will be sent to the developer's server and the event will be pushed to Developers, if you close the photo album at the same time, you may receive a message from the developer later.
8. location_select: After the user clicks the button of the pop-up geographical location selector, the WeChat client will launch the location selection tool. After completing the selection operation, the selected geographical location will be sent to the developer's server. At the same time Hide the location and select the
tool, and you may receive a message from the developer.
9. media_id: After the user clicks the
media_id type button to send a message (except text message), the WeChat server will deliver the material corresponding to the permanent material id filled in by the developer to the user. The permanent material class
The type can be pictures, audio, video, graphic messages. Please note: the permanent material ID must be the legal ID obtained after uploading through the "Material Management/Add Permanent Material"
interface. 10. view_limited: Jump to the image and text message URL. After the user clicks the view_limited type button,
WeChat client will open the image and text message URL corresponding to the permanent material ID filled in by the developer in the button. The permanent material type only supports images and text
information. Please note: the permanent material ID must be a legal ID obtained after uploading through the "Material Management/Add Permanent Material" interface.


Please note that all events from 3 to 8 only support WeChat iPhone 5.4.1 or above, and Android 5.4 or above WeChat users. WeChat users with older versions will not respond after clicking. Developers Event push cannot be received normally. 9 and 10 are event types specially prepared for subscription accounts of third-party platforms that have not been certified by WeChat (specifically, those that have not passed the qualification certification). They do not have event push and their capabilities are relatively limited. Other types of public accounts No need to use.

1. Since the custom menu uses http request method, https protocol must be used. Write a method class to process https and json data.

Create a new class under the package com.cc.wechat.util:

---CommonUtil.java:

package com.cc.wechat.util;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
 
/**
 * 公众平台通用接口工具类
 * @author ICHN
 * 2015-09-04
 */
public class CommonUtil {
 
    /**
     * 发起https请求并获取结果
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr  提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
         
        StringBuffer sb = new StringBuffer();
         
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};
         
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
             
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
             
            URL url = new URL(requestUrl);
            HttpsURLConnection httpsUrlConnection = (HttpsURLConnection)url.openConnection();
            httpsUrlConnection.setSSLSocketFactory(ssf);
            httpsUrlConnection.setDoInput(true);
            httpsUrlConnection.setDoOutput(true);
            httpsUrlConnection.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpsUrlConnection.setRequestMethod(requestMethod);
             
            //对请求方式进行判断 equalsIgnoreCase不区分大小写
            if("GET".equalsIgnoreCase(requestMethod)) {
                //建立连接
                httpsUrlConnection.connect();
            }
             
            //当有数据需要提交时
            if(null != outputStr) {
                OutputStream os = httpsUrlConnection.getOutputStream();
                // 注意编码格式,防止中文乱码
                os.write(outputStr.getBytes("UTF-8"));
                os.close();
            }
             
            //将返回的输入流转换成字符串
            InputStream is = httpsUrlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
             
            String strLine = null;
             
            while((strLine = br.readLine()) != null) {
                sb.append(strLine);
            }
             
            br.close();
            isr.close();
             
            //释放资源
            is.close();
            is = null;
             
        } catch (Exception e) {
            e.printStackTrace();
        }
         
        return sb.toString();
    }
}
Copy after login

2. Define various types of buttons and put common The variables are extracted and written in a class.

Create related classes under package com.cc.wechat.menu:

1 ---Button.java:

package com.cc.wechat.menu;
 
/**
 * 菜单按钮
 * @author ICHN
 */
public class Button {
 
    //菜单标题,不超过16个字节,子菜单不超过40个字节
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}
Copy after login

2 ---ClickButton.java:

package com.cc.wechat.menu;
 
/**
 * click类型按钮
 * @author ICHN
 *
 */
public class ClickButton extends Button{
 
    //菜单的响应动作类型 
    private String type;
    //菜单KEY值,用于消息接口推送,不超过128字节 
    private String key;
     
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
}
Copy after login

3 ---ComplexButton.java:

package com.cc.wechat.menu;
 
/**
 * 二级菜单数组
 * 个数应为1~5个
 * @author ICHN
 *
 */
public class ComplexButton extends Button {
 
    //二级菜单数组
    private Button[] sub_button;
 
    public Button[] getSub_button() {
        return sub_button;
    }
 
    public void setSub_button(Button[] sub_button) {
        this.sub_button = sub_button;
    }
}
Copy after login

4 ---Menu.java:

package com.cc.wechat.menu;
 
/**
 * 菜单
 * @author ICHN
 *
 */
public class Menu {
 
    private Button[] button;
 
    public Button[] getButton() {
        return button;
    }
 
    public void setButton(Button[] button) {
        this.button = button;
    }
}
Copy after login

5 ---ViewButton.java:

package com.cc.wechat.menu;
 
/**
 * view类型按钮
 * @author ICHN
 *
 */
public class ViewButton extends Button {
 
    //菜单的响应动作类型 
    private String type;
    //网页链接,用户点击菜单可打开链接,不超过256字节
    private String url;
     
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}
Copy after login

3. Create a new test source folder test, build a package com.cc.wechat.test in it, and write related classes for creating menus in this package.

Write a class to get access_token:

---GetAccessToken.java:

package com.cc.wechat.test;
 
import com.cc.wechat.util.CommonUtil;
 
/**
 * 获取access_token
 * @author ICHN
 * 测试账号的appID和appsecret
 * 
 * access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。
 * 开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。
 * access_token的有效期目前为2个小时,需定时刷新,
 * 重复获取将导致上次获取的access_token失效
 */
public class GetAccessToken {
 
    public static void main(String[] args) {
         
        //打印出access_token
        System.out.println(CommonUtil.httpsRequest(
        "&secret=此处填写appsecret", 
        "GET",
         null
         )
        );
    }
}
Copy after login

2. Create and delete menus:

---MenuTest.java:

package com.cc.wechat.test;
 
import net.sf.json.JSONObject;
 
import com.cc.wechat.menu.Button;
import com.cc.wechat.menu.ClickButton;
import com.cc.wechat.menu.ComplexButton;
import com.cc.wechat.menu.Menu;
import com.cc.wechat.util.CommonUtil;
/**
 * 执行菜单的创建
 * @author ICHN
 *
 */
public class MenuTest {
 
    public static void main(String[] args) {
        /**
         * 按钮类型就两种:
         * click类型
         * view类型
         */
         
        /**
         *click类型
         * 二级菜单1
         * 所包含的二级菜单:
         *             clickButton_11
         *             ...
         * 可以定义5个
         */
        ClickButton clickButton_11 = new ClickButton();
        //设置按钮名称
        clickButton_11.setName("");
        //设置按钮类别 尊照微信开发文档给出的定义
        clickButton_11.setType("");
        //设置按钮key值
        clickButton_11.setKey("");
         
        //.....可以定义5个.....
         
        /**
         * 二级菜单2
         * 所包含的二级菜单:
         *         clickButton_21
         *      ...
         */
        ClickButton clickButton_21 = new ClickButton();
        clickButton_21.setName("");
        clickButton_21.setType("");
        clickButton_21.setKey("");
         
        /**
         * 定义一个一级菜单数组,
         * 个数应为1~3个
         */
        ClickButton button_3 = new ClickButton();
        button_3.setName("");
        button_3.setType("");
        button_3.setKey("");
         
        /**
         * 上面的二级菜单定义好后,
         * 用一个带二级菜单的按钮(ComplexButton)装起来
         */
         
        //一级菜单1
        ComplexButton complexButton1 = new ComplexButton();
        complexButton1.setName("一级菜单1");
        complexButton1.setSub_button(new Button[] {clickButton_11});
         
        //一级菜单2
        ComplexButton complexButton2 = new ComplexButton();
        complexButton2.setName("");
        complexButton2.setSub_button(new Button[] {clickButton_21});
         
        //一级菜单3定义在上面
         
        //用一个menu(相当于总菜单,在最外层)来把上面的菜单装起来
        Menu menu = new Menu();
        menu.setButton(new Button[] {complexButton1, complexButton2, button_3});
         
        //把menu转换为json数组
        String jsonMenu = JSONObject.fromObject(menu).toString();
         
        /**
         * 创建和删除都是采用https协议
         * http请求方式:POST(请使用https协议)
         */
        //创建菜单接口
        //https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
        String createRequest = CommonUtil.httpsRequest(
                //requestUrl
                "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=此处填写上面GetAccessToken类获取的access_token", 
                //requestMethod
                "POST", 
                //outputStr
                jsonMenu
            );
         
        //打印出创建状态信息(同时执行创建)
        //System.out.println(createRequest);
         
        //删除菜单接口
        //https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN
        String deleteResult = CommonUtil.httpsRequest(
                "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=此处填写上面GetAccessToken类获取的access_token", 
                "POST", 
                jsonMenu
            );
         
        //打印出删除状态信息(同时执行删除)
        System.out.println(deleteResult);
    }
}
Copy after login

The above is the detailed content of Detailed introduction to the creation and deletion of custom menus in WeChat public platform development. 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 WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

Using PHP to develop WeChat mass messaging tools Using PHP to develop WeChat mass messaging tools May 13, 2023 pm 05:00 PM

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

PHP WeChat development: How to implement user tag management PHP WeChat development: How to implement user tag management May 13, 2023 pm 04:31 PM

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

PHP WeChat development: How to implement group message sending records PHP WeChat development: How to implement group message sending records May 13, 2023 pm 04:31 PM

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

PHP WeChat development: How to implement voting function PHP WeChat development: How to implement voting function May 14, 2023 am 11:21 AM

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

PHP WeChat development: How to implement customer service chat window management PHP WeChat development: How to implement customer service chat window management May 13, 2023 pm 05:51 PM

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

Steps to implement WeChat public account development using PHP Steps to implement WeChat public account development using PHP Jun 27, 2023 pm 12:26 PM

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

How to use PHP for WeChat development? How to use PHP for WeChat development? May 21, 2023 am 08:37 AM

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform

See all articles