微信公眾號建立自定義選單(公眾號跳轉小程式功能)
使用JAVA後端去自定義建立選單,微信公眾號開發文件中提供了API:
建立選單中有一些要注意的地方:
1、自定義選單最多包括3個一級選單,每個一級選單最多包含5個二級選單。
2、一級選單最多4個漢字,二級選單最多7個漢字,多出來的部分將會以“...”代替。
3、建立自定義選單後,選單的重新整理策略是,在使用者進入公眾號會話頁或公眾號profile頁時,如果發現上一次拉取選單的請求在5分鐘以前,就會拉取一下選單,如果選單有更新,就會重新整理客戶端的選單。測試時可以嘗試取消關注公眾賬號後再次關注,則可以看到建立後的效果。
這些可以說是建立選單中的格式或者是規則,下面是選單的型別,每個型別代表給他建立的選單中的功能是不一樣的,請認真檢視文件
程式碼例項:
HttpUtils.java(傳送POST請求):
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLDecoder;
/**
* <p>User: qrn
* <p>Date: 14-1-28
* <p>Version: 1.0
* 描述: http請求的工具類
*/
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class); //日誌記錄
/**
* httpPost
*
* @param url 路徑
* @param jsonParam 引數
* @return JSONObject
*/
public static JSONObject httpPost(String url, String jsonParam) {
return httpPost(url, jsonParam, false);
}
/**
* post請求
*
* @param url url地址
* @param param 引數
* @param noNeedResponse 不需要返回結果
* @return JSONObject
*/
public static JSONObject httpPost(String url, String param, boolean noNeedResponse) {
//post請求返回結果
HttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (null != param) {
//解決中文亂碼問題
StringEntity entity = new StringEntity(param, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**請求傳送成功,並得到響應**/
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
try {
/**讀取伺服器返回過來的json字串資料**/
str = EntityUtils.toString(result.getEntity());
System.out.println(str);
if (noNeedResponse) {
return null;
}
/**把json字串轉換成json物件**/
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
logger.error("post請求提交失敗:" + url, e);
}
}
} catch (IOException e) {
logger.error("post請求提交失敗:" + url, e);
}
return jsonResult;
}
}
建立選單的方法(SpringMvc):
/**
* 建立自定義選單:
*/
@RequestMapping("/getAccount_txt")
@ResponseBody
public void getAccount_txt() {
String access_token = accountsService.Accountaccess_token(); //這裡是獲取的TOken介面
String url=WeChatTools.create+access_token; //這裡是建立選單的介面和token拼接 https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
System.out.println("傳送的url"+url);
String sun="{\r\n" +
" \"button\":[\r\n" +
" { \r\n" +
" \"type\":\"click\",\r\n" +
" \"name\":\"今日歌曲\",\r\n" +
" \"key\":\"V1001_TODAY_MUSIC\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"name\":\"選單\",\r\n" +
" \"sub_button\":[\r\n" +
" { \r\n" +
" \"type\":\"view\",\r\n" +
" \"name\":\"搜尋\",\r\n" +
" \"url\":\"http://www.soso.com/\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"type\":\"miniprogram\",\r\n" +
" \"name\":\"wxa\",\r\n" +
" \"url\":\"http://mp.weixin.qq.com\",\r\n" +
" \"appid\":\"wx286b93c14bbf93aa\",\r\n" +
" \"pagepath\":\"pages/lunar/index\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"type\":\"click\",\r\n" +
" \"name\":\"贊一下我們\",\r\n" +
" \"key\":\"V1001_GOOD\"\r\n" +
" }]\r\n" +
" }]\r\n" +
" }";
JSONObject jsonObjects=JSONObject.fromObject(sun);
HttpUtils.httpPost(url,jsonObjects.toString());
}
這樣根據自己所需要的去拼寫相應的型別就可以實現了
下面是進行了封裝的建立選單:
Button.java:
/**
* 選單:
* @author Administrator
*
*/
public class Button {
/**
* 選單名稱:
*/
private String name;
public Button() {
super();
}
public Button(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Button other = (Button) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Button [name=" + name + "]";
}
}
CommonButton.java:
/**
* 二級選單(CLICK型別)
* @author Administrator
*
*/
public class CommonButton extends Button {
/**
* 選單名稱:
*/
private String name;
/**
* 型別
*/
private String type;
/**
* 響應動作型別
*/
private String key;
public CommonButton() {
super();
}
public CommonButton(String name, String type, String key) {
super();
this.name = name;
this.type = type;
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommonButton other = (CommonButton) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString() {
return "CommonButton [name=" + name + ", type=" + type + ", key=" + key + "]";
}
}
ComplexButton.java:
import java.util.Arrays;
/**
* 一級選單:
* @author Administrator
*
*/
public class ComplexButton extends Button{
/**
* 選單名稱:
*/
private String name;
/**
* 子級選單:
*/
private Button[] sub_button;
public ComplexButton() {
super();
}
public ComplexButton(String name, Button[] sub_button) {
super();
this.name = name;
this.sub_button = sub_button;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Button[] getSub_button() {
return sub_button;
}
public void setSub_button(Button[] sub_button) {
this.sub_button = sub_button;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Arrays.hashCode(sub_button);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ComplexButton other = (ComplexButton) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (!Arrays.equals(sub_button, other.sub_button))
return false;
return true;
}
@Override
public String toString() {
return "ComplexButton [name=" + name + ", sub_button=" + Arrays.toString(sub_button) + "]";
}
}
Menu.java:
import java.util.Arrays;
/**
* 表示要建立的選單
* @author Administrator
*
*/
public class Menu {
private ComplexButton[] button;
public Menu() {
super();
}
public Menu(ComplexButton[] button) {
super();
this.button = button;
}
public ComplexButton[] getButton() {
return button;
}
public void setButton(ComplexButton[] button) {
this.button = button;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(button);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Menu other = (Menu) obj;
if (!Arrays.equals(button, other.button))
return false;
return true;
}
@Override
public String toString() {
return "Menu [button=" + Arrays.toString(button) + "]";
}
}
ViewButton.java:
/**
* 二級選單:(view)型別:
* @author Administrator
*
*/
public class ViewButton extends Button{
/**
* 選單名稱:
*/
private String name;
/**
* 型別:
*/
private String type;
/**
* 響應的網頁:
*/
private String url;
public ViewButton() {
super();
}
public ViewButton(String name, String type, String url) {
super();
this.name = name;
this.type = type;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ViewButton other = (ViewButton) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
@Override
public String toString() {
return "ViewButton [name=" + name + ", type=" + type + ", url=" + url + "]";
}
}
MiniprogramButton.java:
/**
* 跳轉到小程式:
* @author Administrator
*
*/
public class MiniprogramButton extends Button{
/**
* 型別:
*/
private String type;
/**
* 名稱:
*/
private String name;
/**
* 路徑:
*/
private String url;
/**
* 小程式 appid
*/
private String appid;
/**
* 小程式的頁面
*/
private String pagepath;
public MiniprogramButton() {
super();
}
public MiniprogramButton(String type, String name, String url, String appid, String pagepath) {
super();
this.type = type;
this.name = name;
this.url = url;
this.appid = appid;
this.pagepath = pagepath;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getPagepath() {
return pagepath;
}
public void setPagepath(String pagepath) {
this.pagepath = pagepath;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appid == null) ? 0 : appid.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((pagepath == null) ? 0 : pagepath.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MiniprogramButton other = (MiniprogramButton) obj;
if (appid == null) {
if (other.appid != null)
return false;
} else if (!appid.equals(other.appid))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (pagepath == null) {
if (other.pagepath != null)
return false;
} else if (!pagepath.equals(other.pagepath))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
@Override
public String toString() {
return "MiniprogramButton [type=" + type + ", name=" + name + ", url=" + url + ", appid=" + appid
+ ", pagepath=" + pagepath + "]";
}
}
MenuUtil.java:
/**
* 選單工具類:
* @author Administrator
*
*/
public class MenuUtil {
/**
* 封裝選單資料
* @return
*/
public static Menu getMenu() {
//建立view型別的選單
ViewButton cb_4 = new ViewButton();
cb_4.setType("view");
cb_4.setName("選單的名稱");
cb_4.setUrl("跳轉的網頁路徑");
//建立click型別的選單
CommonButton cb_2 = new CommonButton();
cb_2.setType("click");
cb_2.setName("選單的名稱");
cb_2.setKey("xxxxxxx");
//建立click型別的選單
CommonButton cb_3 = new CommonButton();
cb_3.setType("click");
cb_3.setName("選單的名稱");
cb_3.setKey("xxxxxxxxxxxx");
//建立第一個一級選單
ComplexButton cx_1 = new ComplexButton();
cx_1.setName("一級選單名稱");
cx_1.setSub_button(new Button[]{cb_4,cb_2,cb_3});
//建立第二個一級選單
ComplexButton cx_2 = new ComplexButton();
cx_2.setName("一級選單名稱");
//建立公眾號跳轉到小程式的選單
MiniprogramButton miniprogramButton = new MiniprogramButton();
miniprogramButton.setName("選單名稱");
miniprogramButton.setType("miniprogram");
miniprogramButton.setAppid("要跳轉的小程式APPID");
miniprogramButton.setUrl("http://mp.weixin.qq.com");
miniprogramButton.setPagepath("小程式要展示的頁面路徑");
cx_2.setSub_button(new Button[]{miniprogramButton});
ComplexButton cx_3 = new ComplexButton();
cx_3.setName("選單名稱");
CommonButton commonButton = new CommonButton();
commonButton.setKey("key3");
commonButton.setName("選單名稱");
commonButton.setType("click");
cx_3.setSub_button(new Button[] {commonButton}); //封裝選單資料
Menu menu=new Menu();
menu.setButton(new ComplexButton[]{cx_2,cx_3,cx_1});
return menu;
}
}
/**
* 建立自定義選單:
*/
@RequestMapping("/getAccount_txt")
@ResponseBody
public void getAccount_txt() {
String access_token = accountsService.Accountaccess_token(); //這裡是獲取的TOken介面
String url=WeChatTools.create+access_token; //這裡是建立選單的介面和token拼接 https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
System.out.println("傳送的url"+url);
Menu menu = MenuUtil.getMenu();
JSONObject jsonObjects=JSONObject.fromObject(menu);
HttpUtils.httpPost(url,jsonObjects.toString());
}
這裡就是建立自定義選單的例項了,這些程式碼應該是沒有問題的,如果有問題可以在下發評論