Java Micro-trust public number development case _java

Source: Internet
Author: User
Tags cdata documentation set set stub java web stringbuffer

The development of micro-credit public number is generally for enterprises and organizations, individuals can only apply for subscription number, and the interface is limited, below we will briefly describe the access to the public number of steps :

1, first you need a mailbox in the micro-credit platform for registration;
Registered in the way there are subscription number, public number, applet and enterprise number, individuals we can only select the subscription number

2, after registration, we login to the public platform---> Development---> Basic configuration, here need to fill in the URL and Token,url is our use of the server interface;

3, the Java Web server program compiled and deployed on the server can be run, can be in the micro-public number of online interface debugging:

1), select the appropriate interface
2), the system will generate the parameters of the interface table, you can directly fill in the text box in the corresponding parameter values (red asterisk indicates that the field must be filled)
3), click to check the problem button, you can get the appropriate debugging information

Eg: Steps to get Access_token:

1), Interface type: basic support
2), interface list: Get Access_token interface/token
3), fill in the corresponding parameters: Grant_type, AppID, secret
4), click to check the problem
5, the success of the validation will return results and prompts, the result is: OK, hint: Request successful that the success of verification

Here we verify a lot of the message interface debugging: Text messages, picture messages, voice messages, video messages, etc

4, the interface has not understood place, may enter the development--> Developer Tool--> the developer document to inquire

5, interface permissions: Subscribe to the main basic support, receive messages and Web services inside some of the interface

Here we talk about how the subscription number receives the message :

1, need to apply for a person's micro-credit subscription number
2, URL server and server-side code deployment (can be used Tencent cloud or Aliyun server)

1, Accountsservlet.java class, verify message processing from micro-trust server and micro-server

Package cn.jon.wechat.servlet; 
Import java.io.IOException; 
 
Import Java.io.PrintWriter; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
 
Import Javax.servlet.http.HttpServletResponse; 
Import Cn.jon.wechat.service.AccountsService; 
 
Import Cn.jon.wechat.utils.SignUtil; 
 public class Accountsservlet extends HttpServlet {public accountsservlet () {super (); 
 public void Destroy () {Super.destroy (); Put your code here}/** * Confirmation request from the micro-mail server/public void doget (HttpServletRequest request, httpservletrespons E response) throws Servletexception, IOException {System.out.println ("interface Test started!!! 
  "); 
  Micro-letter Encrypted signature String signature = request.getparameter ("signature"); 
  Timestamp String timestamp = request.getparameter ("timestamp"); 
  Random number String nonce = Request.getparameter ("nonce"); 
  
  Random string echostr = Request.getparameter ("Echostr"); PrintWriter out =Response.getwriter (); 
  Verify the request through the validation signature, if the verification is successful, return the ECHOSTR, indicating the successful access, otherwise access failure if (Signutil.checksignature (signature,timestamp,nonce)) { 
  Out.print (ECHOSTR); 
  } out.close (); 
out = null; 
  
  
 Response.encoderedirecturl ("success.jsp"); /** * Processing the message from the micro-trust server * * public void DoPost (HttpServletRequest request, httpservletresponse response) throws Ser 
 Vletexception, IOException {//message acceptance, processing, Response request.setcharacterencoding ("Utf-8"); 
 Response.setcharacterencoding ("Utf-8"); 
  
 Call core business type Accept message, process message String Respmessage = accountsservice.processrequest (request); 
 Response message PrintWriter out = Response.getwriter (); 
 Out.print (Respmessage); 
  
  
 Out.close (); 
 public void Init () throws Servletexception {//Put your code here}}

2), Signutil.java class, request validation tool class, token required and micro-letter filled in token consistent

Package cn.jon.wechat.utils; 
Import Java.security.MessageDigest; 
Import java.security.NoSuchAlgorithmException; 
Import Java.util.Arrays; 
Import Java.util.Iterator; 
Import Java.util.Map; 
Import Java.util.Set; 
 
Import Java.util.concurrent.ConcurrentHashMap; 
 
 /** * Request Verification Tool class * @author Jon/public class Signutil {//token consistent with the micro-configuration of the private static String token = ""; public static Boolean Checksignature (string signature, string timestamp, string nonce) {string[] Arra = new string[ 
 ]{token,timestamp,nonce}; 
 The signature,timestamp,nonce is composed of an array for dictionary sorting arrays.sort (ARRA); 
 StringBuilder sb = new StringBuilder (); 
 for (int i=0;i<arra.length;i++) {sb.append (arra[i]); 
 } messagedigest MD = null; 
 String stnstr = null; 
  try {md = messagedigest.getinstance ("SHA-1"); 
  Byte[] Digest = Md.digest (Sb.tostring (). GetBytes ()); 
 STNSTR = Bytetostr (digest); 
 catch (NoSuchAlgorithmException e) {//TODO auto-generated catch block E.printstacktrace ();}//free memory SB = NULL; 
 Compares the SHA1 encrypted string with the signature, identifying the request from the micro-letter return Stnstr!=null?stnstr.equals (Signature.touppercase ()): false; 
 /** * Converts a byte array to a hexadecimal string * @param Digestarra * @return/private static string Bytetostr (byte[] digestarra) { 
 TODO auto-generated Method Stub String digeststr = ""; 
 for (int i=0;i<digestarra.length;i++) {digeststr + = Bytetohexstr (Digestarra[i]); 
 return digeststr; 
 /** * Converts bytes to hexadecimal strings */private static string Bytetohexstr (Byte dbyte) {//TODO auto-generated method stub 
 Char[] Digit = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '}; 
 char[] Tmparr = new char[2]; 
 Tmparr[0] = digit[(dbyte>>>4) &0X0F]; 
 TMPARR[1] = digit[dbyte&0x0f]; 
 string s = new string (Tmparr); 
 return s; 
 public static void Main (string[] args) {/*byte dbyte = ' A '; System.out.println (Bytetohexstr (Dbyte)); * map<string,string> Map = new concurrenthashmap<string, String 
 > (); MAp.put ("4", "Zhangsan"); 
 Map.put ("M", "Lisi"); 
 Set set = Map.keyset (); 
 Iterator iter = Set.iterator (); 
  while (Iter.hasnext ()) {//String keyv = (string) iter.next (); 
  String key = (string) iter.next (); 
System.out.println (Map.get (key)); 
 System.out.println (Map.get (Iter.next ())); 
 /*for (int i=0;i<map.size (); i++) {}*/}}

3), Accountsservice.java service class, mainly the request and response processing of the message, and when the user is concerned about your public number, you can set the default push message

Package cn.jon.wechat.service; 
Import Java.util.Date; 
 
Import Java.util.Map; 
 
Import Javax.servlet.http.HttpServletRequest; 
Import Cn.jon.wechat.message.req.ImageMessage; 
Import Cn.jon.wechat.message.req.LinkMessage; 
Import Cn.jon.wechat.message.req.LocationMessage; 
Import Cn.jon.wechat.message.req.VideoMessage; 
Import Cn.jon.wechat.message.req.VoiceMessage; 
Import Cn.jon.wechat.message.resp.TextMessage; 
 
Import Cn.jon.wechat.utils.MessageUtil; /** * Decoupling enables the control layer to separate from the business logic layer, mainly processing requests, responding * @author Jon/public class Accountsservice {public static String PROCESSR 
 Equest (HttpServletRequest request) {String respmessage = null; The text message content returned by default String respcontent = "Request handling exception, please try later!" 
 "; 
  
  try {//xml request parsing map<string,string> requestmap = messageutil.parexml (request); 
  Sender account (open_id) String fromusername = Requestmap.get ("Fromusername"); 
  Public account String Tousername = Requestmap.get ("Tousername"); Message type String Msgtype = Requestmap.get ("Msgtype"); 
  The default reply to this text message textmessage Defaulttextmessage = new TextMessage (); 
  Defaulttextmessage.settousername (Fromusername); 
  Defaulttextmessage.setfromusername (Tousername); 
  Defaulttextmessage.setcreatetime (New Date (). GetTime ()); 
  Defaulttextmessage.setmsgtype (Messageutil.messsage_type_text); 
  Defaulttextmessage.setfuncflag (0); Because the value of the HREF attribute must be enclosed in double quotes, which conflicts with the double quotes of the string itself, Escape defaulttextmessage.setcontent ("Welcome to <a href=\" http://blog.csdn.net/ 
J086924\ ">jon's blog </a>!"); 
  Defaulttextmessage.setcontent (Getmainmenu ()); 
 
  
  Converts a text message object to an XML string respmessage = Messageutil.textmessagetoxml (defaulttextmessage); Text message if (Msgtype.equals (Messageutil.messsage_type_text)) {//respcontent = "Hi, you are sending a text message!" 
  "; 
Reply text message TextMessage TextMessage = new TextMessage (); 
Textmessage.settousername (Tousername); 
  Textmessage.setfromusername (Fromusername); 
  Here need to pay attention, otherwise cannot reply the message to the user textmessage.settousername (Fromusername); Textmessage.setfromusername (Tousername); 
  Textmessage.setcreatetime (New Date (). GetTime ()); 
  Textmessage.setmsgtype (Messageutil.messsage_type_text); 
  Textmessage.setfuncflag (0); 
  Respcontent = "Hi, you send the message is:" +requestmap.get ("Content"); 
  Textmessage.setcontent (respcontent); 
  Respmessage = Messageutil.textmessagetoxml (TextMessage); }//Picture message else if (Msgtype.equals (messageutil.messsage_type_image)) {imagemessage imagemessage=new imagemessage 
  (); 
  Imagemessage.settousername (Fromusername); 
  Imagemessage.setfromusername (Tousername); 
  Imagemessage.setcreatetime (New Date (). GetTime ()); 
  Imagemessage.setmsgtype (Messageutil.messsage_type_image); 
  Respcontent=requestmap.get ("Picurl"); 
  Imagemessage.setpicurl ("yun_qi_img/12103112092_230x306.jpg"); 
  Respmessage = Messageutil.imagemessagetoxml (imagemessage); }//Geography else if (Msgtype.equals (messageutil.messsage_type_location)) {locationmessage locationmessage=new Locatio 
  Nmessage (); 
  Locationmessage.settousername (Fromusername); LocationMessage.setfromusername (Tousername); 
  Locationmessage.setcreatetime (New Date (). GetTime ()); 
  Locationmessage.setmsgtype (messageutil.messsage_type_location); 
  Locationmessage.setlocation_x (Requestmap.get ("location_x")); 
  Locationmessage.setlocation_y (Requestmap.get ("location_y")); 
  Locationmessage.setscale (Requestmap.get ("Scale")); 
  Locationmessage.setlabel (Requestmap.get ("Label")); 
   
  Respmessage = Messageutil.locationmessagetoxml (locationmessage); //Video message else if (Msgtype.equals (Messageutil.messsage_type_video)) {videomessage videomessage=new videomessage ( 
  ); 
  Videomessage.settousername (Fromusername); 
  Videomessage.setfromusername (Tousername); 
  Videomessage.setcreatetime (New Date (). GetTime ()); 
  Videomessage.setmsgtype (Messageutil.messsage_type_video); 
  Videomessage.setmediaid (Requestmap.get ("MediaId")); 
  Videomessage.setthumbmediaid (Requestmap.get ("Thumbmediaid")); 
   
  Respmessage = Messageutil.videomessagetoxml (videomessage); }//Link message 
  else if (msgtype.equals (Messageutil.messsage_type_link)) {linkmessage linkmessage=new linkmessage (); 
  Linkmessage.settousername (Fromusername); 
  Linkmessage.setfromusername (Tousername); 
  Linkmessage.setcreatetime (New Date (). GetTime ()); 
  Linkmessage.setmsgtype (Messageutil.messsage_type_link); 
  Linkmessage.settitle (Requestmap.get ("Title")); 
  Linkmessage.setdescription (Requestmap.get ("Description")); 
  Linkmessage.seturl (Requestmap.get ("Url")); 
  Respmessage = Messageutil.linkmessagetoxml (linkmessage); 
  }//Voice message else if (Msgtype.equals (Messageutil.messsage_type_voice)) {voicemessage voicemessage=new voicemessage (); 
  Voicemessage.settousername (Fromusername); 
  Voicemessage.setfromusername (Tousername); 
  Voicemessage.setcreatetime (New Date (). GetTime ()); 
  Voicemessage.setmsgtype (Messageutil.messsage_type_voice); 
  Voicemessage.setmediaid (Requestmap.get ("MediaId")); 
  Voicemessage.setformat (Requestmap.get ("Format")); Respmessage = Messageutil.voicemessaGetoxml (Voicemessage); }//Event push else if (msgtype.equals (messageutil.messsage_type_event)) {//Event type String EventType = Requestmap.get ("E 
  Vent "); Subscribe to if (Eventtype.equals (Messageutil.event_type_subscribe)) {respcontent = "Thank you for your attention!" 
  "; 
   
  //Unsubscribe else if (eventtype.equals (Messageutil.event_type_unsubscribe)) {//System.out.println ("unsubscribe"); 
  else if (eventtype.equals (Messageutil.event_type_click)) {//custom menu Message Processing System.out.println ("custom menu Message Handling"); 
 (Exception e) {//TODO auto-generated catch block E.printstacktrace (); 
 return respmessage; 
 public static String Getmainmenu () {StringBuffer buffer =new stringbuffer (); 
 Buffer.append ("Hello, I'm Jon, please reply to the number selection service:"). Append ("\ n"); 
 Buffer.append ("1, My Blog"). Append ("\ n"); 
 Buffer.append ("2, Song on Demand"). Append ("\ n"); 
 Buffer.append ("3, Classic Game"). Append ("\ n"); 
 Buffer.append ("4, chatting and playing cards"). Append ("\ n"); 
 Buffer.append ("reply" + "0" + "Show Help Menu"); 
  
 return buffer.tostring (); } 
} 
 

4), Messageutil.java help class, including definition of constants and XML message conversion and processing

Package cn.jon.wechat.utils; 
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 Cn.jon.wechat.message.req.ImageMessage; 
Import Cn.jon.wechat.message.req.LinkMessage; 
Import Cn.jon.wechat.message.req.LocationMessage; 
Import Cn.jon.wechat.message.req.VideoMessage; 
Import Cn.jon.wechat.message.req.VoiceMessage; 
Import cn.jon.wechat.message.resp.Article; 
Import Cn.jon.wechat.message.resp.MusicMessage; 
Import Cn.jon.wechat.message.resp.NewsMessage; 
 
Import Cn.jon.wechat.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; /** * Processing class for various messages * @author Jon/public class Messageutil {/** * Text type * * public static final String messs 
 Age_type_text = "TEXT"; 
 /** * Musical Type * * public static final String messsage_type_music = "Music"; 
 
 /** * Graphic type/public static final String messsage_type_news = "NEWS"; 
 /** * Video type/public static final String Messsage_type_video = "Vedio"; 
 /** * Picture Type * * public static final String messsage_type_image = "image"; 
 /** * LINK TYPE */public static final String Messsage_type_link = "link"; 
 /** * location type/public static final String messsage_type_location = "LOCATION"; 
 /** * Audio Type * * public static final String Messsage_type_voice = "VOICE"; 
 /** * Push type/public static final String messsage_type_event = "EVENT"; 
 /** * Event Type: Subscribe (subscribe)/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 click event)/public static final String event_type_click= "click"; /** * Parsing the request XML/@SuppressWarnings ("unchecked") public static map<string,string> Parexml (httpservletre Quest request) throws Exception {//To store the results of the resolution in HashMap map<string,string> Reqmap = new hashmap<string, Stri 
  
 Ng> (); 
 Obtain input stream InputStream InputStream = Request.getinputstream () from request; 
 Read input stream Saxreader reader = new Saxreader (); 
 Document document = Reader.read (InputStream); 
 Gets the XML root element root = Document.getrootelement (); 
 Gets all the child nodes of the root element list<element> elementlist = root.elements (); 
 Iterate through all the child nodes to obtain the information class tolerance for (Element elem:elementlist) {reqmap.put (Elem.getname (), Elem.gettext ()); 
 }//release of resources inputstream.close (); 
  
 InputStream = null; 
 return reqmap; /** * Response message converted to XML return * Text object converted to XML/public static String Textmessagetoxml (TextMessage textmessage) {XStream. 
 Alias ("xml", Textmessage.getclass ()); return xStream.toxml (TextMessage); /** * Speech Object Conversion to XML * */public static String Voicemessagetoxml (Voicemessage voicemessage) {Xstream.alias ("XM 
 L ", Voicemessage.getclass ()); 
 Return Xstream.toxml (Voicemessage); /** * Video object is converted to XML */public static String Videomessagetoxml (Videomessage videomessage) {Xstream.alias (" 
 XML ", Videomessage.getclass ()); 
 Return Xstream.toxml (Videomessage); /** * Music Object converted to XML */public static String Musicmessagetoxml (Musicmessage musicmessage) {Xstream.alias (" 
 XML ", Musicmessage.getclass ()); 
 Return Xstream.toxml (Musicmessage); /** * Text Object converted to XML */public static String Newsmessagetoxml (Newsmessage newsmessage) {xstream.alias ("xml") 
 Newsmessage.getclass ()); 
 Xstream.alias ("Item", new Article (). GetClass ()); 
 Return Xstream.toxml (Newsmessage); /** * Picture Object converted to XML */public static String Imagemessagetoxml (Imagemessage imagemessage) {Xstream.alia S ("xml", Imagemessage.getclass ()); 
  
 Return Xstream.toxml (Imagemessage); /** * Link Object converted to XML */public static String Linkmessagetoxml (Linkmessage linkmessage) {Xstream.alias (" 
 XML ", Linkmessage.getclass ()); 
  
 Return Xstream.toxml (Linkmessage); /** * Geographic object converted to XML */public static String Locationmessagetoxml (Locationmessage locationmessage) {x 
 Stream.alias ("xml", Locationmessage.getclass ()); 
  
 Return Xstream.toxml (Locationmessage); /** * Expands XStream to support CDATA Block * * */private static XStream XStream = new XStream (new Xppdriver () {public Hiera  Rchicalstreamwriter Createwriter (Writer out) {return new Prettyprintwriter (out) {//conversions to all XML nodes add 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); 
 } 
  } 
  }; 
 
} 
 }); 
 }

5), Basemessage.java message base class (including: Developer micro-signal, user account, creation time, message type, message ID variable), text, video, picture message will inherit this base class, on this basis to expand their own variables, can be defined according to the various message properties in the developer documentation

Package cn.jon.wechat.message.req; 
 /** * Message base class (general user-public number) * @author Jon * * * * Basemessage {//Developer micro-signal private String tousername; 
 Sender account (an 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 String MsgId; 
 Public Basemessage () {super (); TODO auto-generated Constructor stub} public basemessage (string tousername, String fromusername, Long createtime 
 , string Msgtype, String msgId) {super (); 
 Tousername = Tousername; 
 Fromusername = Fromusername; 
 Createtime = Createtime; 
 Msgtype = Msgtype; 
 MsgId = 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 String Getmsgid () {return MsgId; 
 } public void Setmsgid (String msgId) {msgId = MsgId; 
 } 
}

6, Textmessage.java text message, inherits from 5 base class, extends content attribute

Package cn.jon.wechat.message.req; 
/** 
 * Text message 
 * @author Jon 
/public class TextMessage extends basemessage{ 
 //message content 
 private String content; 
 
 Public String getcontent () {return 
 content; 
 } 
 
 public void SetContent (String content) { 
 this.content = content; 
 } 
 
} 

7), Imagemessage.java picture message

Package cn.jon.wechat.message.req; 
/** 
 * Picture Message 
 * @author Jon 
/public class Imagemessage extends basemessage{ 
 //Picture link 
 Private String Picurl; 
 
 Public String Getpicurl () {return 
 picurl; 
 } 
 
 public void Setpicurl (String picurl) { 
 picurl = Picurl; 
 } 

8), Videomessage.java video message

Package cn.jon.wechat.message.req; 
 
public class Videomessage extends Basemessage { 
 
 private String mediaId; 
 Private String Thumbmediaid; 
 Public String Getmediaid () {return 
 mediaId; 
 } 
 public void Setmediaid (String mediaId) { 
 this.mediaid = mediaId; 
 } 
 Public String Getthumbmediaid () {return 
 thumbmediaid; 
 } 
 public void Setthumbmediaid (String thumbmediaid) { 
 this.thumbmediaid = Thumbmediaid; 
 } 
 

Other message classes can be done according to the developer's documentation, and developers can also apply for a public platform test account to test the relevant content of the development.

This article has been organized into the "Android micro-credit Development tutorial Summary," Welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.