/// <summary> /// 验证微信签名 /// </summary> /// <returns></returns> /// 将token、timestamp、nonce三个参数进行字典序排序 /// 将三个参数字符串拼接成一个字符串进行sha1加密 /// 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 private bool CheckSignature() { string signature = Convert.ToString(Request["signature"]); string timestamp = Convert.ToString(Request["timestamp"]); string nonce = Convert.ToString(Request["nonce"]); string[] ArrTmp = { Token, timestamp, nonce }; Array.Sort(ArrTmp); //字典排序 string tmpStr = string.Join("", ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { return true; } else { return false; } }
签名验证通过,再加载菜单
//加载菜单
public void GetMenuList() { string menu = ""; menu = @" { ""button"":[ { ""type"":""click"", ""name"":""你好!"", ""key"":""hello"" }, { ""type"":""view"", ""name"":""公司简介"", ""url"":""http://www.xnfhtech.com/index.html"" }, { ""name"":""产品介绍"", ""sub_button"":[ { ""type"":""click"", ""name"":""产品1"", ""key"":""p1"" }, { ""type"":""click"", ""name"":""产品2"", ""key"":""p2"" }] }] } "; string access_token = IsExistAccess_Token(); string i = MenuCreate(menu, access_token); Response.Write(i); } public string MenuCreate(string MenuJson, string access_token) { JavaScriptSerializer Jss = new JavaScriptSerializer(); string setMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}"; setMenuUrl = string.Format(setMenuUrl, access_token);//获取token、拼凑url string respText = WebRequestPostOrGet(setMenuUrl, MenuJson); Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText); return respDic["errcode"].ToString();//返回0发布成功 } /// <summary> /// Post/get 提交调用抓取 /// </summary> /// <param name="url">提交地址</param> /// <param name="param">参数</param> /// <returns>string</returns> public string WebRequestPostOrGet(string sUrl, string sParam) { byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam); Uri uriurl = new Uri(sUrl); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param); req.Method = "Post"; req.Timeout = 120 * 1000; req.ContentType = "application/x-www-form-urlencoded;"; req.ContentLength = bt.Length; using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存 { reqStream.Write(bt, 0, bt.Length); reqStream.Flush(); } try { using (WebResponse res = req.GetResponse()) { //在这里对接收到的页面内容进行处理 Stream resStream = res.GetResponseStream(); StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8); string resLine; System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder(); while ((resLine = resStreamReader.ReadLine()) != null) { resStringBuilder.Append(resLine + System.Environment.NewLine); } resStream.Close(); resStreamReader.Close(); return resStringBuilder.ToString(); } } catch (Exception ex) { return ex.Message;//url错误时候回报错 } }
/// <summary> /// 防止每次请求的token两个小时的变化 /// </summary> public class WA_GetAccess_Token { public WA_GetAccess_Token() { } public static WAEntity.Access_token GetAccess_Token() { string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ ConfigurationManager.AppSettings["AppID"] + "&secret="+ ConfigurationManager.AppSettings["AppSecret"]; Access_token entity = new Access_token(); try { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "GET"; using (WebResponse wr = req.GetResponse()) { HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8); string content = reader.ReadToEnd(); Access_token token = new Access_token(); token = JsonHelper.ParseFromJson<Access_token>(content); entity.access_token = token.access_token; entity.expires_in = token.expires_in; } } catch{ //记录日志} return entity; } /// <summary> /// 根据当前日期 判断Access_Token 是否超期 如果超期返回新的Access_Token 否则返回之前的Access_Token /// </summary> /// <param name="datetime"></param> /// <returns></returns> public static string IsExistAccess_Token() { try { string Token = string.Empty; DateTime YouXRQ; //读取XML文件中的数据,并显示出来 string filepath = HttpContext.Current.Request.MapPath("~/XMLFile.xml"); StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); xml.Load(str); str.Close(); str.Dispose(); Token = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText; YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText); if (DateTime.Now > YouXRQ) { DateTime _youxrq = DateTime.Now; WAEntity.Access_token mode = GetAccess_Token(); xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token; _youxrq = _youxrq.AddSeconds(Convert.ToInt32(mode.expires_in)); xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString(); xml.Save(filepath); Token = mode.access_token; } return Token; } catch (Exception ex) { return "";//记录日志 } } } public class Access_token { public Access_token() { } public string access_token { get; set; } public string expires_in { get; set; } } public class JsonHelper { /// <summary> /// 生成Json格式 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string GetJson<T>(T obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } /// <summary> /// 获取Json的Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="szJson"></param> /// <returns></returns> public static T ParseFromJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } }
XMLFile.xml
<?xml version="1.0" encoding="utf-8"?> <xml> <Access_Token>获取TOKEN</Access_Token> <Access_YouXRQ>2015/9/12 17:56:31</Access_YouXRQ> </xml>