本篇主要介绍如何使用senparc来处理微信公众平台的接收消息与发送消息。
首先微信端会将用户的发送的信息以post请求发送到填写的url上,服务端代码如下:
1 [HttpPost]2 public ActionResult Get(PostModel postModel)3 {4 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel);5 6 messageHandler.Execute();//执行微信处理过程7 8 return Content(messageHandler.ResponseDocument.ToString());9 }
新建一个CustomMessageHandler类和一个CustomMessageContext类,CustomMessageHandler类继承MessageHandler<CustomMessageContext>,CustomMessageContext类继承MessageContext<IRequestMessageBase,IResponseMessageBase>,CustomMessageContext类的方法此处不贴出,主要是实现CustomMessageHandler类的方法,代码如下:
1 public CustomMessageHandler(Stream inputStream, PostModel postModel) 2 : base(inputStream, postModel) 3 { 4 5 } 6 7 public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage) 8 { 9 var responseMessage = base.CreateResponseMessage<ResponseMessageText>(); //ResponseMessageText指返回文本信息10 responseMessage.Content = "这条消息来自DefaultResponseMessage。"+requestMessage.MsgId;11 return responseMessage;12 }
返回信息的格式多种多样,如:ResponseMessageText,ResponseMessageNews,ResponseMessageImage等。接收信息的格式也分很多种,不同格式有不同的处理方法:OnTextRequest,OnImageRequest,OnEvent_ViewRequest等。如果没有重写相应方法,就默认执行DefaultResponseMessage方法。本篇重写2个方法作为简单的例子。
用户发送文本信息情况下的返回信息处理
1 public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)2 {3 var responseMessage = base.CreateResponseMessage<ResponseMessageText>();4 responseMessage.Content = "您的OpenID是:" + requestMessage.FromUserName 5 + "。/r/n您发送了文字信息:" + requestMessage.Content; 6 return responseMessage;7 }
菜单点击事件情况下的返回信息处理
1 public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage) 2 { 3 IResponseMessageBase reponseMessage = null; 4 //菜单点击,需要跟创建菜单时的Key匹配 5 switch (requestMessage.EventKey) 6 { 7 case "OneClick": 8 { 9 var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();10 reponseMessage = strongResponseMessage;11 strongResponseMessage.Articles.Add(new Article()12 {13 Title = "您点击了菜单图文按钮",14 Description = "您点击图文链接按钮,这是一条图文信息。",15 PicUrl = "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3233073314,694013259&fm=58&s=39C718720E8EBE011B398BAC0300F024",16 Url = "http://www.baidu.com"17 });18 }19 break;20 case "SubClickRoot_Text":21 {22 var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();23 reponseMessage = strongResponseMessage;24 strongResponseMessage.Content = "您点击了子菜单按钮。";25 }26 break;27 default:28 {29 var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();30 strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;31 reponseMessage = strongResponseMessage;32 }33 break;34 }35 36 return reponseMessage;37 }
新闻热点
疑难解答