码迷,mamicode.com
首页 > 微信 > 详细

微信公众平台接口,asp.net实现

时间:2014-12-24 17:44:58      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:

原文: 微信公众平台接口,asp.net实现

我为自己的笑话网开发了一个微信公众平台的接口,在这里分享给大家,希望能对朋友们有帮助,如果有什么地方写的不好,好请大家指点!

首先是要进行认证,认证的时候,只需要在Page_Load事件里面单独去执行 认证的方法就可以了,具体代码见下面的RenZheng()

认证通过之后就可以对网友的消息进行处理,可以根据微信平台推送过来的数据进行分析!我相信大家在看到这篇文章的时候,在此之前肯定对平台都有所了解了,所以,废话不多说,直接上代码! 如果有什么疑问的欢迎加群:242384606 进行讨论!


    protected void Page_Load(object sender, EventArgs e)
        {
            wxmessage wx = GetWxMessage();
            string res = "";
            //新用户添加
            if (!string.IsNullOrEmpty(wx.EventName) && wx.EventName.Trim() == "subscribe")
            {
                string content = "";
                content = "/:rose欢迎关注52冷笑话/:rose\n看笑话请直接回复“x”\n无聊时候还可以找我聊聊天哦!";
                res = sendTextMessage(wx, content);
            }
            else
            {
                bool sendJoke = false;
                //看笑话
                List<string> xhList = new List<string>() { "x", "笑话", "笑話" };
                foreach (string item in xhList)
                {
                    if (wx.Content.Trim().ToLower().Contains(item))
                    {
                        sendJoke = true;
                        break;
                    }
                }
                if (sendJoke)
                {
                    JokeDemo joke = GetJoke(wx.FromUserName);
                    if (string.IsNullOrEmpty(joke.Img))
                    {
                        string title = string.Format("编号{0}:{1}\n-----------------\n", joke.ID, joke.Title);
                        string content = joke.Content;
                        if (content.Length > 300)
                        {
                            content = GetSubString(content, 300) + "\n-----------------\n点击连接阅读全文:URL"

                        }
                        res = sendTextMessage(wx, title + content);
                    }
                    else
                    {
                        res = sendPictureMessage(wx, joke);
                    }
                }
                //智能学聊天
                if (res == "" && Regex.IsMatch(wx.Content, "问(:|:)(.+?)答(:|:)(.+?)", RegexOptions.IgnoreCase))
                {
                    string content = "";
                    string key = Regex.Match(wx.Content, "问(:|:)(.+?)答(:|:)(.+?)", RegexOptions.IgnoreCase).Groups[2].Value.Trim();
                    int startIndex = wx.Content.IndexOf("答:") + 2;
                    if (startIndex < 3)
                    {
                        startIndex = wx.Content.IndexOf("答:") + 2;
                    }
                    string rep = wx.Content.Substring(startIndex, wx.Content.Length - startIndex).Trim();

            // Regex.Match(wx.Content, "问(:|:)(.+?)答(:|:)(.+?)", RegexOptions.IgnoreCase).Groups[4].Value;
                    if ((new ChatBLL()).isExists(key))
                    {
                        content = "/::)O啦!学会啦\n不信你问问!";
                    }
                    else
                    {
                        if ((new ChatBLL()).Add(key, rep) > 0)
                        {
                            content = "好啦,这个问题我学会啦!\n你现在提问我吧!/::P";
                        }
                        else
                        {
                            content = "糟糕了,系统出了点儿小意外!\n麻烦你再试一次!";
                        }
                    }
                    res = sendTextMessage(wx, content);
                }
                //未知情况
                if (res == "")
                {
                    string content = (new ChatBLL()).GetReplyByKey(wx.Content.Trim());
                    if (content == "")
                    {
                        content = "/:,@-D啊哦,你在说什么?\n你可以按照下面的格式告诉我:\n问:你说的话 答:你想让我说什么\n看笑话请直接回复“x”!";
                    }
                    res = sendTextMessage(wx, content);
                }
            }
            Response.Write(res);
        }


        /// <summary>
        /// 发送文字消息
        /// </summary>
        /// <param name="wx">获取的收发者信息</param>
        /// <param name="content">笑话内容</param>
        /// <returns></returns>
        private string sendTextMessage(wxmessage wx, string content)
        {
            string res = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{3}]]></Content> <FuncFlag>0</FuncFlag></xml> ",
                wx.FromUserName, wx.ToUserName, DateTime.Now, 内容);
            return res;
        }

        /// <summary>
        /// 发送图文消息
        /// </summary>
        /// <param name="wx">获取的收发者信息</param>
        /// <param name="joke">笑话信息</param>
        /// <returns></returns>
        private string sendPictureMessage(wxmessage wx, JokeDemo joke)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<xml><ToUserName><![CDATA[{0}]]></ToUserName>", wx.FromUserName);
            sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wx.ToUserName);
            sb.AppendFormat("<CreateTime>{0}</CreateTime>", DateTime.Now);
            sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content>");
            sb.AppendFormat("<ArticleCount>1</ArticleCount>");
            sb.AppendFormat("<Articles><item>");
            sb.AppendFormat("<Title><![CDATA[{0}]]></Title>", 标题);
            sb.AppendFormat("<Description><![CDATA[{0}]]></Description>", 说明文字);
            sb.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl>", 图片地址);
            sb.AppendFormat("<Url><![CDATA[{0}]]></Url>", 连接地址);
            sb.AppendFormat("</item></Articles><FuncFlag>0</FuncFlag></xml>");
            return sb.ToString();
        }

        /// <summary>
        /// 获取请求过来的微信信息
        /// </summary>
        /// <returns></returns>
        private wxmessage GetWxMessage()
        {
            wxmessage wx = new wxmessage();
            StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);
            XmlDocument xml = new XmlDocument();
            xml.Load(str);
            wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
            wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
            wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
            if (wx.MsgType.Trim() == "text")
            {
                wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;
            }
            if (wx.MsgType.Trim() == "event")
            {
                wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
            }
            return wx;
        }

        /// <summary>
        /// 微信认证
        /// </summary>
        private void RenZheng()
        {
            #region 微信认证
            //string res = "";
            //string token = "52lxh";
            //string signature = Request["signature"];
            //string timestamp = Request["timestamp"];
            //string nonce = Request["nonce"];
            //string echostr = Request["echostr"];
            //if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(echostr))
            //{
            //    using (StreamWriter sw = new StreamWriter(Server.MapPath("wx.txt")))
            //    {
            //        sw.Write("参数错误" + Request.Url);
            //    }
            //}
            //else
            //{
            //    ArrayList arr = new ArrayList() { token, timestamp, nonce };
            //    arr.Sort();
            //    string signature1 = GetSHA1(arr[0].ToString() + arr[1].ToString() + arr[2].ToString());
            //    if (signature == signature1.ToLower())
            //    {
            //        res = echostr;
            //    }
            //    else
            //    {
            //        res = "error";
            //    }

            //    Response.Write(res);
            //}
            #endregion
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        private string GetSHA1(string password)
        {
            string shh1string = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
            return shh1string;
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="content"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private string GetSubString(string content, int length)
        {
            if (content.Length >= length)
            {
                return content.Substring(0, length);
            }
            else
            {
                return content;
            }
        }

        //自定义一个微信消息实体类
        class wxmessage
        {
            public string FromUserName { get; set; }
            public string ToUserName { get; set; }
            public string MsgType { get; set; }
            public string EventName { get; set; }
            public string Content { get; set; }
        }


   

52冷笑话官网:http://www.52lxh.com 随时欢迎您!

欢迎关注52冷笑话微信看笑话!

技术分享

微信公众平台接口,asp.net实现

标签:

原文地址:http://www.cnblogs.com/lonelyxmas/p/4182883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!