上一篇了解微信开发者中心 URL的配置验证;
- 验证成功后,就可以对获取的接口权限进行操作
自定义菜单接口可实现多种类型按钮,用的比较多的是
1.click:点击推事件
用户点击click类型按钮后,微信服务器会通过消息接口推送消息类型为event 的结构给开发者(参考消息接口指南),并且带上按钮中开发者填写的key值,开发者可以通过自定义的key值与用户进行交互;
2、view:跳转URL
用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的网页URL,可与网页授权获取用户基本信息接口结合,获得用户基本信息。
自定义菜单接口调用:
http请求方式:POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
ACCESS_TOKEN 需要通过接口获取
由于ACCESS_TOKEN 一天只能调用 2000,可以将ACCESS_TOKEN 保存起来,有效时间内不需要重新调用接口
/// <summary> /// 获取凭证接口 /// </summary> /// <param name="grant_type">获取access_token填写client_credential</param> /// <param name="appid">第三方用户唯一凭证</param> /// <param name="secret">第三方用户唯一凭证密钥,既appsecret</param> /// <returns></returns> public static string GetAccessToken(string appid, string secret) { string token = OperationXml.GetXMLToken(); if (token == "") { string strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret)); token = GetJsonValue(strJson, "access_token"); OperationXml.UpdateXMLToken(token, DateTime.Now); } return token; } public static string RequestUrl(string strUrl) { // 设置参数 HttpWebRequest request = WebRequest.Create(strUrl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; } #region 获取Json字符串某节点的值 /// <summary> /// 获取Json字符串某节点的值 /// </summary> public static string GetJsonValue(string jsonStr, string key) { string result = string.Empty; if (!string.IsNullOrEmpty(jsonStr)) { key = "\"" + key.Trim(\'"\') + "\""; int index = jsonStr.IndexOf(key) + key.Length + 1; if (index > key.Length + 1) { //先截逗号,若是最后一个,截“}”号,取最小值 int end = jsonStr.IndexOf(\',\', index); if (end == -1) { end = jsonStr.IndexOf(\'}\', index); } result = jsonStr.Substring(index, end - index); result = result.Trim(new char[] { \'"\', \' \', \'\\'\' }); //过滤引号或空格 } } return result; } #endregion /// <summary> /// 获取XML文件路径 /// </summary> public static string xmlName = AppDomain.CurrentDomain.BaseDirectory + @"\AccessToken.xml"; /// <summary> /// 读取XML Token /// </summary> /// <param name="xmlUrl"></param> /// <returns></returns> public static string GetXMLToken() { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlName); XmlNode xn = xmlDoc.SelectSingleNode("ACCESS_TOKEN"); XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型 string Token = ""; string CreateTime = ""; foreach (XmlNode xn1 in xe)//遍历 { XmlElement xe2 = (XmlElement)xn1;//转换类型 if (xe2.Name == "Token")//如果找到 { Token = xe2.InnerText;//则修改 } if (xe2.Name == "CreateTime")//如果找到 { CreateTime = xe2.InnerText;//则修改 } } int seconds = 0; if (CreateTime.Trim() != "") { DateTime ct = Convert.ToDateTime(CreateTime); TimeSpan ts = (DateTime.Now - ct); seconds = ts.Milliseconds; } LogTextHelper.WriteLogToFile("Token:" + Token); if (seconds > 7200 || seconds == 0) { return ""; } else { return Token; } } catch (Exception ex) { LogTextHelper.WriteLogToFile("异常:" + ex.ToString()); return ""; } } /// <summary> /// 修改Token /// </summary> /// <param name="token"></param> /// <param name="createTime"></param> public static void UpdateXMLToken(string token, DateTime createTime) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlName); XmlNode xn = xmlDoc.SelectSingleNode("ACCESS_TOKEN"); XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型 foreach (XmlNode xn1 in xe)//遍历 { XmlElement xe2 = (XmlElement)xn1;//转换类型 if (xe2.Name == "Token")//如果找到 { xe2.InnerText = token;//则修改 } if (xe2.Name == "CreateTime")//如果找到 { xe2.InnerText = createTime.ToString();//则修改 } } xmlDoc.Save(xmlName); }
1 #region 创建菜单 2 3 public string CreateMenuPage(string posturl, string postData) 4 { 5 Stream outstream = null; 6 Stream instream = null; 7 StreamReader sr = null; 8 HttpWebResponse response = null; 9 HttpWebRequest request = null; 10 Encoding encoding = Encoding.UTF8; 11 byte[] data = encoding.GetBytes(postData); 12 // 准备请求... 13 try 14 { 15 // 设置参数 16 request = WebRequest.Create(posturl) as HttpWebRequest; 17 CookieContainer cookieContainer = new CookieContainer(); 18 request.CookieContainer = cookieContainer; 19 request.AllowAutoRedirect = true; 20 request.Method = "POST"; 21 request.ContentType = "application/x-www-form-urlencoded"; 22 request.ContentLength = data.Length; 23 outstream = request.GetRequestStream(); 24 outstream.Write(data, 0, data.Length); 25 outstream.Close(); 26 //发送请求并获取相应回应数据 27 response = request.GetResponse() as HttpWebResponse; 28 //直到request.GetResponse()程序才开始向目标网页发送Post请求 29 instream = response.GetResponseStream(); 30 sr = new StreamReader(instream, encoding); 31 //返回结果网页(html)代码 32 string content = sr.ReadToEnd(); 33 string err = string.Empty; 34 Response.Write(content); 35 return content; 36 } 37 catch (Exception ex) 38 { 39 string err = ex.Message; 40 return string.Empty; 41 } 42 } 43 44 #endregion 45 46 #region 删除菜单 47 48 public JsonResult DelMenu() 49 { 50 string postUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={0}"; 51 postUrl = string.Format(postUrl, CommonApi.GetAccessToken(strAppID, strAppSecret)); 52 string menuInfo = getMenuInfo(); 53 string result = CommonApi.PostWebRequest(postUrl, menuInfo); 54 55 return Json(result, JsonRequestBehavior.AllowGet); 56 } 57 58 #endregion 59 60 #region 获取菜单 61 62 public string GetMenuList(string posturl) 63 { 64 Stream instream = null; 65 StreamReader sr = null; 66 HttpWebResponse response = null; 67 HttpWebRequest request = null; 68 Encoding encoding = Encoding.UTF8; 69 // 准备请求... 70 try 71 { 72 // 设置参数 73 request = WebRequest.Create(posturl) as HttpWebRequest; 74 CookieContainer cookieContainer = new CookieContainer(); 75 request.CookieContainer = cookieContainer; 76 request.AllowAutoRedirect = true; 77 request.Method = "GET"; 78 request.ContentType = "application/x-www-form-urlencoded"; 79 //发送请求并获取相应回应数据 80 response = request.GetResponse() as HttpWebResponse; 81 //直到request.GetResponse()程序才开始向目标网页发送Post请求 82 instream = response.GetResponseStream(); 83 sr = new StreamReader(instream, encoding); 84 //返回结果网页(html)代码 85 string content = sr.ReadToEnd(); 86 string err = string.Empty; 87 Response.Write(content); 88 return content; 89 } 90 catch (Exception ex) 91 { 92 string err = ex.Message; 93 return string.Empty; 94 } 95 } 96 97 #endregion 98 99 private string getMenuInfo() 100 { 101 { 102 "button":[ 103 { 104 "type":"click", 105 "name":"今日歌曲", 106 "key":"V1001_TODAY_MUSIC" 107 }, 108 { 109 "name":"菜单", 110 "sub_button":[ 111 { 112 "type":"view", 113 "name":"搜索", 114 "url":"http://www.soso.com/" 115 }, 116 { 117 "type":"view", 118 "name":"视频", 119 "url":"http://v.qq.com/" 120 }, 121 { 122 "type":"click", 123 "name":"赞一下我们", 124 "key":"V1001_GOOD" 125 }] 126 }] 127 } 128 }
发布服务器,执行下,在微信公众号上就可以看到自己定义的菜单了
-------------------------------------------------------------------------------------
如果你觉得有帮助 请关注我的微信公众号,没有帮助你也可以添加哟!o(∩_∩)o 哈哈
请发表评论