Receive text messages in WeChat development

Source: Internet
Author: User
The message types include text, image, voice, video, geographical location, link, and event message. Except for event messages, other messages are collectively referred to as common messages. Message push and response are transmitted using xml data packets. When a user sends a message to the public account, if the server fails to receive the response within five seconds, the connection is disconnected and the request is re-initiated. a total of three retries are made. You can use msgid to remove duplicate messages to avoid the impact of duplicate messages on business logic. The message types include text, image, voice, video, geographical location, link, and event message. Except for event messages, other messages are collectively referred to as common messages. Message push and response are transmitted using xml data packets. When a user sends a message to the public account, If the server fails to receive the response within five seconds, the connection will be disconnected and the server will initiate a new request. a total of three retries will be made.. You can use msgid to remove duplicate messages to avoid the impact of duplicate messages on business logic.

If the server cannot process and reply within five seconds, it can directly reply to an empty string. the server will not process the block and will not initiate a retry. It should be noted that the reply empty string here is not a reply to an empty text message, but a direct Response. Write.

The following describes common messages.

Text message:
  
  toUser
   
  fromUser
    
  
   1348831860
   
  text
   
  this is a test
   
  
   1234567890123456
   
 
Image message:
  
  toUser
   
  fromUser
   
  
   1348831860
   
  image
   
  this is a url
   
  media_id
   
  
   1234567890123456
   
 
Voice message:
 
  toUser
  
  fromUser
  
  
   1357290913
  
  voice
  
  media_id
  
  Format
  
  
   1234567890123456
  
 
Video message:
 
  toUser
  
  fromUser
  
  
   1357290913
  
  video
  
  media_id
  
  thumb_media_id
  
  
   1234567890123456
  
 
Geographic location message:
 
  toUser
  
  fromUser
  
  
   
1351776360
  
  location
  
  
   
23.134521
  
  
   
113.358803
  
  
   
20
  
  位置信息
  
   
1234567890123456
  
 
Link message:
 
  toUser
  
  fromUser
  
  
   
1351776360
  
  link
  
  <! [CDATA [Official website of the public platform]>
  公众平台官网链接
  
  url
  
  
   
1234567890123456
  
 

Careful programmers should have discovered that all messages (including event messages) contain the following fields:

Parameters Description
ToUserName Recipient number
FromUserName Sender ID. if it is a common user, it is an OpenID.
CreateTime Message creation time
MsgType Message Type

The message types have been introduced at the beginning of the article, including text, image, voice, video, and location ), link and event)

To facilitate management and code writing, we can write an enumeration for these message types. As follows:

////// Message type enumeration ///Public enum MsgType {////// Text type ///TEXT ,////// Image type ///IMAGE ,////// Speech type ///VOICE ,////// Video type ///VIDEO ,////// Geographic location type ///LOCATION ,////// Link type ///LINK ,////// Event type ///EVENT}

Here, the event in C # is a keyword, so the event cannot be used in enumeration. Therefore, for unification, all enumeration here are in uppercase.

Since all the message bodies have the following fields, you can write a base class, and different message entities inherit this base class. (I have been entangled in a problem. I used to write all the fields in the message body in a class, which is also very convenient to call, but the fields in the class are getting more and more, and it seems uncomfortable. In addition, I am not easy to learn and use object-oriented skills, so I have always listed all the fields in a class.

Directly call var ss = WeiXinRequest. RequestHelper (token, EncodingAESKey, appid );

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

Today, I made another adjustment, that is, dividing the base class of sub-classes. the code readability is improved, but it is not convenient to call it. you may give me some suggestions.

)

Below are message entities

Base class:

Public abstract class BaseMessage {////// Developer id ///Public string ToUserName {get; set ;}////// Sender account (one OpenID )///Public string FromUserName {get; set ;}////// Message creation time (integer )///Public string CreateTime {get; set ;}////// Message type ///Public MsgType {get; set;} public virtual void ResponseNull () {Utils. responseWrite ("");} public virtual void ResText (EnterParam param, string content ){}////// Reply to the message (music )///Public void ResMusic (EnterParam param, Music mu) {} public void ResVideo (EnterParam param, Video v ){}////// Reply to the message (image )///Public void ResPicture (EnterParam param, Picture pic, string domain ){}////// Reply to the message (text list )/////////Public void ResArticles (EnterParam param, List art ){}////// Multi-customer service forwarding //////Public void ResDKF (EnterParam param ){}////// Multi-customer service forwarding if the specified customer service does not have the access capability (not online, automatic access is not enabled, or automatic access is full ), this user will not be accepted by other customer service personnel until the specified customer service has the access capability. When specifying customer service, we recommend that you first query the access capability of customer service and specify the customer service that can be accessed to ensure that the customer can receive services in a timely manner. //////Message body sent by the user///Multiple customer service accountsPublic void ResDKF (EnterParam param, string KfAccount) {} private void Response (EnterParam param, string data ){}}

The basic class defines the public fields of the message body and the virtual methods used to respond to user requests (the response message is not the focus of this article, so the method body is not posted. please follow up on the subsequent articles ).

The parameters of methods in the base class are of the EnterParam type. These parameters are required for user access and message authenticity verification, including tokens, encryption keys, and appid. Definition:

////// Access parameters ///Public class EnterParam {////// Encrypted ///Public bool IsAes {get; set ;}////// Access token ///Public string token {get; set ;}////// 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 ;}}

Image 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 ;}}

Speech 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 ;}}

Link entity:

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 ;}}

The message entity is defined. The next step is to parse the message body pushed by the server into the corresponding entity. I plan to use the C # built-in xml serialization and Serialization component. I tried to report the error of xmls. I simply wrote a processing method using 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 it is mainly compatible with the newly added menu type. Nnd, actually has a sub-attribute, so here we make a sub-attribute processing 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") // Obtain the message model {pr. setValue (t, (MsgType) Enum. parse (typeof (MsgType), element. value. toUpper (), null); continue;} if (pr. propertyType. name = "Event") // Obtain 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 xml processing method is defined, the corresponding entity is parsed based on 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 transmits data packets (such as encrypted data, which must be decrypted before being passed in), and returns the corresponding entity in the form of a base class.

At this point, the reception of common messages is almost finished. combined with the previous blog, the modified access code is now published as follows:

Public class WxRequest {public static BaseMessage Load (EnterParam param, bool bug = true) {string postStr = ""; Stream s = VqiRequest. getInputStream (); // This method is for System. web. httpContext. current. request. inputStream encapsulation, code byte [] B = new byte [s. length]; s. read (B, 0, (int) s. length); postStr = Encoding. UTF8.GetString (B); // Obtain the string var timestamp = VqiRequest. getQueryString ("timestamp"); 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") // process in encryption mode {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 );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.