Skip to content

Commit 63ef885

Browse files
authored
Merge pull request #58 from nadirvishun/master
修改为支持多账号的形式
2 parents c3ef16b + 507b580 commit 63ef885

File tree

4 files changed

+115
-109
lines changed

4 files changed

+115
-109
lines changed

src/main/java/com/github/binarywang/demo/wx/miniapp/config/WxMaConfiguration.java

Lines changed: 20 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,18 @@
99
import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
1010
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
1111
import com.google.common.collect.Lists;
12-
import com.google.common.collect.Maps;
1312
import lombok.extern.slf4j.Slf4j;
1413
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
1514
import me.chanjar.weixin.common.error.WxErrorException;
1615
import me.chanjar.weixin.common.error.WxRuntimeException;
1716
import org.springframework.beans.factory.annotation.Autowired;
1817
import org.springframework.boot.context.properties.EnableConfigurationProperties;
18+
import org.springframework.context.annotation.Bean;
1919
import org.springframework.context.annotation.Configuration;
2020
import redis.clients.jedis.JedisPool;
2121

22-
import javax.annotation.PostConstruct;
2322
import java.io.File;
2423
import java.util.List;
25-
import java.util.Map;
2624
import java.util.stream.Collectors;
2725

2826
/**
@@ -34,54 +32,37 @@
3432
public class WxMaConfiguration {
3533
private final WxMaProperties properties;
3634

37-
private static final Map<String, WxMaMessageRouter> routers = Maps.newHashMap();
38-
private static Map<String, WxMaService> maServices;
39-
4035
@Autowired
4136
public WxMaConfiguration(WxMaProperties properties) {
4237
this.properties = properties;
4338
}
4439

45-
public static WxMaService getMaService(String appid) {
46-
WxMaService wxService = maServices.get(appid);
47-
if (wxService == null) {
48-
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
49-
}
50-
51-
return wxService;
52-
}
53-
54-
public static WxMaMessageRouter getRouter(String appid) {
55-
return routers.get(appid);
56-
}
57-
58-
@PostConstruct
59-
public void init() {
40+
@Bean
41+
public WxMaService wxMaService() {
6042
List<WxMaProperties.Config> configs = this.properties.getConfigs();
6143
if (configs == null) {
6244
throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
6345
}
64-
65-
maServices = configs.stream()
66-
.map(a -> {
67-
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
46+
WxMaService maService = new WxMaServiceImpl();
47+
maService.setMultiConfigs(
48+
configs.stream()
49+
.map(a -> {
50+
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
6851
// WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
69-
// 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常
70-
config.setAppid(a.getAppid());
71-
config.setSecret(a.getSecret());
72-
config.setToken(a.getToken());
73-
config.setAesKey(a.getAesKey());
74-
config.setMsgDataFormat(a.getMsgDataFormat());
75-
76-
WxMaService service = new WxMaServiceImpl();
77-
service.setWxMaConfig(config);
78-
routers.put(a.getAppid(), this.newRouter(service));
79-
return service;
80-
}).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
52+
// 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常
53+
config.setAppid(a.getAppid());
54+
config.setSecret(a.getSecret());
55+
config.setToken(a.getToken());
56+
config.setAesKey(a.getAesKey());
57+
config.setMsgDataFormat(a.getMsgDataFormat());
58+
return config;
59+
}).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
60+
return maService;
8161
}
8262

83-
private WxMaMessageRouter newRouter(WxMaService service) {
84-
final WxMaMessageRouter router = new WxMaMessageRouter(service);
63+
@Bean
64+
public WxMaMessageRouter wxMaMessageRouter(WxMaService wxMaService) {
65+
final WxMaMessageRouter router = new WxMaMessageRouter(wxMaService);
8566
router
8667
.rule().handler(logHandler).next()
8768
.rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end()
Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,24 @@
11
package com.github.binarywang.demo.wx.miniapp.controller;
22

3-
import java.io.File;
4-
import java.io.IOException;
5-
import java.util.Iterator;
6-
import java.util.List;
7-
import javax.servlet.http.HttpServletRequest;
8-
9-
import org.slf4j.Logger;
10-
import org.slf4j.LoggerFactory;
11-
import org.springframework.web.bind.annotation.GetMapping;
12-
import org.springframework.web.bind.annotation.PathVariable;
13-
import org.springframework.web.bind.annotation.PostMapping;
14-
import org.springframework.web.bind.annotation.RequestMapping;
15-
import org.springframework.web.bind.annotation.RestController;
16-
import org.springframework.web.multipart.MultipartFile;
17-
import org.springframework.web.multipart.MultipartHttpServletRequest;
18-
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
19-
203
import cn.binarywang.wx.miniapp.api.WxMaService;
214
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
22-
import com.github.binarywang.demo.wx.miniapp.config.WxMaConfiguration;
5+
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
236
import com.google.common.collect.Lists;
247
import com.google.common.io.Files;
8+
import lombok.AllArgsConstructor;
9+
import lombok.extern.slf4j.Slf4j;
2510
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
2611
import me.chanjar.weixin.common.error.WxErrorException;
12+
import org.springframework.web.bind.annotation.*;
13+
import org.springframework.web.multipart.MultipartFile;
14+
import org.springframework.web.multipart.MultipartHttpServletRequest;
15+
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
16+
17+
import javax.servlet.http.HttpServletRequest;
18+
import java.io.File;
19+
import java.io.IOException;
20+
import java.util.Iterator;
21+
import java.util.List;
2722

2823
/**
2924
* <pre>
@@ -34,9 +29,11 @@
3429
* @author <a href="https://github.com/binarywang">Binary Wang</a>
3530
*/
3631
@RestController
32+
@AllArgsConstructor
33+
@Slf4j
3734
@RequestMapping("/wx/media/{appid}")
3835
public class WxMaMediaController {
39-
private final Logger logger = LoggerFactory.getLogger(this.getClass());
36+
private final WxMaService wxMaService;
4037

4138
/**
4239
* 上传临时素材
@@ -45,11 +42,14 @@ public class WxMaMediaController {
4542
*/
4643
@PostMapping("/upload")
4744
public List<String> uploadMedia(@PathVariable String appid, HttpServletRequest request) throws WxErrorException {
48-
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
45+
if (!wxMaService.switchover(appid)) {
46+
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
47+
}
4948

5049
CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
5150

5251
if (!resolver.isMultipart(request)) {
52+
WxMaConfigHolder.remove();//清理ThreadLocal
5353
return Lists.newArrayList();
5454
}
5555

@@ -60,16 +60,16 @@ public List<String> uploadMedia(@PathVariable String appid, HttpServletRequest r
6060
try {
6161
MultipartFile file = multiRequest.getFile(it.next());
6262
File newFile = new File(Files.createTempDir(), file.getOriginalFilename());
63-
this.logger.info("filePath is :" + newFile.toString());
63+
log.info("filePath is :" + newFile.toString());
6464
file.transferTo(newFile);
65-
WxMediaUploadResult uploadResult = wxService.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, newFile);
66-
this.logger.info("media_id : " + uploadResult.getMediaId());
65+
WxMediaUploadResult uploadResult = wxMaService.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, newFile);
66+
log.info("media_id : " + uploadResult.getMediaId());
6767
result.add(uploadResult.getMediaId());
6868
} catch (IOException e) {
69-
this.logger.error(e.getMessage(), e);
69+
log.error(e.getMessage(), e);
7070
}
7171
}
72-
72+
WxMaConfigHolder.remove();//清理ThreadLocal
7373
return result;
7474
}
7575

@@ -78,8 +78,11 @@ public List<String> uploadMedia(@PathVariable String appid, HttpServletRequest r
7878
*/
7979
@GetMapping("/download/{mediaId}")
8080
public File getMedia(@PathVariable String appid, @PathVariable String mediaId) throws WxErrorException {
81-
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
82-
83-
return wxService.getMediaService().getMedia(mediaId);
81+
if (!wxMaService.switchover(appid)) {
82+
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
83+
}
84+
File media = wxMaService.getMediaService().getMedia(mediaId);
85+
WxMaConfigHolder.remove();//清理ThreadLocal
86+
return media;
8487
}
8588
}

src/main/java/com/github/binarywang/demo/wx/miniapp/controller/WxMaUserController.java

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,31 @@
11
package com.github.binarywang.demo.wx.miniapp.controller;
22

3-
import org.apache.commons.lang3.StringUtils;
4-
import org.slf4j.Logger;
5-
import org.slf4j.LoggerFactory;
6-
import org.springframework.web.bind.annotation.GetMapping;
7-
import org.springframework.web.bind.annotation.PathVariable;
8-
import org.springframework.web.bind.annotation.RequestMapping;
9-
import org.springframework.web.bind.annotation.RestController;
10-
113
import cn.binarywang.wx.miniapp.api.WxMaService;
124
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
135
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
146
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
15-
import com.github.binarywang.demo.wx.miniapp.config.WxMaConfiguration;
7+
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
168
import com.github.binarywang.demo.wx.miniapp.utils.JsonUtils;
9+
import lombok.AllArgsConstructor;
10+
import lombok.extern.slf4j.Slf4j;
1711
import me.chanjar.weixin.common.error.WxErrorException;
12+
import org.apache.commons.lang3.StringUtils;
13+
import org.springframework.web.bind.annotation.GetMapping;
14+
import org.springframework.web.bind.annotation.PathVariable;
15+
import org.springframework.web.bind.annotation.RequestMapping;
16+
import org.springframework.web.bind.annotation.RestController;
1817

1918
/**
2019
* 微信小程序用户接口
2120
*
2221
* @author <a href="https://github.com/binarywang">Binary Wang</a>
2322
*/
2423
@RestController
24+
@AllArgsConstructor
25+
@Slf4j
2526
@RequestMapping("/wx/user/{appid}")
2627
public class WxMaUserController {
27-
private final Logger logger = LoggerFactory.getLogger(this.getClass());
28+
private final WxMaService wxMaService;
2829

2930
/**
3031
* 登陆接口
@@ -35,17 +36,21 @@ public String login(@PathVariable String appid, String code) {
3536
return "empty jscode";
3637
}
3738

38-
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
39+
if (!wxMaService.switchover(appid)) {
40+
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
41+
}
3942

4043
try {
41-
WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
42-
this.logger.info(session.getSessionKey());
43-
this.logger.info(session.getOpenid());
44+
WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
45+
log.info(session.getSessionKey());
46+
log.info(session.getOpenid());
4447
//TODO 可以增加自己的逻辑,关联业务相关数据
4548
return JsonUtils.toJson(session);
4649
} catch (WxErrorException e) {
47-
this.logger.error(e.getMessage(), e);
50+
log.error(e.getMessage(), e);
4851
return e.toString();
52+
} finally {
53+
WxMaConfigHolder.remove();//清理ThreadLocal
4954
}
5055
}
5156

@@ -57,16 +62,19 @@ public String login(@PathVariable String appid, String code) {
5762
@GetMapping("/info")
5863
public String info(@PathVariable String appid, String sessionKey,
5964
String signature, String rawData, String encryptedData, String iv) {
60-
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
65+
if (!wxMaService.switchover(appid)) {
66+
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
67+
}
6168

6269
// 用户信息校验
63-
if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
70+
if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
71+
WxMaConfigHolder.remove();//清理ThreadLocal
6472
return "user check failed";
6573
}
6674

6775
// 解密用户信息
68-
WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
69-
76+
WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
77+
WxMaConfigHolder.remove();//清理ThreadLocal
7078
return JsonUtils.toJson(userInfo);
7179
}
7280

@@ -78,16 +86,19 @@ public String info(@PathVariable String appid, String sessionKey,
7886
@GetMapping("/phone")
7987
public String phone(@PathVariable String appid, String sessionKey, String signature,
8088
String rawData, String encryptedData, String iv) {
81-
final WxMaService wxService = WxMaConfiguration.getMaService(appid);
89+
if (!wxMaService.switchover(appid)) {
90+
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
91+
}
8292

8393
// 用户信息校验
84-
if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
94+
if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
95+
WxMaConfigHolder.remove();//清理ThreadLocal
8596
return "user check failed";
8697
}
8798

8899
// 解密
89-
WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
90-
100+
WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
101+
WxMaConfigHolder.remove();//清理ThreadLocal
91102
return JsonUtils.toJson(phoneNoInfo);
92103
}
93104

0 commit comments

Comments
 (0)