forked from chanjarster/weixin-java-tools
-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
MP_同步回复消息
Binary Wang edited this page Nov 9, 2023
·
4 revisions
WxMessageRouter
默认使用异步的方式处理消息,如果要使用同步回复微信消息,那么:
- 需要将路由规则配置为同步
- 且handler需要返回一个
WxMpXmlOutMessage
// 将WxXmlMessage交给消息路由器
HttpServletRequest request = ...;
WxXmlMessage inMsg = ...;
WxMpXmlOutMessage reMsg = router.route(inMsg);
if (reMsg != null) {
// 说明是同步回复的消息
// 将xml写入HttpServletResponse
response.setCharacterEncoding("UTF-8");
response.getWriter().write(reMsg.toXml());
} else {
// 说明是异步回复的消息,直接将空字符串写入HttpServletResponse
}
WxMpXmlOutTextMessage
是同步回复给微信消息的对象,不同类型的消息类型可以用不同的方式构造:
WxMpXmlOutMessage.TEXT()
.content("content")
.fromUser("to")
.toUser("from")
.build();
WxMpXmlOutMessage.IMAGE()
.mediaId("ddfefesfsdfef")
.fromUser("to")
.toUser("from")
.build();
WxMpXmlOutMessage.VOICE()
.mediaId("ddfefesfsdfef")
.fromUser("to")
.toUser("from")
.build();
WxMpXmlOutMessage.VIDEO()
.mediaId("media_id")
.fromUser("toUser")
.toUser("fromUser")
.title("title")
.description("ddfff")
.build();
WxMpXmlOutMessage.MUSIC()
.fromUser("toUser")
.toUser("fromUser")
.title("title")
.description("ddfff")
.hqMusicUrl("hQMusicUrl")
.musicUrl("musicUrl")
.thumbMediaId("thumbMediaId")
.build();
WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
item.setDescription("description");
item.setPicUrl("picUrl");
item.setTitle("title");
item.setUrl("url");
WxMpXmlOutNewsMessage m = WxMpXmlOutMessage.NEWS()
.fromUser("toUser")
.toUser("fromUser")
.addArticle(item)
.build();
String encType = request.getParameter("encrypt_type");
String nonce = request.getParameter("nonce");
String timestamp = request.getParameter("timestamp");
String msgSignature = request.getParameter("msg_signature");
String signature = request.getParameter("signature");
String openid = request.getParameter("openid");
log.info("接收微信请求:[openid=[{}], [openid=[{}],[signature=[{}], encType=[{}], msgSignature=[{}],"
+ " timestamp=[{}], nonce=[{}], requestBody=[{}] ",
appid, openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
// 请求里面没有对应信息。 // if (!this.wxMpService.switchover(appid)) { //appid // throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); // }
if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
throw new IllegalArgumentException("非法请求,可能属于伪造的请求!");
}
return ResponseEntity.ok("");