微信公眾平台接入:其實很簡單,把兩個參數(地址和token)填入微信公眾平台后台,暫時選擇明文模式 ,其中token自己定義。微信服務器會根據后台填寫的地址訪問,並且帶上對於的參數 如 url+&signature=0dab3e6f983b6bdccfdbe3ceca01526f1522748a×tamp=1436257899&nonce=1868246535&echostr=echostr 根據參數用微信文檔中指定的方法加密檢驗是否來自微信然后返回隨機數echostr(當然你可以直接返回隨機數,好處是簡單,但是這樣非微信服務器也可以訪問你的服務器)
此處的方法是:新建一個一般處理程序(通常的做法是有偽靜態處理,不生成偽靜態地址也可以)代碼如下 token自定義,token類似密碼,如果泄露和微信的密鑰一樣可以修改。因為接入非常簡單這里就不多寫,可以直接看代碼。
我寫的demo測試地址為:http://wxdemo.sohovan.com/API.ashx token:sohovan 下載源碼的github地址:https://github.com/xiejun-net/weixin
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using System.Web.Security; namespace sohovan.com.wxdemo { /// <summary> /// API 的摘要說明 /// </summary> public class API : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; if (context.Request.HttpMethod.ToLower() == "post") { //回復消息的時候也需要驗證消息,這個很多開發者沒有注意這個,存在安全隱患 //微信中 誰都可以獲取信息 所以 關系不大 對於普通用戶 但是對於某些涉及到驗證信息的開發非常有必要 if (CheckSignature()) { //接收消息 } else { HttpContext.Current.Response.Write("消息並非來自微信"); HttpContext.Current.Response.End(); } } else { CheckWechat(); } } #region 驗證微信簽名 /// <summary> /// 返回隨機數表示驗證成功 /// </summary> private void CheckWechat() { if (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["echoStr"])) { HttpContext.Current.Response.Write("消息並非來自微信"); HttpContext.Current.Response.End(); } string echoStr = HttpContext.Current.Request.QueryString["echoStr"]; if (CheckSignature()) { HttpContext.Current.Response.Write(echoStr); HttpContext.Current.Response.End(); } } /// <summary> /// 驗證微信簽名 /// </summary> /// <returns></returns> /// * 將token、timestamp、nonce三個參數進行字典序排序 /// * 將三個參數字符串拼接成一個字符串進行sha1加密 /// * 開發者獲得加密后的字符串可與signature對比,標識該請求來源於微信。 private bool CheckSignature() { string access_token = "sohovan"; string signature = HttpContext.Current.Request.QueryString["signature"].ToString(); string timestamp = HttpContext.Current.Request.QueryString["timestamp"].ToString(); string nonce = HttpContext.Current.Request.QueryString["nonce"].ToString(); string[] ArrTmp = { access_token, timestamp, nonce }; Array.Sort(ArrTmp); //字典排序 string tmpStr = string.Join("", ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); if (tmpStr.ToLower() == signature) { return true; } else { return false; } } #endregion public bool IsReusable { get { return false; } } } }
本文版權歸作者(謝俊)和博客園所有,歡迎轉載,轉載請標明出處。
原文地址:http://www.cnblogs.com/net-xiejun/
完整源碼下載:https://github.com/xiejun-net/weixin
個人公眾賬號:


