微信自定義菜單,信自定義菜單
自己寫的構造自定義菜單的方法,雖然有些重復,但畢竟是自己寫的感覺更清楚些!各位有什麼好的意見指出來呀!
兩個類SubButton(子菜單),ParentButton(父級菜單)。
public class ParentButton
{
public string name;
public List<SubButton> list;
}
public class SubButton
{
public string name;
public string type;
public string url;
public string key;
}
構造好的菜單傳給GetCustomMenuJsonData得到正確的Json格式數據。

![]()
public string GetCustomMenuJsonData(List<ParentButton> list)
{
string jsonStr = "";
string str = "";
if (list != null && list.Count > 0)
{
foreach (ParentButton parentButton in list)
{
if (parentButton != null)
{
string subStr = "";
if (parentButton.list != null && parentButton.list.Count > 0)
{
foreach (SubButton button in parentButton.list)
{
if (button != null)
{
if (subStr != "")
{
subStr += ",";
}
if (button.type == "click")
{
subStr += "{ \"type\":\"click\", \"name\":\"" + button.name + "\",\"key\":\"" + button.key + "\" }";
}
else
{
subStr += "{ \"type\":\"view\", \"name\":\"" + button.name + "\",\"url\":\"" + button.url + "\" }";
}
}
}
}
if (str != "")
{
str += ",";
}
str += " {\"name\":\"" + parentButton.name + "\", \"sub_button\":[" + subStr + "]}";
}
}
jsonStr = ("{ \"button\":[" + str + "]}");
}
return jsonStr;
}
View Code
舉例:

![]()
Publish List<ParentButton> CreateCustomButton()
{
ParentButton button1 = new ParentButton();
List<SubButton> subButtonList1 = new List<SubButton>();
SubButton subButton = new SubButton();
subButton.name = "百度";
subButton.type = "view";
subButton.url = "www.baidu.com";
subButtonList1.Add(subButton);
subButton = new SubButton();
subButton.name = "谷歌";
subButton.type = "view";
subButton.url = "www.google.com";
subButtonList1.Add(subButton);
button1.name = "搜索";
button1.list = subButtonList1;
ParentButton button2 = new ParentButton();
button2.name="其他";
List<ParentButton> list = new List<ParentButton>();
list.Add(button1);
list.Add(button2);
return list;
}
View Code
得到json數據後通過
https://api.wexin.qq.com/cgi-bin/token?grant_type=client_credential&appid=AppId&secret=AppSecret
獲取到accesstoken,然後通過
https://api.weixin.qq.com/cgi-bin/menu/create?access_token=AccessToken
提交自定義菜單的json數據,生成菜單!