c# 微信开发 《内容回复或事件触发》
///验签绑定公众号的时候,有回复信息的入口
public void ProcessRequest(HttpContext context) { string postString = string.Empty; if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { using (Stream stream = HttpContext.Current.Request.InputStream) { Byte[] postBytes = new Byte[stream.Length]; stream.Read(postBytes, 0, (Int32)stream.Length); postString = Encoding.UTF8.GetString(postBytes); } if (!string.IsNullOrEmpty(postString)) { WeiXinService.ResponseMsg(postString, context); } } else { Auth(); //微信接入的测试 } }
/// <summary> /// 处理回复消息 /// </summary> /// <param name="postString"></param> /// <returns></returns> public void ResponseMsg(string postString, HttpContext context) { //通过信息类型返回相应的处理类 IHandler handler = HandlerFactory.CreateHandler(postString); if (handler != null) { handler.HandleRequest(context); } } /// <summary> /// 创建处理器 /// </summary> /// <param name="requestXml">请求的xml</param> /// <returns>IHandler对象</returns> public static IHandler CreateHandler(string requestXml) { IHandler handler = null; if (!string.IsNullOrEmpty(requestXml)) { //解析数据 XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(requestXml); XmlNode node = doc.SelectSingleNode("/xml/MsgType"); if (node != null) { XmlCDataSection section = node.FirstChild as XmlCDataSection; if (section != null) { string msgType = section.Value; //工厂类 switch (msgType) { case "text": handler = new TextHandler(requestXml); break; case "event": handler = new EventHandler(requestXml); break; } } } } return handler; }
/// <summary> /// 事件处理,处理请求 /// </summary> /// <returns></returns> public void HandleRequest(HttpContext context) { string response = string.Empty; EventMessage em = EventMessage.LoadFromXml(RequestXml); switch (em.Event.ToLower()) { case ("unsubscribe")://取消关注 UnSubscribeEventHandler(em, context); break; case ("subscribe"): //关注 SubscribeEventHandler(em, context); break; case "click": //点击事件 ClickEventHandler(em, context); break; } }
点击事件 /// <summary> /// 处理点击事件 /// </summary> /// <param name="em"></param> /// <returns></returns> private void ClickEventHandler(EventMessage em, HttpContext context) { string result = string.Empty; if (em != null && em.EventKey != null) { switch (em.EventKey.ToUpper()) { case "BTN_HELP": btnHelpClick(em, context); break; case "BTN_QRCODE": btnQrcodeClick(em, context); break; } } }
/// <summary> /// /// </summary> /// <param name="em"></param> /// <returns></returns> private void btnHelpClick(EventMessage em, HttpContext context) { //回复欢迎消息 TextMessage tm = new TextMessage(); tm.ToUserName = em.FromUserName; tm.FromUserName = em.ToUserName; tm.CreateTime = WeiXinCommom.GetNowTime(); tm.Content = “回复内容”; string response = TextTemplate.NormalText(tm.ToUserName, tm.FromUserName, tm.Content); context.Response.Clear(); context.Response.Charset = "UTF-8"; context.Response.Write(response);//回复消息 context.Response.End(); }