微信公众平台开发(一) ——实现URL接入

一、填写服务器配置

       登录微信公众平台,点击开发者中心,点击“修改配置”按钮,填写服务器地址(URL)、Token和EncodingAESKey。URL是开发者用来接收微信消息和事件的接口URL。Token可以任意填写,用作生成签名。EncodingAESKey可以手动填写或随机生成。

     

二、验证服务器的有效性

      以下内容来自开发者文档

      开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带四个参数:

参数描述
signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp 时间戳
nonce 随机数
echostr 随机字符串

      开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接 入失败。

加密/校验流程如下:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

实现方法
新建一般处理程序WXService.ashx

WXService.ashx.cs
 public void ProcessRequest(HttpContext context)
        {
            string postString = string.Empty;
            if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
            {
} else { Auth(); } }
 
        /// <summary>
        /// 验证签名
        /// </summary>
        private void Auth()
        {
            string token = ConfigurationManager.AppSettings["wechatToken"].ToString(); //此处是自己填写的token
            if (!string.IsNullOrEmpty(token))
            {
                string echoString = HttpContext.Current.Request.QueryString["echostr"];  /*接收微信服务器发送GET请求携带的参数内容*/
                string signature = HttpContext.Current.Request.QueryString["signature"];
                string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
                string nonce = HttpContext.Current.Request.QueryString["nonce"];
if (new BasicApi().CheckSignature(token, signature, timestamp, nonce))
                {
                    if (!string.IsNullOrEmpty(echoString))
                    {
                        HttpContext.Current.Response.Write(echoString); //返回echoString
                        HttpContext.Current.Response.End();
                    }
                }
            }
        }
BasicApi.cs
public bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);  //将token、timestamp、nonce三个参数进行排序
            string tmpStr = string.Join("", ArrTmp); //使用String的join方法将数组元素拼接成字符串

            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr,"SHA1"); //SHA1加密
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)  //加密后的字符串与signature对比
            {
                return true;
            }
            else
            {
                return false;
            }
        }


 

 


 


 

posted @ 2015-06-23 12:38  豆腐爱鱼儿  阅读(1497)  评论(0编辑  收藏  举报