Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to receive text messages developed by Wechat

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to receive text messages in Wechat development. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

The message types in Wechat are: text, picture, voice, video, geographic location, link and event message. In addition to event messages, other messages are collectively referred to as ordinary messages. The push and response of messages in Wechat are transmitted in xml packets. When the user sends a message to the official account, the Wechat server will disconnect and re-initiate the request for a total of three retries if it does not receive a response within five seconds. Ordinary messages can be weighed using msgid to avoid the impact of duplicate messages on business logic.

If the server can not guarantee processing and reply within five seconds, you can directly reply to the empty string, Wechat server will not do anything to this seat, and will not initiate a retry. It is important to note that the empty reply string here is not an empty text message, but a direct Response.Write ("").

The following is a brief explanation of the general messages.

Text message: 1348831860 1234567890123456 Picture message: 1348831860 1234567890123456 Voice message: 135729091334567890123456 Video message: 135729091334567890123456 Geographic location message: 135177636023.134521113.358803201234567890123456 Link message: 1351776360124567890123456

A careful programmer should have noticed that all messages (including event messages) contain the following fields

Parameter describes the ToUserName receiver WeChat FromUserName sender WeChat. If it is an ordinary user, it is an OpenIDCreateTime message creation time MsgType message type.

The types of messages are already mentioned at the beginning of the article, namely: text (text), picture (image), voice (voice), video (video), geographic location (location), link (link), event (event).

To facilitate management and coding, we can write an enumeration of these message types. As follows:

/ message type enumeration / public enum MsgType {/ text type / TEXT, / picture type / IMAGE, / voice type / VOICE / Video type / VIDEO, / geolocation type / LOCATION, / link type / LINK / event type / EVENT}

As explained here, event is a keyword in C#, so event cannot be used in enumerations, so for the sake of uniformity, all enumerations here are in uppercase.

Since all message bodies have the above fields, you can write a base class, and then different message entities inherit this base class. (I have been struggling with a problem. In the past, I used to write all the fields in the message body in one class, which is also very convenient to call, but there are more and more fields in the class, which makes me uncomfortable. In addition, I am not very talented and not proficient in object-oriented, so I always list all the fields in one class.

When calling, directly var ss = WeiXinRequest.RequestHelper (token, EncodingAESKey, appid)

Return a WeiXinRequest, and then determine and respond to the message type and event type.

Today, I made a new adjustment, that is, it is divided into subclasses and base classes, the readability of the code has been improved, but it is not as convenient to call it as before.

)

The following are the message entities

Base class:

Public abstract class BaseMessage {/ developer Wechat / public string ToUserName {get; set;} / sender account (an OpenID) / public string FromUserName {get; set } / message creation time (integer) / public string CreateTime {get; set;} / public MsgType MsgType {get; set;} public virtual void ResponseNull () {Utils.ResponseWrite (") } public virtual void ResText (EnterParam param, string content) {} / reply message (music) / public void ResMusic (EnterParam param, Music mu) {} public void ResVideo (EnterParam param) Video v) {} / reply message (picture) / public void ResPicture (EnterParam param, Picture pic, string domain) {} / reply message (picture and text list) / public void ResArticles (EnterParam param List art) {} / public void ResDKF (EnterParam param) {} / multiple customer service forwarding if the specified customer service does not have access capability (not online, does not enable automatic access, or automatic access is full) The user will wait for the designated customer service to have access capability before it will be accessed, and will not be received by other customer service. It is recommended that when assigning customer service, you should first inquire about the access capability of customer service and assign it to the customer service that has the ability to access, so as to ensure that customers can receive service in a timely manner. / / the body of the message sent by the user / multiple customer service account public void ResDKF (EnterParam param, string KfAccount) {} private void Response (EnterParam param, string data) {}}

The public field of the message body is defined in the base class, as well as the virtual method used to respond to the user's request (the response message is not the focus of this article, so the method body is not posted, please follow the following article).

One of the parameters of the method in the base class is of type EnterParam, which is used when the user accesses and verifies the authenticity of the message, including token, encryption key, appid, and so on. The definition is as follows:

/ Wechat access parameters / public class EnterParam {/ whether to encrypt / public bool IsAes {get; set;} / access token / public string token {get; set } / Wechat appid / public string appid {get; set;} / encryption key / public string EncodingAESKey {get; set;}}

Text entity:

Public class TextMessage:BaseMessage {/ message content / public string Content {get; set;} / message id,64 bit integer / public string MsgId {get; set;}}

Picture entity:

Public class ImgMessage: BaseMessage {/ Image path / public string PicUrl {get; set;} / message id,64 bit integer / public string MsgId {get; set;} / Media ID / public string MediaId {get; set }}

Voice entity:

Public class VoiceMessage: BaseMessage {/ thumbnail ID / public string MsgId {get; set;} / format / / public string Format {get; set;} / Media ID / public string MediaId {get; set } / speech recognition result / public string Recognition {get; set;}}

Video entity:

Public class VideoMessage: BaseMessage {/ thumbnail ID / public string ThumbMediaId {get; set;} / message id,64 bit integer / public string MsgId {get; set;} / Media ID / public string MediaId {get; set }}

Linked entities:

Public class LinkMessage: BaseMessage {/ thumbnail ID / public string MsgId {get; set;} / title / public string Title {get; set;} / description / public string Description {get; set } / Link address / public string Url {get; set;}}

Once the message entity is defined, the next step is to parse it into the corresponding entity according to the message body pushed by Wechat server. Originally intended to use the xml included in C# to serialize and send serialized components, as a result, I tried to always report something wrong with xmls, so I wrote a handling method with reflection:

Public static T ConvertObj (string xmlstr) {XElement xdoc = XElement.Parse (xmlstr); var type = typeof (T); var t = Activator.CreateInstance (); foreach (XElement element in xdoc.Elements ()) {var pr = type.GetProperty (element.Name.ToString ()) If (element.HasElements) {/ / here is mainly compatible with the newly added menu types of Wechat. Nnd, which actually has sub-attributes, so here we do the processing of sub-attributes foreach (var ele in element.Elements ()) {pr = type.GetProperty (ele.Name.ToString ()); pr.SetValue (t, Convert.ChangeType (ele.Value, pr.PropertyType), null) } continue;} if (pr.PropertyType.Name = = "MsgType") / / get message model {pr.SetValue (t, (MsgType) Enum.Parse (typeof (MsgType), element.Value.ToUpper ()), null); continue } if (pr.PropertyType.Name = = "Event") / / gets the event type. {pr.SetValue (t, (Event) Enum.Parse (typeof (Event), element.Value.ToUpper ()), null); continue;} pr.SetValue (t, Convert.ChangeType (element.Value, pr.PropertyType), null);} return t;}

After the method for handling xml is defined, the following is about parsing the corresponding entity according to different message types:

Public class MessageFactory {public static BaseMessage CreateMessage (string xml) {XElement xdoc = XElement.Parse (xml); var msgtype = xdoc.Element ("MsgType"). Value.ToUpper (); MsgType type = (MsgType) Enum.Parse (typeof (MsgType), msgtype); switch (type) {case MsgType.TEXT: return Utils.ConvertObj (xml) Case MsgType.IMAGE: return Utils.ConvertObj (xml); case MsgType.VIDEO: return Utils.ConvertObj (xml); case MsgType.VOICE: return Utils.ConvertObj (xml); case MsgType.LINK: return Utils.ConvertObj (xml); case MsgType.LOCATION: return Utils.ConvertObj (xml) Case MsgType.EVENT:// event type {} break; default: return Utils.ConvertObj (xml);}

The CreateMessage method passes in the packet (such as encryption, which needs to be decrypted) and returns the corresponding entity in the form of a base class.

At this point, we are almost done with the reception of ordinary messages. Combined with the previous blog post, now post the modified access code as follows:

Public class WxRequest {public static BaseMessage Load (EnterParam param, bool bug = true) {string postStr = ""; Stream s = VqiRequest.GetInputStream (); / / this method encapsulates System.Web.HttpContext.Current.Request.InputStream and can be directly coded with byte [] b = new byte [s.Length]; s.Read (b, 0, (int) s.Length) PostStr = Encoding.UTF8.GetString (b); / / get the string var timestamp = VqiRequest.GetQueryString ("timestamp") pushed from Wechat server; var nonce = VqiRequest.GetQueryString ("nonce"); var msg_signature = VqiRequest.GetQueryString ("msg_signature"); var encrypt_type = VqiRequest.GetQueryString ("encrypt_type"); string data = "" If (encrypt_type== "aes") / / encryption mode processing {param.IsAes = true; var ret = new MsgCrypt (param.token, param.EncodingAESKey, param.appid); int r = ret.DecryptMsg (msg_signature, timestamp, nonce, postStr, ref data) If (r! = 0) {WxApi.Base.WriteBug ("message decryption failed"); return null;}} else {param.IsAes = false; data = postStr } if (bug) {Utils.WriteTxt (data);} return MessageFactory.CreateMessage (data) }} this is the end of the article on "how to receive text messages in Wechat development". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report