This example is to realize the addition and deletion management of WeChat menus in the management background.
1. First we need to create a new database table for storing menu items
The fields that can be included are id, parent class id, name, sort, whether to display, type (view, click), link, adddate
Note that when menu menu data is stored in the background, parentId=-1 is the first-level menu, or parentId is the id of the first-level menu as the second-level menu under the first-level menu.
2. During the setting menu, you need to pass menuJson string to the WeChat interface, so you must first splice the string and define a creatMenu() in the background.
public bool creatMenu() { string menuJson = ""; // Here the default parentId=-1 is the outermost menu, isactive=1 is the display, responseType=1 is the click type DataTable dtAMenu = Service.SelectDataTable("id, name, responseType, jsonStr,url", "WEIXINMENU", " parentId=-1 and isactive=1 order by sort"); if (dtAMenu.Rows.Count > 0) { menuJson = "{/"button/":["; for (int i = 0; i < dtAMenu.Rows.Count; i++) { DataTable dtBMenu = Service.SelectDataTable("id, name, responseType, jsonStr,url", wx, " parentId=" + dtAMenu.Rows[i]["id"].ToString() + " and isactive=1 order by sort"); if (dtBMenu.Rows.Count > 0) { menuJson += "{/"name/":/"" + dtAMenu.Rows[i]["name"].ToString() + "/",/"sub_button/":["; for (int j = 0; j < dtBMenu.Rows.Count; j++) { if (Convert.ToInt32(dtBMenu.Rows[j]["responseType"]) == 2) { menuJson += "{/"type/":/"view/",/"name/":/"" + dtBMenu.Rows[j]["name"].ToString() + "/",/"url/":/"" + dtBMenu.Rows[j]["jsonStr"].ToString() + "/"},"; } else { menuJson += "{/"type/":/"click/",/"name/":/"" + dtBMenu.Rows[j]["name"].ToString() + "/",/"key/":/"eventKey_" + dtBMenu.Rows[j]["id"].ToString() + "/"},"; } } menuJson = menuJson.TrimEnd(','); menuJson += "]},"; } else { //if (Convert.ToInt32(dtAMenu.Rows[i]["responseType"]) == 2) //{ menuJson += "{/"type/":/"view/",/"name/":/"" + dtAMenu.Rows[i]["name"].ToString() + "/",/"url/":/"" + dtAMenu.Rows[i]["jsonStr"].ToString() + "/"},"; //} //else //{ // menuJson += "{/"type/":/"click/",/"name/":/"" + dtAMenu.Rows[i]["name"].ToString() + "/",/"key/":/"eventKey_" + dtAMenu.Rows[i]["id"].ToString() + "/"},"; //} } dtBMenu.Dispose(); } dtAMenu.Dispose(); menuJson = menuJson.TrimEnd(','); menuJson += "]}"; menuJson = menuJson.Trim(); return requestZmToCreatMent(menuJson); } else { return false; } }3. After obtaining the menujson string, call the WeChat interface to create a menu. You need to obtain the assessment token first. For the assessment token, please refer to: Obtain AccessToken
/// <summary> /// Request to the WeChat server to create a custom menu /// </summary> /// <param name="jsonStr"></param> /// <returns></returns> /// private bool requestZmToCreatMent(string jsonStr) { try { var AccessToken = "";// accesstoken needs to be retrieved exceptions. Generally, you can get the database at the beginning and get it from the database next time. Note that the accesstoken is valid for 7200 seconds//Declare an HttpWebRequest request string interfaceUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + AccessToken; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(interfaceUrl); //Set the connection timeout request.Timeout = 30000; request.KeepAlive = true; Encoding encodeType = Encoding.GetEncoding("UTF-8"); request.Headers.Set("Pragma", "no-cache"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322); Http STdns"; request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; request.CookieContainer = new CookieContainer(); byte[] Bytes = encodeType.GetBytes(jsonStr); request.ContentLength = Bytes.Length; request.AllowAutoRedirect = true; //Send data using (Stream writer = request.GetRequestStream()) { writer.Write(Bytes, 0, Bytes.Length); writer.Close(); } StringBuilder strb = new StringBuilder(); //Receive data using (Stream reader = request.GetResponse().GetResponseStream()) { StreamReader sr = new StreamReader(reader, encodeType); strb.Append(sr.ReadToEnd()); sr.Close(); reader.Close(); } if ((strb.ToString().IndexOf("/"errcode/":42001") != -1) || (strb.ToString().IndexOf("/"errcode/":40001") != -1) || (strb.ToString().IndexOf("/"errcode/":40014") != -1) || (strb.ToString().IndexOf("/"errcode/":41001") != -1)) //access_token error{ // AccessToken = getAccessToken(); getzmAccessToken(); return requestZmToCreatMent(jsonStr); } else { if (strb.ToString() == "{/"errcode/":0,/"errmsg/":/"ok/"}") { return true; } else { return false; } } } catch (Exception exp) { return false; } }Summarize
The above is the example code for setting a custom menu for WeChat public account development introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!