當普通微信用戶向公眾賬號發消息時,微信服務器將POST消息的XML數據包到開發者填寫的URL上。
請注意:
各消息類型的推送XML數據包結構如下:
文本消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[this is a test]]></Content> <MsgId>1234567890123456</MsgId> </xml>
圖片消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[image]]></MsgType> <PicUrl><![CDATA[this is a url]]></PicUrl> <MediaId><![CDATA[media_id]]></MediaId> <MsgId>1234567890123456</MsgId> </xml>
語音消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1357290913</CreateTime> <MsgType><![CDATA[voice]]></MsgType> <MediaId><![CDATA[media_id]]></MediaId> <Format><![CDATA[Format]]></Format> <MsgId>1234567890123456</MsgId> </xml>
請注意,開通語音識別後,用戶每次發送語音給公眾號時,微信會在推送的語音消息XML數據包中,增加一個Recongnition字段 (注:由於客戶端緩存,開發者開啟或者關閉語音識別功能,對新關注者立刻生效,對已關注用戶需要24小時生效。開發者可以重新關注此帳號進行測試)。開啟語音識別後的語音XML數據包如下:
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1357290913</CreateTime> <MsgType><![CDATA[voice]]></MsgType> <MediaId><![CDATA[media_id]]></MediaId> <Format><![CDATA[Format]]></Format> <Recognition><![CDATA[騰訊微信團隊]]></Recognition> <MsgId>1234567890123456</MsgId> </xml>
多出的字段中,Format為語音格式,一般為amr,Recognition為語音識別結果,使用UTF8編碼。
視頻消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1357290913</CreateTime> <MsgType><![CDATA[video]]></MsgType> <MediaId><![CDATA[media_id]]></MediaId> <ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId> <MsgId>1234567890123456</MsgId> </xml>
小視頻消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1357290913</CreateTime> <MsgType><![CDATA[shortvideo]]></MsgType> <MediaId><![CDATA[media_id]]></MediaId> <ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId> <MsgId>1234567890123456</MsgId> </xml>
地理位置消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[location]]></MsgType> <Location_X>23.134521</Location_X> <Location_Y>113.358803</Location_Y> <Scale>20</Scale> <Label><![CDATA[位置信息]]></Label> <MsgId>1234567890123456</MsgId> </xml>
鏈接消息
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[link]]></MsgType> <Title><![CDATA[公眾平台官網鏈接]]></Title> <Description><![CDATA[公眾平台官網鏈接]]></Description> <Url><![CDATA[url]]></Url> <MsgId>1234567890123456</MsgId> </xml>
接上篇,看ResponseXML(postString);方法如下
/// <summary> /// 獲取用戶發送的消息 /// </summary> /// <param name="postString"></param> private void ResponseXML(string postString) { //使用XMLDocument加載信息結構 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(postString); XmlElement rootElement = xmlDoc.DocumentElement;//獲取文檔的根 XmlNode MsgType = rootElement.SelectSingleNode("MsgType"); //獲取消息的文本類型 RequestXML requestXML = new RequestXML();//聲明實例,獲取各個屬性並賦值 requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;//公眾號 requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;//用戶 requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;//創建時間 requestXML.MsgType = MsgType.InnerText;//消息類型 ///對消息的不同類型進行賦值 if (requestXML.MsgType == "text") { //賦值文本信息內容 requestXML.Content = rootElement.SelectSingleNode("Content").InnerText; } if (requestXML.MsgType.Trim() == "location") { ///賦值地理位置緯度,經度,地圖縮放比例,地理位置說明 requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText; requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText; requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText; requestXML.Label = rootElement.SelectSingleNode("Label").InnerText; } if (requestXML.MsgType.Trim().ToLower() == "event") { ///賦值事件名稱和事件key值 requestXML.EventName = rootElement.SelectSingleNode("Event").InnerText; requestXML.EventKey = rootElement.SelectSingleNode("EventKey").InnerText; } if (requestXML.MsgType.Trim().ToLower() == "voice") { ///賦值語音識別結果,賦值之前一定要記得在開發者模式下,把語音識別功能開啟,否則獲取不到 requestXML.Recognition = rootElement.SelectSingleNode("Recognition").InnerText; } ResponseMsg(requestXML); }
語音識別功能開啟如下:
requestXML是我單獨創建的一個類,該類聲明了消息中常用的屬性字段,如下:
/// <summary> /// 接收消息的實體類 /// </summary> public class RequestXML { private String toUserName = String.Empty; /// <summary> /// 本公眾號 /// </summary> public String ToUserName{get;set;} /// <summary> /// 用戶微信號 /// </summary> public String FromUserName{get;set;} /// <summary> /// 創建時間 /// </summary> public String CreateTime{get;set;} /// <summary> /// 信息類型 /// </summary> public String MsgType{get;set;} /// <summary> /// 信息內容 /// </summary> public String Content{get;set;} /*以下為事件類型的消息特有的屬性*/ /// <summary> /// 事件名稱 /// </summary> public String EventName{get;set;} /// <summary> /// 事件值 /// </summary> public string EventKey { get; set; } /*以下為圖文類型的消息特有的屬性*/ /// <summary> /// 圖文消息的個數 /// </summary> public int ArticleCount { get; set; } /// <summary> /// 圖文消息的標題 /// </summary> public string Title { get; set; } /// <summary> /// 圖文消息的簡介 /// </summary> public string Description { get; set; } /// <summary> /// 圖文消息圖片的鏈接地址 /// </summary> public string PicUrl { get; set; } /// <summary> /// 圖文消息詳情鏈接地址 /// </summary> public string Url { get; set; } /// <summary> /// 圖文消息集合 /// </summary> public List<RequestXML> Articles { get; set;} /*以下為地理位置類型的消息特有的屬性*/ /// <summary> /// 地理位置緯度 /// </summary> public String Location_X { get; set; } /// <summary> /// 地理位置經度 /// </summary> public String Location_Y { get; set; } /// <summary> /// 地圖縮放比例 /// </summary> public String Scale { get; set; } /// <summary> /// 地圖位置說明 /// </summary> public String Label { get; set; } /// <summary> /// 語音消息特有字段 /// </summary> public String Recognition { get; set; } }
繼續關注 ResponseMsg(requestXML);方法如下
private void ResponseMsg(RequestXML requestXML) { string MsgType = requestXML.MsgType; try { //根據消息類型判斷發送何種類型消息 switch (MsgType) { case "text": SendTextCase(requestXML);//發送文本消息 break; case "event"://發送事件消息 if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("subscribe")) { SendWelComeMsg(requestXML);//關注時返回的圖文消息 } else if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("CLICK")) { SendEventMsg(requestXML);//發送事件消息 } break; case "voice": SendVoiceMsg(requestXML);//發送語音消息 break; case "location"://發送位置消息 SendMapMsg(requestXML); break; default: break; } } catch (Exception ex) { HttpContext.Current.Response.Write(ex.ToString()); } }
先來關注發送文本消息,SendTextCase(requestXML);//發送文本消息
/// <summary> /// 發送文本 /// </summary> /// <param name="requestXML"></param> private void SendTextCase(RequestXML requestXML) { string responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content); HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); HttpContext.Current.Response.End(); }
FormatTextXML方法制定格式
/// <summary> /// 返回格式化的Xml格式內容 /// </summary> /// <param name="p1">公眾號</param> /// <param name="p2">用戶號</param> /// <param name="p3">回復內容</param> /// <returns></returns> private string FormatTextXML(string p1, string p2, string p3) { return "<xml><ToUserName><![CDATA[" + p1 + "]]></ToUserName><FromUserName><![CDATA[" + p2 + "]]></FromUserName><CreateTime>" + DateTime.Now.Subtract(new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds.ToString() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + p3 + "]]></Content><FuncFlag>1</FuncFlag></xml>"; }
這樣就能實現消息的應答,如果用戶點擊的按鈕,如下代碼:
case "event"://發送事件消息 if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("subscribe")) { SendWelComeMsg(requestXML);//關注時返回的圖文消息 } else if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("CLICK")) { SendEventMsg(requestXML);//發送事件消息 } break; /// <summary> /// 發送響應事件消息 /// </summary> /// <param name="requestXML"></param> private void SendEventMsg(RequestXML requestXML) { string keyStr = requestXML.EventKey.ToString(); switch (keyStr) { case "mypay": SendPayDetails(requestXML);//發送薪資賬單 break; case "tianqiyubao": SendWeaterMessage(requestXML);//發送天氣預報 break; case "kaixinyixiao": SendKaiXinMessage(requestXML);//發送開心一笑結果集 break; case "updateMessage": SendUpdateMessage(requestXML);//發送修改信息鏈接 break; case "yuangonghuodong": SendYuanGongHuoDong(requestXML);//發送學生活動 break; case "yuangongtongzhi": SendYuanGongTongZhi(requestXML);//發送員工通知 break; case "youwenbida": SendWenti(requestXML);//發送員工提交問題鏈接 break; case "mywen": SendWentiList(requestXML);//發送問題列表鏈接 break; case "PhoneSerices": SendKeFuMessage(requestXML);//接入客服 break; default: String responseContent = String.Empty; responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName,"此功能暫未開放!敬請期待!"); HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); HttpContext.Current.Response.End(); break; } }
SendWelComeMsg(requestXML);//關注時返回的圖文消息
/// <summary> /// 發送關注時的圖文消息 /// </summary> /// <param name="requestXML"></param> private void SendWelComeMsg(RequestXML requestXML) { String responseContent = String.Empty; string newdate = DateTime.Now.Subtract(new DateTime(1970, 1, 1, 8, 0, 0)).TotalSeconds.ToString(); string PUrlfileName = "http://www.deqiaohr.com.cn/weixin/welcome.jpg"; responseContent = string.Format(Message_News_Main, requestXML.FromUserName, requestXML.ToUserName, newdate, "1", string.Format(Message_News_Item, "歡迎關注德橋員工服務中心", "蘇州德橋人力資源創立於2002年...", PUrlfileName, "http://www.deqiaohr.com.cn/weixin/WxGsjianjie.aspx")); HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); HttpContext.Current.Response.End(); }
Message_News_Main 和Message_News_Item是圖文消息格式化
/// <summary> /// 返回圖文消息主體 /// </summary> public static string Message_News_Main { get { return @"<xml> <ToUserName><![CDATA[{0}]]></ToUserName> <FromUserName><![CDATA[{1}]]></FromUserName> <CreateTime>{2}</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>{3}</ArticleCount> <Articles> {4} </Articles> </xml> "; } } /// <summary> /// 返回圖文消息項 /// </summary> public static string Message_News_Item { get { return @"<item> <Title><![CDATA[{0}]]></Title> <Description><![CDATA[{1}]]></Description> <PicUrl><![CDATA[{2}]]></PicUrl> <Url><![CDATA[{3}]]></Url> </item>"; } } /// <summary> /// 發送響應語音識別結果 /// </summary> /// <param name="requestXML"></param> private void SendVoiceMsg(RequestXML requestXML) { string responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName, "您剛才說的語音消息識別結果為:" + requestXML.Recognition.ToString()); HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); HttpContext.Current.Response.End(); }
精彩專題分享:ASP.NET微信開發教程匯總,歡迎大家學習。
以上就是關於asp.net微信開發的第二篇,針對消息應答進行學習,之後會有更新更多關於asp.net微信開發的文章,希望大家持續關注。