亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development Using java to develop WeChat public account case code

Using java to develop WeChat public account case code

Mar 14, 2017 pm 02:16 PM
java WeChat public account

This article uses Java to develop the WeChat public account case code, how to access the public account, how about the subscription accountReceive messages, has certain reference value, interested friends can refer to it

WeChat public account development is generally aimed at enterprises and organizations. Individuals can generally only apply for a subscription account, and the interface called is limited. Let’s briefly describe the access. Steps for public account :

1. First, you need an email address to register on the WeChat public account platform;
Registration methods include subscription account, public account, mini program and enterprise account , personally we can only choose the subscription account

2. After registration, we log in to the official account platform --->Development--->Basic configuration, here we need to fill in the URL and token , the URL is the interface we use the server;

3. If the Java Web server program is compiled and deployed on the server and can run, the online interface can be performed on the WeChat official accountDebugging

1). Select the appropriate interface
2) The system will generate the parameter table of the interface. You can directly fill in the corresponding parameter value in the text box (red asterisk indicates This field is required)
3) Click the Check Problem button to get the corresponding debugging information

eg: Steps to obtain 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 Question
5) If the verification is successful, the result and prompt will be returned. The result is: 200 ok. The prompt: Request successful means the verification is successful.

What we verify more here is the message interface debugging: text Messages, picturesmessages, voice messages, videomessages, etc

4. If you don’t understand the interface, you can enter development-->Development Developer tools-->Developer documentation for query

5. Interface permissions: Subscription accounts mainly have basic support, receiving messages and some interfaces in web services

Below we will mainly talk about the case of how subscription accounts receive messages:

1. You need to apply for a personal WeChat subscription account
2. URL server And server-side code deployment (you can use Tencent Cloud or Alibaba Cloud server)

1), AccountsServlet.java class, verification comes from WeChat Message processing of the server and WeChat 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 
 } 
 /** 
 * 確認(rèn)請(qǐng)求來(lái)自于微信服務(wù)器 
 */ 
 
 public void doGet(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException { 
  System.out.println("接口測(cè)試開(kāi)始!??!"); 
  //微信加密簽名 
  String signature = request.getParameter("signature"); 
  //時(shí)間戳 
  String timestamp = request.getParameter("timestamp"); 
  //隨機(jī)數(shù) 
  String nonce = request.getParameter("nonce"); 
  //隨機(jī)字符串 
  String echostr = request.getParameter("echostr"); 
  
  PrintWriter out = response.getWriter(); 
  //通過(guò)校驗(yàn)signature對(duì)請(qǐng)求進(jìn)行校驗(yàn),若校驗(yàn)成功則原樣返回echostr,表示接入成功,否則接入失敗 
  if(SignUtil.checkSignature(signature,timestamp,nonce)){ 
  out.print(echostr); 
  } 
  out.close(); 
  out = null; 
//  response.encodeRedirectURL("success.jsp"); 
  
  
 } 
 /** 
 * 處理微信服務(wù)器發(fā)來(lái)的消息 
 */ 
 public void doPost(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException { 
 //消息的接受、處理、響應(yīng) 
 request.setCharacterEncoding("utf-8"); 
 response.setCharacterEncoding("utf-8"); 
 //調(diào)用核心業(yè)務(wù)類(lèi)型接受消息、處理消息 
 String respMessage = AccountsService.processRequest(request); 
  
 //響應(yīng)消息 
 PrintWriter out = response.getWriter(); 
 out.print(respMessage); 
 out.close(); 
  
  
 } 
 
 public void init() throws ServletException { 
 // Put your code here 
 } 
 
}

2), SignUtil.java class, request verification tool class, the token needs to be consistent with the token filled in WeChat


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; 
 
/** 
 * 請(qǐng)求校驗(yàn)工具類(lèi) 
 * @author jon 
 */ 
public class SignUtil { 
 //與微信配置中的的Token一致 
 private static String token = ""; 
 
 public static boolean checkSignature(String signature, String timestamp, 
  String nonce) { 
 String[] arra = new String[]{token,timestamp,nonce}; 
 //將signature,timestamp,nonce組成數(shù)組進(jìn)行字典排序 
 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(); 
 } 
 //釋放內(nèi)存 
 sb = null; 
 //將sha1加密后的字符串與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來(lái)源于微信 
 return stnStr!=null?stnStr.equals(signature.toUpperCase()):false; 
 } 
 /** 
 * 將字節(jié)數(shù)組轉(zhuǎn)換成十六進(jìn)制字符串 
 * @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; 
 } 
 /** 
 * 將字節(jié)轉(zhuǎn)換成為十六進(jìn)制字符串 
 */ 
 private static String byteToHexStr(byte dByte) { 
 // TODO Auto-generated method stub 
 char[] Digit = {&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;}; 
 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 = &#39;A&#39;; 
 System.out.println(byteToHexStr(dByte));*/ 
 Map<String,String> map = new ConcurrentHashMap<String, String>(); 
 map.put("4", "zhangsan"); 
 map.put("100", "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 for message request and response processing, and when the user follows your official account, 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; 
 
/** 
 * 解耦,使控制層與業(yè)務(wù)邏輯層分離開(kāi)來(lái),主要處理請(qǐng)求,響應(yīng) 
 * @author jon 
 */ 
public class AccountsService { 
 
 public static String processRequest(HttpServletRequest request) { 
 String respMessage = null; 
 //默認(rèn)返回的文本消息內(nèi)容 
 String respContent = "請(qǐng)求處理異常,請(qǐng)稍后嘗試!"; 
 try { 
  //xml請(qǐng)求解析 
  Map<String,String> requestMap = MessageUtil.pareXml(request); 
  
  //發(fā)送方賬號(hào)(open_id) 
  String fromUserName = requestMap.get("FromUserName"); 
  //公眾賬號(hào) 
  String toUserName = requestMap.get("ToUserName"); 
  //消息類(lèi)型 
  String msgType = requestMap.get("MsgType"); 
  
  //默認(rèn)回復(fù)此文本消息 
  TextMessage defaultTextMessage = new TextMessage(); 
  defaultTextMessage.setToUserName(fromUserName); 
  defaultTextMessage.setFromUserName(toUserName); 
  defaultTextMessage.setCreateTime(new Date().getTime()); 
  defaultTextMessage.setMsgType(MessageUtil.MESSSAGE_TYPE_TEXT); 
  defaultTextMessage.setFuncFlag(0); 
  // 由于href屬性值必須用雙引號(hào)引起,這與字符串本身的雙引號(hào)沖突,所以要轉(zhuǎn)義 
  defaultTextMessage.setContent("歡迎訪問(wèn)<a href=\"http://blog.csdn.net/j086924\">jon的博客</a>!"); 
//  defaultTextMessage.setContent(getMainMenu()); 
  // 將文本消息對(duì)象轉(zhuǎn)換成xml字符串 
  respMessage = MessageUtil.textMessageToXml(defaultTextMessage); 
 
  
  //文本消息 
  if(msgType.equals(MessageUtil.MESSSAGE_TYPE_TEXT)){ 
  //respContent = "Hi,您發(fā)送的是文本消息!"; 
  //回復(fù)文本消息 
  TextMessage textMessage = new TextMessage(); 
//  textMessage.setToUserName(toUserName); 
//  textMessage.setFromUserName(fromUserName); 
  //這里需要注意,否則無(wú)法回復(fù)消息給用戶了 
  textMessage.setToUserName(fromUserName); 
  textMessage.setFromUserName(toUserName); 
  textMessage.setCreateTime(new Date().getTime()); 
  textMessage.setMsgType(MessageUtil.MESSSAGE_TYPE_TEXT); 
  textMessage.setFuncFlag(0); 
  respContent = "Hi,你發(fā)的消息是:"+requestMap.get("Content"); 
  textMessage.setContent(respContent); 
  respMessage = MessageUtil.textMessageToXml(textMessage); 
  } 
  //圖片消息 
  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("http://img24.pplive.cn//2013//07//24//12103112092_230X306.jpg"); 
  respMessage = MessageUtil.imageMessageToXml(imageMessage); 
  } 
  //地理位置 
  else if(msgType.equals(MessageUtil.MESSSAGE_TYPE_LOCATION)){ 
  LocationMessage locationMessage=new LocationMessage(); 
  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); 
   
  } 
  
  //視頻消息 
  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); 
   
  } 
  //鏈接消息 
  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); 
  } 
  //語(yǔ)音消息 
  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); 
  } 
  //事件推送 
  else if(msgType.equals(MessageUtil.MESSSAGE_TYPE_EVENT)){ 
  //事件類(lèi)型 
  String eventType = requestMap.get("Event"); 
  //訂閱 
  if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)){ 
   respContent = "謝謝關(guān)注!"; 
  } 
  //取消訂閱 
  else if(eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)){ 
   // 
   System.out.println("取消訂閱"); 
   
  } 
  else if(eventType.equals(MessageUtil.EVENT_TYPE_CLICK)){ 
   //自定義菜單消息處理 
   System.out.println("自定義菜單消息處理"); 
  } 
  } 
  
 } catch (Exception e) { 
  // TODO Auto-generated catch block 
  e.printStackTrace(); 
 } 
 return respMessage; 
 } 
 
 public static String getMainMenu() 
 { 
 StringBuffer buffer =new StringBuffer(); 
 buffer.append("您好,我是jon,請(qǐng)回復(fù)數(shù)字選擇服務(wù):").append("\n"); 
 buffer.append("1、我的博客").append("\n"); 
 buffer.append("2、 歌曲點(diǎn)播").append("\n"); 
 buffer.append("3、 經(jīng)典游戲").append("\n"); 
 buffer.append("4 、聊天打牌").append("\n\n"); 
 buffer.append("回復(fù)"+"0"+"顯示幫助菜單"); 
 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; 
 
/** 
 * 各種消息的處理類(lèi) 
 * @author jon 
 */ 
 
public class MessageUtil { 
 /** 
 * 文本類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_TEXT = "text"; 
 /** 
 * 音樂(lè)類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_MUSIC = "music"; 
 /** 
 * 圖文類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_NEWS = "news"; 
 
 /** 
 * 視頻類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_VIDEO = "video"; 
 /** 
 * 圖片類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_IMAGE = "image"; 
 /** 
 * 鏈接類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_LINK = "link"; 
 /** 
 * 地理位置類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_LOCATION = "location"; 
 /** 
 * 音頻類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_VOICE = "voice"; 
 /** 
 * 推送類(lèi)型 
 */ 
 public static final String MESSSAGE_TYPE_EVENT = "event"; 
 /** 
 * 事件類(lèi)型:subscribe(訂閱) 
 */ 
 public static final String EVENT_TYPE_SUBSCRIBE = "subscribe"; 
 /** 
 * 事件類(lèi)型:unsubscribe(取消訂閱) 
 */ 
 public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe"; 
 /** 
 * 事件類(lèi)型:click(自定義菜單點(diǎn)擊事件) 
 */ 
 public static final String EVENT_TYPE_CLICK= "CLICK"; 
 
 /** 
 * 解析微信發(fā)來(lái)的請(qǐng)求 XML 
 */ 
 @SuppressWarnings("unchecked") 
 public static Map<String,String> pareXml(HttpServletRequest request) throws Exception { 
  
 //將解析的結(jié)果存儲(chǔ)在HashMap中 
 Map<String,String> reqMap = new HashMap<String, String>(); 
  
 //從request中取得輸入流 
 InputStream inputStream = request.getInputStream(); 
 //讀取輸入流 
 SAXReader reader = new SAXReader(); 
 Document document = reader.read(inputStream); 
 //得到xml根元素 
 Element root = document.getRootElement(); 
 //得到根元素的所有子節(jié)點(diǎn) 
 List<Element> elementList = root.elements(); 
 //遍歷所有的子節(jié)點(diǎn)取得信息類(lèi)容 
 for(Element elem:elementList){ 
  reqMap.put(elem.getName(),elem.getText()); 
 } 
 //釋放資源 
 inputStream.close(); 
 inputStream = null; 
  
 return reqMap; 
 } 
 /** 
 * 響應(yīng)消息轉(zhuǎn)換成xml返回 
 * 文本對(duì)象轉(zhuǎn)換成xml 
 */ 
 public static String textMessageToXml(TextMessage textMessage) { 
 xstream.alias("xml", textMessage.getClass()); 
 return xstream.toXML(textMessage); 
 } 
 /** 
 * 語(yǔ)音對(duì)象的轉(zhuǎn)換成xml 
 * 
 */ 
 public static String voiceMessageToXml(VoiceMessage voiceMessage) { 
 xstream.alias("xml", voiceMessage.getClass()); 
 return xstream.toXML(voiceMessage); 
 } 
 
 /** 
 * 視頻對(duì)象的轉(zhuǎn)換成xml 
 * 
 */ 
 public static String videoMessageToXml(VideoMessage videoMessage) { 
 xstream.alias("xml", videoMessage.getClass()); 
 return xstream.toXML(videoMessage); 
 } 
 
 /** 
 * 音樂(lè)對(duì)象的轉(zhuǎn)換成xml 
 * 
 */ 
 public static String musicMessageToXml(MusicMessage musicMessage) { 
 xstream.alias("xml", musicMessage.getClass()); 
 return xstream.toXML(musicMessage); 
 } 
 /** 
 * 圖文對(duì)象轉(zhuǎn)換成xml 
 * 
 */ 
 public static String newsMessageToXml(NewsMessage newsMessage) { 
 xstream.alias("xml", newsMessage.getClass()); 
 xstream.alias("item", new Article().getClass()); 
 return xstream.toXML(newsMessage); 
 } 
 
 /** 
 * 圖片對(duì)象轉(zhuǎn)換成xml 
 * 
 */ 
 
 public static String imageMessageToXml(ImageMessage imageMessage) 
 { 
 xstream.alias("xml",imageMessage.getClass()); 
 return xstream.toXML(imageMessage); 
  
 } 
 
 /** 
 * 鏈接對(duì)象轉(zhuǎn)換成xml 
 * 
 */ 
 
 public static String linkMessageToXml(LinkMessage linkMessage) 
 { 
 xstream.alias("xml",linkMessage.getClass()); 
 return xstream.toXML(linkMessage); 
  
 } 
 
 /** 
 * 地理位置對(duì)象轉(zhuǎn)換成xml 
 * 
 */ 
 
 public static String locationMessageToXml(LocationMessage locationMessage) 
 { 
 xstream.alias("xml",locationMessage.getClass()); 
 return xstream.toXML(locationMessage); 
  
 } 
 
 /** 
 * 拓展xstream,使得支持CDATA塊 
 * 
 */ 
 private static XStream xstream = new XStream(new XppDriver(){ 
 public HierarchicalStreamWriter createWriter(Writer out){ 
  return new PrettyPrintWriter(out){ 
  //對(duì)所有的xml節(jié)點(diǎn)的轉(zhuǎn)換都增加CDATA標(biāo)記 
  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 WeChat ID, user account, creation time, message type, message IDVariables ), text, video, and picture messages will inherit this base class, and extend your own variables on this basis, which can be defined according to various message attributes in the developer documentation


package cn.jon.wechat.message.req; 
/** 
 * 消息基類(lèi) (普通用戶-公眾號(hào)) 
 * @author jon 
 */ 
public class BaseMessage { 
 
 //開(kāi)發(fā)者微信號(hào) 
 private String ToUserName; 
 //發(fā)送方賬號(hào)(一個(gè)openId) 
 private String FromUserName; 
 //消息創(chuàng)建時(shí)間(整型) 
 private long CreateTime; 
 //消息類(lèi)型(text/image/location/link...) 
 private String MsgType; 
 //消息id 64位整型 
 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, inherited from the base class in 5, extended content attribute


package cn.jon.wechat.message.req; 
/** 
 * 文本消息 
 * @author jon 
 */ 
public class TextMessage extends BaseMessage{ 
 //消息內(nèi)容 
 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; 
/** 
 * 圖片消息 
 * @author jon 
 */ 
public class ImageMessage extends BaseMessage{ 
 //圖片鏈接 
 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; 
 } 
 
}

The above is the detailed content of Using java to develop WeChat public account case code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome cannot open local files Google Chrome cannot open local files Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

See all articles