1. 程式人生 > >微信公眾號開發者申請,Token驗證

微信公眾號開發者申請,Token驗證


    /// <summary>
    /// Post 的摘要說明
    /// </summary>
    public class Post : IHttpHandler
    {
        WXCore m_wxCore = new WXCore();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml;charset=utf-8";
            //context.Response.Write("Hello World"); 打印出這一句,會造成配置不成功
if (context.Request.HttpMethod.ToLower() == "post") { } else { m_wxCore.Auth(); } } public bool IsReusable { get { return false; } } }
public void Auth()
        {
            string echoStr = HttpContext.Current.Request.QueryString["echostr"];
            if (CheckSignature()) //校驗簽名是否正確
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    HttpContext.Current.Response.Write(echoStr); //返回原值表示校驗成功
HttpContext.Current.Response.End(); } } } /// <summary> /// 驗證微信簽名 /// * 將token、timestamp、nonce三個引數進行字典序排序 /// * 將三個引數字串拼接成一個字串進行sha1加密 /// * 開發者獲得加密後的字串可與signature對比,標識該請求來源於微信。 /// </summary> /// <returns></returns> private bool CheckSignature() { string signature = HttpContext.Current.Request.QueryString["signature"]; string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; //加密/校驗流程: //1. 將token、timestamp、nonce三個引數進行字典序排序 string[] ArrTmp = { ConfigHelper.Token, timestamp, nonce }; Array.Sort(ArrTmp);//字典排序 //2.將三個引數字串拼接成一個字串進行sha1加密 string tmpStr = string.Join("", ArrTmp); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); //3.開發者獲得加密後的字串可與signature對比,標識該請求來源於微信。 if (tmpStr == signature) { return true; } else { return false; } }