Skip to content

Commit

Permalink
update sdk to 3.3.7.B
Browse files Browse the repository at this point in the history
  • Loading branch information
binarywang committed Apr 1, 2019
1 parent d28f4af commit 608348d
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 83 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
application.yml
/.idea/
*.iml
/ngrok/
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<description>Spring Boot Demo with wechat MP</description>

<properties>
<weixin-java-mp.version>3.3.0</weixin-java-mp.version>
<weixin-java-mp.version>3.3.7.B</weixin-java-mp.version>

<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
Expand Down
Original file line number Diff line number Diff line change
@@ -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.*;

Expand Down Expand Up @@ -70,37 +60,29 @@ public WxMpConfiguration(LogHandler logHandler, NullHandler nullHandler, KfSessi
this.properties = properties;
}

public static Map<String, WxMpMessageRouter> getRouters() {
return routers;
}

public static Map<String, WxMpService> getMpServices() {
return mpServices;
}

@PostConstruct
public void initServices() {
@Bean
public WxMpService wxMpService() {
// 代码里 getConfigs()处报错的同学,请注意仔细阅读项目说明,你的IDE需要引入lombok插件!!!!
final List<WxMpProperties.MpConfig> 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);

// 记录所有事件的日志 (异步执行)
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -29,6 +24,12 @@
@RestController
@RequestMapping("/wx/menu/{appid}")
public class WxMenuController {
private WxMpService wxService;

@Autowired
public WxMenuController(WxMpService wxService) {
this.wxService = wxService;
}

/**
* <pre>
Expand All @@ -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")
Expand Down Expand Up @@ -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);
}

Expand All @@ -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);
}

/**
Expand All @@ -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
* </pre>
*
* @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);
}

/**
Expand All @@ -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();
}

/**
Expand All @@ -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);
}

/**
Expand All @@ -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();
}

/**
Expand All @@ -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);
}

/**
Expand All @@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -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,
Expand All @@ -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)) {
Expand All @@ -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("非法请求,可能属于伪造的请求!");
}
Expand All @@ -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 "";
}
Expand All @@ -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 "";
}
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 608348d

Please sign in to comment.