1. 程式人生 > >C#微信公眾號全攻略(3)--接管所有訊息驗證部分 C#程式碼

C#微信公眾號全攻略(3)--接管所有訊息驗證部分 C#程式碼

新建網站 新建一般處理程式

這裡寫圖片描述

怎麼操作SQL資料庫不寫了 只發一些關鍵部分程式碼

一般處理程式關鍵程式碼

    public class Interface : IHttpHandler
    {
        public static readonly string SqlConnectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;

        public void ProcessRequest(HttpContext context)
        {
            string
postString = string.Empty; WXHelper myWXHelper = new WXHelper(SqlConnectionString); if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { using (Stream stream = HttpContext.Current.Request.InputStream) { Byte[] postBytes = new
Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); postString = Encoding.UTF8.GetString(postBytes); if (!string.IsNullOrEmpty(postString)) { /// <summary> ///
處理資訊並應答
/// </summary> //Handle(postString); } } } else { /// <summary> /// 微信接入驗證 /// </summary> myWXHelper.Auth(); } } /// <summary> /// 處理資訊並應答 /// </summary> private void Handle(string postStr) { messageHelp help = new messageHelp(SqlConnectionString); string responseContent = help.ReturnMessage(postStr); HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); } public bool IsReusable { get { return false; } } }

說明:
接入驗證是GET,其他後續的訊息都是POST方式。
WXHelpermessageHelper自己封裝的2個類。

WXHelper關鍵程式碼

    private readonly string token = "按自己的填";  //按自己的填

    //微信接入時對伺服器的驗證
    public void Auth()
    {
        if (string.IsNullOrEmpty(token))
        {
            return;
        }

        string echoStr = HttpContext.Current.Request.QueryString["echoStr"];
        string signature = HttpContext.Current.Request.QueryString["signature"];
        string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
        string nonce = HttpContext.Current.Request.QueryString["nonce"];

        if (!string.IsNullOrEmpty(echoStr))
        {
            string StrSQL = "";
            using (SqlConnection mySqlConnection = new SqlConnection(mySqlConnectionString))
            {
                StrSQL = "INSERT INTO [WX_Auth] ([signature], [timestamp], [nonce], [echoStr], [FromIPAddress]) VALUES (";
                StrSQL += "@signature, @timestamp, @nonce, @echoStr, @FromIPAddress)";
                SqlCommand mySqlCommand = new SqlCommand(StrSQL, mySqlConnection);

                mySqlCommand.Parameters.AddWithValue("@signature", signature);
                mySqlCommand.Parameters.AddWithValue("@timestamp", timestamp);
                mySqlCommand.Parameters.AddWithValue("@nonce", nonce);
                mySqlCommand.Parameters.AddWithValue("@echoStr", echoStr);
                mySqlCommand.Parameters.AddWithValue("@FromIPAddress", getIp());

                mySqlConnection.Open();
                mySqlCommand.ExecuteNonQuery();
                mySqlConnection.Close();
            }

            HttpContext.Current.Response.Write(echoStr);
            HttpContext.Current.Response.End();
        }
    }


    //獲取客戶端的IP地址
    public static string getIp()
    {
        if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];
        else
            return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }

說明:
getIP()用來獲取客戶機的IP,這裡當然獲取微信驗證伺服器的IP
程式碼裡把驗證的請求資訊寫進了資料庫,資料庫建立對應的表
返回echoStr給微信驗證伺服器就算通過了
一次驗證通不過多點幾次,有時候微信驗證伺服器卡