Java WeChat public platform development news management, you must first read the official documents
WeChat message management is divided into receiving ordinary messages, receiving event push, sending messages (passive reply), customer service messages, mass messages, and template messages.
1. Receive ordinary messages
When an ordinary WeChat user sends a message to a public account, the WeChat server will package the XML data packet of the POST message to the URL filled in by the developer.
Regarding MsgId, the official explanation is equivalent to each message ID. Regarding the retry message weight, it is recommended to use msgid to queue. If the WeChat server fails to receive a response within five seconds, it will disconnect and re-initiate a request, and retry three times in total.
For example, the Xml example of text message
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[this is a test]]></Content> <MsgId>1234567890123456</MsgId> </xml>
Check other messages in the official document, and simply encapsulate the following message abstract base class AbstractMsg.java
package com.phil.wechat.msg.model.req; import java.io.Serializable; /** * Basic message class* * @author phil * */ public abstract class AbstractMsg implements Serializable { private static final long serialVersionUID = -6244277633057415731L; private String ToUserName; // Developer WeChat ID private String FromUserName; // Sender account (OpenID) private String MsgType = SetMsgType(); // Message type, for example /text/image private long CreateTime; // Message creation time (integer) private long MsgId; // Message id, 64-bit integer/** * Message type* * @return */ public abstract String SetMsgType(); }Text Message TextMsg.java
package com.phil.wechat.msg.model.req; /** * Text message* @author phil * @date June 30, 2017* */ public class TextMsg extends AbstractMsg { private static final long serialVersionUID = -1764016801417503409L; private String Content; // Text message @Override public String SetMsgType() { return "text"; } }Others are like this...
2. Passively reply to user messages
After the WeChat server sends the user's message to the developer server address (configured at the developer center) of the official account, the WeChat server will disconnect if it fails to receive the response within five seconds and initiate a request again, and try three times in total. If during debugging, it is found that the user cannot receive the response message, you can check whether the message processing timed out. If the server cannot guarantee that it will process and reply within five seconds, it can directly reply to the empty string. The WeChat server will not handle this and will not initiate a retry.
If "This official account cannot provide services for the time being, please try again later", there are two reasons for this.
For example, the reply text message Xml example
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[Hello]]></Content> </xml>
In simple package
Reply message abstract base class RespAbstractMsg.java
package com.phil.wechat.msg.model.resp; import java.io.Serializable; /** * Message base class (public account-> ordinary user) * * @author phil * */ public abstract class RespAbstractMsg{ // Receiver account (received OpenID) private String ToUserName; // Developer WeChat ID private String FromUserName; // Message creation time (integral) private long CreateTime; // Message type (text/music/news) private String MsgType = setMsgType(); // Message type public abstract String setMsgType(); } Reply text message RespTextMsg.java
package com.phil.wechat.msg.model.resp; /** * Reply to image messages* * @author phil * @data March 26, 2017* */ public class RespImageMsg extends RespAbstractMsg { private Image Image; @Override public String setMsgType() { return "image"; } /** * * @author phil * @date July 19, 2017* */ public class Image { // Upload multimedia files through the interface in material management to obtain the id. private String MediaId; public String getMediaId() { return MediaId; } public void setMediaId(String mediaId) { MediaId = mediaId; } } } Other message types are as follows...
3. Message processing
Master xml parsing
package com.phil.wechat.msg.controller; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.dom4j.DocumentException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.phil.modules.config.WechatConfig; import com.phil.modules.util.MsgUtil; import com.phil.modules.util.SignatureUtil; import com.phil.modules.util.XmlUtil; import com.phil.wechat.base.controller.BaseController; import com.phil.wechat.base.result.WechatResult; import com.phil.wechat.msg.model.req.BasicMsg; import com.phil.wechat.msg.model.resp.RespAbstractMsg; import com.phil.wechat.msg.model.resp.RespNewsMsg; import com.phil.wechat.msg.model.resp.RespNewsMsg; import com.phil.wechat.msg.service.WechatMsgService; /** * @author phil * @date September 19, 2017* */ @Controller @RequestMapping("/wechat") public class WeChatMsgController extends BaseController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private WechatMsgService wechatMsgService; /** * Verify whether the information is sent from the WeChat server and process the message* @param out * @throws IOException */ @RequestMapping(value = "/handler", method = { RequestMethod.GET, RequestMethod.POST }) public void processPost() throws Exception { this.getRequest().setCharacterEncoding("UTF-8"); this.getResponse().setCharacterEncoding("UTF-8"); boolean ispost = Objects.equals("POST", this.getRequest().getMethod().toUpperCase()); if (ispost) { logger.debug("Access is successful, logic is being processed"); String respXml = defaultMsgDisPose(this.getRequest().getInputStream());//processRequest(request, response); if (StringUtils.isNotBlank(respXml)) { this.getResponse().getWriter().write(respXml); } } else { String signature = this.getRequest().getParameter("signature"); // Timestamp String timestamp = this.getRequest().getParameter("timestamp"); // Random number String nonce = this.getRequest().getParameter("nonce"); // Verify the request by checking the signature. If the verification is successful, return echostr as is, indicating that the access is successful. Otherwise, the access fails if (SignatureUtil.checkSignature(signature, timestamp, nonce)) { // Random string String echostr = this.getRequest().getParameter("echostr"); logger.debug("Enter successful, echostr {}", echostr); this.getResponse().getWriter().write(echostr); } } } /** * Default processing method* @param input * @return * @throws Exception * @throws DocumentException */ private String defaultMsgDisPose(InputStream inputStream) throws Exception { String result = null; if (inputStream != null) { Map<String, String> params = XmlUtil.parseStreamToMap(inputStream); if (params != null && params.size() > 0) { BasicMsg msgInfo = new BasicMsg(); String createTime = params.get("CreateTime"); String msgId = params.get("MsgId"); msgInfo.setCreateTime((createTime != null && !"".equals(createTime)) ? Integer.parseInt(createTime) : 0); msgInfo.setFromUserName(params.get("FromUserName")); msgInfo.setMsgId((msgId != null && !"".equals(msgId)) ? Long.parseLong(msgId) : 0); msgInfo.setToUserName(params.get("ToUserName")); WechatResult resultObj = coreHandler(msgInfo, params); if(resultObj == null){ // return null; } boolean success = resultObj.isSuccess(); // If true, it means that the xml file is returned, and it can be converted directly, otherwise according to type if (success) { result = resultObj.getObject().toString(); } else { int type = resultObj.getType(); // 1 graphic message is specified here, otherwise it will be converted directly if (type == WechatResult.NEWSMSG) { RespNewsMsg newsMsg = (RespNewsMsg) resultObj.getObject(); result = MsgUtil.newsMsgToXml(newsMsg); } else { RespAbstractMsg basicMsg = (RespAbstractMsg) resultObj.getObject(); result = MsgUtil.msgToXml(basicMsg); } } else { result = "msg is wrong"; } } return result; } /** * Core processing* * @param msg * Message base class* @param params * xml parsed data* @return */ private WechatResult coreHandler(BasicMsg msg, Map<String, String> params) { WechatResult result = null; String msgType = params.get("MsgType"); if (StringUtils.isEmpty(msgType)) { switch (msgType) { case WechatConfig.REQ_MESSAGE_TYPE_TEXT: // Text message result = wechatMsgService.textMsg(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_IMAGE: // Image message result = wechatMsgService.imageMsg(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_LINK: // Link message result = wechatMsgService.linkMsg(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_LOCATION: // Geographic location result = wechatMsgService.locationMsg(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_VOICE: // Audio message result = wechatMsgService.voiceMsg(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_SHORTVIDEO: // Short video message result = wechatMsgService.shortvideo(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_VIDEO: // Video message result = wechatMsgService.shortvideo(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_VIDEO: // Video message result = wechatMsgService.videoMsg(msg, params); break; case WechatConfig.REQ_MESSAGE_TYPE_EVENT: // Event message String eventType = params.get("Event"); // if (eventType != null && !"".equals(eventType)) { switch (eventType) { case WechatConfig.EVENT_TYPE_SUBSCRIBE: result = wechatMsgService.subscribe(msg, params); break; case WechatConfig.EVENT_TYPE_UNSUBSCRIBE: result = wechatMsgService.unsubscribe(msg, params); break; case WechatConfig.EVENT_TYPE_SCAN: result = wechatMsgService.scan(msg, params); break; case WechatConfig.EVENT_TYPE_LOCATION: result = wechatMsgService.eventLocation(msg, params); break; case WechatConfig.EVENT_TYPE_CLICK: result = wechatMsgService.eventClick(msg, params); break; case WechatConfig.EVENT_TYPE_VIEW: result = wechatMsgService.eventView(msg, params); break; case WechatConfig.KF_CREATE_SESSION: result = wechatMsgService.kfCreateSession(msg, params); break; case WechatConfig.KF_CLOSE_SESSION: result = wechatMsgService.kfCloseSession(msg, params); break; case WechatConfig.KF_CLOSE_SESSION: result = wechatMsgService.kfCloseSession(msg, params); break; case WechatConfig.KF_SWITCH_SESSION: result = wechatMsgService.kfSwitchSession(msg, params); break; default: wechatMsgService.eventDefaultReply(msg, params); break; } } break; default: wechatMsgService.defaultMsg(msg, params); } } return result; } }Just provide an idea, please move if you refer to the code
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.