diff --git a/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java b/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java index 046802e321..0b965cf2da 100644 --- a/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java +++ b/epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java @@ -440,6 +440,28 @@ public class RedisKeys { return rootPrefix.concat("thirdplatform:accesstoken:").concat(platformId); } + /** + * @Description 第三方平台信息key + * @param platformId + * @return java.lang.String + * @author wxz + * @date 2021.08.31 14:44:35 + */ + public static String getThirdPlatformInfoKey(String platformId) { + return rootPrefix.concat("thirdplatform:info:").concat(platformId); + } + + /** + * @Description 第三方平台操作urlkey + * @param platformId + * @return java.lang.String + * @author wxz + * @date 2021.08.31 15:15:15 + */ + public static String getThirdPlatformActionUrlKey(String platformId) { + return rootPrefix.concat("thirdplatform:actions:").concat(platformId); + } + /** * @return 设置组员已读、未读标识 * @param source :act notice diff --git a/epmet-gateway/src/main/resources/bootstrap.yml b/epmet-gateway/src/main/resources/bootstrap.yml index 91552a59b1..4f65034c7d 100644 --- a/epmet-gateway/src/main/resources/bootstrap.yml +++ b/epmet-gateway/src/main/resources/bootstrap.yml @@ -495,6 +495,7 @@ epmet: - /data/stats/project/** - /data/stats/basereport/** - /data/stats/governance/** + - /third/private-epmet/push-component-access-token # 对外开放接口认证白名单 diff --git a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/constant/ThirdPlatformActions.java b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/constant/ThirdPlatformActions.java index dc17deca39..bd0875b2e2 100644 --- a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/constant/ThirdPlatformActions.java +++ b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/constant/ThirdPlatformActions.java @@ -19,4 +19,10 @@ public interface ThirdPlatformActions { */ String UPLOAD_FILE = "UPLOAD_FILE"; + /** 推送 微信component access token */ + String PUSH_COMPONENT_ACCESS_TOKEN = "PUSH_COMPONENT_ACCESS_TOKEN"; + + /** 推送 微信 authorizer access token */ + String PUSH_AUTHORIZER_ACCESS_TOKEN = "PUSH_AUTHORIZER_ACCESS_TOKEN"; + } diff --git a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/ThirdPlatformActionsResultDTO.java b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/ThirdPlatformActionsResultDTO.java new file mode 100644 index 0000000000..a1a81ee406 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/ThirdPlatformActionsResultDTO.java @@ -0,0 +1,19 @@ +package com.epmet.dto.result; + +import lombok.Data; + +/** + * @Description 第三方平台及其支持的action result + * @author wxz + * @date 2021.08.30 17:06:42 +*/ +@Data +public class ThirdPlatformActionsResultDTO { + + private String platformId; + private String platformKey; + private String platformName; + private String actionKey; + private String apiUrl; + +} diff --git a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/privateepmet/GetAccessTokenResultDTO.java b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/privateepmet/GetAccessTokenResultDTO.java new file mode 100644 index 0000000000..e2cc8ab4c3 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/privateepmet/GetAccessTokenResultDTO.java @@ -0,0 +1,18 @@ +package com.epmet.dto.result.privateepmet; + +import lombok.Data; + +/** + * @Description 获取accesstoken结果 + * @author wxz + * @date 2021.08.30 17:40:25 +*/ +@Data +public class GetAccessTokenResultDTO { + + // token + private String accessToken; + // 有效时长 + private Long expireTime; + +} diff --git a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/ThirdOpenFeignClient.java b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/ThirdOpenFeignClient.java index 9cfd126d4c..d4efa88cc9 100644 --- a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/ThirdOpenFeignClient.java +++ b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/ThirdOpenFeignClient.java @@ -2,6 +2,8 @@ package com.epmet.feign; import com.epmet.commons.tools.constant.ServiceConstant; import com.epmet.commons.tools.utils.Result; +import com.epmet.dto.form.AuthorizerAccessTokenFormDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; import com.epmet.dto.form.SaveOrUpdateCustSelPlatformFormDTO; import com.epmet.dto.form.ThirdPlatformFormDTO; import com.epmet.dto.result.ThirdplatformResultDTO; @@ -35,4 +37,24 @@ public interface ThirdOpenFeignClient { */ @PostMapping("/third/thirdplatform/customer/list-available-platforms-by-action") Result> listAvailablePlatformsByCustomerAndAction(@RequestBody ThirdPlatformFormDTO input); + + /** + * @Description 私有化平台接收component-access推送 + * @param input + * @return com.epmet.commons.tools.utils.Result + * @author wxz + * @date 2021.08.30 16:40:17 + */ + @PostMapping("/third/private-epmet/push-component-access-token") + Result pushComponentAccessToken(@RequestBody ComponentAccessTokenFormDTO input); + + /** + * @Description 接收推送AuthorizerTokens + * @param input + * @return com.epmet.commons.tools.utils.Result + * @author wxz + * @date 2021.08.30 16:36:02 + */ + @PostMapping("/third/private-epmet/push-authorizer-tokens") + Result pushAuthorizerTokens(@RequestBody AuthorizerAccessTokenFormDTO input); } diff --git a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/ThirdOpenFeignClientFallback.java b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/ThirdOpenFeignClientFallback.java index 76098de169..b6929b9883 100644 --- a/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/ThirdOpenFeignClientFallback.java +++ b/epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/ThirdOpenFeignClientFallback.java @@ -3,6 +3,8 @@ package com.epmet.feign.fallback; import com.epmet.commons.tools.constant.ServiceConstant; import com.epmet.commons.tools.utils.ModuleUtils; import com.epmet.commons.tools.utils.Result; +import com.epmet.dto.form.AuthorizerAccessTokenFormDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; import com.epmet.dto.form.SaveOrUpdateCustSelPlatformFormDTO; import com.epmet.dto.form.ThirdPlatformFormDTO; import com.epmet.dto.result.ThirdplatformResultDTO; @@ -22,4 +24,14 @@ public class ThirdOpenFeignClientFallback implements ThirdOpenFeignClient { public Result> listAvailablePlatformsByCustomerAndAction(ThirdPlatformFormDTO input) { return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "listAvailablePlatformsByCustomerAndAction", input); } + + @Override + public Result pushComponentAccessToken(ComponentAccessTokenFormDTO input) { + return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "pushComponentAccessToken", input); + } + + @Override + public Result pushAuthorizerTokens(AuthorizerAccessTokenFormDTO input) { + return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "pushAuthorizerTokens", input); + } } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/ApiService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/ApiService.java index 36117287e1..a43689e321 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/ApiService.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/ApiService.java @@ -1,7 +1,8 @@ package com.epmet.apiservice; +import cn.hutool.core.bean.BeanUtil; import com.alibaba.fastjson.JSON; -import com.epmet.apiservice.result.LZGridPlatformBaseResult; +import com.epmet.commons.tools.exception.ExceptionUtils; import com.epmet.commons.tools.exception.RenException; import com.epmet.commons.tools.redis.RedisKeys; import com.epmet.commons.tools.utils.HttpClientManager; @@ -10,19 +11,21 @@ import com.epmet.commons.tools.utils.SpringContextUtils; import com.epmet.dao.ThirdplatformActionDao; import com.epmet.dao.ThirdplatformCustomerRegisterDao; import com.epmet.dao.ThirdplatformDao; -import com.epmet.dto.form.ProjectApplyAssistFormDTO; -import com.epmet.dto.form.TPFDemoFormDTO; -import com.epmet.dto.form.UploadFileFormDTO; +import com.epmet.dto.form.*; import com.epmet.dto.result.ProjectAssistResult; import com.epmet.dto.result.UploadFileResultDTO; import com.epmet.entity.ThirdplatformActionEntity; import com.epmet.entity.ThirdplatformCustomerRegisterEntity; import com.epmet.entity.ThirdplatformEntity; +import com.epmet.redis.ThirdPlatformCache; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import java.io.File; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -32,7 +35,7 @@ import java.util.concurrent.TimeUnit; * 此抽象类中定义方法的具体返回类型,所有子类都要统一使用,在具体实现中做转换。若是不需要返回,返回null即可。 */ @Slf4j -public abstract class ApiService { +public abstract class ApiService { /** * 重试次数 */ @@ -61,13 +64,13 @@ public abstract class ApiService { * @param headers * @return */ - public String sendGetRequest(String platformId, String action, Map params, Map headers) { + public R sendGetRequest(String platformId, String action, Map params, Map headers) { // 1.获取token String accessToken = getAccessToken(platformId); //2.获取url - ThirdplatformEntity thirdplatform = SpringContextUtils.getBean(ThirdplatformDao.class).selectById(platformId); - ThirdplatformActionEntity actionEntity = SpringContextUtils.getBean(ThirdplatformActionDao.class) - .getByPlatformIdAndActionKey(platformId, action); + ThirdPlatformCache thirdPlatformInfo = getThirdPlatformInfo(platformId); + String actionUrl = getThirdPlatformActionUrl(platformId, action); + if (headers == null) { headers = new HashMap<>(); @@ -76,8 +79,8 @@ public abstract class ApiService { // 填充access token到头当中 headers.put("X-Access-Token", accessToken); log.info("apiService sendGetRequest param:{},headers:{}",params,headers); - Result result = HttpClientManager.getInstance().sendGet(thirdplatform.getBaseUrl().concat(actionEntity.getApiUrl()), - thirdplatform.getBaseUrl().startsWith("https://"), + Result result = HttpClientManager.getInstance().sendGet(thirdPlatformInfo.getBaseUrl().concat(actionUrl), + thirdPlatformInfo.getBaseUrl().startsWith("https://"), params, headers); log.info("apiService sendGetRequest result:{}",JSON.toJSONString(result)); @@ -87,37 +90,51 @@ public abstract class ApiService { if (result.success()) { throw new RenException("请求第三方平台,获取AccessToken失败。"); } - LZGridPlatformBaseResult platformResult = JSON.parseObject(result.getData(), LZGridPlatformBaseResult.class); - judgeResultSuccess(platformResult); - return result.getData(); + return parsePlatformResponseResult(result.getData(), String.class); } + /** + * @Description + accesstoken header名称。如果不需要AccessToken,与getAccessToken()方法共同返回null即可 + * @return java.lang.String + * @author wxz + * @date 2021.08.30 14:06:26 + */ + public abstract String getAccessTokenHeaderName(); + /** * 发送post请求 * @param platformId * @param action * @param jsonString * @param headers - * @return + * @return 平台对应返回值的Result类 */ - public String sendPostRequest(String platformId, String action, String jsonString, Map headers) { + public R sendPostRequest(String platformId, String action, String jsonString, Map headers, Map urlParams) { // 1.获取token String accessToken = getAccessToken(platformId); //2.获取url - ThirdplatformEntity thirdplatform = SpringContextUtils.getBean(ThirdplatformDao.class).selectById(platformId); - ThirdplatformActionEntity actionEntity = SpringContextUtils.getBean(ThirdplatformActionDao.class) - .getByPlatformIdAndActionKey(platformId, action); + ThirdPlatformCache platformFromCache = getThirdPlatformInfo(platformId); + String actionUrl = getThirdPlatformActionUrl(platformId, action); if (headers == null) { headers = new HashMap<>(); } // 填充access token到头当中 - headers.put("X-Access-Token", accessToken); + if (StringUtils.isNotBlank(accessToken)) { + //headers.put("X-Access-Token", accessToken); + String accessTokenHeaderName = getAccessTokenHeaderName(); + if (StringUtils.isBlank(accessTokenHeaderName)) { + throw new RenException("没有指定AccessToken的Header名字"); + } + headers.put(accessTokenHeaderName, accessToken); + } log.info("apiService sendPostRequest param:{},headers:{}",jsonString,headers); - Result result = HttpClientManager.getInstance().sendPost(thirdplatform.getBaseUrl().concat(actionEntity.getApiUrl()), - thirdplatform.getBaseUrl().startsWith("https://"), + String urlParmsStr = this.convertQueryParams2String(urlParams); + Result result = HttpClientManager.getInstance().sendPost(platformFromCache.getBaseUrl().concat(actionUrl).concat(urlParmsStr), + platformFromCache.getBaseUrl().startsWith("https://"), jsonString, headers); log.info("apiService sendPostRequest result:{}",JSON.toJSONString(result)); @@ -128,12 +145,10 @@ public abstract class ApiService { throw new RenException("请求第三方平台,发送Post请求失败。错误信息:" + result.getMsg()); } - LZGridPlatformBaseResult platformResult = JSON.parseObject(result.getData(), LZGridPlatformBaseResult.class); - judgeResultSuccess(platformResult); - return result.getData(); + return parsePlatformResponseResult(result.getData(), String.class); } - public String sendPostRequestToUploadFile(String platformId, String action, File file, String fileName) { + public R sendPostRequestToUploadFile(String platformId, String action, File file, String fileName) { // 1.获取token String accessToken = getAccessToken(platformId); //2.获取url @@ -159,8 +174,6 @@ public abstract class ApiService { throw new RenException("请求第三方平台,发送Post请求失败。错误信息:" + result.getMsg()); } - LZGridPlatformBaseResult platformResult = JSON.parseObject(result.getData(), LZGridPlatformBaseResult.class); - // token过期重试逻辑,先不加 //if ("402".equals(platformResult.getCode())) { // // 如果token过期 @@ -168,8 +181,37 @@ public abstract class ApiService { // getAccessToken(platformId); // return sendPostRequest(platformId, action, jsonString, headers); //} - judgeResultSuccess(platformResult); - return result.getData(); + return parsePlatformResponseResult(result.getData(), String.class); + } + + /** + * @Description 将url参数拼接为字符串 + * @param queryParams + * @return java.lang.String + * @author wxz + * @date 2021.08.31 14:08:17 + */ + protected String convertQueryParams2String(Map queryParams) { + try { + if (queryParams == null || queryParams.size() == 0) { + return ""; + } + StringBuilder sb = new StringBuilder(""); + queryParams.entrySet().forEach(entry -> { + String key = entry.getKey(); + String value = entry.getValue(); + sb.append("&").append(key).append("=").append(value); + }); + String result = sb.toString(); + if (result.startsWith("&")) { + result = result.substring(1); + return "?".concat(result); + } + return ""; + } catch (Exception e) { + log.warn("gateway中将url参数转化为String失败,程序继续执行,错误信息:".concat(ExceptionUtils.getErrorStackTrace(e))); + return ""; + } } /** @@ -202,6 +244,36 @@ public abstract class ApiService { stringRedisTemplate.opsForValue().set(RedisKeys.getThirdPlatformAccessTokenKey(platformId), accessToken, expire, timeUnit); } + /** + * @Description 将第三方平台信息存入缓存 + * @param cache + * @return void + * @author wxz + * @date 2021.08.31 14:55:48 + */ + protected void addPlatformToCache(ThirdPlatformCache cache) { + RedisTemplate stringRedisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class); + Map stringObjectMap = BeanUtil.beanToMap(cache); + stringRedisTemplate.opsForHash().putAll(RedisKeys.getThirdPlatformInfoKey(cache.getPlatformId()), stringObjectMap); + } + + /** + * @Description 从缓存中取第三方平台信息 + * @param thirdPlatformKey + * @return com.epmet.redis.ThirdPlatformCache + * @author wxz + * @date 2021.08.31 14:55:28 + */ + protected ThirdPlatformCache getPlatformFromCache(String thirdPlatformKey) { + HashOperations hashOperations = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class).opsForHash(); + Map entries = hashOperations.entries(RedisKeys.getThirdPlatformInfoKey(thirdPlatformKey)); + if (entries.size() == 0) { + return null; + } + ThirdPlatformCache thirdPlatformCache = BeanUtil.mapToBean(entries, ThirdPlatformCache.class, true); + return thirdPlatformCache; + } + /** * @Description 从缓存中取token * @return @@ -210,7 +282,87 @@ public abstract class ApiService { */ protected String getAccessTokenFromCache(String platformId) { RedisTemplate stringRedisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class); - return stringRedisTemplate.opsForValue().get(platformId); + return stringRedisTemplate.opsForValue().get(RedisKeys.getThirdPlatformAccessTokenKey(platformId)); + } + + /** + * @Description 从缓存查询第三方平台操作url + * @param platformId + * @param action + * @return java.lang.String + * @author wxz + * @date 2021.08.31 15:18:06 + */ + protected String getThirdPlatformActionUrlFromCache(String platformId, String action) { + HashOperations ops = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class).opsForHash(); + String url = ops.get(RedisKeys.getThirdPlatformActionUrlKey(platformId), action); + return url; + } + + /** + * @Description 将第三方平台操作url添加至缓存 + * @param platformId + * @param map + * @return java.lang.String + * @author wxz + * @date 2021.08.31 15:20:45 + */ + protected void addThirdPlatformActionUrlsToCache(String platformId, Map map) { + String redisKey = RedisKeys.getThirdPlatformActionUrlKey(platformId); + + RedisTemplate redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class); + HashOperations ops = redisTemplate.opsForHash(); + ops.putAll(redisKey, map); + } + + /** + * @Description 从缓存里面读取平台信息,如果缓存中没有,从db读取,放入缓存 + * @param platformId 平台id + * @return com.epmet.redis.ThirdPlatformCache + * @author wxz + * @date 2021.08.31 15:02:19 + */ + protected ThirdPlatformCache getThirdPlatformInfo(String platformId) { + ThirdPlatformCache platform = getPlatformFromCache(platformId); + if (platform == null) { + platform = new ThirdPlatformCache(); + ThirdplatformEntity platformEntity = SpringContextUtils.getBean(ThirdplatformDao.class).selectById(platformId); + platform.setPlatformId(platformEntity.getId()); + platform.setApiService(platformEntity.getApiService()); + platform.setBaseUrl(platformEntity.getBaseUrl()); + platform.setPlatformKey(platformEntity.getPlatformKey()); + platform.setPlatformName(platformEntity.getPlatformName()); + platform.setPlatformSecret(platformEntity.getPlatformSecret()); + addPlatformToCache(platform); + } + return platform; + } + + /** + * @Description 获取第三放平台操作url。优先读取缓存,没有则读取db + * @param platformId + * @param actionKey + * @return java.util.Map + * @author wxz + * @date 2021.08.31 15:21:39 + */ + protected String getThirdPlatformActionUrl(String platformId, String actionKey) { + String url = getThirdPlatformActionUrlFromCache(platformId, actionKey); + if (StringUtils.isBlank(url)) { + List actions = SpringContextUtils.getBean(ThirdplatformActionDao.class) + .listPlatformActions(platformId); + + Map map = new HashMap<>(actions.size()); + // 将action:url映射至map + for (ThirdplatformActionEntity a : actions) { + map.put(a.getActionKey(), a.getApiUrl()); + if (actionKey.equals(a.getActionKey())) { + url = a.getApiUrl(); + } + } + addThirdPlatformActionUrlsToCache(platformId, map); + } + return url; } /** @@ -246,16 +398,38 @@ public abstract class ApiService { } /** - * @Description 判断第三方平台返回结果成功失败。如果失败,则抛出异常 - * @return + * @Description 解析第三方平台返回结果 + * @param resultString + * @param clazz R的泛型对象T的clazz + * @return R 泛型,不同平台的Result DTO类型 * @author wxz - * @date 2021.03.22 10:32 - */ - public abstract void judgeResultSuccess(LZGridPlatformBaseResult result); + * @date 2021.08.31 13:36:11 + */ + public abstract R parsePlatformResponseResult(String resultString, Class clazz); public UploadFileResultDTO uploadFile(UploadFileFormDTO formDTO) { return null; } + /** + * @Description 推送ComponentAccessToken + * @param form + * @return void 保持空实现,让子类去实现 + * @author wxz + * @date 2021.08.30 17:15:01 + */ + public void pushComponentAccessToken(ComponentAccessTokenFormDTO form, String platformId, String platformKey) {} + + /** + * @description 推送小程序token + * + * @param form + * @param platformId + * @param platformKey + * @return + * @author wxz + * @date 2021.08.31 20:26:51 + */ + public void pushAuthorizerAccessToken(AuthorizerAccessTokenFormDTO form, String platformId, String platformKey) {}; } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/DemoApiService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/DemoApiService.java index 63f718a0d5..ed06d5059a 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/DemoApiService.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/DemoApiService.java @@ -14,10 +14,15 @@ import org.springframework.stereotype.Component; * demo api service */ @Component(value = "demoApiService") -public class DemoApiService extends ApiService { +public class DemoApiService extends ApiService { Logger logger = LoggerFactory.getLogger(DemoApiService.class); + @Override + public String getAccessTokenHeaderName() { + return null; + } + @Override public String getAccessToken(String platformId) { return null; @@ -29,8 +34,15 @@ public class DemoApiService extends ApiService { return null; } + /** + * @Description 解析平台返回结果 + * @param resultString 平台返回结果string + * @return java.lang.String + * @author wxz + * @date 2021.08.30 22:43:24 + */ @Override - public void judgeResultSuccess(LZGridPlatformBaseResult result) { - + public String parsePlatformResponseResult(String resultString, Class clazz) { + return null; } } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/LuzhouGridPlatformApiService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/LuzhouGridPlatformApiService.java index abbaad2255..dee2cd8137 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/LuzhouGridPlatformApiService.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/LuzhouGridPlatformApiService.java @@ -31,7 +31,12 @@ import java.util.concurrent.TimeUnit; */ @Slf4j @Component("luzhouGridPlatformApiService") -public class LuzhouGridPlatformApiService extends ApiService { +public class LuzhouGridPlatformApiService extends ApiService { + + @Override + public String getAccessTokenHeaderName() { + return "X-Access-Token"; + } @Override public String getAccessToken(String platformId) { @@ -58,11 +63,8 @@ public class LuzhouGridPlatformApiService extends ApiService { throw new RenException("请求第三方平台,获取AccessToken失败。"); } - LZGridPlatformBaseResult platformResult = JSON.parseObject(result.getData(), LZGridPlatformBaseResult.class); - judgeResultSuccess(platformResult); - - token = platformResult.getResult(); - addAccessTokenToCache(platformId, token, (long)(3600*1.8*1000), TimeUnit.MILLISECONDS); + LZGridPlatformBaseResult lzGridPlatformBaseResult = parsePlatformResponseResult(result.getData(), String.class); + addAccessTokenToCache(platformId, lzGridPlatformBaseResult.getResult(), (long)(3600*1.8*1000), TimeUnit.MILLISECONDS); } return token; } @@ -83,30 +85,24 @@ public class LuzhouGridPlatformApiService extends ApiService { // 正式调用第三方平台 String argsStr = JSON.toJSONString(formDTO); - String result = sendPostRequest(platformId, ThirdPlatformActions.PROJECT_ASSIST, argsStr, null); + LZGridPlatformBaseResult result = sendPostRequest(platformId, ThirdPlatformActions.PROJECT_ASSIST, argsStr, null, null); // 开发阶段临时写死 //String result = "{\"eventId\":\"test-task-id\"}"; ProjectAssistResult projectAssistResult = new ProjectAssistResult(); - if (!StringUtils.isBlank(result)) { - // 此处要经过一系列业务处理,将第三方平台返回的数据进行解析,等处理最后转换成ProjectAssistResult类型,返回。ProjectAssistResult这个类型是 - // 所有apiService的projectAssist方法返回值的统一类型,是我们的epmet-cloud所需要的数据的实体, - // 所有apiService都要想办法转化成这个类型。 - LZGridPlatformBaseResult lzResult = JSON.parseObject(result, LZGridPlatformBaseResult.class); - - // 此处设置为第三方系统返回的唯一id - projectAssistResult.setTaskId(lzResult.getResult()); - } + // 此处设置为第三方系统返回的唯一id + projectAssistResult.setTaskId(result.getResult()); log.info("projectAssist 泸州网格化平台项目协助发送成功"); return projectAssistResult; } @Override - public void judgeResultSuccess(LZGridPlatformBaseResult result) { - //LZGridPlatformBaseResult; - if (!"200".equalsIgnoreCase(result.getCode())) { - throw new RenException("泸州网格化平台:返回失败结果,错误码:" + result.getCode()); + public LZGridPlatformBaseResult parsePlatformResponseResult(String resultString, Class clazz) { + LZGridPlatformBaseResult baseResult = JSON.parseObject(resultString, LZGridPlatformBaseResult.class); + if (!"200".equalsIgnoreCase(baseResult.getCode())) { + throw new RenException("泸州网格化平台:返回失败结果,错误码:" + baseResult.getCode()); } + return baseResult; } @Override @@ -118,16 +114,9 @@ public class LuzhouGridPlatformApiService extends ApiService { // 正式调用第三方平台 File file = new File(formDTO.getFile().getOriginalFilename()); FileUtils.copyInputStreamToFile(formDTO.getFile().getInputStream(), file); - String result = sendPostRequestToUploadFile(platformId, ThirdPlatformActions.UPLOAD_FILE, file, fileName); - if (!StringUtils.isBlank(result)) { - // 此处要经过一系列业务处理,将第三方平台返回的数据进行解析,等处理最后转换成ProjectAssistResult类型,返回。ProjectAssistResult这个类型是 - // 所有apiService的projectAssist方法返回值的统一类型,是我们的epmet-cloud所需要的数据的实体, - // 所有apiService都要想办法转化成这个类型。 - LZGridPlatformBaseResult lzResult = JSON.parseObject(result, LZGridPlatformBaseResult.class); - - // 此处设置为第三方系统返回的唯一id - resultDTO.setUrl((String) lzResult.getResult()); - } + LZGridPlatformBaseResult baseResult = sendPostRequestToUploadFile(platformId, ThirdPlatformActions.UPLOAD_FILE, file, fileName); + // 此处设置为第三方系统返回的唯一id + resultDTO.setUrl(baseResult.getResult()); System.out.println("泸州网格化平台项目文件上传成功"); } catch (Exception e) { throw new RenException("上传失败"); diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/PingyinPrivateEpmetApiService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/PingyinPrivateEpmetApiService.java new file mode 100644 index 0000000000..da62386442 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/PingyinPrivateEpmetApiService.java @@ -0,0 +1,169 @@ +package com.epmet.apiservice.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.epmet.apiservice.ApiService; +import com.epmet.commons.tools.exception.EpmetErrorCode; +import com.epmet.commons.tools.exception.ExceptionUtils; +import com.epmet.commons.tools.exception.RenException; +import com.epmet.commons.tools.feign.ResultDataResolver; +import com.epmet.commons.tools.utils.ConvertUtils; +import com.epmet.commons.tools.utils.HttpClientManager; +import com.epmet.commons.tools.utils.Result; +import com.epmet.constant.ThirdPlatformActions; +import com.epmet.dto.form.AuthorizerAccessTokenFormDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; +import com.epmet.dto.result.privateepmet.GetAccessTokenResultDTO; +import com.epmet.openapi.sdk.sign.OpenApiSignUtils; +import com.epmet.redis.ThirdPlatformCache; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +@Component("pingyinPrivateEpmetApiService") +@Slf4j +public class PingyinPrivateEpmetApiService extends ApiService implements ResultDataResolver { + + // 认证方式 + private String authType = "take_token"; + + @Override + public String getAccessTokenHeaderName() { + return "AccessToken"; + } + + @Override + public String getAccessToken(String platformId) { + String accessTokenFromCache = super.getAccessTokenFromCache(platformId); + if (StringUtils.isBlank(accessTokenFromCache)) { + ThirdPlatformCache thirdPlatformInfo = super.getThirdPlatformInfo(platformId); + String apiUrl = getThirdPlatformActionUrl(platformId, ThirdPlatformActions.GET_ACCESS_TOKEN); + String baseUrl = thirdPlatformInfo.getBaseUrl(); + String platformKey = thirdPlatformInfo.getPlatformKey(); + String platformSecret = thirdPlatformInfo.getPlatformSecret(); + String uuid = UUID.randomUUID().toString(); + long currentTimeMillis = System.currentTimeMillis(); + + try { + String sign = createSign(platformKey, platformSecret, uuid, currentTimeMillis, authType, null); + log.info("【调用平阴私有化平台获取AccessToken】参数列表:sign:{}, app_id:{}, auth_type:{}, nonce:{}, timestamp:{}", sign, platformKey, platformSecret, uuid, currentTimeMillis); + String urlParams = super.convertQueryParams2String(constructCommonUrlParamsMap(platformKey, authType, uuid, currentTimeMillis, sign)); + String requestUrl = baseUrl.concat(apiUrl).concat(urlParams); + Result stringResult = HttpClientManager.getInstance().sendPostByHttps(requestUrl, "{}"); + String remoteResultString = getResultDataOrThrowsException(stringResult, "【调用平阴私有化平台获取AccessToken】", EpmetErrorCode.SERVER_ERROR.getCode(), null); + Result remoteResult = parsePlatformResponseResult(remoteResultString, GetAccessTokenResultDTO.class); + log.info("【调用平阴私有化平台获取AccessToken】结果:{}", remoteResultString); + accessTokenFromCache = remoteResult.getData().getAccessToken(); + //(15 * 60 * 1000)为提前获取token。对方token有效期2小时,我们设置有效期为1小时45分钟,留15分钟容错时间,防止时间差 + long expire = remoteResult.getData().getExpireTime() - System.currentTimeMillis() - (15 * 60 * 1000); + super.addAccessTokenToCache(platformId, accessTokenFromCache, expire, TimeUnit.MILLISECONDS); + } catch (Exception e) { + throw new RenException(ExceptionUtils.getErrorStackTrace(e)); + } + } + return accessTokenFromCache; + } + + /** + * @Description 创建签名 + * @param platformKey + * @param platformSecret + * @param nonce + * @param timeMillis + * @param authType + * @return java.lang.String + * @author wxz + * @date 2021.08.31 15:37:58 + */ + private String createSign(String platformKey, String platformSecret, String nonce, Long timeMillis, String authType, Map requestBodyMap) { + HashMap contentMap = new HashMap<>(); + contentMap.put("app_id", platformKey); + contentMap.put("auth_type", authType); + contentMap.put("nonce", nonce); + contentMap.put("timestamp", String.valueOf(timeMillis)); + + if (requestBodyMap != null && requestBodyMap.size() > 0) { + contentMap.putAll(requestBodyMap); + } + + String sign; + try { + sign = OpenApiSignUtils.createSign(contentMap, platformSecret); + } catch (Exception e) { + String detail = ExceptionUtils.getErrorStackTrace(e); + log.error(detail); + throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode(), "【平阴私有化平台apService】创建签名失败"); + } + return sign; + } + + /** + * @Description 构造url参数map + * @param platformKey + * @param authType + * @param nonce + * @param timeMillis + * @param sign + * @return java.util.Map + * @author wxz + * @date 2021.08.31 14:19:41 + */ + private Map constructCommonUrlParamsMap(String platformKey, String authType, String nonce, Long timeMillis, String sign) { + HashMap map = new HashMap<>(); + map.put("app_id", platformKey); + map.put("auth_type", authType); + map.put("nonce", nonce); + map.put("timestamp", String.valueOf(timeMillis)); + map.put("sign", sign); + return map; + } + + @Override + public Result parsePlatformResponseResult(String resultString, Class clazz) { + Result result; + try { + result = JSON.parseObject(resultString, new TypeReference>(clazz){}); + } catch (Exception e) { + String errorStackTrace = ExceptionUtils.getErrorStackTrace(e); + log.error(errorStackTrace); + throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode(), "【调用平阴私有化服务器,解析返回结果失败】"); + } + if (!result.success()) { + throw new RenException(String.format("【请求平阴私有化平台】失败,返回结果string:%s", resultString)); + } + return result; + } + + @Override + public void pushComponentAccessToken(ComponentAccessTokenFormDTO form, String platformId, String platformKey) { + ThirdPlatformCache thirdPlatformInfo = getThirdPlatformInfo(platformId); + String nonce = UUID.randomUUID().toString(); + long timeMillis = System.currentTimeMillis(); + + Map bodyMap = null; + try { + bodyMap = ConvertUtils.entityToMap(form); + } catch (Exception e) { + String detail = ExceptionUtils.getErrorStackTrace(e); + log.error(detail); + throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode(), "【推送ComponentAccessToken】requestBody转化为map失败"); + } + + String sign = createSign(platformKey, thirdPlatformInfo.getPlatformSecret(), nonce, timeMillis, authType, bodyMap); + Map urlParams = constructCommonUrlParamsMap(platformKey, authType, nonce, timeMillis, sign); + + String jsonString = JSON.toJSONString(form); + Result result = super.sendPostRequest(platformId, ThirdPlatformActions.PUSH_COMPONENT_ACCESS_TOKEN, jsonString, null, urlParams); + getResultDataOrThrowsException(result, "【平阴私有化平台】推送ComponentAccessToken", EpmetErrorCode.SERVER_ERROR.getCode(), null); + } + + @Override + public void pushAuthorizerAccessToken(AuthorizerAccessTokenFormDTO form, String platformId, String platformKey) { + + } +} diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/PrivateEpmetController.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/PrivateEpmetController.java new file mode 100644 index 0000000000..1135562069 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/PrivateEpmetController.java @@ -0,0 +1,50 @@ +package com.epmet.controller; + +import com.epmet.commons.tools.utils.Result; +import com.epmet.dto.form.AuthorizerAccessTokenFormDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; +import com.epmet.service.PrivateEpmetService; +import org.springframework.beans.factory.annotation.Autowired; +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; + +/** + * @Description 私有化平台相关controller + * @author wxz + * @date 2021.08.30 15:18:51 +*/ +@RestController +@RequestMapping("/private-epmet") +public class PrivateEpmetController { + + @Autowired + private PrivateEpmetService privateEpmetService; + + /** + * @Description 接收推送component access + * @param input + * @return com.epmet.commons.tools.utils.Result + * @author wxz + * @date 2021.08.30 15:18:57 + */ + @PostMapping("push-component-access-token") + public Result pushComponentAccessToken(@RequestBody ComponentAccessTokenFormDTO input) { + privateEpmetService.pushComponentAccessToken(input); + return new Result(); + } + + /** + * @Description 接收推送AuthorizerTokens + * @param input + * @return com.epmet.commons.tools.utils.Result + * @author wxz + * @date 2021.08.30 16:36:02 + */ + @PostMapping("push-authorizer-tokens") + public Result pushAuthorizerTokens(@RequestBody AuthorizerAccessTokenFormDTO input) { + privateEpmetService.pushAuthorizerTokens(input); + return new Result(); + } +} diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/TestConttroller.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/TestConttroller.java new file mode 100644 index 0000000000..f5d81f987d --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/TestConttroller.java @@ -0,0 +1,30 @@ +package com.epmet.controller; + +import com.epmet.commons.tools.utils.Result; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; +import com.epmet.service.ComponentVerifyTicketService; +import com.epmet.service.PrivateEpmetService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Date; + +@RestController +@RequestMapping("test") +public class TestConttroller { + + @Autowired + private ComponentVerifyTicketService componentVerifyTicketService; + + @PostMapping("push-component-access-token") + public Result testPushComponentAccessToken() { + ComponentAccessTokenFormDTO form = new ComponentAccessTokenFormDTO(); + form.setComponentAccessToken("token..."); + form.setExpiresInTime(new Date()); + componentVerifyTicketService.pushComponentAccessToken2PrivateEpmetPlatforms(form); + return new Result(); + } + +} diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformActionDao.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformActionDao.java index 50de9d3629..405ae52529 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformActionDao.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformActionDao.java @@ -22,6 +22,8 @@ import com.epmet.entity.ThirdplatformActionEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; +import java.util.List; + /** * * @@ -38,4 +40,12 @@ public interface ThirdplatformActionDao extends BaseDao listPlatformActions(@Param("platformId") String platformId); } \ No newline at end of file diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformCustomerRegisterDao.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformCustomerRegisterDao.java index 3dc3001baf..5f1fe6f038 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformCustomerRegisterDao.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformCustomerRegisterDao.java @@ -19,6 +19,7 @@ package com.epmet.dao; import com.epmet.commons.mybatis.dao.BaseDao; import com.epmet.dto.form.PlatformUnregisterFormDTO; +import com.epmet.dto.result.ThirdPlatformActionsResultDTO; import com.epmet.entity.ThirdplatformCustomerRegisterEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -55,4 +56,13 @@ public interface ThirdplatformCustomerRegisterDao extends BaseDao + * @author wxz + * @date 2021.08.30 17:07:32 + */ + List listPlatformsByActionKey(@Param("actionKey") String actionKey); } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/ThirdPlatformCache.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/ThirdPlatformCache.java new file mode 100644 index 0000000000..c8c3409bc2 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/ThirdPlatformCache.java @@ -0,0 +1,19 @@ +package com.epmet.redis; + +import lombok.Data; + +/** + * @Description 第三方平台缓存对象 + * @author wxz + * @date 2021.08.31 14:41:49 +*/ +@Data +public class ThirdPlatformCache { + //String platformKey, String platformSecret, String platformName, String apiService, String baseUrl + private String platformId; + private String platformKey; + private String platformSecret; + private String platformName; + private String apiService; + private String baseUrl; +} diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java index 28cfae2fde..8d3ce45cbf 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java @@ -2,6 +2,7 @@ package com.epmet.service; import com.epmet.commons.tools.security.dto.TokenDto; import com.epmet.dto.form.AuthCodeAndTimeFromDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; import org.springframework.web.bind.annotation.RequestBody; import javax.servlet.http.HttpServletRequest; @@ -48,4 +49,6 @@ public interface ComponentVerifyTicketService { */ void redirectUri(TokenDto tokenDto, @RequestBody AuthCodeAndTimeFromDTO fromDTO); + public void pushComponentAccessToken2PrivateEpmetPlatforms(ComponentAccessTokenFormDTO input); + } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/PrivateEpmetService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/PrivateEpmetService.java new file mode 100644 index 0000000000..3ab6a0b870 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/PrivateEpmetService.java @@ -0,0 +1,19 @@ +package com.epmet.service; + +import com.epmet.dto.form.AuthorizerAccessTokenFormDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; + +public interface PrivateEpmetService { + void pushAuthorizerTokens(AuthorizerAccessTokenFormDTO input); + + /** + * @Description 推送component access token + * @param input + * @return void + * @author wxz + * @date 2021.08.30 16:17:48 + */ + void pushComponentAccessToken(ComponentAccessTokenFormDTO input); + + void pushVerifyTicket(String ticket); +} diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ThirdPlatformService.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ThirdPlatformService.java index 570ce04d49..33224b3497 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ThirdPlatformService.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ThirdPlatformService.java @@ -5,6 +5,7 @@ import com.epmet.dto.form.CustomerFormDTO; import com.epmet.dto.form.ThirdPlatformFormDTO; import com.epmet.dto.form.PlatformRegisterFormDTO; import com.epmet.dto.form.PlatformUnregisterFormDTO; +import com.epmet.dto.result.ThirdPlatformActionsResultDTO; import com.epmet.dto.result.ThirdplatformResultDTO; import java.util.List; @@ -100,4 +101,13 @@ public interface ThirdPlatformService { * @Date 10:15 2021-04-09 **/ void registerThirdPlatformCustomer(PlatformRegisterFormDTO formDTO); + + /** + * @Description 已知操作的key,查询哪些app可以做此操作 + * @param actionKey + * @return java.util.List + * @author wxz + * @date 2021.08.30 16:59:13 + */ + List listPlatformsByActionKey(String actionKey); } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java index a23d9ac77f..2ac3e225b2 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java @@ -4,12 +4,15 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.nacos.client.config.utils.IOUtils; import com.dingtalk.api.request.OapiRobotSendRequest; +import com.epmet.apiservice.ApiService; import com.epmet.commons.tools.constant.NumConstant; +import com.epmet.commons.tools.exception.ExceptionUtils; import com.epmet.commons.tools.exception.RenException; import com.epmet.commons.tools.security.dto.TokenDto; import com.epmet.commons.tools.utils.ConvertUtils; import com.epmet.commons.tools.utils.HttpClientManager; import com.epmet.constant.ModuleConstant; +import com.epmet.constant.ThirdPlatformActions; import com.epmet.constant.ThirdRedisKeyConstant; import com.epmet.constant.ThirdRunTimeInfoConstant; import com.epmet.dao.*; @@ -21,7 +24,9 @@ import com.epmet.feign.OperCrmOpenFeignClient; import com.epmet.mpaes.WXBizMsgCrypt; import com.epmet.mpaes.WXXmlToMapUtil; import com.epmet.redis.RedisThird; +import com.epmet.service.ApiServiceSelector; import com.epmet.service.ComponentVerifyTicketService; +import com.epmet.service.ThirdPlatformService; import com.epmet.wxapi.constant.WxMaCodeConstant; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -47,7 +52,7 @@ import static com.epmet.constant.ThirdRunTimeInfoConstant.*; */ @Slf4j @Service -public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketService { +public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketService, ApiServiceSelector { @Autowired private RedisThird redisThird; @@ -94,6 +99,9 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe @Autowired private PaCustomerDao paCustomerDao; + @Autowired + private ThirdPlatformService thirdPlatformService; + @Value("${third.platform.appId}") private String componentAppId; @Value("${third.platform.appSecret}") @@ -104,8 +112,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe private String token; /** - * @Description 获得授权事件的票据 * @param + * @Description 获得授权事件的票据 * @author zxc */ @Transactional(rollbackFor = Exception.class) @@ -123,23 +131,23 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe String nonce = request.getParameter(ModuleConstant.NONCE); String encryptType = request.getParameter(ModuleConstant.ENCRYPT_TYPE); String signature = request.getParameter(ModuleConstant.SIGNATURE); - log.info(String.format(ThirdRunTimeInfoConstant.VERIFY_TICKET,msgSignature,timeStamp,nonce,encryptType,signature)); + log.info(String.format(ThirdRunTimeInfoConstant.VERIFY_TICKET, msgSignature, timeStamp, nonce, encryptType, signature)); // 从请求中读取整个post数据 InputStream inputStream; String postData = null; inputStream = request.getInputStream(); - postData= IOUtils.toString(inputStream,ModuleConstant.UTF8); - WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token,aesKey,componentAppId); + postData = IOUtils.toString(inputStream, ModuleConstant.UTF8); + WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token, aesKey, componentAppId); String msg = wxBizMsgCrypt.decryptMsg(msgSignature, timeStamp, nonce, postData); - log.info(String.format(ThirdRunTimeInfoConstant.MSG,msg)); + log.info(String.format(ThirdRunTimeInfoConstant.MSG, msg)); // 将xml转为map Map result = WXXmlToMapUtil.xmlToMap(msg); String infotype = result.get(ModuleConstant.INFO_TYPE); - log.info(String.format(ThirdRunTimeInfoConstant.INFO_TYPE,infotype)); - switch (infotype){ + log.info(String.format(ThirdRunTimeInfoConstant.INFO_TYPE, infotype)); + switch (infotype) { case ModuleConstant.TICKET_UNDERLINE_KEY: //接收票据 【component_verify_ticket】 String ComponentVerifyTicket = result.get(ModuleConstant.TICKET_KEY); - log.info(String.format(COMPONENT_VERIFY_TICKET,ComponentVerifyTicket)); + log.info(String.format(COMPONENT_VERIFY_TICKET, ComponentVerifyTicket)); // 缓存 ticket redisThird.setComponentVerifyTicket(ComponentVerifyTicket); // 存数据库 @@ -149,7 +157,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe //先逻辑删 ticketDao.deleteOldComponentVerifyTicket(); ticketDao.insertComponentVerifyTicket(ticketFormDTO); - log.info(ModuleConstant.TICKET_UNDERLINE_KEY+":"+ComponentVerifyTicket); + log.info(ModuleConstant.TICKET_UNDERLINE_KEY + ":" + ComponentVerifyTicket); break; case ModuleConstant.AUTHORIZED: //授权成功 this.disposeAuthResult(result); @@ -173,7 +181,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } log.info(ThirdRunTimeInfoConstant.END_TICKET); Integer tokenCount = componentAccessTokenDao.selectAccessTokenCount(); - if (tokenCount == NumConstant.ZERO){ + if (tokenCount == NumConstant.ZERO) { String accessTokenCountFlag = ModuleConstant.ACCOUNT_TOKEN_FLAG_ONE; this.getComponentAccessToken(accessTokenCountFlag); } @@ -181,14 +189,14 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 授权结果插入 * @param result + * @Description 授权结果插入 * @author zxc */ @Transactional(rollbackFor = Exception.class) - public void disposeAuthResult(Map result){ + public void disposeAuthResult(Map result) { Map tempMap = result; - Map data = tempMap; + Map data = tempMap; AuthResultRecordFormDTO authResultRecord = ConvertUtils.mapToEntity(data, AuthResultRecordFormDTO.class); authResultRecord.setWechatCreateTime(this.sToDate(result.get(ModuleConstant.CREATE_TIME))); if (result.containsKey(ModuleConstant.AUTHORIZATION_CODE_EXPIRED_TIME)) { @@ -199,9 +207,9 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 定时获取 (令牌,component_access_token) 第三方与微信交互使用的component_access_token - * 每十分钟执行一次,判断是否有马上超时的(15分钟以内算马上超时) * @param accessTokenCountFlag 表里的 component_access_token的数量 + * @Description 定时获取 (令牌,component_access_token) 第三方与微信交互使用的component_access_token + * 每十分钟执行一次,判断是否有马上超时的(15分钟以内算马上超时) * @author zxc */ @Transactional(rollbackFor = Exception.class) @@ -218,7 +226,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId); jsonObject.put(ModuleConstant.COMPONENT_APPSECRET, appSecret); jsonObject.put(ModuleConstant.TICKET_UNDERLINE_KEY, componentVerifyTicket); - log.info(String.format(ThirdRunTimeInfoConstant.COMPONENT_ACCESS_TOKEN,componentVerifyTicket)); + log.info(String.format(ThirdRunTimeInfoConstant.COMPONENT_ACCESS_TOKEN, componentVerifyTicket)); String post = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_COMPONENT_TOKEN_URL, JSON.toJSONString(jsonObject)).getData(); Map hashMap = JSON.parseObject(post, Map.class); if (!hashMap.containsKey(ModuleConstant.ERR_MSG)) { @@ -236,6 +244,13 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe componentAccessTokenDao.insertComponentAccessToken(formDTO); //存缓存 redisThird.setComponentAccessToken(componentAccessToken); + //推送到私有化平台们 + try { + pushComponentAccessToken2PrivateEpmetPlatforms(formDTO); + } catch (Exception e) { + String detail = ExceptionUtils.getErrorStackTrace(e); + log.error(detail); + } } else { throw new RenException(ThirdRunTimeInfoConstant.FAILURE_ACCESS_TOKEN); } @@ -245,8 +260,29 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 获取预授权码 + * @param input + * @return void + * @Description 推送component access token到私有化平台 + * @author wxz + * @date 2021.08.30 17:12:15 + */ + public void pushComponentAccessToken2PrivateEpmetPlatforms(ComponentAccessTokenFormDTO input) { + List platforms = thirdPlatformService.listPlatformsByActionKey(ThirdPlatformActions.PUSH_COMPONENT_ACCESS_TOKEN); + platforms.stream().forEach(p -> { + log.info("推送component-access-token到私有化平台:platformId:{}, platformKey:{}, platformName:{}, apiUrl:{}", p.getPlatformId(), p.getPlatformKey(), p.getPlatformName(), p.getApiUrl()); + ApiService apiService = selectApiService(p.getPlatformId()); + try { + apiService.pushComponentAccessToken(input, p.getPlatformId(), p.getPlatformKey()); + } catch (Exception e) { + String detail = ExceptionUtils.getErrorStackTrace(e); + log.error(detail); + } + }); + } + + /** * @param + * @Description 获取预授权码 * @author zxc */ @Transactional(rollbackFor = Exception.class) @@ -258,7 +294,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe JSONObject jsonObject = new JSONObject(); jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId); String post = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_CREATE_PREAUTHCODE_URL + accessToken, JSON.toJSONString(jsonObject)).getData(); - log.info(String.format(POST_RESULT,post)); + log.info(String.format(POST_RESULT, post)); Map hashMap = JSON.parseObject(post, Map.class); if (!hashMap.containsKey(ModuleConstant.ERR_MSG)) { preAuthCode = hashMap.get(ModuleConstant.PRE_AUTH_CODE).toString(); @@ -283,11 +319,11 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 使用授权码获取授权信息 请求参数:【component_access_token、component_appid、authorization_code】 + * @Description 使用授权码获取授权信息 请求参数:【component_access_token、component_appid、authorization_code】 * @author zxc */ @Transactional(rollbackFor = Exception.class) - public AuthorizationInfoResultDTO authInfoByAuthCode(String authCode,String customerId,String clientType) { + public AuthorizationInfoResultDTO authInfoByAuthCode(String authCode, String customerId, String clientType) { log.info(START_GET_AUTH_INFO); AuthorizationInfoResultDTO authorizationInfoResultDTO = new AuthorizationInfoResultDTO(); // 获取令牌【component_access_token】 @@ -297,11 +333,11 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId); jsonObject.put(ModuleConstant.AUTHORIZATION_CODE, authCode); String authInfo = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_QUERY_AUTH_URL + accessToken, JSON.toJSONString(jsonObject)).getData(); - HashMap hashMap = JSON.parseObject(authInfo, HashMap.class); + HashMap hashMap = JSON.parseObject(authInfo, HashMap.class); Map map = hashMap.get(ModuleConstant.AUTHORIZATION_INFO); authorizationInfoResultDTO = ConvertUtils.mapToEntity(map, AuthorizationInfoResultDTO.class); String authAppId = authorizationInfoResultDTO.getAuthorizer_appid(); - log.info("授权信息:"+map); + log.info("授权信息:" + map); String expiresIn = authorizationInfoResultDTO.getExpires_in().toString(); Date expiresInTime = this.countExpirationTime(expiresIn); //授权信息分为两张表,基础信息authorization_info,授权列表func_info @@ -314,14 +350,14 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe authInfoDTO.setCustomerId(customerId); authInfoDTO.setClientType(clientType); List func_info = authorizationInfoResultDTO.getFunc_info(); - log.info("权限列表信息:"+func_info); + log.info("权限列表信息:" + func_info); String funcInfo = JSON.toJSONString(func_info); authInfoDTO.setFuncInfo(funcInfo); //先逻辑删除,在插入 authorizationInfoDao.updateOldAuthorizationInfo(authAppId); authorizationInfoDao.insertAuthorizationInfo(authInfoDTO); // 授权信息放入缓存 - redisThird.setAuthInfo(authorizationInfoResultDTO,customerId,clientType); + redisThird.setAuthInfo(authorizationInfoResultDTO, customerId, clientType); //authorizer_refresh_token 放入缓存 redisThird.setAuthorizerRefreshToken(authInfoDTO); log.info(END_GET_AUTH_INFO); @@ -329,8 +365,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 获取/刷新接口调用令牌 * @param + * @Description 获取/刷新接口调用令牌 * @author zxc */ @Transactional(rollbackFor = Exception.class) @@ -338,7 +374,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe public void refreshToken() { //查询 即将过期的 authorizer_access_token List willOverDueResultDTOS = authorizationInfoDao.checkWillOverDue(); - if (willOverDueResultDTOS.size() != NumConstant.ZERO && null != willOverDueResultDTOS){ + if (willOverDueResultDTOS.size() != NumConstant.ZERO && null != willOverDueResultDTOS) { log.info("查询到即将过期的authorizer_access_token"); willOverDueResultDTOS.forEach(willOverDueDTO -> { String authAppId = willOverDueDTO.getAuthAppId(); @@ -346,10 +382,10 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe String clientType = willOverDueDTO.getClientType(); JSONObject jsonObject = new JSONObject(); //授权方AppId - jsonObject.put(ModuleConstant.AUTHORIZER_APPID,authAppId); + jsonObject.put(ModuleConstant.AUTHORIZER_APPID, authAppId); //第三方平台AppId - jsonObject.put(ModuleConstant.COMPONENT_APPID,componentAppId); - jsonObject.put(ModuleConstant.AUTHORIZER_REFRESH_TOKEN,willOverDueDTO.getAuthorizerRefreshToken()); + jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId); + jsonObject.put(ModuleConstant.AUTHORIZER_REFRESH_TOKEN, willOverDueDTO.getAuthorizerRefreshToken()); String componentAccessToken = redisThird.getComponentAccessToken(); String data = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_AUTHORIZER_TOKEN_URL + componentAccessToken, JSON.toJSONString(jsonObject)).getData(); Map map = JSON.parseObject(data, HashMap.class); @@ -368,7 +404,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe formDTO.setAuthAppid(authAppId); formDTO.setClientType(clientType); AuthorizationInfoFormDTO authorizationInfo = new AuthorizationInfoFormDTO(); - BeanUtils.copyProperties(formDTO,authorizationInfo); + BeanUtils.copyProperties(formDTO, authorizationInfo); authorizationInfo.setAuthorizerAppid(authAppId); //先逻辑删除,在插入 authorizationInfoDao.deleteOldAuthorizerAccessToken(customerId, clientType); @@ -380,7 +416,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe resultDTO.setAuthorizer_refresh_token(authorizerRefreshToken); resultDTO.setAuthorizer_appid(authAppId); resultDTO.setExpires_in(7200); - redisThird.setAuthInfo(resultDTO,customerId,clientType); + redisThird.setAuthInfo(resultDTO, customerId, clientType); } }); log.info("更新authorizer_access_token成功"); @@ -389,13 +425,13 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 授权回调URL,回调时并获取授权信息 * @param + * @Description 授权回调URL, 回调时并获取授权信息 * @author zxc */ @Transactional(rollbackFor = Exception.class) @Override - public void redirectUri(TokenDto tokenDto, @RequestBody AuthCodeAndTimeFromDTO authCodeAndTime){ + public void redirectUri(TokenDto tokenDto, @RequestBody AuthCodeAndTimeFromDTO authCodeAndTime) { log.info("开始执行回调URL"); String authCode = authCodeAndTime.getAuthCode(); String clientType = authCodeAndTime.getClientType(); @@ -413,7 +449,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe formDTO.setClientType(clientType); formDTO.setCustomerId(customerId); log.info(ThirdRunTimeInfoConstant.BEGIN_DELETE_INSERT_AUTH_CODE); - authCodeDao.deleteCustomerAuthCode(customerId,clientType); + authCodeDao.deleteCustomerAuthCode(customerId, clientType); authCodeDao.insertRedirectAuthCode(formDTO); //authCode存缓存 redisThird.setAuthCode(formDTO); @@ -423,12 +459,12 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe List fixationAppIdResultDTOS = fixationAppIdDao.selectFixationInfos(); String finalCustomerId = customerId;// fixationAppIdResultDTOS.forEach(fixationAppId -> { - if (fixationAppId.getAppId().equals(authAppId)){ + if (fixationAppId.getAppId().equals(authAppId)) { // TODO 是城阳项目或者党群e事通 // crm表中的customerId【原customerId】 String masterCustomerId = fixationAppId.getMasterCustomerId(); formDTO.setCustomerId(masterCustomerId); - authCodeDao.deleteCustomerAuthCode(finalCustomerId,clientType); + authCodeDao.deleteCustomerAuthCode(finalCustomerId, clientType); authCodeDao.insertRedirectAuthCode(formDTO); //authCode存缓存 redisThird.setAuthCode(formDTO); @@ -447,37 +483,37 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe //替换 新customerId为旧customerId customerId = formDTO.getCustomerId(); // 2. 创建开放平台账号并绑定 或者 直接绑定开放平台 - this.createAndBindOpenAccount(customerId,authAppId,clientType); + this.createAndBindOpenAccount(customerId, authAppId, clientType); // 3. 更新 customer_mp 表授权状态和AuthAppId - this.updateCustomerMpAppId(customerId,authAppId,clientType); - authCodeDao.updateAppId(customerId,clientType,authAppId); + this.updateCustomerMpAppId(customerId, authAppId, clientType); + authCodeDao.updateAppId(customerId, clientType, authAppId); // 4. 保存授权方账户信息 - this.saveAuthAccountInfo(customerId,authAppId,clientType); + this.saveAuthAccountInfo(customerId, authAppId, clientType); // 5. 校验客户居民端、工作端小程序是否全部授权,全部授权完成的推送钉钉消息 sun this.checkAuthorization(customerId); log.info("回调结束"); } /** - * @Description 获取授权方的帐号基本信息并保存 * @param customerId * @param authAppId + * @Description 获取授权方的帐号基本信息并保存 * @author zxc */ @Transactional(rollbackFor = Exception.class) - public void saveAuthAccountInfo(String customerId, String authAppId,String clientType) { + public void saveAuthAccountInfo(String customerId, String authAppId, String clientType) { log.info("开始执行保存授权账户基本信息"); JSONObject jsonObject = new JSONObject(); - jsonObject.put(ModuleConstant.COMPONENT_APP_ID,componentAppId); - jsonObject.put(ModuleConstant.AUTHORIZER_APP_ID,authAppId); + jsonObject.put(ModuleConstant.COMPONENT_APP_ID, componentAppId); + jsonObject.put(ModuleConstant.AUTHORIZER_APP_ID, authAppId); String componentAccessToken = redisThird.getComponentAccessToken(); - String data = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_GET_AUTHORIZER_INFO + componentAccessToken , JSON.toJSONString(jsonObject)).getData(); - Map map = JSON.parseObject(data, Map.class); + String data = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_GET_AUTHORIZER_INFO + componentAccessToken, JSON.toJSONString(jsonObject)).getData(); + Map map = JSON.parseObject(data, Map.class); Map authorizerInfo = map.get(ModuleConstant.AUTHORIZER_INFO); - log.info("授权信息:"+authorizerInfo); + log.info("授权信息:" + authorizerInfo); // 存在 “miniprograminfo” 字段为小程序,不存在为公众号 boolean keyExist = authorizerInfo.containsKey(ModuleConstant.MINI_PROGRAM_INFO); - if (keyExist == true){ + if (keyExist == true) { log.info("授权方为小程序 并 开始插入信息"); MiniInfoFormDTO miniInfoFormDTO = ConvertUtils.mapToEntity(authorizerInfo, MiniInfoFormDTO.class); miniInfoFormDTO.setCustomerId(customerId); @@ -498,22 +534,22 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe businessInfoForm.setPrimaryId(primaryId); businessInfoList.add(businessInfoForm); }); - businessInfoDao.deleteBusinessInfo(customerId,clientType); + businessInfoDao.deleteBusinessInfo(customerId, clientType); businessInfoDao.insertBusinessInfo(businessInfoList); //todo 小程序配置的合法域名信息插入 Map miniProgramInfo = (Map) authorizerInfo.get(ModuleConstant.MINI_PROGRAM_INFO); List networkInfoList = new ArrayList<>(); Map networkInfo = (Map) miniProgramInfo.get(ModuleConstant.NETWORK); - networkInfo.forEach((key,value) -> { + networkInfo.forEach((key, value) -> { MiniNetworkInfoFormDTO miniNetworkInfoForm = new MiniNetworkInfoFormDTO(); - miniNetworkInfoForm .setCustomerId(customerId); + miniNetworkInfoForm.setCustomerId(customerId); miniNetworkInfoForm.setClientType(clientType); miniNetworkInfoForm.setNetworkType(key.toString()); miniNetworkInfoForm.setUrl(value.toString()); miniNetworkInfoForm.setPrimaryId(primaryId); networkInfoList.add(miniNetworkInfoForm); }); - miniNetworkInfoDao.deleteNetworkInfo(customerId,clientType); + miniNetworkInfoDao.deleteNetworkInfo(customerId, clientType); miniNetworkInfoDao.insertNetworkInfo(networkInfoList); //todo 小程序配置的类目信息插入 List categoryInfoList = new ArrayList<>(); @@ -533,7 +569,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe miniCategoryInfoDao.deleteCategoryInfo(customerId, clientType); miniCategoryInfoDao.insertCategoryInfo(categoryInfoList); } - }else { + } else { log.info("授权方为公众号 并 开始插入信息"); PaInfoFormDTO paInfoFormDTO = ConvertUtils.mapToEntity(authorizerInfo, PaInfoFormDTO.class); //公众号基本信息插入 @@ -551,7 +587,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe businessInfoForm.setPrimaryId(primaryId); businessInfoList.add(businessInfoForm); }); - businessInfoDao.deleteBusinessInfo(customerId,clientType); + businessInfoDao.deleteBusinessInfo(customerId, clientType); businessInfoDao.insertBusinessInfo(businessInfoList); } log.info("保存授权方基本信息结束"); @@ -559,12 +595,12 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 回填 customer_mp appId , 更改授权状态 * @param + * @Description 回填 customer_mp appId , 更改授权状态 * @author zxc */ @Transactional(rollbackFor = Exception.class) - public void updateCustomerMpAppId(String customerId,String authAppId,String clientType){ + public void updateCustomerMpAppId(String customerId, String authAppId, String clientType) { log.info("==========回填customer_mp开始=========="); Integer checkBindCount = customerMpDao.checkBind(authAppId, clientType); if (checkBindCount == NumConstant.ZERO) { @@ -578,14 +614,14 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe log.info("==========回填customer_mp结束=========="); } - public void createAndBindOpenAccount(String customerId,String authAppId,String clientType){ + public void createAndBindOpenAccount(String customerId, String authAppId, String clientType) { log.info(ThirdRunTimeInfoConstant.BEGIN_CREATE_OPEN); Map authorizerRefreshToken = redisThird.getAuthorizerRefreshToken(customerId + ThirdRedisKeyConstant.COLON + clientType); String authorizerAccessToken = authorizerRefreshToken.get("authorizerAccessToken").toString(); JSONObject bindInfoForm = new JSONObject(); - bindInfoForm.put(ModuleConstant.LOW_APP_ID,authAppId); + bindInfoForm.put(ModuleConstant.LOW_APP_ID, authAppId); String bindResult = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_OPEN_GET + authorizerAccessToken, JSON.toJSONString(bindInfoForm)).getData(); - Map bindInfo = JSON.parseObject(bindResult, Map.class); + Map bindInfo = JSON.parseObject(bindResult, Map.class); boolean bindStatus = bindInfo.containsKey(ModuleConstant.OPEN_APP_ID); if (bindStatus != true) { Integer authCount = customerMpDao.selectAuthCount(customerId); @@ -663,11 +699,11 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 转换过期时间 * @param expiresIn + * @Description 转换过期时间 * @author zxc */ - public Date countExpirationTime(String expiresIn){ + public Date countExpirationTime(String expiresIn) { expiresIn = expiresIn + "000"; Date date = new Date(); long l = date.getTime() + Long.valueOf(expiresIn); @@ -676,21 +712,21 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe } /** - * @Description 查询客户Id * @param tokenDto + * @Description 查询客户Id * @author zxc */ - public String getLoginUserCustomerId(TokenDto tokenDto){ + public String getLoginUserCustomerId(TokenDto tokenDto) { PaCustomerUserAgencyDTO result = paCustomerUserAgencyDao.selectCustomerIdByUserId(tokenDto.getUserId()); return result.getCustomerId(); } /** - * @Description 时间戳(秒级)转换 Date * @param t + * @Description 时间戳(秒级)转换 Date * @author zxc */ - public Date sToDate(String t){ + public Date sToDate(String t) { Long aLong = Long.valueOf(t + "000"); Date date = new Date(); date.setTime(aLong); @@ -699,24 +735,24 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe /** * @author sun - * @Description 校验客户两哥小程序是否完成授权 + * @Description 校验客户两哥小程序是否完成授权 */ - private void checkAuthorization(String customerId){ + private void checkAuthorization(String customerId) { List list = customerMpDao.selectByCustomerId(customerId); AtomicBoolean bl = new AtomicBoolean(false); - list.forEach(mp->{ - if(mp.getAuthorizationFlag()!=NumConstant.ONE){ + list.forEach(mp -> { + if (mp.getAuthorizationFlag() != NumConstant.ONE) { bl.set(true); } }); - if(!bl.get()){ + if (!bl.get()) { dDingNews(customerId); } } /** * @author sun - * @Description 发送钉钉消息,通知运营人员有新客户完成授权 + * @Description 发送钉钉消息,通知运营人员有新客户完成授权 */ private String dDingNews(String customerId) { //1.查询客户及管理员信息,用于发送消息使用 @@ -739,8 +775,29 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe "> 管理员称谓: " + result.getAppellation() + "\n\n" + "> 联系方式: " + result.getPhone() + "\n"); request.setMarkdown(markdown); - HttpClientManager.getInstance().sendDingMsg(JSON.toJSONString(request),url,secret); + HttpClientManager.getInstance().sendDingMsg(JSON.toJSONString(request), url, secret); return null; } + /** + * @Description 推送AuthorizerAccessToken到私有化平台们 + * @param form + * @return void + * @author wxz + * @date 2021.08.31 17:22:04 + */ + public void pushAuthorizerAccessToken2PrivateEpmets(AuthorizerAccessTokenFormDTO form) { + List platforms = thirdPlatformService.listPlatformsByActionKey(ThirdPlatformActions.PUSH_AUTHORIZER_ACCESS_TOKEN); + platforms.stream().forEach(p -> { + log.info("推送authorizer-access-token到私有化平台:platformId:{}, platformKey:{}, platformName:{}, apiUrl:{}", p.getPlatformId(), p.getPlatformKey(), p.getPlatformName(), p.getApiUrl()); + ApiService apiService = selectApiService(p.getPlatformId()); + try { + apiService.pushAuthorizerAccessToken(form, p.getPlatformId(), p.getPlatformKey()); + } catch (Exception e) { + String detail = ExceptionUtils.getErrorStackTrace(e); + log.error(detail); + } + }); + } + } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PrivateEpmetServiceImpl.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PrivateEpmetServiceImpl.java new file mode 100644 index 0000000000..35cb59cad1 --- /dev/null +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PrivateEpmetServiceImpl.java @@ -0,0 +1,71 @@ +package com.epmet.service.impl; + +import com.epmet.constant.ThirdRunTimeInfoConstant; +import com.epmet.dao.AuthorizationInfoDao; +import com.epmet.dao.ComponentAccessTokenDao; +import com.epmet.dao.ComponentVerifyTicketDao; +import com.epmet.dto.form.AuthorizationInfoFormDTO; +import com.epmet.dto.form.AuthorizerAccessTokenFormDTO; +import com.epmet.dto.form.ComponentAccessTokenFormDTO; +import com.epmet.dto.result.AuthorizationInfoResultDTO; +import com.epmet.redis.RedisThird; +import com.epmet.service.PrivateEpmetService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Slf4j +public class PrivateEpmetServiceImpl implements PrivateEpmetService { + + @Autowired + private ComponentVerifyTicketDao componentVerifyTicketDao; + + @Autowired + private AuthorizationInfoDao authorizationInfoDao; + + @Autowired + private ComponentAccessTokenDao componentAccessTokenDao; + + @Autowired + private RedisThird redisThird; + + @Transactional(rollbackFor = RuntimeException.class) + @Override + public void pushAuthorizerTokens(AuthorizerAccessTokenFormDTO input) { + System.out.println("收到AuthorizerAccessTokenFormDTO:" + input); + + //AuthorizationInfoFormDTO authorizationInfo = new AuthorizationInfoFormDTO(); + //BeanUtils.copyProperties(input,authorizationInfo); + //authorizationInfo.setAuthorizerAppid(input.getAuthAppid()); + ////先逻辑删除,在插入 + //authorizationInfoDao.deleteOldAuthorizerAccessToken(input.getCustomerId(), input.getClientType()); + //authorizationInfoDao.insertAuthorizerAccessToken(input); + ////缓存 refreshAuthorizerAccessToken + //redisThird.setAuthorizerRefreshToken(authorizationInfo); + //AuthorizationInfoResultDTO resultDTO = new AuthorizationInfoResultDTO(); + //resultDTO.setAuthorizer_access_token(input.getAuthorizerAccessToken()); + //resultDTO.setAuthorizer_refresh_token(input.getAuthorizerRefreshToken()); + //resultDTO.setAuthorizer_appid(input.getAuthAppid()); + //resultDTO.setExpires_in(7200); + //redisThird.setAuthInfo(resultDTO,input.getCustomerId(),input.getClientType()); + } + + @Override + @Transactional(rollbackFor = RuntimeException.class) + public void pushComponentAccessToken(ComponentAccessTokenFormDTO componentAccessToken) { + System.out.println("收到componentAccessToken:" + componentAccessToken); + //先逻辑删,在插入 + //componentAccessTokenDao.deleteOldComponentAccessToken(); + //componentAccessTokenDao.insertComponentAccessToken(componentAccessToken); + ////存缓存 + //redisThird.setComponentAccessToken(componentAccessToken.getComponentAccessToken()); + } + + @Override + public void pushVerifyTicket(String ticket) { + + } +} diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ThirdPlatformServiceImpl.java b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ThirdPlatformServiceImpl.java index 3d6393e17e..a3e0930e7a 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ThirdPlatformServiceImpl.java +++ b/epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ThirdPlatformServiceImpl.java @@ -12,6 +12,7 @@ import com.epmet.dto.form.CustomerFormDTO; import com.epmet.dto.form.ThirdPlatformFormDTO; import com.epmet.dto.form.PlatformRegisterFormDTO; import com.epmet.dto.form.PlatformUnregisterFormDTO; +import com.epmet.dto.result.ThirdPlatformActionsResultDTO; import com.epmet.dto.result.ThirdplatformResultDTO; import com.epmet.entity.ThirdplatformCustomerActionEntity; import com.epmet.entity.ThirdplatformCustomerRegisterEntity; @@ -160,4 +161,9 @@ public class ThirdPlatformServiceImpl implements ThirdPlatformService { thirdplatformCustomerRegisterDao.batchInsertThirdplatformCustomerRegister(entityList); } } + + @Override + public List listPlatformsByActionKey(String actionKey) { + return thirdplatformCustomerRegisterDao.listPlatformsByActionKey(actionKey); + } } diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformActionDao.xml b/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformActionDao.xml index 39de22dca5..954b8a96e6 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformActionDao.xml +++ b/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformActionDao.xml @@ -30,6 +30,23 @@ from thirdplatform_action ta where ta.PLATFORM_ID = #{platformId} and ACTION_KEY = #{action} + and ta.DEL_FLAG=0 + + + diff --git a/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformCustomerRegisterDao.xml b/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformCustomerRegisterDao.xml index 9ab368a8bc..66d039fc3c 100644 --- a/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformCustomerRegisterDao.xml +++ b/epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformCustomerRegisterDao.xml @@ -36,6 +36,20 @@ and DEL_FLAG = 0 + + + insert into thirdplatform_customer_register ( diff --git a/epmet-openapi/epmet-openapi-sdk/pom.xml b/epmet-openapi/epmet-openapi-sdk/pom.xml new file mode 100644 index 0000000000..c006c05b10 --- /dev/null +++ b/epmet-openapi/epmet-openapi-sdk/pom.xml @@ -0,0 +1,15 @@ + + + + epmet-openapi + com.epmet + 2.0.0 + + 4.0.0 + + epmet-openapi-sdk + + + \ No newline at end of file diff --git a/epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/encrypt/Md5Util.java b/epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/encrypt/Md5Util.java new file mode 100644 index 0000000000..0838048629 --- /dev/null +++ b/epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/encrypt/Md5Util.java @@ -0,0 +1,133 @@ +package com.epmet.openapi.sdk.encrypt; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class Md5Util { + /** + * 加密盐 值 + */ + public static final String SALT = "EPMET_UMD_SALT"; + + public static String md5(String string) throws Exception { + if (string == null || string.trim().length() == 0) { + return null; + } + return getMD5(string.getBytes("GBK")); + } + + private static final char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + private static String getMD5(byte[] source) throws Exception { + String s = null; + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(source); + byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数, + // 用字节表示就是 16 个字节 + char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符, + // 所以表示成 16 进制需要 32 个字符 + int k = 0; // 表示转换结果中对应的字符位置 + for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节 + // 转换成 16 进制字符的转换 + byte byte0 = tmp[i]; // 取第 i 个字节 + str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, + // >>> 为逻辑右移,将符号位一起右移 + str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换 + } + s = new String(str); // 换后的结果转换为字符串 + return s; + } + + private static String byteArrayToHexString(byte b[]) { + StringBuffer resultSb = new StringBuffer(); + for (int i = 0; i < b.length; i++) + resultSb.append(byteToHexString(b[i])); + + return resultSb.toString(); + } + + private static String byteToHexString(byte b) { + int n = b; + if (n < 0) + n += 256; + int d1 = n / 16; + int d2 = n % 16; + return hexDigits[d1] + "" + hexDigits[d2]; + } + + public static String MD5Encode(String origin, String charsetname) throws Exception { + String resultString = null; + resultString = new String(origin); + MessageDigest md = MessageDigest.getInstance("MD5"); + if (charsetname == null || "".equals(charsetname)) + resultString = byteArrayToHexString(md.digest(resultString + .getBytes())); + else + resultString = byteArrayToHexString(md.digest(resultString + .getBytes(charsetname))); + return resultString; + } + + + public static void main(String[] args) { + for (int i = 0; i < 5; i++) { + String uuid = "03a1dcd8cb1811eabac1c03fd56f7847"; + System.out.println(get12Char(uuid)); + } + } + + /** + * 获取短字符 + * + * @param str + * @return 大写 + */ + public static String get12Char(String str) { + String arr[] = ShortText(str); + String rst = (arr[0] + arr[1]).toUpperCase(); + return rst.substring(0, 4) + rst.substring(4, 8) + rst.substring(8, 12); + } + + private static String[] ShortText(String string) { + String[] chars = new String[]{ // 要使用生成URL的字符 + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", + "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", + "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", + "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; + + String hex = ""; + + MessageDigest md = null; + try { + md = MessageDigest.getInstance("MD5"); + hex = byteArrayToHexString(md.digest(SALT.concat(string) + .getBytes("utf-8"))); + } catch (Exception e) { + e.printStackTrace(); + } + + int hexLen = hex.length(); + int subHexLen = hexLen / 8; + String[] ShortStr = new String[4]; + + for (int i = 0; i < subHexLen; i++) { + String outChars = ""; + int j = i + 1; + String subHex = hex.substring(i * 8, j * 8); + long idx = Long.valueOf("3FFFFFFF", 16) & Long.valueOf(subHex, 16); + + for (int k = 0; k < 6; k++) { + int index = (int) (Long.valueOf("0000003D", 16) & idx); + outChars += chars[index]; + idx = idx >> 5; + } + ShortStr[i] = outChars; + } + + return ShortStr; + } + +} diff --git a/epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/sign/OpenApiSignUtils.java b/epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/sign/OpenApiSignUtils.java new file mode 100644 index 0000000000..e44b17aa30 --- /dev/null +++ b/epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/sign/OpenApiSignUtils.java @@ -0,0 +1,109 @@ +package com.epmet.openapi.sdk.sign; + +import com.epmet.openapi.sdk.encrypt.Md5Util; + +import java.util.*; + +/** + * OpenApi签名工具 + */ +public class OpenApiSignUtils { + + /** + * @Description 创建签名 + * @return + * @author wxz + * @date 2021.03.22 16:47 + */ + public static String createSign(Map contentMap, String signKey) throws Exception { + String str2beSigned = mapToSignStr(contentMap); + str2beSigned = str2beSigned.concat("&sign_key=").concat(signKey); + return Md5Util.md5(str2beSigned); + } + + /** + * @Description 验签 + * @return + * @author wxz + * @date 2021.03.22 16:51 + */ + public static boolean checkSign(Map contentMap, String signKey) throws Exception { + String newSign = createSign(contentMap, signKey); + return newSign.equals(contentMap.get("sign")); + } + + /** + * @Description map转化为签名明文 + * @return + * @author wxz + * @date 2021.03.22 16:47 + */ + public static String mapToSignStr(Map map) { + Set keySet = map.keySet(); + String[] keyArray = (String[])keySet.toArray(new String[keySet.size()]); + Arrays.sort(keyArray); + StringBuilder sb = new StringBuilder(); + + for(int i = 0; i < keyArray.length; ++i) { + String key = keyArray[i]; + String val = (String)map.get(key); + if (val != null && val.trim().length() > 0 && !"sign".equals(key)) { + if (!sb.toString().isEmpty()) { + sb.append("&"); + } + + sb.append(key).append("=").append((String)map.get(key)); + } + } + + return sb.toString(); + } + + public static void main(String[] args) throws Exception { + generateGetAccessTokenSign(); + System.out.println("=============="); + generateGetOrgDetailSign(); + } + + private static void generateGetAccessTokenSign() throws Exception { + long now = System.currentTimeMillis(); + System.out.println(now); + + String uuid = UUID.randomUUID().toString().replace("-", ""); + + HashMap content = new HashMap<>(); + content.put("app_id", "7d98b8af2d05752b4225709c4cfd4bd0"); + content.put("timestamp", String.valueOf(now)); + content.put("nonce", uuid); + content.put("auth_type", "take_token"); + + String secret = "3209ee9f41704482be1a1fb5873a25376f2899191ca846119d44168316bc3e44"; + + String sign = createSign(content, secret); + + System.out.println("时间戳:" + now); + System.out.println("随机数:" + uuid); + System.out.println("签名:" + sign); + } + + private static void generateGetOrgDetailSign() throws Exception { + long now = System.currentTimeMillis(); + String uuid = UUID.randomUUID().toString().replace("-", "");; + System.out.println("时间戳:" + now); + System.out.println("随机数:" + uuid); + + HashMap content = new HashMap<>(); + //content.put("orgId", "aaa"); + //content.put("test", null); + content.put("gridId", "12128e0f614f1c00a058ea9a107033b2"); + content.put("app_id", "7d98b8af2d05752b4225709c4cfd4bd0"); + content.put("timestamp", String.valueOf(now)); + content.put("nonce", uuid); + content.put("auth_type", "take_token"); + + String secret = "3209ee9f41704482be1a1fb5873a25376f2899191ca846119d44168316bc3e44"; + + String sign = createSign(content, secret); + System.out.println("签名:" + sign); + } +} diff --git a/epmet-openapi/pom.xml b/epmet-openapi/pom.xml index 9db62073f3..a3be582a53 100644 --- a/epmet-openapi/pom.xml +++ b/epmet-openapi/pom.xml @@ -13,6 +13,7 @@ epmet-openapi epmet-openapi-scan + epmet-openapi-sdk \ No newline at end of file