本篇主要介紹如何使用senparc來處理微信公眾平臺的接收消息與發送消息。首先微信端會將用戶的發送的信息以post請求發送到填寫的url上,服務端代碼如下:1 [HttpPost]2 public ActionResult Get(PostModel postMode...
本篇主要介紹如何使用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 }