asp.net C# 实现微信服务器配置

微信服务器配置接收页面示例代码

         /// <summary>      
        /// 微信的Token      
        /// </summary>      
        const string Token = "Token令牌";

        protected void Page_Load(object sender, EventArgs e)
        {
            string postStr = "";
            //配置信息,只有在微信做提交配置的时候才会执行。
            Valid();
            if (Request.HttpMethod.ToLower() == "post")
            {
                postStr = PostInput();
                if (false == string.IsNullOrEmpty(postStr))
                {
                    ResponseMsg(postStr);
                }
            }     
        }
        /// <summary>      
        /// 返回信息结果(微信信息返回)      
        /// </summary>      
        /// <param name="weixinXML"></param>  

        private void ResponseMsg(string weixinXML)
        {
            //回复消息的部分:你的代码写在这里          
            //根据关键词 自定义回复  
            string ToUserName = "";
            string FromUserName = "";
            string CreateTime = "";
            try
            {
                WriteLog(weixinXML);
                var xDoc = XDocument.Parse(weixinXML);
                var q = (from c in xDoc.Elements() select c).ToList();
                var msgType = q.Elements("MsgType").First().Value; // 获取信息内容的类型

                //按钮事件
                if (0 == string.Compare("event", msgType, true))
                {
                    ToUserName = q.Elements("ToUserName").First().Value;//开发者微信号
                    FromUserName = q.Elements("FromUserName").First().Value;//发送方帐号(一个OpenID)
                    #region 事件
                    string strEvent = "";
                    string strEventKey = "";
                    strEvent = q.Elements("Event").First().Value;
                    CreateTime = q.Elements("CreateTime").First().Value;
                    //单击事件
                    if (strEvent.ToLower() == "click")
                    {
                        //图文推送
                        strEventKey = q.Elements("EventKey").First().Value;
                    }
                    //关注公众号
                    else if (strEvent.ToLower() == "subscribe")
                    {
                        strEventKey = q.Elements("EventKey").First().Value;
                      
                        //未关注扫描带参数的二维码
                        if (strEventKey.Contains("qrscene_"))
                        {
                            string vaule = strEventKey.Replace("qrscene_", "");
                        }

                    }
                    //已关注扫描带参数的二维码
                    else if (strEvent.ToLower() == "scan")
                    {
                        strEventKey = q.Elements("EventKey").First().Value;
                    }
                    #endregion
                }
                //用户文本信息
                else if (0 == string.Compare("text", msgType, true))
                {
                    
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString());
            }
            Response.End();
        }

        /// <summary>
        /// 图片消息
        /// </summary>
        /// <param name="ToUsername"></param>
        /// <param name="FromUserName"></param>
        /// <returns></returns>
        public static bool SendWxPic(string ToUsername, string FromUserName, string MediaId)
        {
            var textTpl = "<xml>"
                + "<ToUserName><![CDATA[{0}]]></ToUserName>"
                + "<FromUserName><![CDATA[{1}]]></FromUserName>"
                + "<CreateTime>{2}</CreateTime>"
                + "<MsgType><![CDATA[image]]></MsgType>"
                +"<Image>"
                +"<MediaId><![CDATA[{3}]]></MediaId>"
                +"</Image>"
                + "</xml>";
            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.Write(string.Format(textTpl, FromUserName, ToUsername, ConvertDateTimeInt(DateTime.Now), MediaId));
            return true;
        }
        /// <summary>
        /// 消息转发到客服
        /// </summary>
        /// <param name="ToUsername"></param>
        /// <param name="FromUserName"></param>
        /// <returns></returns>
        public static bool SendWx(string ToUsername, string FromUserName)
        {
            var textTpl = "<xml>"
                + "<ToUserName><![CDATA[{0}]]></ToUserName>"
                + "<FromUserName><![CDATA[{1}]]></FromUserName>"
                + "<CreateTime>{2}</CreateTime>"
                + "<MsgType><![CDATA[transfer_customer_service]]></MsgType>"
                + "</xml>";
            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.Write(string.Format(textTpl, FromUserName, ToUsername, ConvertDateTimeInt(DateTime.Now)));
            return true;
        }

        /// <summary>
        /// 回复文本消息
        /// </summary>
        /// <param name="ToUsername"></param>
        /// <param name="FromUserName"></param>
        /// <param name="_tmpContent"></param>
        /// <returns></returns>
        public static bool SendWx(string ToUsername, string FromUserName, string _tmpContent)
        {
            var textTpl = "<xml>"
                + "<ToUserName><![CDATA[{0}]]></ToUserName>"
                + "<FromUserName><![CDATA[{1}]]></FromUserName>"
                + "<CreateTime>{2}</CreateTime>"
                + "<MsgType><![CDATA[{3}]]></MsgType>"
                + "<Content><![CDATA[{4}]]></Content>"
                + "</xml>";

            //_tmpContent = "你已经选择了明细,谢谢!";
            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.Write(string.Format(textTpl, FromUserName, ToUsername, ConvertDateTimeInt(DateTime.Now), "text", _tmpContent));
            return true;

        }

        /// <summary>
        /// 检验signature
        /// </summary>
        private void Valid()
        {
            //微信服务器配置提交时,echoStr才不为空。
            string echoStr = Request.QueryString["echoStr"];
            if (echoStr != null)
            {
                if (CheckSignature())
                {
                    if (!string.IsNullOrEmpty(echoStr))
                    {
                        Response.Write(echoStr); Response.End();
                    }
                }
            }
        }

        /// <summary>      
        /// 验证微信签名      
        /// </summary>      
        /// * 将token、timestamp、nonce三个参数进行字典序排序      
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密      
        /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。      
        /// <returns></returns>  
        private bool CheckSignature()
        {
            string signature = Request.QueryString["signature"].ToString();
            string timestamp = Request.QueryString["timestamp"].ToString();
            string nonce = Request.QueryString["nonce"].ToString();
            string[] ArrTmp = { Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序          
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = Cryptography.SHA1_Hash(tmpStr);
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>      
        /// 获取POST返回来的数据      
        /// </summary>      
        /// <returns></returns>
        private string PostInput()
        {
            try
            {
                System.IO.Stream s = Request.InputStream;
                int count = 0;
                byte[] buffer = new byte[s.Length];
                StringBuilder builder = new StringBuilder();
                while ((count = s.Read(buffer, 0, buffer.Length)) > 0)
                {
                    builder.Append(Request.ContentEncoding.GetString(buffer, 0, count));
                }
                s.Flush();
                s.Close();
                s.Dispose();
                return builder.ToString();
            }
            catch (Exception ex)
            { throw ex; }

        }

        /// <summary>      
        /// unix时间转换为datetime      
        /// </summary>      
        /// <param name="timeStamp"></param>      
        /// <returns></returns>
        private DateTime UnixTimeToTime(string timeStamp)
        {

            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>      
        /// datetime转换为unixtime      
        /// </summary>      
        /// <param name="time"></param>      
        /// <returns></returns>      
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>      
        /// 写日志(用于跟踪)      
        /// </summary>      
        private void WriteLog(string strMemo)
        {
            string filename = Server.MapPath("~/logs/log.txt");
            if (!Directory.Exists(Server.MapPath("//logs//")))
                Directory.CreateDirectory(Server.MapPath("//logs//"));
            StreamWriter sr = null;
            try
            {
                if (!File.Exists(filename))
                {
                    sr = File.CreateText(filename);
                }
                else
                {
                    sr = File.AppendText(filename);
                }
                sr.WriteLine(strMemo);
            }
            catch
            {
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }

 以上代码是公司要做微信一些功能做的代码总结,网上找的时候感觉代码虽然封装的很好。但是要用麻烦。觉得没必要封装的那么简洁。如果需要封装,自己在去封装。

 

posted @ 2016-09-09 10:27  caiyitao  阅读(2417)  评论(0编辑  收藏  举报