.Net 實現微信公共服務平台開發的認證,認證成為開發者,具體內容如下
這些代碼也就開始認證的時候用一次,以後就不用了:
const string Token = "XXXXX";//你的token protected void Page_Load(object sender, EventArgs e) { string postStr = ""; if (Request.HttpMethod.ToLower() == "post") { System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] b = new byte[s.Length]; s.Read(b, 0, (int)s.Length); postStr = System.Text.Encoding.UTF8.GetString(b); if (!string.IsNullOrEmpty(postStr)) { //ResponseMsg(postStr); Response.Write(ResponseMsg(postStr)); Response.End(); } //WriteLog("postStr:" + postStr); } else { Valid(); } } /// <summary> /// 驗證微信簽名 /// </summary> /// * 將token、timestamp、nonce三個參數進行字典序排序 /// * 將三個參數字符串拼接成一個字符串進行sha1加密 /// * 開發者獲得加密後的字符串可與signature對比,標識該請求來源於微信。 /// <returns></returns> private bool CheckSignature() { string signature = Request.QueryString["signature"].ToString(); string timestamp = Request.QueryString["timestamp"].ToString(); string nonce = Request.QueryString["nonce"].ToString(); 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; } } .private void Valid() { string echoStr = Request.QueryString["echoStr"].ToString(); if (CheckSignature()) { if (!string.IsNullOrEmpty(echoStr)) { Response.Write(echoStr); Response.End(); } } } /// <summary> /// 寫日志(用於跟蹤) /// </summary> private void WriteLog(string strMemo) { string filename = Server.MapPath("/logs/log.txt"); if (!Directory.Exists(Server.MapPath("//logs//"))) Directory.CreateDirectory("//logs//"); StreamWriter sr = null; try { if (!File.Exists(filename)) { sr = File.CreateText(filename); } else { sr = File.AppendText(filename); } sr.WriteLine(strMemo); } catch { } finally { if (sr != null) sr.Close(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。