Browse Source

1.提取openapi-sdk

2.调整third apiService相关逻辑
3.完成推送component access token到私有化平台接口
dev_shibei_match
wxz 4 years ago
parent
commit
b5d66cebfd
  1. 22
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/redis/RedisKeys.java
  2. 1
      epmet-gateway/src/main/resources/bootstrap.yml
  3. 6
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/constant/ThirdPlatformActions.java
  4. 19
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/ThirdPlatformActionsResultDTO.java
  5. 18
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/privateepmet/GetAccessTokenResultDTO.java
  6. 22
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/ThirdOpenFeignClient.java
  7. 12
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/ThirdOpenFeignClientFallback.java
  8. 244
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/ApiService.java
  9. 18
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/DemoApiService.java
  10. 45
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/LuzhouGridPlatformApiService.java
  11. 169
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/apiservice/impl/PingyinPrivateEpmetApiService.java
  12. 50
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/PrivateEpmetController.java
  13. 30
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/TestConttroller.java
  14. 10
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformActionDao.java
  15. 10
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/ThirdplatformCustomerRegisterDao.java
  16. 19
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/ThirdPlatformCache.java
  17. 3
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java
  18. 19
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/PrivateEpmetService.java
  19. 10
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ThirdPlatformService.java
  20. 81
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java
  21. 71
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PrivateEpmetServiceImpl.java
  22. 6
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ThirdPlatformServiceImpl.java
  23. 17
      epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformActionDao.xml
  24. 14
      epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformCustomerRegisterDao.xml
  25. 15
      epmet-openapi/epmet-openapi-sdk/pom.xml
  26. 133
      epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/encrypt/Md5Util.java
  27. 109
      epmet-openapi/epmet-openapi-sdk/src/main/java/com/epmet/openapi/sdk/sign/OpenApiSignUtils.java
  28. 1
      epmet-openapi/pom.xml

22
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

1
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
# 对外开放接口认证白名单

6
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";
}

19
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;
}

18
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;
}

22
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<List<ThirdplatformResultDTO>> 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);
}

12
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<List<ThirdplatformResultDTO>> 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);
}
}

244
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<R> {
/**
* 重试次数
*/
@ -61,13 +64,13 @@ public abstract class ApiService {
* @param headers
* @return
*/
public String sendGetRequest(String platformId, String action, Map<String, Object> params, Map<String, Object> headers) {
public R sendGetRequest(String platformId, String action, Map<String, Object> params, Map<String, Object> 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<String> result = HttpClientManager.getInstance().sendGet(thirdplatform.getBaseUrl().concat(actionEntity.getApiUrl()),
thirdplatform.getBaseUrl().startsWith("https://"),
Result<String> 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<String, Object> headers) {
public R sendPostRequest(String platformId, String action, String jsonString, Map<String, Object> headers, Map<String, String> 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<String> result = HttpClientManager.getInstance().sendPost(thirdplatform.getBaseUrl().concat(actionEntity.getApiUrl()),
thirdplatform.getBaseUrl().startsWith("https://"),
String urlParmsStr = this.convertQueryParams2String(urlParams);
Result<String> 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<String, String> 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<String, String> stringRedisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
Map<String, Object> 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<String, String, Object> hashOperations = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class).opsForHash();
Map<String, Object> 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<String, String> 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<String, String, String> 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<String, Object> map) {
String redisKey = RedisKeys.getThirdPlatformActionUrlKey(platformId);
RedisTemplate redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
HashOperations<String, String, Object> 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<java.lang.String,java.lang.String>
* @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<ThirdplatformActionEntity> actions = SpringContextUtils.getBean(ThirdplatformActionDao.class)
.listPlatformActions(platformId);
Map<String, Object> 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
* @date 2021.08.31 13:36:11
*/
public abstract void judgeResultSuccess(LZGridPlatformBaseResult result);
public abstract <T> R parsePlatformResponseResult(String resultString, Class<T> 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) {};
}

18
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<String> {
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 <T> String parsePlatformResponseResult(String resultString, Class<T> clazz) {
return null;
}
}

45
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<LZGridPlatformBaseResult> {
@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<String> platformResult = JSON.parseObject(result.getData(), LZGridPlatformBaseResult.class);
judgeResultSuccess(platformResult);
token = platformResult.getResult();
addAccessTokenToCache(platformId, token, (long)(3600*1.8*1000), TimeUnit.MILLISECONDS);
LZGridPlatformBaseResult<String> 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<String> 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<String> lzResult = JSON.parseObject(result, LZGridPlatformBaseResult.class);
// 此处设置为第三方系统返回的唯一id
projectAssistResult.setTaskId(lzResult.getResult());
}
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 <T> LZGridPlatformBaseResult<T> parsePlatformResponseResult(String resultString, Class<T> clazz) {
LZGridPlatformBaseResult<T> 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);
LZGridPlatformBaseResult<String> baseResult = sendPostRequestToUploadFile(platformId, ThirdPlatformActions.UPLOAD_FILE, file, fileName);
// 此处设置为第三方系统返回的唯一id
resultDTO.setUrl((String) lzResult.getResult());
}
resultDTO.setUrl(baseResult.getResult());
System.out.println("泸州网格化平台项目文件上传成功");
} catch (Exception e) {
throw new RenException("上传失败");

169
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<Result> 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<String> stringResult = HttpClientManager.getInstance().sendPostByHttps(requestUrl, "{}");
String remoteResultString = getResultDataOrThrowsException(stringResult, "【调用平阴私有化平台获取AccessToken】", EpmetErrorCode.SERVER_ERROR.getCode(), null);
Result<GetAccessTokenResultDTO> 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<String, String> requestBodyMap) {
HashMap<String, String> 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<java.lang.String,java.lang.String>
* @author wxz
* @date 2021.08.31 14:19:41
*/
private Map<String, String> constructCommonUrlParamsMap(String platformKey, String authType, String nonce, Long timeMillis, String sign) {
HashMap<String, String> 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 <T> Result<T> parsePlatformResponseResult(String resultString, Class<T> clazz) {
Result<T> result;
try {
result = JSON.parseObject(resultString, new TypeReference<Result<T>>(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<String, String> 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<String, String> 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) {
}
}

50
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();
}
}

30
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();
}
}

10
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<ThirdplatformActionEntit
* @date 2021.03.16 13:35
*/
ThirdplatformActionEntity getByPlatformIdAndActionKey(@Param("platformId") String platformId, @Param("action") String action);
/**
* @Description 列出平台的操作列表
* @param platformId
* @return com.epmet.entity.ThirdplatformActionEntity
* @author wxz
* @date 2021.08.31 15:23:14
*/
List<ThirdplatformActionEntity> listPlatformActions(@Param("platformId") String platformId);
}

10
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<ThirdplatformC
* @Date 10:15 2021-04-09
**/
void unregisterPlatformCustomer(PlatformUnregisterFormDTO formDTO);
/**
* @Description 已知操作的key查询哪些app可以做此操作
* @param actionKey 操作key
* @return java.util.List<com.epmet.dto.result.ThirdPlatformActionsResultDTO>
* @author wxz
* @date 2021.08.30 17:07:32
*/
List<ThirdPlatformActionsResultDTO> listPlatformsByActionKey(@Param("actionKey") String actionKey);
}

19
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;
}

3
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);
}

19
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);
}

10
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<com.epmet.dto.result.ThirdplatformResultDTO>
* @author wxz
* @date 2021.08.30 16:59:13
*/
List<ThirdPlatformActionsResultDTO> listPlatformsByActionKey(String actionKey);
}

81
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)
@ -181,8 +189,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 授权结果插入
* @param result
* @Description 授权结果插入
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@ -199,9 +207,9 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @param accessTokenCountFlag 表里的 component_access_token的数量
* @Description 定时获取 (令牌component_access_token) 第三方与微信交互使用的component_access_token
* 每十分钟执行一次,判断是否有马上超时的15分钟以内算马上超时
* @param accessTokenCountFlag 表里的 component_access_token的数量
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@ -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<ThirdPlatformActionsResultDTO> 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)
@ -329,8 +365,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 获取/刷新接口调用令牌
* @param
* @Description 获取/刷新接口调用令牌
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@ -389,8 +425,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 授权回调URL,回调时并获取授权信息
* @param
* @Description 授权回调URL, 回调时并获取授权信息
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@ -459,9 +495,9 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 获取授权方的帐号基本信息并保存
* @param customerId
* @param authAppId
* @Description 获取授权方的帐号基本信息并保存
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@ -559,8 +595,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 回填 customer_mp appId , 更改授权状态
* @param
* @Description 回填 customer_mp appId , 更改授权状态
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@ -663,8 +699,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 转换过期时间
* @param expiresIn
* @Description 转换过期时间
* @author zxc
*/
public Date countExpirationTime(String expiresIn) {
@ -676,8 +712,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 查询客户Id
* @param tokenDto
* @Description 查询客户Id
* @author zxc
*/
public String getLoginUserCustomerId(TokenDto tokenDto) {
@ -686,8 +722,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
}
/**
* @Description 时间戳秒级转换 Date
* @param t
* @Description 时间戳秒级转换 Date
* @author zxc
*/
public Date sToDate(String t) {
@ -743,4 +779,25 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
return null;
}
/**
* @Description 推送AuthorizerAccessToken到私有化平台们
* @param form
* @return void
* @author wxz
* @date 2021.08.31 17:22:04
*/
public void pushAuthorizerAccessToken2PrivateEpmets(AuthorizerAccessTokenFormDTO form) {
List<ThirdPlatformActionsResultDTO> 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);
}
});
}
}

71
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) {
}
}

6
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<ThirdPlatformActionsResultDTO> listPlatformsByActionKey(String actionKey) {
return thirdplatformCustomerRegisterDao.listPlatformsByActionKey(actionKey);
}
}

17
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
</select>
<select id="listPlatformActions" resultType="com.epmet.entity.ThirdplatformActionEntity">
select id,
platform_id,
action_key,
api_url,
del_flag,
revision,
created_by,
created_time,
updated_by,
updated_time
from thirdplatform_action ta
where ta.PLATFORM_ID = #{platformId}
and ta.DEL_FLAG=0
</select>

14
epmet-module/epmet-third/epmet-third-server/src/main/resources/mapper/ThirdplatformCustomerRegisterDao.xml

@ -36,6 +36,20 @@
and DEL_FLAG = 0
</select>
<!--已知操作的key,查询哪些app可以做此操作-->
<select id="listPlatformsByActionKey" resultType="com.epmet.dto.result.ThirdPlatformActionsResultDTO">
select thirdplatform_action.PLATFORM_ID,
thirdplatform.PLATFORM_KEY,
thirdplatform.PLATFORM_NAME,
thirdplatform_action.ACTION_KEY,
thirdplatform_action.API_URL
from thirdplatform
inner join thirdplatform_action
on (thirdplatform.ID = thirdplatform_action.PLATFORM_ID and thirdplatform_action.DEL_FLAG = 0)
and thirdplatform_action.ACTION_KEY = #{actionKey}
and thirdplatform.DEL_FLAG = 0
</select>
<insert id="batchInsertThirdplatformCustomerRegister" parameterType="map">
insert into thirdplatform_customer_register
(

15
epmet-openapi/epmet-openapi-sdk/pom.xml

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>epmet-openapi</artifactId>
<groupId>com.epmet</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>epmet-openapi-sdk</artifactId>
</project>

133
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;
}
}

109
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<String, String> 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<String, String> 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<String, String> map) {
Set<String> 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<String, String> 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<String, String> 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);
}
}

1
epmet-openapi/pom.xml

@ -13,6 +13,7 @@
<artifactId>epmet-openapi</artifactId>
<modules>
<module>epmet-openapi-scan</module>
<module>epmet-openapi-sdk</module>
</modules>
</project>
Loading…
Cancel
Save