Tips for developing message responses in asp.net WeChat
Mar 10, 2017 pm 02:45 PMThis article mainly introduces the relevant content of message response in asp.net WeChat development. Friends who need it can refer to it
When ordinary WeChat users send messages to public accounts, the WeChat server will POST the message XML data package to the URL filled in by the developer.
Please note:
#1. Regarding retry message duplication, it is recommended to use msgid to deduplicate messages.
2. If the WeChat server does not receive a response within five seconds, it will disconnect and re-initiate the request, retrying three times in total. If the server cannot guarantee to process and reply within five seconds, you can directly reply with an empty string. The WeChat server will not do anything with this and will not initiate a retry. For details, please see "Send a Message - Passive Reply to a Message".
3. In order to ensure higher security, developers can set up message encryption in the developer center on the official website of the public platform. After encryption is turned on, messages sent by users will be encrypted, and messages passively replied to users by official accounts also need to be encrypted (but developers sending messages to users through API calls such as customer service interfaces will not be affected). For detailed instructions on message encryption and decryption, please see "Message Encryption and Decryption Instructions".
The push XML data packet structure of each message type is as follows:
Text message
<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>
## Picture message
<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>
Voice messages
<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>
activating voice recognition, every time the user sends a voice to the official account, WeChat will add a Recongnition field to the pushed voice message XML packet (Note: Due to client caching, developers enable or disable the speech recognition function, which will take effect immediately for new followers and take 24 hours for already followed users. Development Users can re-follow this account for testing). The voice XML data packet after enabling voice recognition is as follows:
<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[騰訊微信團(tuán)隊(duì)]]></Recognition> <MsgId>1234567890123456</MsgId> </xml>
In the extra fields, Format is the voice format, usually amr, and Recognition is Speech recognition results are encoded using UTF8.
Video message
<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>
Small video Message
<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>
## Geolocation message
<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>
Link message
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[link]]></MsgType> <Title><![CDATA[公眾平臺(tái)官網(wǎng)鏈接]]></Title> <Description><![CDATA[公眾平臺(tái)官網(wǎng)鏈接]]></Description> <Url><![CDATA[url]]></Url> <MsgId>1234567890123456</MsgId> </xml>
/// <summary> /// 獲取用戶發(fā)送的消息 /// </summary> /// <param name="postString"></param> private void ResponseXML(string postString) { //使用XMLDocument加載信息結(jié)構(gòu) XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(postString); XmlElement rootElement = xmlDoc.DocumentElement;//獲取文檔的根 XmlNode MsgType = rootElement.SelectSingleNode("MsgType"); //獲取消息的文本類型 RequestXML requestXML = new RequestXML();//聲明實(shí)例,獲取各個(gè)屬性并賦值 requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;//公眾號(hào) requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;//用戶 requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;//創(chuàng)建時(shí)間 requestXML.MsgType = MsgType.InnerText;//消息類型 ///對(duì)消息的不同類型進(jìn)行賦值 if (requestXML.MsgType == "text") { //賦值文本信息內(nèi)容 requestXML.Content = rootElement.SelectSingleNode("Content").InnerText; } if (requestXML.MsgType.Trim() == "location") { ///賦值地理位置緯度,經(jīng)度,地圖縮放比例,地理位置說(shuō)明 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") { ///賦值語(yǔ)音識(shí)別結(jié)果,賦值之前一定要記得在開發(fā)者模式下,把語(yǔ)音識(shí)別功能開啟,否則獲取不到 requestXML.Recognition = rootElement.SelectSingleNode("Recognition").InnerText; } ResponseMsg(requestXML); }
The voice recognition function is turned on as follows:
requestXML是我單獨(dú)創(chuàng)建的一個(gè)類,該類聲明了消息中常用的屬性字段,如下:
/// <summary> /// 接收消息的實(shí)體類 /// </summary> public class RequestXML { private String toUserName = String.Empty; /// <summary> /// 本公眾號(hào) /// </summary> public String ToUserName{get;set;} /// <summary> /// 用戶微信號(hào) /// </summary> public String FromUserName{get;set;} /// <summary> /// 創(chuàng)建時(shí)間 /// </summary> public String CreateTime{get;set;} /// <summary> /// 信息類型 /// </summary> public String MsgType{get;set;} /// <summary> /// 信息內(nèi)容 /// </summary> public String Content{get;set;} /*以下為事件類型的消息特有的屬性*/ /// <summary> /// 事件名稱 /// </summary> public String EventName{get;set;} /// <summary> /// 事件值 /// </summary> public string EventKey { get; set; } /*以下為圖文類型的消息特有的屬性*/ /// <summary> /// 圖文消息的個(gè)數(shù) /// </summary> public int ArticleCount { get; set; } /// <summary> /// 圖文消息的標(biāo)題 /// </summary> public string Title { get; set; } /// <summary> /// 圖文消息的簡(jiǎn)介 /// </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> /// 地理位置經(jīng)度 /// </summary> public String Location_Y { get; set; } /// <summary> /// 地圖縮放比例 /// </summary> public String Scale { get; set; } /// <summary> /// 地圖位置說(shuō)明 /// </summary> public String Label { get; set; } /// <summary> /// 語(yǔ)音消息特有字段 /// </summary> public String Recognition { get; set; } }
繼續(xù)關(guān)注 ResponseMsg(requestXML);方法如下
private void ResponseMsg(RequestXML requestXML) { string MsgType = requestXML.MsgType; try { //根據(jù)消息類型判斷發(fā)送何種類型消息 switch (MsgType) { case "text": SendTextCase(requestXML);//發(fā)送文本消息 break; case "event"://發(fā)送事件消息 if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("subscribe")) { SendWelComeMsg(requestXML);//關(guān)注時(shí)返回的圖文消息 } else if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("CLICK")) { SendEventMsg(requestXML);//發(fā)送事件消息 } break; case "voice": SendVoiceMsg(requestXML);//發(fā)送語(yǔ)音消息 break; case "location"://發(fā)送位置消息 SendMapMsg(requestXML); break; default: break; } } catch (Exception ex) { HttpContext.Current.Response.Write(ex.ToString()); } }
先來(lái)關(guān)注發(fā)送文本消息,SendTextCase(requestXML);//發(fā)送文本消息
/// <summary> /// 發(fā)送文本 /// </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格式內(nèi)容 /// </summary> /// <param name="p1">公眾號(hào)</param> /// <param name="p2">用戶號(hào)</param> /// <param name="p3">回復(fù)內(nèi)容</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>"; }
這樣就能實(shí)現(xiàn)消息的應(yīng)答,如果用戶點(diǎn)擊的按鈕,如下代碼:
case "event"://發(fā)送事件消息 if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("subscribe")) { SendWelComeMsg(requestXML);//關(guān)注時(shí)返回的圖文消息 } else if (!string.IsNullOrWhiteSpace(requestXML.EventName) && requestXML.EventName.ToString().Trim().Equals("CLICK")) { SendEventMsg(requestXML);//發(fā)送事件消息 } break; /// <summary> /// 發(fā)送響應(yīng)事件消息 /// </summary> /// <param name="requestXML"></param> private void SendEventMsg(RequestXML requestXML) { string keyStr = requestXML.EventKey.ToString(); switch (keyStr) { case "mypay": SendPayDetails(requestXML);//發(fā)送薪資賬單 break; case "tianqiyubao": SendWeaterMessage(requestXML);//發(fā)送天氣預(yù)報(bào) break; case "kaixinyixiao": SendKaiXinMessage(requestXML);//發(fā)送開心一笑結(jié)果集 break; case "updateMessage": SendUpdateMessage(requestXML);//發(fā)送修改信息鏈接 break; case "yuangonghuodong": SendYuanGongHuoDong(requestXML);//發(fā)送學(xué)生活動(dòng) break; case "yuangongtongzhi": SendYuanGongTongZhi(requestXML);//發(fā)送員工通知 break; case "youwenbida": SendWenti(requestXML);//發(fā)送員工提交問(wèn)題鏈接 break; case "mywen": SendWentiList(requestXML);//發(fā)送問(wèn)題列表鏈接 break; case "PhoneSerices": SendKeFuMessage(requestXML);//接入客服 break; default: String responseContent = String.Empty; responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName,"此功能暫未開放!敬請(qǐng)期待!"); HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); HttpContext.Current.Response.End(); break; } }
SendWelComeMsg(requestXML);//關(guān)注時(shí)返回的圖文消息
/// <summary> /// 發(fā)送關(guān)注時(shí)的圖文消息 /// </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, "歡迎關(guān)注德橋員工服務(wù)中心", "蘇州德橋人力資源創(chuàng)立于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> /// 返回圖文消息項(xiàng) /// </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> /// 發(fā)送響應(yīng)語(yǔ)音識(shí)別結(jié)果 /// </summary> /// <param name="requestXML"></param> private void SendVoiceMsg(RequestXML requestXML) { string responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName, "您剛才說(shuō)的語(yǔ)音消息識(shí)別結(jié)果為:" + requestXML.Recognition.ToString()); HttpContext.Current.Response.ContentType = "text/xml"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Write(responseContent); HttpContext.Current.Response.End(); }
The above is the detailed content of Tips for developing message responses in asp.net WeChat. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform
