11package com .github .binarywang .demo .spring .controller ;
22
3+ import org .apache .commons .lang3 .StringUtils ;
34import org .slf4j .Logger ;
45import org .slf4j .LoggerFactory ;
56import org .springframework .web .bind .annotation .RequestBody ;
@@ -27,7 +28,8 @@ public abstract class AbstractWxPortalController {
2728 @ RequestParam ("timestamp" ) String timestamp ,
2829 @ RequestParam ("nonce" ) String nonce ,
2930 @ RequestParam ("echostr" ) String echostr ) {
30- this .logger .info ("接收到来自微信服务器的认证消息" );
31+ this .logger .info ("\n 接收到来自微信服务器的认证消息:[{},{},{},{}]" ,
32+ signature , timestamp , nonce , echostr );
3133
3234 if (this .getWxService ().checkSignature (timestamp , nonce , signature )) {
3335 return echostr ;
@@ -37,24 +39,40 @@ public abstract class AbstractWxPortalController {
3739 }
3840
3941 @ RequestMapping (method = RequestMethod .POST , produces = "application/xml; charset=UTF-8" )
40- public @ ResponseBody String post (@ RequestBody String requestBody ) {
41-
42- this .logger .debug ("\n 接收微信请求:{} " , requestBody );
43-
44- BaseWxService wxService = this .getWxService ();
45-
46- WxMpXmlOutMessage out = wxService
47- .route (WxMpXmlMessage .fromXml (requestBody ));
48-
49- if (out == null ) {
50- return "" ;
42+ public @ ResponseBody String post (@ RequestBody String requestBody ,
43+ @ RequestParam ("signature" ) String signature ,
44+ @ RequestParam ("encrypt_type" ) String encType ,
45+ @ RequestParam ("msg_signature" ) String msgSignature ,
46+ @ RequestParam ("timestamp" ) String timestamp ,
47+ @ RequestParam ("nonce" ) String nonce ) {
48+ this .logger .info ("\n 接收微信请求:[{},{},{},{},{}]\n {} " ,
49+ signature , encType , msgSignature , timestamp , nonce , requestBody );
50+
51+ String out = null ;
52+ if (encType == null ) {
53+ // 明文传输的消息
54+ WxMpXmlMessage inMessage = WxMpXmlMessage .fromXml (requestBody );
55+ WxMpXmlOutMessage outMessage = this .getWxService ().route (inMessage );
56+ if (outMessage == null ) {
57+ return "" ;
58+ }
59+ out = outMessage .toXml ();
60+ }else if ("aes" .equals (encType )) {
61+ // aes加密的消息
62+ WxMpXmlMessage inMessage = WxMpXmlMessage .fromEncryptedXml (requestBody ,
63+ this .getWxService ().getWxMpConfigStorage (), timestamp , nonce , msgSignature );
64+ this .logger .debug ("\n 消息解密后内容为:\n {} " , inMessage .toString ());
65+ WxMpXmlOutMessage outMessage = this .getWxService ().route (inMessage );
66+ if (outMessage == null ) {
67+ return "" ;
68+ }
69+
70+ out = outMessage .toEncryptedXml (this .getWxService ().getWxMpConfigStorage ());
5171 }
5272
53- String outXml = out .toXml ();
54-
55- this .logger .debug ("\n 组装回复信息:{}" , outXml );
73+ this .logger .debug ("\n 组装回复信息:{}" , out );
5674
57- return outXml ;
75+ return out ;
5876 }
5977
6078 protected abstract BaseWxService getWxService ();
0 commit comments