微信开发-验证服务器

微信自己开发的第一步要验证自己的服务器,只需写一个空网页,接收微信服务器发过来的字符串,然后验证签名后将字符串原样返回,微信服务器收到这个字符串后即可验证成功。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

namespace Weixin
{
    public partial class Index : System.Web.UI.Page
    {
        public const String TOKEN = "zhuoteng123"; 
        protected void Page_Load(object sender, EventArgs e)
        {
            String echoStr = Request["echostr"];

            Debug.Write("soupld:"
                + DateTime.Now.ToString("HH-mm-ss")
                + "load page");

            if (this.checkSignature())
            {
                Response.Write(echoStr);
            }
        }

        //验证
        private bool checkSignature()
        {
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];

            string token = TOKEN;
            string[] tmpArr = new string[] { token, timestamp, nonce };
            Array.Sort(tmpArr);
            string tmpStr = string.Join("", tmpArr);
            //sha1加密
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] secArr = sha1.ComputeHash(System.Text.Encoding.Default.GetBytes(tmpStr));
            tmpStr = BitConverter.ToString(secArr).Replace("-", "").ToLower();

            Debug.Write("soupld:" 
                + DateTime.Now.ToString("HH-mm-ss") 
                + ":signature=" + signature 
                + ";timestamp=" + timestamp 
                + ";nonce=" + nonce 
                + ";");
            
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


写好的网页放到服务器上,用IIS配置好网站,注意要把将此页面设置为默认页面,让网站启动后即可接受微信服务器消息。

版权声明:

posted on 2015-04-08 16:50  moffis  阅读(195)  评论(0编辑  收藏  举报

导航