首页 > 代码库 > 微信公众平台-接收消息与发送被动消息

微信公众平台-接收消息与发送被动消息

接收消息代码如下(包含回复消息调用):

    /// <summary>
    /// 接收用户消息
    /// iftrue
    /// 2014-07-08
    /// </summary>
    public class Receive
    {
        public delegate Models.Send_Msg delegate_SendMsg(string msgType);
        public delegate void delegate_RececiveHandler(Models.Receive_Msg model,ref string msg);

        /// <summary>
        /// 获取消息对象并且回复消息(需要根据MsgType强制转换成需要的实体类)
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="getSendMsg">获取回复消息的方法</param>   
        /// <param name="receiveHandler">处理接收消息的方法(如:持久化数据库)</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public Models.Receive_Msg GetReceiveMsgAndReply(HttpContext context, delegate_SendMsg getSendMsg,delegate_RececiveHandler receiveHandler, ref string msg)
        {
            if (context == null)
                return null;
            try
            {
                string _xml = new HttpHelper().PostInput(context.Request);
                if (string.IsNullOrEmpty(_xml))
                    return null;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(_xml);
                XmlElement element = doc.DocumentElement;
                Models.Receive_Msg model = GetReceiveModel(element);
                //发送被动响应消息
                Models.Send_Msg sendModel = getSendMsg(model.MsgType);
                if (sendModel != null)
                {
                    sendModel.ToUserName = model.FromUserName;
                    sendModel.FromUserName = model.ToUserName;
                    Send send = new Send();
                    string strSend = send.Send_Msg<Models.Send_Msg>(sendModel, ref msg);
                    if (!string.IsNullOrEmpty(strSend))
                    {
                        context.Response.Output.Write(strSend);
                    }
                }
                //调用消息处理方法
                try
                {
                    receiveHandler(model, ref msg);
                }
                catch (Exception ex)
                {
                    msg = "receiveHandler异常:" + ex.Message;
                }
                return model;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return null;
            }
        }

        /// <summary>
        /// 获取消息对象直接回复空串(需要根据MsgType强制转换成需要的实体类)
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="getSendMsg">获取回复消息的方法</param>   
        /// <param name="receiveHandler">处理接收消息的方法(如:持久化数据库)</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public Models.Receive_Msg GetReceiveMsg(HttpContext context, delegate_RececiveHandler receiveHandler, ref string msg)
        {
            if (context == null)
                return null;
            try
            {
                //直接回复空串,避免腾讯重复发送
                context.Response.Output.Write("");
                string _xml = new HttpHelper().PostInput(context.Request);
                if (string.IsNullOrEmpty(_xml))
                    return null;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(_xml);
                XmlElement element = doc.DocumentElement;
                Models.Receive_Msg model = GetReceiveModel(element);

                //调用消息处理方法
                try
                {
                    receiveHandler(model, ref msg);
                }
                catch (Exception ex)
                {
                    msg = "receiveHandler异常:" + ex.Message;
                }
                return model;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return null;
            }
        }

        /// <summary>
        /// 解析XML,转换为实体
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        private Models.Receive_Msg GetReceiveModel(XmlElement element)
        {
            Models.Receive_Msg model = null;
            string msgType = element.SelectSingleNode("MsgType").InnerText;
            switch (msgType)
            {
                case MsgType.text: model = new Models.Receive_Text(); break;
                case MsgType.image: model = new Models.Receive_Image(); break;
                case MsgType.voice: model = new Models.Receive_Voice(); break;
                case MsgType.video: model = new Models.Receive_Video(); break;
                case MsgType.location: model = new Models.Receive_Location(); break;
                case MsgType.link: model = new Models.Receive_Link(); break;
                case MsgType.events: model = GetEventModel(element.SelectSingleNode("Event").InnerText, element.SelectSingleNode("EventKey") == null ? "" : element.SelectSingleNode("EventKey").InnerText); break;
            }
            try
            {
                foreach (System.Reflection.PropertyInfo p in model.GetType().GetProperties())
                {
                    if (p.Name != "Xml")
                    {
                        p.SetValue(model, element.SelectSingleNode(p.Name).InnerText, null);
                    }
                    else
                    {
                        p.SetValue(model, element.OuterXml, null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return model;
        }

        /// <summary>
        /// 获取事件对象
        /// </summary>
        /// <param name="evt">事件类型</param>
        /// <param name="eventKey">事件KEY值</param>
        /// <returns></returns>
        private Models.Receive_Msg GetEventModel(string evt, string eventKey)
        {
            Models.Receive_Msg model = null;
            switch (evt)
            {
                case Event.subscribe:
                    if (string.IsNullOrEmpty(eventKey))
                    {
                        model = new Models.Receive_Event();
                    }
                    else
                    {
                        model = new Models.Receive_Event_Scan();
                    }
                    break;
                case Event.unsubscribe:
                    model = new Models.Receive_Event();
                    break;
                case Event.scan:
                    model = new Models.Receive_Event_Scan();
                    break;
                case Event.location:
                    model = new Models.Receive_Event_Location();
                    break;
                case Event.click:
                    model = new Models.Receive_Event_Click();
                    break;
                case Event.view:
                    model = new Models.Receive_Event_View();
                    break;
            }
            return model;
        }
    }

发送消息代码:

 
    /// <summary>
    /// 发送微信
    /// 2014-07-15
    /// iftrue
    /// </summary>
    public class Send
    {
        public string Send_Msg<T>(T t, ref string msg)
        {
            if (t == null)
                return "";
            StringBuilder strB = new StringBuilder();
            strB.Append("<xml>");
            foreach (System.Reflection.PropertyInfo p in t.GetType().GetProperties())
            {
                strB.Append(string.Format("<{0}>{1}</{0}>", p.Name, p.GetValue(t, null).ToString()));
            }
            strB.Append("</xml>");
            return strB.ToString();
        }
    }

初始化参数代码:

/// <summary>
    /// 初始化参数
    /// 2014-07-03
    /// iftrue
    /// </summary>
    public class Init
    {
        /// <summary>
        /// 微信公众平台-开发者中心-服务器配置 中的Token
        /// </summary>
        public static string Token;

        /// <summary>
        /// 静态构造
        /// </summary>
        static Init()
        {
            string _token = ConfigurationManager.AppSettings["weixin_token"];
            if (!string.IsNullOrEmpty(_token))
                Token = _token;
        }
    }

    /// <summary>
    /// 消息类型
    /// </summary>
    public class MsgType
    {
       public const string text="text";
       public const string image = "image";
       public const string voice = "voice";
       public const string video = "video";
       public const string location = "location";
       public const string link = "link";
       public const string events = "event";
    }

    /// <summary>
    /// 事件类型
    /// </summary>
    public class Event
    {
        public const string subscribe = "subscribe";
        public const string unsubscribe = "unsubscribe";
        public const string scan = "SCAN";
        public const string location = "LOCATION";
        public const string click = "CLICK";
        public const string view = "VIEW";

    }

代码中还使用到实体类,为方便修改,使用了T4模板。

原码下载:微信公众平台接收(回复)消息C#版