1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| @Slf4j @RestController @RequestMapping("/api/wx") public class WeChatController {
@Autowired private WxMpService wxService;
@Autowired private WxMpMessageRouter messageRouter;
@Autowired private SignUtil signUtil;
@GetMapping(value = "/message") public String message(@RequestParam(value = "signature") String signature, @RequestParam(value = "timestamp") String timestamp, @RequestParam(value = "nonce") String nonce, @RequestParam(value = "echostr") String echostr) {
log.info("微信校验接口:signature={},timestamp={},nonce={},echostr={}", signature, timestamp, nonce, echostr); try { if (signUtil.checkSignature(signature, timestamp, nonce)) { log.info("接口校验成功!!"); return echostr; } return null; } catch (Exception e) { log.error("微信校验失败", e); } return null; }
@PostMapping(value = "/message", produces = "application/xml; charset=UTF-8") public String message(@RequestBody String requestBody, @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestParam("openid") String openid, @RequestParam(name = "encrypt_type", required = false) String encType, @RequestParam(name = "msg_signature", required = false) String msgSignature) {
log.info("\n接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}]," + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
if (!wxService.checkSignature(timestamp, nonce, signature)) { throw new IllegalArgumentException("非法请求,可能属于伪造的请求!"); }
String out = null; if (encType == null) { WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody); WxMpXmlOutMessage outMessage = this.route(inMessage); if (outMessage == null) { return ""; }
out = outMessage.toXml(); } else if ("aes".equalsIgnoreCase(encType)) { WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature); log.debug("\n消息解密后内容为:\n{} ", inMessage.toString()); WxMpXmlOutMessage outMessage = this.route(inMessage); if (outMessage == null) { return ""; }
out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage()); }
log.debug("\n组装回复信息:{}", out); return out; }
private WxMpXmlOutMessage route(WxMpXmlMessage message) { try { return this.messageRouter.route(message); } catch (Exception e) { log.error("路由消息时出现异常!", e); }
return null; }
|