How to create and delete custom menus for WeChat public platform development

Source: Internet
Author: User
This article describes how to create and delete custom menus developed by the public platform. when creating menus, data is transmitted based on JSON. to use JSON, download related packages and click to download them:

The public platform development documents are described as follows:

Note:

1. a custom menu can contain up to three level-1 menus, and each level-1 menu can contain up to five level-2 menus.
2. a level-1 menu can contain up to four Chinese characters, and a level-2 menu can contain up to seven Chinese characters. the Extra content will be replaced.
3. after creating a custom menu, it takes 24 hours for the client to be displayed due to client cache. During the test, you can try to remove the public account and then follow it again. then you can see the created effect.

The custom menu interface supports multiple types of buttons as follows:

1. click: after clicking the PUSH event user clicks the click type button, the server will push the message type as event through the Message Interface
The structure is provided to the developer (reference Message Interface Guide), and the key value entered by the developer in the button is included. the developer can customize
To interact with the user;
2. view: after a jump URL user clicks the view type button, the client will open
The webpage URL entered in the button can be combined with the webpage authorization interface to obtain basic user information.
3. scancode_push
Scan result (if it is a URL, it will enter the URL), and the result of the scan code will be sent to the developer, the developer can send a message.
4. scancode_waitmsg
After scanning the code, send the result of scanning the code to the developer, collapse the scanning tool, and then pop up the "message
"Receiving" prompt box, and you may receive a message from the developer later.
5. pic_sysphoto,
The system will send the photos taken to the developer, push the events to the developer, hide the system camera, and then may receive
Message.
6. pic_photo_or_album
For users to choose "photo" or "select from cell phone Album ". After the user selects this option, the other two processes are followed.
7. pic_weixin
Then, send the selected photo to the developer's server, push the event to the developer, and collapse the album.
The message sent by the sender.
8. location_select
Location selection tool. after the selection operation is completed, the selected geographic location is sent to the developer's server, and the location selection
Tool. you may receive messages from the developer later.
9. media_id: click to send messages (except text messages ).
After the media_id type button, the server will send the materials corresponding to the permanent material id filled by the developer to the user.
Images, audios, videos, and text messages. Note: The permanent material id must be in "Material Management/add permanent materials"
The valid id obtained after the API is uploaded. 10. view_limited: Jump to the text message URL. after you click the view_limited type button,
The client will open the text message URL corresponding to the permanent material id filled in by the developer in the button. the permanent material type only supports text
Message. Note: The permanent clip id must be the valid id obtained after the "clip management/add permanent clip" API is uploaded.

Please note that all events from 3 to 8 only support users of iPhone 5.4.1 and later versions, and users of Android 5.4 or later versions do not respond after clicking the old version, the developer cannot receive event push normally. 9 and 10 are events that are specially prepared for subscription numbers of unauthenticated third-party platforms (specifically, they are not certified). they are not pushed by events, capability is relatively limited, and other types of public accounts do not need to be used.

1. because the custom menu adopts the http request method, the https protocol is used. Write a Method class to process https and json data.

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

--- 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;/*** common public platform interface tool class * @ author ICHN * 2015-09-04 */public class CommonUtil {/*** to initiate an https request And GET the result * @ param requestUrl request address * @ param requestMethod request method (GET, POST) * @ param outputStr submitted data * @ return JSONObject (through JSONObject. get (key) method to get the attribute value of the json object) */public static String httpsRequest (String requestUrl, String requestMethod, String outputStr) {StringBuffer sb = new StringBuffer (); // Create an SSLContext object and use the trusted manager we specified to initialize TrustManager [] tm = {new MyX509TrustManager ()}; try {SSLContext sslContext = SSLContext. getInstance ("SSL", "SunJSSE"); sslContext. init (null, tm, new java. security. secureRandom (); // Obtain the SSLSocketFactory object SSLSocketFactory ssf = SSLContext from the sslContext object. getSocketFactory (); URL url = new URL (requestUrl); HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) url. openConnection (); httpsUrlConnection. setSSLSocketFactory (ssf); httpsUrlConnection. setDoInput (true); httpsU RlConnection. setDoOutput (true); httpsUrlConnection. setUseCaches (false); // sets the request method (GET/POST) httpsUrlConnection. setRequestMethod (requestMethod); // judge the request method using the condition signorecase case-insensitive if ("GET ". equalsIgnoreCase (requestMethod) {// establish a connection to httpsUrlConnection. connect () ;}// if (null! = OutputStr) {OutputStream OS = httpsUrlConnection. getOutputStream (); // pay attention to the encoding format to prevent Chinese garbled OS. write (outputStr. getBytes ("UTF-8"); OS. close () ;}// convert the returned input stream to the string 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 (); // release the resource is. close (); is = null;} catch (Exception e) {e. printStackTrace ();} return sb. toString ();}}

2. define various types of buttons and extract common variables into a class.

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

1 --- Button. java:

Package com. cc. wechat. menu;/*** menu Button * @ author ICHN */public class Button {// menu title, no more than 16 bytes, and no more than 40 bytes of private String name in the sub-menu; public String getName () {return name;} public void setName (String name) {this. name = name ;}}

2 --- ClickButton. java:

Package com. cc. wechat. menu;/*** click Button * @ author ICHN **/public class ClickButton extends Button {// menu response action type private String type; // menu KEY value, used for Message Interface push, private String key of up to 128 bytes; 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;/*** number of list menu arrays * should be 1 ~ Five * @ author ICHN **/public class ComplexButton extends Button {// list menu array 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;/*** 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 type Button * @ author ICHN **/public class ViewButton extends Button {// menu response action type private String type; // webpage link, you can click the menu to open the link, with no more than 256 bytes of 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 test source folder, create a com. cc. wechat. test package, and write related classes for the created menu in this package.

Write a class to get access_token:

--- GetAccessToken. java:

Package com. cc. wechat. test; import com. cc. wechat. util. commonUtil;/*** get access_token * @ author ICHN * The appID and appsecret of the test account ** access_token are the globally unique tickets of the public account. access_token is required when the public account calls each interface. * Developers must properly save the settings. The storage of access_token must contain at least 512 characters. * The validity period of access_token is currently 2 hours and must be refreshed regularly. * repeated access_token acquisition will invalidate the last access_token */public class getaccesen en {public static void main (String [] args) {// Print the 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;/*** create execution menu * @ author ICHN **/public class MenuTest {public static void main (String [] args) {/*** there are two button types: * click type * view type * // The two contained in * click type * level-2 menu 1 * Level menu: * clickButton_11 *... * You can define five */ClickButton clickButton_11 = new ClickButton (); // Set the button name clickButton_11.setName (""); // Set the button category as defined in the development document clickButton_11.setType (""); // Set the button key value clickButton_11.setKey ("");//..... you can define five ..... /The level-2 menu included in *** level-2 menu: * clickButton_21 *... */ClickButton clickButton_21 = new ClickButton (); clickButton_21.setName (""); clickButton_21.setType (""); clickButton_21. SetKey ("");/*** defines a level-1 menu array. * The number should be 1 ~ 3 */ClickButton button_3 = new ClickButton (); button_3.setName (""); button_3.setType (""); button_3.setKey (""); /*** after the preceding level-2 menu is defined, * use a button with a level-2 menu (ComplexButton) to install it * // level-1 Menu 1 ComplexButton complexButton1 = new ComplexButton (); complexButton1.setName ("Level 1 Menu 1"); complexButton1.setSub _ button (new Button [] {clickButton_11}); // level 1 Menu 2 ComplexButton complexButton2 = new ComplexButton (); complexButton2.setName (""); complexButton2.setSub _ button (new Button [] {clickButton_21}); // level 1 menu 3 is defined above. // use a menu (equivalent to the total menu, in the outermost layer) to install the above Menu menu Menu = new menu (); Menu. setButton (new Button [] {complexButton1, complexButton2, button_3}); // converts the menu to a json Array String jsonMenu = JSONObject. fromObject (menu ). toString ();/*** both creation and deletion use the https protocol * http request method: POST (please use the https protocol) * // create a menu interface // 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= Enter the access_token ", // requestMethod" POST ", // outputStr jsonMenu obtained by the above GetAccessToken class); // Print the creation status information (create at the same time) // System. out. println (createRequest); // you can call this operation to delete a menu // 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= Enter the access_token "," POST ", jsonMenu) obtained by the above GetAccessToken class. // Print the deletion status information (delete simultaneously) System. out. println (deleteResult );}}

The above is a detailed introduction to the creation and deletion of custom menus for public platform development. For more information, see other related articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.