WeChat Public Account Development tutorial 4th-Packaging _php Tutorials for messaging and message processing tools

Source: Internet
Author: User
工欲善其事 its prerequisite! This article focuses on how to encapsulate public platform-defined messages and message-related operations into tool classes for later use. It needs to be clear that the message is actually sent to your public account by the user, the message is first received by the platform, and then the platform will transfer the message to the URL you specified in the Development mode interface configuration.

Public platform Messaging Interface

To receive the message sent by the platform, we need to familiarize ourselves with the message Interface section of the Public Platform API, click here, and then enter into the Message Interface Guide section as shown in:

On the left you can see three types of interfaces currently open on the public platform: message interface, common interface, and custom menu interface. Universal interface and custom menu interface only to get the beta qualification can be called, and the application of the beta qualification has been closed, we only look forward to a day in the future will be open to the public, so no beta qualified users will not waste time on these two interfaces, just need to use good message interface on it.

Message push and message reply

The following will mainly describe the message interface. For receiving and responding to messages, we just need to focus on the "4 message Push" and "5 message reply" is enough.

Let us first understand what "message push" means in the interface, click "4 Message Push", you can see "message push" in the interface refers to "when the ordinary user sends a message to the public account, the server will post the message to the filled URL", that is defined here is what type of message users can send, What fields are in the message, and how the message is forwarded to our public account backstage by the server.

Message push defines the type of message we will receive 5 kinds: text message, picture message, geo-location message, link message and event push, in fact voice message we can also receive, just can't get the specific voice file (need to be qualified to get voice file).

The message reply in the interface defines the message type, message field, and message format that we can reply to the user, as described in the interface guide of the public platform:

There are 5 messages that we can reply to users, but there are only 3 messages that can be replied to in development mode: text messages, music messages, and graphics messages, while voice messages and video messages are currently only available in edit mode.

Encapsulation of messages

The next thing to do is to encapsulate the message that is defined in the message push (request), message reply (response), and create the corresponding Java class (Java is an object-oriented programming language that is more convenient to use after encapsulation), and the following request message refers to the message defined in the message push. A response message refers to a message that is defined in a message reply.

base class for Request messages

Extracts the fields of all messages defined in the message push into a base class, which includes: Tousername (developer number), Fromusername (sender account, open_id), Createtime (message creation time), Msgtype (message type), MSGID (Message ID), the code for the post-encapsulation base class Org.liufeng.course.message.req.BaseMessage is as follows:

Package org.liufeng.course.message.req;/** * Message base class (general user, public account) *  * @author Liufeng * @date 2013-05-19 */public CLA  SS Basemessage {//Developer number private string tousername;//sender account (one OpenID) private string fromusername;//message creation time (integer) Private long createtime;//message type (text/image/location/link) private String msgtype;//message id,64 bit integer private long msgid;public String Gettousername () {return tousername;} public void Settousername (String tousername) {tousername = Tousername;} Public String Getfromusername () {return fromusername;} public void Setfromusername (String fromusername) {fromusername = Fromusername;} Public long Getcreatetime () {return createtime;} public void Setcreatetime (long createtime) {createtime = Createtime;} Public String Getmsgtype () {return msgtype;} public void Setmsgtype (String msgtype) {msgtype = Msgtype;} Public long Getmsgid () {return MsgId;} public void Setmsgid (long msgId) {msgId = MsgId;}}

The text message of the request message

Package org.liufeng.course.message.req;/** * Text message *  * @author Liufeng * @date 2013-05-19 */public class TextMessage ex Tends Basemessage {//message content private string Content;public string GetContent () {return content;} public void SetContent (String content) {content = content;}}

Picture message of the request message

Package org.liufeng.course.message.req;/** * Picture message *  * @author Liufeng * @date 2013-05-19 */public class Imagemessage E Xtends Basemessage {//Picture link private string Picurl;public string Getpicurl () {return picurl;} public void Setpicurl (String picurl) {picurl = Picurl;}}

Geo-Location message of the request message

Package org.liufeng.course.message.req;/** * Geolocation message *  * @author Liufeng * @date 2013-05-19 */public class locationmess Age extends Basemessage {//Geography dimension private String location_x;//geographic longitude private string location_y;//map zoom Small private string Sca le;//geolocation Information private string Label;public string getlocation_x () {return location_x;} public void setlocation_x (String location_x) {location_x = location_x;} Public String getlocation_y () {return location_y;} public void setlocation_y (String location_y) {location_y = location_y;} Public String Getscale () {return scale;} public void Setscale (String scale) {scale = scale;} Public String Getlabel () {return Label;} public void SetLabel (String label) {label = label;}}

The link message for the request message

Package org.liufeng.course.message.req; /** * Link Message * * @author Liufeng * @date 2013-05-19 * * public class Linkmessage extends Basemessage {//message header private String Title; Message description private String Description; Message link private String Url; public string GetTitle () {return Title,} public void Settitle (String title) {title = title;} public String Getdescript Ion () {return Description;} public void SetDescription (String Description) {Description = Description;} public String GetUrl () {return URL;} public void SetUrl (String url) {url = URL;}}

Voice message of the request message

Package org.liufeng.course.message.req;/** * Audio message *  * @author Liufeng * @date 2013-05-19 */public class Voicemessage E Xtends Basemessage {//Media idprivate string mediaid;//speech format private string Format;public string Getmediaid () {return mediaid; }public void Setmediaid (String mediaid) {mediaid = MediaID;} Public String GetFormat () {return Format;} public void SetFormat (String format) {format = format;}}

Base class for response messages

Similarly, the fields of all messages defined in the message reply are extracted and encapsulated into a base class, which includes: Tousername (receiver account, user's open_id), Fromusername (Developer's number), Createtime (Message creation time), Msgtype (message type), Funcflag (Star ID of the message), the code for the base class Org.liufeng.course.message.resp.BaseMessage after encapsulation is as follows:

Package org.liufeng.course.message.resp;/** * Message base class (public account, normal user) *  * @author Liufeng * @date 2013-05-19 */public cl Basemessage {//Receiver account (received OpenID) private string tousername;//developer number private string fromusername;//message creation time (integer) Private lo NG createtime;//Message type (text/music/news) private String msgtype;//bit 0x0001 is flagged when the star has just received the message private int funcflag;public String Gettousername () {return tousername;} public void Settousername (String tousername) {tousername = Tousername;} Public String Getfromusername () {return fromusername;} public void Setfromusername (String fromusername) {fromusername = Fromusername;} Public long Getcreatetime () {return createtime;} public void Setcreatetime (long createtime) {createtime = Createtime;} Public String Getmsgtype () {return msgtype;} public void Setmsgtype (String msgtype) {msgtype = Msgtype;} public int Getfuncflag () {return funcflag;} public void Setfuncflag (int funcflag) {funcflag = Funcflag;}}

Text message of the response message

Package org.liufeng.course.message.resp;/** * Text message *  * @author Liufeng * @date 2013-05-19 */public class TextMessage E Xtends Basemessage {//Reply message content private string Content;public string GetContent () {return content;} public void SetContent (String content) {content = content;}}

Music Messages for response messages

Package org.liufeng.course.message.resp;/** * Music message *  * @author Liufeng * @date 2013-05-19 */public class Musicmessage Extends Basemessage {//musical private Music Music;public-Getmusic () {return music;} public void Setmusic (music music) {music = music;}}

Text Message of Response message

Package Org.liufeng.course.message.resp;import java.util.list;/** * Text message *  * @author Liufeng * @date 2013-05-19 */pub Lic class Newsmessage extends Basemessage {///text message number, limited to 10 private int articlecount;//More than one message information, the default first item is large map private List articles;public int Getarticlecount () {return articlecount;} public void Setarticlecount (int articlecount) {articlecount = Articlecount;} Public List Getarticles () {return articles;} public void Setarticles (List articles) {articles = articles;}}

Definition of article class in text message

Package org.liufeng.course.message.resp;/** * Graphic model *  * @author Liufeng * @date 2013-05-19 */public class Article {/ /text message name private string title;//text message description private string description;//picture link, support JPG, PNG format, good effect for large figure 640*320, small figure 80* 80, the domain name that restricts the image link needs to be consistent with the URL in the basic information that the developer fills in the private string picurl;//Click the text message jump link private string Url;public string GetTitle () {return Title;} public void Settitle (String title) {title = title;} Public String GetDescription () {return NULL = = Description? "": Description;} public void SetDescription (String description) {description = description;} Public String Getpicurl () {return NULL = = Picurl? "": Picurl;} public void Setpicurl (String picurl) {picurl = Picurl;} Public String GetUrl () {return NULL = = Url? "": URL;} public void SetUrl (String url) {url = URL;}}

After all message encapsulation is complete, the structure of the message part in the Eclipse project should be consistent with consistency, if inconsistent (class name, attribute name inconsistent) check after the adjustment is consistent, because the following chapters also describe how to develop common class methods, business-independent tool class encapsulation into a jar package, In the future to do the project only need to introduce the jar package, this kind of work can be done once.

How do I parse a request message?

The resolution of the request message is then resolved. The server sends the user's request through the Dopost method, so let's review the definition of the Dopost method that was written in the previous section:

/**      * Handling messages sent by server *      /public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {          //TODO message receive, process, response      }  

How do I convert a response message to an XML return?

We have previously encapsulated the response message into a Java class that we use in our code. So, when the request is received successfully and the processing is complete, how can I return the message? Here is how to convert the response message to XML return, where we will use the Open source framework XStream to implement the Java class-to-XML transformation (Xstream-1.3.1.jar is used here), the code is as follows:

/** * Text message object converted to XML * * @param textmessage Text Message object * @return XML */public static String Textmessagetoxml (TextMessage textMe Ssage) {xstream.alias ("xml", Textmessage.getclass ()); return Xstream.toxml (TextMessage);} /** * Music Message object converted to XML * * @param musicmessage Music Message Object * @return XML */public static String Musicmessagetoxml (Musicmessage mus Icmessage) {xstream.alias ("xml", Musicmessage.getclass ()); return Xstream.toxml (Musicmessage);} /** * Graphic Message object converted to XML * * @param newsmessage Text Message object * @return XML */public static String Newsmessagetoxml (Newsmessage newsme Ssage) {xstream.alias ("xml", Newsmessage.getclass ()); Xstream.alias ("Item", new article (). GetClass ()); return Xstream.toxml (newsmessage);} /** * Extend XStream to support CDATA blocks * * @date 2013-05-19 */private static XStream XStream = new XStream (new Xppdriver () {public Hi Erarchicalstreamwriter Createwriter (Writer out) {return new Prettyprintwriter (out) {////conversion of all XML nodes added CDATA Tag Boolean CDATA = true; @SuppressWarnings ("Unchecked") public void Startnode (String name,Class clazz) {super.startnode (name, clazz);} protected void WriteText (Quickwriter writer, String text) {if (CDATA) {Writer.write ("<![CDATA[");writer.write(text);writer.write("]]>");} else {writer.write (text);}}};});

Description: Because the XStream framework itself does not support the generation of CDATA blocks, the 40~62 line code extends the Xtream to support the addition of CDATA blocks when generating values for each element of the XML.

Encapsulation of message processing tools

Knowing how to parse the request message and how to translate the response message into XML, the next step is to encapsulate all the message-related processing methods in the tool class Messageutil, the complete code for the class is as follows:

Package Org.liufeng.course.util;import Java.io.inputstream;import Java.io.writer;import java.util.HashMap;import Java.util.list;import Java.util.map;import Javax.servlet.http.httpservletrequest;import Org.dom4j.Document;import Org.dom4j.element;import Org.dom4j.io.saxreader;import Org.liufeng.course.message.resp.article;import Org.liufeng.course.message.resp.musicmessage;import Org.liufeng.course.message.resp.newsmessage;import Org.liufeng.course.message.resp.textmessage;import Com.thoughtworks.xstream.xstream;import Com.thoughtworks.xstream.core.util.quickwriter;import Com.thoughtworks.xstream.io.HierarchicalStreamWriter; Import Com.thoughtworks.xstream.io.xml.prettyprintwriter;import com.thoughtworks.xstream.io.xml.xppdriver;/** * Message Tool class * * @author Liufeng * @date 2013-05-19 */public class Messageutil {/** * return message type: text */public static final String RES P_message_type_text = "TEXT";/** * return message type: Music */public static final String resp_message_type_music = "Music";/** * return message type: Figure Wen */public staTic final String resp_message_type_news = "News";/** * Request message type: Text */public static final string req_message_type_text = "Tex T ";/** * Request message type: Picture */public static final String req_message_type_image =" image ";/** * Request message type: Link */public static final Str ing req_message_type_link = "LINK";/** * Request message type: Geo */public static final String req_message_type_location = "Location"; * * Request message type: Audio */public static final string req_message_type_voice = "VOICE";/** * Request message type: Push */public static final string Req_message_type_event = "event";/** * Event Type: Subscribe (subscription) */public static final String event_type_subscribe = "Subscribe" ;/** * Event Type: Unsubscribe (unsubscribe) */public static final String event_type_unsubscribe = "unsubscribe";/** * Event Type: Click (Custom menu Point */public static final String Event_type_click = "click";/** * Parse the sent request (XML) * * @param request * @return * @throws Ex Ception */@SuppressWarnings ("unchecked") public static Map
 
  Parsexml (HttpServletRequest request) throws Exception {//Store parse results in HashMap map
  
   Map = new HashMap
   
    ();//Get input stream from request InputStream InputStream = Request.getinputstream ();//Read input stream Saxreader reader = new Saxreader ();D Ocument document = Reader.read (InputStream);//Gets the XML root elements element root = Document.getrootelement ();//Gets all the child nodes of the root element list
    
     
 Elementlist = Root.elements ();//traverse all child nodes for (Element e:elementlist) map.put (E.getname (), E.gettext ());//Release Resources Inputstre Am.close (); inputstream = Null;return map;} /** * Text message object converted to XML * * @param textmessage Text Message object * @return XML */public static String Textmessagetoxml (TextMessage textMe Ssage) {xstream.alias ("xml", Textmessage.getclass ()); return Xstream.toxml (TextMessage);} /** * Music Message object converted to XML * * @param musicmessage Music Message Object * @return XML */public static String Musicmessagetoxml (Musicmessage mus Icmessage) {xstream.alias ("xml", Musicmessage.getclass ()); return Xstream.toxml (Musicmessage);} /** * Graphic Message object converted to XML * * @param newsmessage Text Message object * @return XML */public static String Newsmessagetoxml (Newsmessage newsme Ssage) {xstream.alias ("xml", Newsmessage.getclass ()); Xstream.alias ("Item", new article (). GetClass ()); return Xstream.toxml (newsmessage);} /** * Extend XStream to support CDATA blocks * * @date 2013-05-19 */private static XStream XStream = new XStream (new Xppdriver () {public Hi Erarchicalstreamwriter CREATEWRITER (Writer out) {return new Prettyprintwriter (out) {////For all XML node conversions are incremented by the CDATA token, Boolean CDATA = true; @SuppressWarnings (" Unchecked ") public void Startnode (String name, Class clazz) {super.startnode (name, clazz);} protected void WriteText (Quickwriter writer, String text) {if (CDATA) {Writer.write ("<![CDATA[");writer.write(text);writer.write("]]>");} else {writer.write (text);}}}});}
    
   
  
 

OK, here's the encapsulation of message and message processing tools here, in fact, is to create a corresponding Java class for the request message/Response message, parse the XML message, and convert the Java object of the response message to XML. The next section describes how to use the tools that are packaged above to identify the types of messages sent by the user and make the correct response.


http://www.bkjia.com/PHPjc/444574.html www.bkjia.com true http://www.bkjia.com/PHPjc/444574.html techarticle 工欲善其事 its prerequisite! This article focuses on how to encapsulate public platform-defined messages and message-related operations into tool classes for later use. It needs to be clear ...

  • 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.