微信開發之(一)微信驗證

   基於微信公衆測試平臺進行開發測試,並在網上找了不少資料再此聲明(若有佔用代碼請聯繫以備修改),因爲比較雜不一一說明謝謝他們的努力。供有須要的人蔘考。html

首先是實現微信的認證,登陸微信測試平臺咱們能夠看到系統自動給了一個微信號,測試號信息:appID和appsecret。數組

在接口配置信息中,有URL和Token 二個文本框,咱們分別在URL上寫上咱們的服務器測試文件的地址,採用的是通常處理程序相似(http://yourdomain.com/valided.ashx).服務器

Token的值咱們能夠自定義。微信

  而後咱們新建一個項目,新建valided.ashx文件用於驗證。網絡

 //在ProcessRequest方法裏面寫上以下代碼:
 if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
     {
              //do something
    }else{

           AuthWechat(); //採用GET方法判斷進入驗證方法
    } 
        ///認證微信
        private void AuthWechat()
        {
            string token = "testweixin";//Token的值
     
            string echoString = 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 (CheckSignature(token, signature, timestamp, nonce))
            {
                if (!string.IsNullOrEmpty(echoString))
                {
                    HttpContext.Current.Response.Write(echoString);
                    HttpContext.Current.Response.End();
                }
            }

        }

        /// <summary>
        /// 對微信傳入參數進行封裝到數組,拼接字符串,進行加密操做
        /// </summary>
        private bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };//將參數放進數組

            Array.Sort(ArrTmp);//對數組進行排序

            string tmpStr = string.Join("", ArrTmp);//將數組進行拼接

            ///對拼接後的字符串進行加密操做
           // tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

            tmpStr=Membership.CreateUser(tmpStr, "SHA1").ToString();

            //轉換成小寫形式
            tmpStr = tmpStr.ToLower();

            //比對成功返回
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

 

上圖中的相關參數說明:app

  描述
signature 微信加密簽名,signature結合了開發者填寫的token參數和請求中的timestamp參數、nonce參數。
timestamp 時間戳
nonce 隨機數
echostr 隨機字符串

 

參考官方文檔地址解析:驗證消息真實性dom

將上面的代碼保存後咱們編譯下而後發佈到服務器,在剛剛的測試號裏面寫好發佈對應的地址,點擊保存的時候系統會提示你是否配置成功,有時多是網絡緣由會提示配置失敗,建議多試幾回,若是沒有問題通常都會提示配置成功!這就實現了驗證和簽名。完成了重要的一步爲其餘接口的開發和實現奠基了基礎。ide

相關文章
相關標籤/搜索