Home  >  Article  >  WeChat Applet  >  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

高洛峰
高洛峰Original
2017-03-22 16:45:313347browse

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();
    }
}

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;
    }
}

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;
    }
}

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;
    }
}

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;
    }
}

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;
    }
}

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
         )
        );
    }
}

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);
    }
}

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:
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