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
| @Api(tags = "企业微信-回调接口服务") @RestController @RequestMapping("/callback/{agentId}") public class WxCallBackController { private final Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping(produces = "text/plain;charset=utf-8") public String authGet(@PathVariable Integer agentId, @RequestParam(name = "msg_signature", required = false) String signature, @RequestParam(name = "timestamp", required = false) String timestamp, @RequestParam(name = "nonce", required = false) String nonce, @RequestParam(name = "echostr", required = false) String echostr) { this.logger.info("\n接收到来自微信服务器的认证消息:signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]", signature, timestamp, nonce, echostr);
if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) { throw new IllegalArgumentException("请求参数非法,请核实!"); }
final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId); if (wxCpService == null) { throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置", agentId)); }
if (wxCpService.checkSignature(signature, timestamp, nonce, echostr)) { return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr); }
return "非法请求"; }
@PostMapping(produces = "application/xml; charset=UTF-8") public String post(@PathVariable Integer agentId, @RequestBody String requestBody, @RequestParam("msg_signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) { this.logger.info("\n接收微信请求:[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", signature, timestamp, nonce, requestBody);
final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId); WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(), timestamp, nonce, signature); this.logger.debug("\n消息解密内容为:\n{} ", JSONObject.toJSONString(inMessage)); WxCpXmlOutMessage outMessage = this.route(agentId, inMessage); if (outMessage == null) { return ""; }
String out = outMessage.toEncryptedXml(wxCpService.getWxCpConfigStorage()); this.logger.debug("\n回复信息:{}", out); return out; }
private WxCpXmlOutMessage route(Integer agentId, WxCpXmlMessage message) { try { return WxCpConfiguration.getRouters().get(agentId).route(message); } catch (Exception e) { this.logger.error(e.getMessage(), e); }
return null; }
}
|