From 608348da25abdf0625a9e217f5a3e346cf94655b Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Mon, 1 Apr 2019 11:57:49 +0800 Subject: [PATCH] update sdk to 3.3.7.B --- .gitignore | 1 + pom.xml | 2 +- .../demo/wx/mp/config/WxMpConfiguration.java | 66 +++++++------------ .../wx/mp/controller/WxMenuController.java | 54 +++++++-------- .../wx/mp/controller/WxPortalController.java | 31 ++++++--- .../mp/controller/WxRedirectController.java | 17 +++-- 6 files changed, 88 insertions(+), 83 deletions(-) diff --git a/.gitignore b/.gitignore index b0af5bd..03117d0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ application.yml /.idea/ *.iml +/ngrok/ diff --git a/pom.xml b/pom.xml index f7eb974..3ff3a1d 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ Spring Boot Demo with wechat MP - 3.3.0 + 3.3.7.B 1.8 1.8 diff --git a/src/main/java/com/github/binarywang/demo/wx/mp/config/WxMpConfiguration.java b/src/main/java/com/github/binarywang/demo/wx/mp/config/WxMpConfiguration.java index e4bb178..ae56d72 100644 --- a/src/main/java/com/github/binarywang/demo/wx/mp/config/WxMpConfiguration.java +++ b/src/main/java/com/github/binarywang/demo/wx/mp/config/WxMpConfiguration.java @@ -1,30 +1,20 @@ package com.github.binarywang.demo.wx.mp.config; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -import com.github.binarywang.demo.wx.mp.handler.KfSessionHandler; -import com.github.binarywang.demo.wx.mp.handler.LocationHandler; -import com.github.binarywang.demo.wx.mp.handler.LogHandler; -import com.github.binarywang.demo.wx.mp.handler.MenuHandler; -import com.github.binarywang.demo.wx.mp.handler.MsgHandler; -import com.github.binarywang.demo.wx.mp.handler.NullHandler; -import com.github.binarywang.demo.wx.mp.handler.ScanHandler; -import com.github.binarywang.demo.wx.mp.handler.StoreCheckNotifyHandler; -import com.github.binarywang.demo.wx.mp.handler.SubscribeHandler; -import com.github.binarywang.demo.wx.mp.handler.UnsubscribeHandler; +import com.github.binarywang.demo.wx.mp.handler.*; import com.google.common.collect.Maps; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import me.chanjar.weixin.mp.api.WxMpMessageRouter; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import me.chanjar.weixin.mp.constant.WxMpEventConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import static me.chanjar.weixin.common.api.WxConsts.*; @@ -70,37 +60,29 @@ public WxMpConfiguration(LogHandler logHandler, NullHandler nullHandler, KfSessi this.properties = properties; } - public static Map getRouters() { - return routers; - } - - public static Map getMpServices() { - return mpServices; - } - - @PostConstruct - public void initServices() { + @Bean + public WxMpService wxMpService() { // 代码里 getConfigs()处报错的同学,请注意仔细阅读项目说明,你的IDE需要引入lombok插件!!!! final List configs = this.properties.getConfigs(); if (configs == null) { throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!"); } - mpServices = configs.stream().map(a -> { - WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage(); - configStorage.setAppId(a.getAppId()); - configStorage.setSecret(a.getSecret()); - configStorage.setToken(a.getToken()); - configStorage.setAesKey(a.getAesKey()); - - WxMpService service = new WxMpServiceImpl(); - service.setWxMpConfigStorage(configStorage); - routers.put(a.getAppId(), this.newRouter(service)); - return service; - }).collect(Collectors.toMap(s -> s.getWxMpConfigStorage().getAppId(), a -> a, (o, n) -> o)); + WxMpService service = new WxMpServiceImpl(); + service.setMultiConfigStorages(configs + .stream().map(a -> { + WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage(); + configStorage.setAppId(a.getAppId()); + configStorage.setSecret(a.getSecret()); + configStorage.setToken(a.getToken()); + configStorage.setAesKey(a.getAesKey()); + return configStorage; + }).collect(Collectors.toMap(WxMpInMemoryConfigStorage::getAppId, a -> a, (o, n) -> o))); + return service; } - private WxMpMessageRouter newRouter(WxMpService wxMpService) { + @Bean + public WxMpMessageRouter messageRouter(WxMpService wxMpService) { final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService); // 记录所有事件的日志 (异步执行) diff --git a/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxMenuController.java b/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxMenuController.java index d76050d..ef5677c 100644 --- a/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxMenuController.java +++ b/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxMenuController.java @@ -1,25 +1,20 @@ package com.github.binarywang.demo.wx.mp.controller; -import java.net.MalformedURLException; -import java.net.URL; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import com.github.binarywang.demo.wx.mp.config.WxMpConfiguration; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.menu.WxMpGetSelfMenuInfoResult; import me.chanjar.weixin.mp.bean.menu.WxMpMenu; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.net.MalformedURLException; +import java.net.URL; import static me.chanjar.weixin.common.api.WxConsts.MenuButtonType; @@ -29,6 +24,12 @@ @RestController @RequestMapping("/wx/menu/{appid}") public class WxMenuController { + private WxMpService wxService; + + @Autowired + public WxMenuController(WxMpService wxService) { + this.wxService = wxService; + } /** *
@@ -42,7 +43,7 @@ public class WxMenuController {
      */
     @PostMapping("/create")
     public String menuCreate(@PathVariable String appid, @RequestBody WxMenu menu) throws WxErrorException {
-        return WxMpConfiguration.getMpServices().get(appid).getMenuService().menuCreate(menu);
+        return this.wxService.switchover1(appid).getMenuService().menuCreate(menu);
     }
 
     @GetMapping("/create")
@@ -91,10 +92,9 @@ public String menuCreateSample(@PathVariable String appid) throws WxErrorExcepti
         if (servletRequestAttributes != null) {
             HttpServletRequest request = servletRequestAttributes.getRequest();
             URL requestURL = new URL(request.getRequestURL().toString());
-            String url = WxMpConfiguration.getMpServices().get(appid)
-                .oauth2buildAuthorizationUrl(
-                    String.format("%s://%s/wx/redirect/%s/greet", requestURL.getProtocol(), requestURL.getHost(), appid),
-                    WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
+            String url = this.wxService.switchover1(appid).oauth2buildAuthorizationUrl(
+                String.format("%s://%s/wx/redirect/%s/greet", requestURL.getProtocol(), requestURL.getHost(), appid),
+                WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
             button34.setUrl(url);
         }
 
@@ -103,7 +103,8 @@ public String menuCreateSample(@PathVariable String appid) throws WxErrorExcepti
         button3.getSubButtons().add(button33);
         button3.getSubButtons().add(button34);
 
-        return WxMpConfiguration.getMpServices().get(appid).getMenuService().menuCreate(menu);
+        this.wxService.switchover(appid);
+        return this.wxService.getMenuService().menuCreate(menu);
     }
 
     /**
@@ -114,12 +115,11 @@ public String menuCreateSample(@PathVariable String appid) throws WxErrorExcepti
      * 详情请见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN
      * 
* - * @param json * @return 如果是个性化菜单,则返回menuid,否则返回null */ @PostMapping("/createByJson") public String menuCreate(@PathVariable String appid, @RequestBody String json) throws WxErrorException { - return WxMpConfiguration.getMpServices().get(appid).getMenuService().menuCreate(json); + return this.wxService.switchover1(appid).getMenuService().menuCreate(json); } /** @@ -130,7 +130,7 @@ public String menuCreate(@PathVariable String appid, @RequestBody String json) t */ @GetMapping("/delete") public void menuDelete(@PathVariable String appid) throws WxErrorException { - WxMpConfiguration.getMpServices().get(appid).getMenuService().menuDelete(); + this.wxService.switchover1(appid).getMenuService().menuDelete(); } /** @@ -143,7 +143,7 @@ public void menuDelete(@PathVariable String appid) throws WxErrorException { */ @GetMapping("/delete/{menuId}") public void menuDelete(@PathVariable String appid, @PathVariable String menuId) throws WxErrorException { - WxMpConfiguration.getMpServices().get(appid).getMenuService().menuDelete(menuId); + this.wxService.switchover1(appid).getMenuService().menuDelete(menuId); } /** @@ -154,7 +154,7 @@ public void menuDelete(@PathVariable String appid, @PathVariable String menuId) */ @GetMapping("/get") public WxMpMenu menuGet(@PathVariable String appid) throws WxErrorException { - return WxMpConfiguration.getMpServices().get(appid).getMenuService().menuGet(); + return this.wxService.switchover1(appid).getMenuService().menuGet(); } /** @@ -167,7 +167,7 @@ public WxMpMenu menuGet(@PathVariable String appid) throws WxErrorException { */ @GetMapping("/menuTryMatch/{userid}") public WxMenu menuTryMatch(@PathVariable String appid, @PathVariable String userid) throws WxErrorException { - return WxMpConfiguration.getMpServices().get(appid).getMenuService().menuTryMatch(userid); + return this.wxService.switchover1(appid).getMenuService().menuTryMatch(userid); } /** @@ -187,6 +187,6 @@ public WxMenu menuTryMatch(@PathVariable String appid, @PathVariable String user */ @GetMapping("/getSelfMenuInfo") public WxMpGetSelfMenuInfoResult getSelfMenuInfo(@PathVariable String appid) throws WxErrorException { - return WxMpConfiguration.getMpServices().get(appid).getMenuService().getSelfMenuInfo(); + return this.wxService.switchover1(appid).getMenuService().getSelfMenuInfo(); } } diff --git a/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxPortalController.java b/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxPortalController.java index f349ee7..fad2d14 100644 --- a/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxPortalController.java +++ b/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxPortalController.java @@ -1,8 +1,10 @@ package com.github.binarywang.demo.wx.mp.controller; +import me.chanjar.weixin.mp.api.WxMpMessageRouter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -11,7 +13,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.github.binarywang.demo.wx.mp.config.WxMpConfiguration; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; @@ -24,6 +25,16 @@ public class WxPortalController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private WxMpService wxService; + + private WxMpMessageRouter messageRouter; + + @Autowired + public WxPortalController(WxMpService wxService, WxMpMessageRouter messageRouter) { + this.wxService = wxService; + this.messageRouter = messageRouter; + } + @GetMapping(produces = "text/plain;charset=utf-8") public String authGet(@PathVariable String appid, @RequestParam(name = "signature", required = false) String signature, @@ -37,9 +48,8 @@ public String authGet(@PathVariable String appid, throw new IllegalArgumentException("请求参数非法,请核实!"); } - final WxMpService wxService = WxMpConfiguration.getMpServices().get(appid); - if (wxService == null) { - throw new IllegalArgumentException(String.format("未找到对应appid=[%d]的配置,请核实!", appid)); + if (!this.wxService.switchover(appid)) { + throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); } if (wxService.checkSignature(timestamp, nonce, signature)) { @@ -58,11 +68,14 @@ public String post(@PathVariable String appid, @RequestParam("openid") String openid, @RequestParam(name = "encrypt_type", required = false) String encType, @RequestParam(name = "msg_signature", required = false) String msgSignature) { - final WxMpService wxService = WxMpConfiguration.getMpServices().get(appid); this.logger.info("\n接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}]," + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", openid, signature, encType, msgSignature, timestamp, nonce, requestBody); + if (!this.wxService.switchover(appid)) { + throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); + } + if (!wxService.checkSignature(timestamp, nonce, signature)) { throw new IllegalArgumentException("非法请求,可能属于伪造的请求!"); } @@ -71,7 +84,7 @@ public String post(@PathVariable String appid, if (encType == null) { // 明文传输的消息 WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody); - WxMpXmlOutMessage outMessage = this.route(inMessage, appid); + WxMpXmlOutMessage outMessage = this.route(inMessage); if (outMessage == null) { return ""; } @@ -82,7 +95,7 @@ public String post(@PathVariable String appid, WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature); this.logger.debug("\n消息解密后内容为:\n{} ", inMessage.toString()); - WxMpXmlOutMessage outMessage = this.route(inMessage, appid); + WxMpXmlOutMessage outMessage = this.route(inMessage); if (outMessage == null) { return ""; } @@ -94,9 +107,9 @@ public String post(@PathVariable String appid, return out; } - private WxMpXmlOutMessage route(WxMpXmlMessage message, String appid) { + private WxMpXmlOutMessage route(WxMpXmlMessage message) { try { - return WxMpConfiguration.getRouters().get(appid).route(message); + return this.messageRouter.route(message); } catch (Exception e) { this.logger.error("路由消息时出现异常!", e); } diff --git a/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxRedirectController.java b/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxRedirectController.java index 0c48baa..fa4e914 100644 --- a/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxRedirectController.java +++ b/src/main/java/com/github/binarywang/demo/wx/mp/controller/WxRedirectController.java @@ -5,28 +5,37 @@ import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import me.chanjar.weixin.mp.bean.result.WxMpUser; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import javax.xml.ws.Action; + /** * @author Edward */ @Controller @RequestMapping("/wx/redirect/{appid}") public class WxRedirectController { + private WxMpService wxService; + @Autowired + public WxRedirectController(WxMpService wxService) { + this.wxService = wxService; + } @RequestMapping("/greet") public String greetUser(@PathVariable String appid, @RequestParam String code, ModelMap map) { - - WxMpService mpService = WxMpConfiguration.getMpServices().get(appid); + if (!this.wxService.switchover(appid)) { + throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); + } try { - WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code); - WxMpUser user = mpService.oauth2getUserInfo(accessToken, null); + WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code); + WxMpUser user = wxService.oauth2getUserInfo(accessToken, null); map.put("user", user); } catch (WxErrorException e) { e.printStackTrace();