Browse Source

Merge branches 'dev' and 'dev_heart' of http://git.elinkit.com.cn:7070/r/epmet-cloud into dev_heart

dev_shibei_match
yinzuomei 6 years ago
parent
commit
54f0651268
  1. 49
      epmet-auth/src/main/java/com/epmet/controller/ThirdLoginController.java
  2. 28
      epmet-auth/src/main/java/com/epmet/dto/form/LoginFormDTO.java
  3. 27
      epmet-auth/src/main/java/com/epmet/service/ThirdLoginService.java
  4. 38
      epmet-auth/src/main/java/com/epmet/service/impl/PublicUserLoginServiceImpl.java
  5. 348
      epmet-auth/src/main/java/com/epmet/service/impl/ThirdLoginServiceImpl.java
  6. 8
      epmet-commons/epmet-commons-tools/pom.xml
  7. 6
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java
  8. 27
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/utils/HttpClientManager.java
  9. 53
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/utils/MultipartFileToFileUtils.java
  10. 2
      epmet-gateway/deploy/docker-compose-test.yml
  11. 2
      epmet-module/epmet-job/epmet-job-server/deploy/docker-compose-dev.yml
  12. 7
      epmet-module/epmet-job/epmet-job-server/pom.xml
  13. 13
      epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/ComponentAccessTokenService.java
  14. 13
      epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/RefreshAuthAccessTokenService.java
  15. 25
      epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/impl/ComponentAccessTokenServiceImpl.java
  16. 23
      epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/impl/RefreshAuthAccessTokenServiceImpl.java
  17. 34
      epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/task/ComponentAccessTokenTask.java
  18. 32
      epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/task/RefreshAuthAccessTokenTask.java
  19. 6
      epmet-module/epmet-third/epmet-third-client/pom.xml
  20. 91
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/CodeExtDTO.java
  21. 2
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/CodeOperationHistoryDTO.java
  22. 7
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/PaCustomerAgencyDTO.java
  23. 18
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/CodeAuditRecordFormDTO.java
  24. 2
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/CodeCommonFormDTO.java
  25. 19
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/MediaUploadFormDTO.java
  26. 14
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/MiniInfoFormDTO.java
  27. 26
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/MyInfoFormDTO.java
  28. 14
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/PaInfoFormDTO.java
  29. 27
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/WxLoginFormDTO.java
  30. 34
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/CodeHistoryResultDTO.java
  31. 4
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/CreateAgencyResultDTO.java
  32. 5
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/CustomerUserResultDTO.java
  33. 32
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/InitCustomerResultDTO.java
  34. 17
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/MediaUploadResultDTO.java
  35. 22
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/PublicCustomerResultDTO.java
  36. 22
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/QrCodeResultDTO.java
  37. 26
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/ReasonResultDTO.java
  38. 2
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/TemplateListResultDTO.java
  39. 57
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/EpmetThirdFeignClient.java
  40. 34
      epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/EpmetThirdFeignClientFallback.java
  41. 2
      epmet-module/epmet-third/epmet-third-server/deploy/docker-compose-dev.yml
  42. 2
      epmet-module/epmet-third/epmet-third-server/deploy/docker-compose-test.yml
  43. 2
      epmet-module/epmet-third/epmet-third-server/pom.xml
  44. 5
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/CodeConstant.java
  45. 8
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/ModuleConstant.java
  46. 8
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/PaConstant.java
  47. 59
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/ThirdApiConstant.java
  48. 2
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/ThirdRunTimeInfoConstant.java
  49. 8
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/AuthRedirectController.java
  50. 133
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CodeController.java
  51. 84
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CodeExtController.java
  52. 32
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CodeOperationHistoryController.java
  53. 2
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/ComponentVerifyTicketController.java
  54. 27
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CustomerMpController.java
  55. 37
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/PaCustomerController.java
  56. 2
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/WarrantController.java
  57. 4
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/WeChatNotifyController.java
  58. 20
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CodeCustomerDao.java
  59. 54
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CodeExtDao.java
  60. 48
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CodeOperationHistoryDao.java
  61. 26
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CustomerMpDao.java
  62. 2
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/FuncInfoDao.java
  63. 8
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/PaCustomerAgencyDao.java
  64. 8
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/PaCustomerDao.java
  65. 8
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/PaUserDao.java
  66. 61
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/entity/CodeExtEntity.java
  67. 4
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/entity/CodeOperationHistoryEntity.java
  68. 65
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/exception/AesException.java
  69. 96
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/AesDecryptUtil.java
  70. 59
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/AesException.java
  71. 26
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/ByteGroup.java
  72. 67
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/PKCS7Encoder.java
  73. 65
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/SHA1.java
  74. 283
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/WXBizMsgCrypt.java
  75. 41
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/WXXmlToMapUtil.java
  76. 73
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/XMLParse.java
  77. 32
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/CodeExtRedis.java
  78. 2
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/CodeOperationHistoryRedis.java
  79. 30
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/RedisThird.java
  80. 19
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeCustomerService.java
  81. 116
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeExtService.java
  82. 37
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeOperationHistoryService.java
  83. 76
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeService.java
  84. 5
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java
  85. 29
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CustomerMpService.java
  86. 22
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/PaCustomerService.java
  87. 3
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/WarrantService.java
  88. 19
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/AppLetAuthorizationServiceImpl.java
  89. 10
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeCustomerServiceImpl.java
  90. 58
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeExtServiceImpl.java
  91. 115
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeOperationHistoryServiceImpl.java
  92. 291
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeServiceImpl.java
  93. 185
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java
  94. 66
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CustomerMpServiceImpl.java
  95. 91
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PaCustomerServiceImpl.java
  96. 11
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PaUserServiceImpl.java
  97. 42
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/WarrantServiceImpl.java
  98. 30
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/OkHttpHelper.java
  99. 63
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/PKCS7EncoderUtil.java
  100. 246
      epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/WXBizMsgCrypt.java

49
epmet-auth/src/main/java/com/epmet/controller/ThirdLoginController.java

@ -0,0 +1,49 @@
package com.epmet.controller;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.dto.form.LoginFormDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.service.ThirdLoginService;
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 第三方-居民端政府端登陆服务
* @author sun
*/
@RestController
@RequestMapping("thirdlogin")
public class ThirdLoginController {
@Autowired
private ThirdLoginService thirdLoginService;
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-居民端微信小程序登录
**/
@PostMapping("resilogin")
public Result<UserTokenResultDTO> resiLogin(@RequestBody LoginFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO);
return new Result<UserTokenResultDTO>().ok(thirdLoginService.resiLogin(formDTO));
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-政府端微信小程序登录
**/
@PostMapping("worklogin")
public Result<UserTokenResultDTO> workLogin(@RequestBody LoginFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO);
return new Result<UserTokenResultDTO>().ok(thirdLoginService.workLogin(formDTO));
}
}

28
epmet-auth/src/main/java/com/epmet/dto/form/LoginFormDTO.java

@ -0,0 +1,28 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 单客户-居民端微信小程序登录
* @Author sun
*/
@Data
public class LoginFormDTO extends LoginCommonFormDTO implements Serializable {
private static final long serialVersionUID = 7950477424010655108L;
/**
* 小程序appId
*/
@NotBlank(message = "appId不能为空",groups = {AddUserInternalGroup.class})
private String appId;
/**
* 用户微信code
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
}

27
epmet-auth/src/main/java/com/epmet/service/ThirdLoginService.java

@ -0,0 +1,27 @@
package com.epmet.service;
import com.epmet.dto.form.LoginFormDTO;
import com.epmet.dto.result.UserTokenResultDTO;
/**
* @Description 第三方-居民端政府端登陆服务
* @author sun
*/
public interface ThirdLoginService {
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-居民端微信小程序登录
**/
UserTokenResultDTO resiLogin(LoginFormDTO formDTO);
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-政府端微信小程序登录
**/
UserTokenResultDTO workLogin(LoginFormDTO formDTO);
}

38
epmet-auth/src/main/java/com/epmet/service/impl/PublicUserLoginServiceImpl.java

@ -12,6 +12,7 @@ import com.epmet.constant.PublicUserLoginConstant;
import com.epmet.constant.SmsTemplateConstant;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.PaUserDTO;
import com.epmet.dto.PaUserWechatDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.CustomerUserResultDTO;
import com.epmet.dto.result.SaveUserResultDTO;
@ -77,7 +78,9 @@ public class PublicUserLoginServiceImpl implements PublicUserLoginService {
//3.获取用户token
String token = this.generateGovWxmpToken(resultDTO.getUserId());
//4.保存到redis
this.saveLatestGovTokenDto(resultDTO, wxMpUser, token);
String openid = wxMpUser.getOpenId();
String unionId = (null == wxMpUser.getUnionId() ? "" : wxMpUser.getUnionId());
this.saveLatestGovTokenDto("", resultDTO.getUserId(), openid, unionId, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
@ -118,17 +121,17 @@ public class PublicUserLoginServiceImpl implements PublicUserLoginService {
}
//保存tokenDto到redis
private void saveLatestGovTokenDto(SaveUserResultDTO resultDTO, WxMpUser wxMpUser, String token) {
private void saveLatestGovTokenDto(String customerId, String userId, String openId, String unionId, String token) {
TokenDto tokenDTO = new TokenDto();
int expire = jwtTokenProperties.getExpire();
tokenDTO.setApp(LoginConstant.APP_PUBLIC);
tokenDTO.setClient(LoginConstant.CLIENT_MP);
tokenDTO.setOpenId(wxMpUser.getOpenId());
tokenDTO.setUnionId(null == wxMpUser.getUnionId() ? "" : wxMpUser.getUnionId());
tokenDTO.setOpenId(openId);
tokenDTO.setUnionId(unionId);
tokenDTO.setToken(token);
//首次初始化时还没有客户
tokenDTO.setCustomerId("");
tokenDTO.setUserId(resultDTO.getUserId());
tokenDTO.setCustomerId(customerId);
tokenDTO.setUserId(userId);
tokenDTO.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
tokenDTO.setUpdateTime(System.currentTimeMillis());
cpUserDetailRedis.set(tokenDTO, expire);
@ -206,19 +209,22 @@ public class PublicUserLoginServiceImpl implements PublicUserLoginService {
logger.error(String.format("验证码错误code[%s],msg[%s]", EpmetErrorCode.MOBILE_CODE_ERROR.getCode(), EpmetErrorCode.MOBILE_CODE_ERROR.getMsg()));
throw new RenException(EpmetErrorCode.MOBILE_CODE_ERROR.getCode());
}
//获取缓存中的token
TokenDto redisTokenDTO = cpUserDetailRedis.get(LoginConstant.APP_PUBLIC, LoginConstant.CLIENT_MP, userDTO.getId(), TokenDto.class);
if (redisTokenDTO == null) {
return null;
}
//4.判断是否存在客户信息,是否需要生成新的token
//生成的token是根据登陆手机号对应的user生成的token,访问记录表记录的是那个user根据自己或他人的手机号登陆的
//4.直接生成一个新的token放入缓存中(不管缓存中是否存在旧的token,都重新生成)
//4-1.生成token
String token = this.generateGovWxmpToken(userDTO.getId());
//4-2.判断是否存在信息,给customerId赋值
PaCustomerDTO customerDTO = resultDTO.getPaCustomerResult();
String customerId = "";
if (null != customerDTO && !StringUtils.isBlank(customerDTO.getId())) {
redisTokenDTO.setCustomerId(customerDTO.getId());
int expire = jwtTokenProperties.getExpire();
cpUserDetailRedis.set(redisTokenDTO, expire);
customerId = customerDTO.getId();
}
//4-3.token存入redis
PaUserWechatDTO wechatDTO = resultDTO.getPaUserWechatResult();
String openid = wechatDTO.getWxOpenId();
String unionId = (null == wechatDTO.getUnionId() ? "" : wechatDTO.getUnionId());
this.saveLatestGovTokenDto(customerId, userDTO.getId(), openid, unionId, token);
//5.登陆成功,访问记录表新增访问记录(访问记录新增失败不应影响用户登陆)
SaveUserVisitedFormDTO visited = new SaveUserVisitedFormDTO();
@ -232,7 +238,7 @@ public class PublicUserLoginServiceImpl implements PublicUserLoginService {
//6.返回token
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(redisTokenDTO.getToken());
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}

348
epmet-auth/src/main/java/com/epmet/service/impl/ThirdLoginServiceImpl.java

@ -0,0 +1,348 @@
package com.epmet.service.impl;
import com.epmet.common.token.constant.LoginConstant;
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.security.dto.GovTokenDto;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.utils.CpUserDetailRedis;
import com.epmet.commons.tools.utils.DateUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.CustomerAgencyDTO;
import com.epmet.dto.GovStaffRoleDTO;
import com.epmet.dto.UserDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.DepartmentListResultDTO;
import com.epmet.dto.result.GridByStaffResultDTO;
import com.epmet.dto.result.StaffLatestAgencyResultDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.feign.EpmetThirdFeignClient;
import com.epmet.feign.EpmetUserOpenFeignClient;
import com.epmet.feign.GovOrgOpenFeignClient;
import com.epmet.jwt.JwtTokenProperties;
import com.epmet.jwt.JwtTokenUtils;
import com.epmet.service.ThirdLoginService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author sun
* @Description 第三方-居民端政府端登陆服务
*/
@Slf4j
@Service
public class ThirdLoginServiceImpl implements ThirdLoginService {
private static final Logger logger = LoggerFactory.getLogger(ThirdLoginServiceImpl.class);
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Autowired
private EpmetThirdFeignClient epmetThirdFeignClient;
@Autowired
private EpmetUserOpenFeignClient epmetUserOpenFeignClient;
@Autowired
private GovOrgOpenFeignClient govOrgOpenFeignClient;
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-居民端微信小程序登录
**/
@Override
public UserTokenResultDTO resiLogin(LoginFormDTO formDTO) {
//1.调用epmet_third服务,校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
WxLoginFormDTO resiLoginFormDTO = new WxLoginFormDTO();
resiLoginFormDTO.setAppId(formDTO.getAppId());
resiLoginFormDTO.setWxCode(formDTO.getWxCode());
Result<UserWechatDTO> result = epmetThirdFeignClient.resiAndWorkLogin(resiLoginFormDTO);
if (!result.success()) {
throw new RenException(result.getCode());
}
UserWechatDTO userWechatDTO = result.getData();
//2.调用epmet-user服务,新增用户信息(先判断用户是否存在,不存在则新增存在则更新)
WxUserFormDTO wxUserFormDTO = new WxUserFormDTO();
wxUserFormDTO.setWechatDTO(userWechatDTO);
wxUserFormDTO.setApp(formDTO.getApp());
Result<UserDTO> userResult = epmetUserOpenFeignClient.saveWxUser(wxUserFormDTO);
if (!userResult.success()) {
throw new RenException(result.getCode());
}
UserDTO userDTO = userResult.getData();
//3.生成业务token
String userId = userDTO.getId();
String token = this.generateToken(formDTO, userId);
//4.存放Redis
this.saveTokenDto(formDTO, userId, userWechatDTO, token);
//5.接口返参
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
/**
* @Description 居民端登陆生成业务token的key
**/
private String generateToken(LoginCommonFormDTO formDTO, String userId) {
Map<String, Object> map = new HashMap<>();
map.put("app", formDTO.getApp());
map.put("client", formDTO.getClient());
map.put("userId", userId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:" + formDTO.getApp() + ";client:" + formDTO.getClient() + ";userId:" + userId + ";生成token[" + token + "]");
return token;
}
/**
* @Description 将token存入redis
**/
private String saveTokenDto(LoginCommonFormDTO formDTO, String userId, UserWechatDTO userWechatDTO, String token) {
int expire = jwtTokenProperties.getExpire();
TokenDto tokenDto = new TokenDto();
tokenDto.setApp(formDTO.getApp());
tokenDto.setClient(formDTO.getClient());
tokenDto.setUserId(userId);
tokenDto.setOpenId(userWechatDTO.getWxOpenId());
tokenDto.setSessionKey(userWechatDTO.getSessionKey());
tokenDto.setUnionId(userWechatDTO.getUnionId());
tokenDto.setToken(token);
tokenDto.setUpdateTime(System.currentTimeMillis());
tokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
cpUserDetailRedis.set(tokenDto, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
return token;
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-政府端微信小程序登录
**/
@Override
public UserTokenResultDTO workLogin(LoginFormDTO formDTO) {
//1.调用epmet_third服务,校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
WxLoginFormDTO resiLoginFormDTO = new WxLoginFormDTO();
resiLoginFormDTO.setAppId(formDTO.getAppId());
resiLoginFormDTO.setWxCode(formDTO.getWxCode());
Result<UserWechatDTO> result = epmetThirdFeignClient.resiAndWorkLogin(resiLoginFormDTO);
if (!result.success()) {
throw new RenException(result.getCode());
}
UserWechatDTO userWechatDTO = result.getData();
//2.根据openid查询用户是否存在历史登陆信息
Result<StaffLatestAgencyResultDTO> latestStaffWechat = epmetUserOpenFeignClient.getLatestStaffWechatLoginRecord(userWechatDTO.getWxOpenId());
if (!latestStaffWechat.success() || null == latestStaffWechat.getData()) {
logger.error(String.format("没有获取到用户最近一次登录账户信息,code[%s],msg[%s]", EpmetErrorCode.PLEASE_LOGIN.getCode(), EpmetErrorCode.PLEASE_LOGIN.getMsg()));
throw new RenException(EpmetErrorCode.PLEASE_LOGIN.getCode());
}
StaffLatestAgencyResultDTO staffLatestAgencyResultDTO = latestStaffWechat.getData();
//3.记录staff_wechat
this.savestaffwechat(staffLatestAgencyResultDTO.getStaffId(), userWechatDTO.getWxOpenId());
//4.记录登录日志
this.saveStaffLoginRecord(staffLatestAgencyResultDTO);
//5.获取用户token
String token = this.generateGovWxmpToken(staffLatestAgencyResultDTO.getStaffId());
//6.保存到redis
this.saveLatestGovTokenDto(staffLatestAgencyResultDTO, userWechatDTO, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
/**
* @param userId openid
* @return
* @Author sun
* @Description 保存微信和当前登录用户关系
**/
private Result savestaffwechat(String userId, String openid) {
StaffWechatFormDTO staffWechatFormDTO = new StaffWechatFormDTO();
staffWechatFormDTO.setUserId(userId);
staffWechatFormDTO.setWxOpenId(openid);
return epmetUserOpenFeignClient.saveStaffWechat(staffWechatFormDTO);
}
/**
* @param latestStaffWechatLoginDTO
* @return
* @Author sun
* @Description 保存登录日志
**/
private Result saveStaffLoginRecord(StaffLatestAgencyResultDTO latestStaffWechatLoginDTO) {
StaffLoginAgencyRecordFormDTO staffLoginAgencyRecordFormDTO = new StaffLoginAgencyRecordFormDTO();
staffLoginAgencyRecordFormDTO.setCustomerId(latestStaffWechatLoginDTO.getCustomerId());
staffLoginAgencyRecordFormDTO.setStaffId(latestStaffWechatLoginDTO.getStaffId());
staffLoginAgencyRecordFormDTO.setWxOpenId(latestStaffWechatLoginDTO.getWxOpenId());
staffLoginAgencyRecordFormDTO.setMobile(latestStaffWechatLoginDTO.getMobile());
staffLoginAgencyRecordFormDTO.setAgencyId(latestStaffWechatLoginDTO.getAgencyId());
Result staffLoginRecordResult = epmetUserOpenFeignClient.saveStaffLoginRecord(staffLoginAgencyRecordFormDTO);
return staffLoginRecordResult;
}
/**
* @Description 生成政府端小程序业务token Key
* @Author sun
**/
private String generateGovWxmpToken(String staffId) {
Map<String, Object> map = new HashMap<>();
map.put("app", LoginConstant.APP_GOV);
map.put("client", LoginConstant.CLIENT_WXMP);
map.put("userId", staffId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:" + LoginConstant.APP_GOV + ";client:" + LoginConstant.CLIENT_WXMP + ";userId:" + staffId + ";生成token[" + token + "]");
return token;
}
/**
* @Description 保存tokenDto到redis
* @Author sun
**/
private void saveLatestGovTokenDto(StaffLatestAgencyResultDTO staffLatestAgency, UserWechatDTO userWechatDTO, String token) {
int expire = jwtTokenProperties.getExpire();
GovTokenDto govTokenDto = new GovTokenDto();
govTokenDto.setApp(LoginConstant.APP_GOV);
govTokenDto.setClient(LoginConstant.CLIENT_WXMP);
govTokenDto.setUserId(staffLatestAgency.getStaffId());
govTokenDto.setOpenId(userWechatDTO.getWxOpenId());
govTokenDto.setSessionKey(userWechatDTO.getSessionKey());
govTokenDto.setUnionId(userWechatDTO.getUnionId());
govTokenDto.setToken(token);
govTokenDto.setUpdateTime(System.currentTimeMillis());
govTokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
govTokenDto.setRootAgencyId(staffLatestAgency.getAgencyId());
govTokenDto.setCustomerId(staffLatestAgency.getCustomerId());
//设置部门,网格,角色列表
govTokenDto.setDeptIdList(getDeptartmentIdList(staffLatestAgency.getStaffId()));
govTokenDto.setGridIdList(getGridIdList(staffLatestAgency.getStaffId()));
CustomerAgencyDTO agency = getAgencyByStaffId(staffLatestAgency.getStaffId());
if (agency != null) {
govTokenDto.setAgencyId(agency.getId());
govTokenDto.setRoleList(queryGovStaffRoles(staffLatestAgency.getStaffId(), agency.getId()));
}
govTokenDto.setOrgIdPath(getOrgIdPath(staffLatestAgency.getStaffId()));
cpUserDetailRedis.set(govTokenDto, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
}
public Set<String> getDeptartmentIdList(String staffId) {
try {
Result<List<DepartmentListResultDTO>> deptListResult = govOrgOpenFeignClient.getDepartmentListByStaffId(staffId);
if (deptListResult.success()) {
if (!CollectionUtils.isEmpty(deptListResult.getData())) {
Set<String> deptIdLists = deptListResult.getData().stream().map(dept -> dept.getDepartmentId()).collect(Collectors.toSet());
return deptIdLists;
}
} else {
logger.error("登录:查询部门列表,远程调用返回错误:{}", deptListResult.getMsg());
}
} catch (Exception e) {
String errorStackTrace = ExceptionUtils.getErrorStackTrace(e);
logger.error("登录:查询部门列表异常:{}", errorStackTrace);
}
return null;
}
/**
* 根据工作人员ID查询网格ID列表
*
* @param staffId
* @return
*/
public Set<String> getGridIdList(String staffId) {
Result<List<GridByStaffResultDTO>> result = govOrgOpenFeignClient.listGridsbystaffid(staffId);
if (!result.success()) {
logger.error("登录:查询网格列表,远程调用返回错误:{}", result.getMsg());
return null;
} else {
List<GridByStaffResultDTO> grids = result.getData();
return grids.stream().map(grid -> grid.getGridId()).collect(Collectors.toSet());
}
}
/**
* 根据staffId查询所属的组织机构
*
* @param staffId
*/
public CustomerAgencyDTO getAgencyByStaffId(String staffId) {
Result<CustomerAgencyDTO> result = govOrgOpenFeignClient.getAgencyByStaff(staffId);
if (!result.success()) {
logger.error("登录:查询登录人所属的机关OrgIdPath失败:{}", result.getMsg());
return null;
}
return result.getData();
}
/**
* 查询人员在某机关单位下的角色列表
*
* @param staffId orgId
*/
public List<GovTokenDto.Role> queryGovStaffRoles(String staffId, String orgId) {
StaffRoleFormDTO formDTO = new StaffRoleFormDTO();
formDTO.setStaffId(staffId);
formDTO.setOrgId(orgId);
Result<List<GovStaffRoleDTO>> gridResult = epmetUserOpenFeignClient.getRolesOfStaff(formDTO);
if (!CollectionUtils.isEmpty(gridResult.getData())) {
//return gridResult.getData().stream().map(role -> role.getId()).collect(Collectors.toSet());
return ConvertUtils.sourceToTarget(gridResult.getData(), GovTokenDto.Role.class);
}
return null;
}
/**
* 查询工作人员的OrgIdPath
*
* @param staffId
* @return
*/
public String getOrgIdPath(String staffId) {
Result<CustomerAgencyDTO> result = govOrgOpenFeignClient.getAgencyByStaff(staffId);
if (!result.success()) {
logger.error("登录:查询登录人所属的机关OrgIdPath失败:{}", result.getMsg());
return null;
}
CustomerAgencyDTO agency = result.getData();
if (agency != null) {
if ("0".equals(agency.getPid())) {
// 顶级
return agency.getId();
} else {
return agency.getPids().concat(":").concat(agency.getId());
}
}
return null;
}
}

8
epmet-commons/epmet-commons-tools/pom.xml

@ -129,6 +129,14 @@
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
</dependencies>
<build>

6
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/exception/EpmetErrorCode.java

@ -85,7 +85,11 @@ public enum EpmetErrorCode {
CUSTOMER_VALIDATE_ERROR(8999, "内部数据校验异常"),
//公众号 865..开头的码
PUBLIC_NOT_EXISTS(8651,"手机号未注册,请先完成信息注册");
PUBLIC_NOT_EXISTS(8651,"手机号未注册,请先完成信息注册"),
SELECT_CUSTOMER_ERROR(8652,"未查询到注册客户信息"),
SELECT_AGENCY_ERROR(8653,"根据客户信息未查询到注册客户组织信息"),
SELECT_USER_ERROR(8654,"根据客户信息未查询到注册客户管理员信息"),
UPDATE_CUSTOMER_ERROR(8655,"更新注册客户信息为已完成初始化失败");
private int code;

27
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/utils/HttpClientManager.java

@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
@ -20,6 +21,8 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
@ -123,6 +126,30 @@ public class HttpClientManager {
}
/**
* 上传临时素材
* @author zhaoqifeng
* @date 2020/7/17 14:33
* @param url
* @param file
* @return com.epmet.commons.tools.utils.Result<java.lang.String>
*/
public Result<String> uploadWxMedia(String url, File file) {
try {
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
FileBody fileBody = new FileBody(file);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("media", fileBody).build();
httppost.setEntity(reqEntity);
return execute(httppost);
} catch (Exception e) {
log.error("send exception", e);
throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode(), EpmetErrorCode.SERVER_ERROR.getMsg());
}
}
/**
* desc: 发送钉钉群消息 简版
* param: url,jsonStrParam

53
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/utils/MultipartFileToFileUtils.java

@ -0,0 +1,53 @@
package com.epmet.commons.tools.utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/17 14:01
*/
public class MultipartFileToFileUtils {
/**
* MultipartFile File
*
* @param file
* @throws Exception
*/
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (("").equals(file) || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
toFile = inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
private static File inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

2
epmet-gateway/deploy/docker-compose-test.yml

@ -2,7 +2,7 @@ version: "3.7"
services:
epmet-gateway-server:
container_name: epmet-gateway-server-test
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-release/epmet-gateway:0.3.25
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-release/epmet-gateway:0.3.26
ports:
- "8080:8080"
network_mode: host # 使用现有网络

2
epmet-module/epmet-job/epmet-job-server/deploy/docker-compose-dev.yml

@ -2,7 +2,7 @@ version: "3.7"
services:
epmet-job-server:
container_name: epmet-job-server-dev
image: 192.168.1.130:10080/epmet-cloud-dev/epmet-job-server:0.3.22
image: 192.168.1.130:10080/epmet-cloud-dev/epmet-job-server:0.3.23
ports:
- "8084:8084"
network_mode: host # 使用现有网络

7
epmet-module/epmet-job/epmet-job-server/pom.xml

@ -2,7 +2,7 @@
<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">
<modelVersion>4.0.0</modelVersion>
<version>0.3.22</version>
<version>0.3.23</version>
<parent>
<groupId>com.epmet</groupId>
<artifactId>epmet-job</artifactId>
@ -33,6 +33,11 @@
<artifactId>data-statistical-client</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-third-client</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

13
epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/ComponentAccessTokenService.java

@ -0,0 +1,13 @@
package com.epmet.service;
import com.epmet.commons.tools.utils.Result;
/**
* @Author zxc
* @CreateTime 2020/7/20 10:21
*/
public interface ComponentAccessTokenService {
Result componentAccessTokenJob();
}

13
epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/RefreshAuthAccessTokenService.java

@ -0,0 +1,13 @@
package com.epmet.service;
import com.epmet.commons.tools.utils.Result;
/**
* @Author zxc
* @CreateTime 2020/7/20 10:44
*/
public interface RefreshAuthAccessTokenService {
Result refreshAuthorizerAccessTokenJob();
}

25
epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/impl/ComponentAccessTokenServiceImpl.java

@ -0,0 +1,25 @@
package com.epmet.service.impl;
import com.epmet.commons.tools.utils.Result;
import com.epmet.feign.EpmetThirdFeignClient;
import com.epmet.service.ComponentAccessTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author zxc
* @CreateTime 2020/7/20 10:22
*/
@Slf4j
@Service
public class ComponentAccessTokenServiceImpl implements ComponentAccessTokenService {
@Autowired
private EpmetThirdFeignClient epmetThirdFeignClient;
@Override
public Result componentAccessTokenJob() {
return epmetThirdFeignClient.getComponentAccessTokenJob();
}
}

23
epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/service/impl/RefreshAuthAccessTokenServiceImpl.java

@ -0,0 +1,23 @@
package com.epmet.service.impl;
import com.epmet.commons.tools.utils.Result;
import com.epmet.feign.EpmetThirdFeignClient;
import com.epmet.service.RefreshAuthAccessTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author zxc
* @CreateTime 2020/7/20 10:44
*/
@Service
public class RefreshAuthAccessTokenServiceImpl implements RefreshAuthAccessTokenService {
@Autowired
private EpmetThirdFeignClient epmetThirdFeignClient;
@Override
public Result refreshAuthorizerAccessTokenJob() {
return epmetThirdFeignClient.refreshAuthorizerAccessTokenJob();
}
}

34
epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/task/ComponentAccessTokenTask.java

@ -0,0 +1,34 @@
package com.epmet.task;
import com.epmet.commons.tools.utils.Result;
import com.epmet.service.ComponentAccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @Author zxc
* @CreateTime 2020/7/20 10:28
*/
@Component("componentAccessToken")
public class ComponentAccessTokenTask implements ITask{
@Autowired
private ComponentAccessTokenService componentAccessTokenService;
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void run(String params) {
logger.info("ComponentAccessTokenTask正在执行定时任务,参数为{}",params);
Result result = componentAccessTokenService.componentAccessTokenJob();
if (result.success()){
logger.info("ComponentAccessTokenTask定时任务执行成功");
}else {
logger.error("ComponentAccessTokenTask定时任务执行失败:" + result.getMsg());
}
}
}

32
epmet-module/epmet-job/epmet-job-server/src/main/java/com/epmet/task/RefreshAuthAccessTokenTask.java

@ -0,0 +1,32 @@
package com.epmet.task;
import com.epmet.commons.tools.utils.Result;
import com.epmet.service.RefreshAuthAccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @Author zxc
* @CreateTime 2020/7/20 10:46
*/
@Component("refreshAuthAccessTokenTask")
public class RefreshAuthAccessTokenTask implements ITask {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RefreshAuthAccessTokenService refreshAuthAccessTokenService;
@Override
public void run(String params) {
logger.info("RefreshAuthAccessTokenTask正在执行定时任务,参数为{}",params);
Result result = refreshAuthAccessTokenService.refreshAuthorizerAccessTokenJob();
if (result.success()){
logger.info("RefreshAuthAccessTokenTask定时任务执行成功");
}else {
logger.error("RefreshAuthAccessTokenTask定时任务执行失败:" + result.getMsg());
}
}
}

6
epmet-module/epmet-third/epmet-third-client/pom.xml

@ -26,6 +26,12 @@
<version>3.6.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-user-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>

91
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/CodeExtDTO.java

@ -0,0 +1,91 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.dto;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-17
*/
@Data
public class CodeExtDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private String id;
/**
* 客户ID
*/
private String customerId;
/**
* 所属端 居民的resi,工作端work
*/
private String clientType;
/**
* APPID
*/
private String appId;
/**
* 自定义配置
*/
private String extJson;
/**
* 乐观锁
*/
private Integer revision;
/**
* 是否删除
*/
private String delFlag;
/**
* 创建人
*/
private String createdBy;
/**
* 创建时间
*/
private Date createdTime;
/**
* 更新人
*/
private String updatedBy;
/**
* 更新时间
*/
private Date updatedTime;
}

2
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/CustomerCodeOperationHistoryDTO.java → epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/CodeOperationHistoryDTO.java

@ -29,7 +29,7 @@ import lombok.Data;
* @since v1.0.0 2020-07-09
*/
@Data
public class CustomerCodeOperationHistoryDTO implements Serializable {
public class CodeOperationHistoryDTO implements Serializable {
private static final long serialVersionUID = 1L;

7
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/PaCustomerAgencyDTO.java

@ -19,6 +19,8 @@ package com.epmet.dto;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@ -52,6 +54,11 @@ public class PaCustomerAgencyDTO implements Serializable {
* 级别
*/
private String level;
/**
* 级别(0.省级1市级2.区县级3.乡镇街道级 4.社区级 5无)
*/
@JsonIgnore
private String levelNum;
/**
* 地区编码

18
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/CodeAuditRecordFormDTO.java

@ -42,12 +42,12 @@ public class CodeAuditRecordFormDTO implements Serializable {
/**
* 小程序的原始 ID
*/
private String toUserName;
private String ToUserName;
/**
* 发送方帐号一个 OpenID此时发送方是系统帐号
*/
private String fromUserName;
private String FromUserName;
/**
* 消息创建时间 整型时间戳
@ -57,7 +57,7 @@ public class CodeAuditRecordFormDTO implements Serializable {
/**
* 消息类型 event
*/
private String msgType;
private String MsgType;
/**
* 事件类型
@ -65,32 +65,32 @@ public class CodeAuditRecordFormDTO implements Serializable {
weapp_audit_fail审核不通过
weapp_audit_delay审核延后
*/
private String event;
private String Event;
/**
* 审核成功时的时间戳
*/
private Date succTime;
private Date SuccTime;
/**
* 审核不通过的时间戳
*/
private Date failTime;
private Date FailTime;
/**
* 审核延后时的时间戳
*/
private Date delayTime;
private Date DelayTime;
/**
* 审核不通过的原因
*/
private String reason;
private String Reason;
/**
* 审核不通过的截图示例 | 分隔的 media_id 的列表可通过获取永久素材接口拉取截图内容
*/
private String screenShot;
private String ScreenShot;
/**
* 删除状态

2
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/CodeCommonFormDTO.java

@ -20,4 +20,6 @@ public class CodeCommonFormDTO implements Serializable {
* 代码ID
*/
private String codeId;
private Integer page;
private Integer limit;
}

19
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/MediaUploadFormDTO.java

@ -0,0 +1,19 @@
package com.epmet.dto.form;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.io.Serializable;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/17 11:15
*/
@Data
public class MediaUploadFormDTO implements Serializable {
private static final long serialVersionUID = -7342624180676221309L;
private String codeId;
private String type;
private MultipartFile media;
}

14
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/MiniInfoFormDTO.java

@ -28,32 +28,32 @@ public class MiniInfoFormDTO implements Serializable {
/**
* 昵称
*/
private String nickName;
private String nick_name;
/**
* 头像
*/
private String headImg;
private String head_img;
/**
* 小程序类型 默认为 0
*/
private String serviceTypeInfo;
private String service_type_info;
/**
* 小程序认证类型 小程序认证类型
*/
private String verifyTypeInfo;
private String verify_type_info;
/**
* 原始 ID
*/
private String userName;
private String user_name;
/**
* 主体名称
*/
private String principalName;
private String principal_name;
/**
* 账号介绍
@ -63,7 +63,7 @@ public class MiniInfoFormDTO implements Serializable {
/**
* 二维码图片的 URL
*/
private String qrcodeUrl;
private String qrcode_url;
private Integer delFlag = 0;

26
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/MyInfoFormDTO.java

@ -1,26 +0,0 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Author sun
* @Description 公众号-查询我的信息-接口入参
*/
@Data
public class MyInfoFormDTO implements Serializable {
private static final long serialVersionUID = -6547893374373422628L;
public interface AddUserInternalGroup {
}
/**
* 客户Id
*/
//@NotBlank(message = "客户Id不能为空", groups = {MyInfoFormDTO.AddUserInternalGroup.class})
private String customerId;
}

14
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/PaInfoFormDTO.java

@ -28,19 +28,19 @@ public class PaInfoFormDTO implements Serializable {
/**
* 昵称
*/
private String nickName;
private String nick_name;
/**
* 头像
*/
private String headImg;
private String head_img;
/**
* 公众号类型 0订阅号
1由历史老帐号升级后的订阅号
2服务号
*/
private String serviceTypeInfo;
private String service_type_info;
/**
* 公众号认证类型 -1未认证
@ -51,17 +51,17 @@ public class PaInfoFormDTO implements Serializable {
4已资质认证通过还未通过名称认证但通过了新浪微博认证
5已资质认证通过还未通过名称认证但通过了腾讯微博认证
*/
private String verifyTypeInfo;
private String verify_type_info;
/**
* 原始ID
*/
private String userName;
private String user_name;
/**
* 主体名称
*/
private String principalName;
private String principal_name;
/**
* 公众号所设置的微信号可能为空 公众号所设置的微信号可能为空
@ -71,7 +71,7 @@ public class PaInfoFormDTO implements Serializable {
/**
* 二维码图片的 URL
*/
private String qrcodeUrl;
private String qrcode_url;
/**
* 删除状态 0正常1删除

27
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/form/WxLoginFormDTO.java

@ -0,0 +1,27 @@
package com.epmet.dto.form;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @Author sun
* @Description 小程序居民端登陆-接口入参
*/
@Data
public class WxLoginFormDTO implements Serializable {
private static final long serialVersionUID = -6163303184086480522L;
/**
* 小程序AppId
*/
private String appId;
/**
* 用户微信code
*/
private String wxCode;
}

34
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/CodeHistoryResultDTO.java

@ -0,0 +1,34 @@
package com.epmet.dto.result;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/16 9:53
*/
@NoArgsConstructor
@Data
public class CodeHistoryResultDTO implements Serializable {
private static final long serialVersionUID = 6030280825893585115L;
/**
* 操作时间
*/
private String operationTime;
/**
* 版本
*/
private String version;
/**
* 操作 上传upload审核audit撤回undo发布release
*/
private String operation;
/**
* 描述
*/
private String describe;
}

4
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/CreateAgencyResultDTO.java

@ -19,9 +19,5 @@ public class CreateAgencyResultDTO implements Serializable {
* 新增客户Id
*/
private String customerId;
/**
* 包含customerId的token
*/
private String token;
}

5
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/CustomerUserResultDTO.java

@ -2,6 +2,7 @@ package com.epmet.dto.result;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.PaUserDTO;
import com.epmet.dto.PaUserWechatDTO;
import lombok.Data;
import java.io.Serializable;
@ -22,4 +23,8 @@ public class CustomerUserResultDTO implements Serializable {
* 用户对应的客户信息
*/
private PaCustomerDTO paCustomerResult;
/**
* 用户对应的微信基本信息
*/
private PaUserWechatDTO paUserWechatResult;
}

32
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/InitCustomerResultDTO.java

@ -0,0 +1,32 @@
package com.epmet.dto.result;
import com.epmet.dto.PaCustomerAgencyDTO;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.PaUserDTO;
import lombok.Data;
import java.io.Serializable;
/**
* @Author sun
* @Description 运营端初始化客户信息-查询客户各项注册信息-接口返参
*/
@Data
public class InitCustomerResultDTO implements Serializable {
private static final long serialVersionUID = 3253989119352850315L;
/**
* 注册客户信息
*/
private PaCustomerDTO paCustomer;
/**
* 注册客户组织信息
*/
private PaCustomerAgencyDTO paAgency;
/**
* 注册客户管理员信息
*/
private PaUserDTO paUser;
}

17
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/MediaUploadResultDTO.java

@ -0,0 +1,17 @@
package com.epmet.dto.result;
import lombok.Data;
import java.io.Serializable;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/17 11:17
*/
@Data
public class MediaUploadResultDTO implements Serializable {
private static final long serialVersionUID = -8462768939270515547L;
private String id;
private String name;
}

22
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/PublicCustomerResultDTO.java

@ -0,0 +1,22 @@
package com.epmet.dto.result;
import com.epmet.dto.PaCustomerDTO;
import lombok.Data;
import java.io.Serializable;
/**
* 根据appid查询公众号注册的客户信息
* @Author sun
*/
@Data
public class PublicCustomerResultDTO implements Serializable {
private static final long serialVersionUID = 4642988014737245076L;
/**
* 客户信息
*/
private PaCustomerDTO customer;
}

22
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/QrCodeResultDTO.java

@ -0,0 +1,22 @@
package com.epmet.dto.result;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/16 9:46
*/
@NoArgsConstructor
@Data
public class QrCodeResultDTO implements Serializable {
private static final long serialVersionUID = -1145375851106140589L;
/**
* 二维码
*/
private Object qrcode;
}

26
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/ReasonResultDTO.java

@ -0,0 +1,26 @@
package com.epmet.dto.result;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/16 9:28
*/
@NoArgsConstructor
@Data
public class ReasonResultDTO implements Serializable {
private static final long serialVersionUID = -1905907350492787127L;
/**
* 失败原因
*/
private String reason;
/**
* 失败的小程序截图url
*/
private List<String> screenshotUrl;
}

2
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/dto/result/TemplateListResultDTO.java

@ -18,7 +18,7 @@ public class TemplateListResultDTO implements Serializable {
/**
* 模板 id
*/
private String templateId;
private String id;
/**
* 模板描述
*/

57
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/EpmetThirdFeignClient.java

@ -2,8 +2,12 @@ package com.epmet.feign;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.SaveUserVisitedFormDTO;
import com.epmet.dto.form.WxLoginFormDTO;
import com.epmet.dto.result.CustomerUserResultDTO;
import com.epmet.dto.result.InitCustomerResultDTO;
import com.epmet.dto.result.PublicCustomerResultDTO;
import com.epmet.dto.result.SaveUserResultDTO;
import com.epmet.feign.fallback.EpmetThirdFeignClientFallback;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
@ -18,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestBody;
*
* @Author zxc
* @CreateTime 2020/7/5 14:45
* ,url="localhost:8110"
*/
@FeignClient(name = ServiceConstant.EPMET_THIRD_SERVER, fallback = EpmetThirdFeignClientFallback.class)
@ -49,4 +54,56 @@ public interface EpmetThirdFeignClient {
**/
@PostMapping(value = "third/pauservisited/saveuservisited")
Result saveUserVisited(@RequestBody SaveUserVisitedFormDTO visited);
/**
* @param customerId
* @return
* @Author sun
* @Description 根据客户Id查询各项注册信息
**/
@PostMapping(value = "third/pacustomer/getcustomeragencyuser/{customerId}")
Result<InitCustomerResultDTO> getCustomerAgencyUser(@PathVariable("customerId") String customerId);
/**
* @param customerId
* @return
* @Author sun
* @Description 修改客户数据状态为已完成初始化
**/
@PostMapping(value = "third/pacustomer/updatecustomer/{customerId}")
Result updateCustomer(@PathVariable("customerId") String customerId);
/**
* @Description 获取component_access_token的定时任务 10min/
* @param
* @author zxc
*/
@PostMapping(value = "third/wechatthird/componentaccesstoken")
Result getComponentAccessTokenJob();
/**
* @Description 获取/刷新接口调用令牌 10min/
* @param
* @author zxc
*/
@PostMapping(value = "third/wechatthird/refreshtoken")
Result refreshAuthorizerAccessTokenJob();
/**
* @param formDTO
* @return
* @Author sun
* @Description 校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
**/
@PostMapping(value = "third/customermp/resiandworklogin")
Result<UserWechatDTO> resiAndWorkLogin(@RequestBody WxLoginFormDTO formDTO);
/**
* @param appId
* @return
* @Author sun
* @Description 根据appId查询公众号注册的客户信息
**/
@PostMapping(value = "third/customermp/getcustomermsg/{appId}")
Result<PublicCustomerResultDTO> getCustomerMsg(@PathVariable("appId") String appId);
}

34
epmet-module/epmet-third/epmet-third-client/src/main/java/com/epmet/feign/fallback/EpmetThirdFeignClientFallback.java

@ -3,8 +3,12 @@ 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.UserWechatDTO;
import com.epmet.dto.form.SaveUserVisitedFormDTO;
import com.epmet.dto.form.WxLoginFormDTO;
import com.epmet.dto.result.CustomerUserResultDTO;
import com.epmet.dto.result.InitCustomerResultDTO;
import com.epmet.dto.result.PublicCustomerResultDTO;
import com.epmet.dto.result.SaveUserResultDTO;
import com.epmet.feign.EpmetThirdFeignClient;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
@ -31,4 +35,34 @@ public class EpmetThirdFeignClientFallback implements EpmetThirdFeignClient {
public Result saveUserVisited(SaveUserVisitedFormDTO visited) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "saveUserVisited", visited);
}
@Override
public Result<InitCustomerResultDTO> getCustomerAgencyUser(String customerId) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "getCustomerAgencyUser", customerId);
}
@Override
public Result updateCustomer(String customerId) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "updateCustomer", customerId);
}
@Override
public Result getComponentAccessTokenJob() {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "getComponentAccessTokenJob");
}
@Override
public Result refreshAuthorizerAccessTokenJob() {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "refreshAuthorizerAccessTokenJob");
}
@Override
public Result<UserWechatDTO> resiAndWorkLogin(WxLoginFormDTO formDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "resiAndWorkLogin", formDTO);
}
@Override
public Result<PublicCustomerResultDTO> getCustomerMsg(String appId) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_THIRD_SERVER, "getCustomerMsg", appId);
}
}

2
epmet-module/epmet-third/epmet-third-server/deploy/docker-compose-dev.yml

@ -2,7 +2,7 @@ version: "3.7"
services:
epmet-third-server:
container_name: epmet-third-server-dev
image: 192.168.1.130:10080/epmet-cloud-dev/epmet-third-server:0.0.13
image: 192.168.1.130:10080/epmet-cloud-dev/epmet-third-server:0.0.27
ports:
- "8110:8110"
network_mode: host # 使用现有网络

2
epmet-module/epmet-third/epmet-third-server/deploy/docker-compose-test.yml

@ -2,7 +2,7 @@ version: "3.7"
services:
epmet-third-server:
container_name: epmet-third-server-test
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-release/epmet-third-server:0.0.13
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-release/epmet-third-server:0.0.14
ports:
- "8110:8110"
network_mode: host # 使用现有网络

2
epmet-module/epmet-third/epmet-third-server/pom.xml

@ -2,7 +2,7 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>0.0.14</version>
<version>0.0.27</version>
<parent>
<groupId>com.epmet</groupId>

5
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/CodeConstant.java

@ -46,4 +46,9 @@ public interface CodeConstant {
* 发布失败
*/
String RELEASE_FAILED = "release_failed";
String OPER_UPLOAD = "上传代码";
String OPER_SUBMIT = "提交审核";
String OPER_UNDO = "审核撤回";
String OPER_RELEASE = "发布";
}

8
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/ModuleConstant.java

@ -11,8 +11,10 @@ public interface ModuleConstant {
//获得授权事件的票据 如下
String UTF8 = "UTF-8";
String MSG_SIGNATURE = "msg_signature";
String SIGNATURE = "signature";
String TIMESTAMP = "timestamp";
String NONCE = "nonce";
String ENCRYPT_TYPE = "encrypt_type";
String INFO_TYPE = "InfoType";
String TICKET_UNDERLINE_KEY = "component_verify_ticket";
String TICKET_KEY = "ComponentVerifyTicket";
@ -29,6 +31,9 @@ public interface ModuleConstant {
String COMPONENT_APPSECRET = "component_appsecret";
String COMPONENT_ACCESS_TOKEN = "component_access_token";
String EXPIRES_IN = "expires_in";
String ACCOUNT_TOKEN_FLAG_ONE = "FIRST";
String ACCOUNT_TOKEN_FLAG_TWO = "JOB";
//获取预授权码 如下
String PRE_AUTH_CODE = "pre_auth_code";
@ -36,6 +41,7 @@ public interface ModuleConstant {
//使用授权码获取授权信息 如下
String AUTHORIZATION_CODE = "authorization_code";
String AUTHORIZATION_INFO = "authorization_info";
String ID = "id";
//获取/刷新接口调用令牌 如下
String AUTHORIZER_APPID = "authorizer_appid";
@ -72,6 +78,8 @@ public interface ModuleConstant {
String DELAY = "delay";
String AUDIT_SUCCESS = "audit_success";
String AUDIT_FAILED = "audit_failed";
String XML = "xml";
String CREATE_TIME = "CreateTime";
int FORTY_THOUSAND_AND_THIRTEEN = 40013;
int EIGHTY_NINE_THOUSAND = 89000;

8
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/PaConstant.java

@ -29,7 +29,9 @@ public interface PaConstant {
String PROVINCE_KEY = "province";
String PROVINCE_NAME = "省级";
String CITY_KEY = "city";
String CITY_NAME = "区县级";
String CITY_NAME = "市级";
String DISTRICT_KEY = "district";
String DISTRICT_NAME = "区县级";
String STREET_KEY = "street";
String STREET_NAME = "乡(镇、街道)级";
String COMMUNITY_KEY = "community";
@ -60,4 +62,8 @@ public interface PaConstant {
* 获取缓存中token信息失败
*/
String TOKEN_EXCEPTION = "token已过期";
/**
* 获取客户信息失败
*/
String SELECT_CUSTOMER_EXCEPTION = "获取客户信息失败";
}

59
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/ThirdApiConstant.java

@ -1,59 +0,0 @@
package com.epmet.constant;
/**
* @Author zxc
* @CreateTime 2020/7/8 17:59
*/
public interface ThirdApiConstant {
/**
* 获取预授权码
*/
String API_CREATE_PREAUTHCODE_URL = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode";
/**
* 使用授权码获取授权信息请求地址
*/
String API_QUERY_AUTH_URL = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth";
/**
* 获取令牌请求地址
*/
String API_COMPONENT_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
String API_AUTHORIZER_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token";
/**
* 授权回调url
*/
String API_REDIRECT_URL = "https://epmet-dev.elinkservice.cn/api/third/redirectauthcode";
/**
* 反参授权回调url
*/
String API_RETURN_REDIRECT_URL = "https://epmet-dev.elinkservice.cn/api/third/redirectauthcode?client=%s&customerId=%s";
/**
* 授权注册页面扫码授权
* component_appid:第三方AppId
* pre_auth_code预授权码
* redirect_uri回调url获取授权码
*/
String API_AUTH_REGISTER_URL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s";
/**
* 创建开放平台帐号并绑定公众号/小程序
*/
String API_CREATE_OPEN = "https://api.weixin.qq.com/cgi-bin/open/create";
/**
* 公众号/小程序绑定到开放平台帐号下
*/
String API_BIND_OPEN = "https://api.weixin.qq.com/cgi-bin/open/bind?";
/**
* 获取授权方的帐号基本信息
*/
String API_GET_AUTHORIZER_INFO = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info";
}

2
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/constant/ThirdRunTimeInfoConstant.java

@ -80,4 +80,6 @@ public interface ThirdRunTimeInfoConstant {
*/
String TO_LIMIT = "该开放平台帐号所绑定的公众号/小程序已达上限(100 个)";
String VERIFY_TICKET = "msgSignature = %s, timeStamp = %s, nonce = %s, encryptType = %s, signature = %s";
}

8
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/AuthRedirectController.java

@ -4,11 +4,13 @@ import com.epmet.commons.tools.utils.Result;
import com.epmet.service.ComponentVerifyTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author zxc
@ -26,9 +28,9 @@ public class AuthRedirectController {
* @param
* @author zxc
*/
@GetMapping("redirect")
public Result redirectUri(HttpServletRequest request, HttpServletResponse response){
componentVerifyTicketService.redirectUri(request,response);
@GetMapping("redirect/{customerId}/{clientType}")
public Result redirectUri(HttpServletRequest request, HttpServletResponse response, @PathVariable("customerId")String customerId, @PathVariable("clientType")String clientType) throws IOException {
componentVerifyTicketService.redirectUri(request,response,customerId,clientType);
return new Result();
}

133
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CodeController.java

@ -1,13 +1,13 @@
package com.epmet.controller;
import com.baomidou.mybatisplus.extension.api.R;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.CodeCommonFormDTO;
import com.epmet.dto.form.CodeUploadFormDTO;
import com.epmet.dto.form.SubmitAuditFormDTO;
import com.epmet.dto.form.UploadListFormDTO;
import com.epmet.dto.result.TemplateListResultDTO;
import com.epmet.dto.result.UploadListResultDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import com.epmet.service.CodeService;
import oracle.jdbc.proxy.annotation.Post;
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;
@ -24,62 +24,159 @@ import java.util.List;
@RequestMapping("code")
public class CodeController {
@Autowired
private CodeService codeService;
/**
* 获取代码模板列表
*
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/14 15:10
* @return com.epmet.commons.tools.utils.Result
*/
@PostMapping("templatelist")
public Result<List<TemplateListResultDTO>> templateList() {
return null;
List<TemplateListResultDTO> list = codeService.templateList();
return new Result<List<TemplateListResultDTO>>().ok(list);
}
/**
* 获取客户第三方配置
*
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<java.lang.String>
* @author zhaoqifeng
* @date 2020/7/17 16:22
*/
@PostMapping("getextjson")
public Result<String> getExtJson(CodeUploadFormDTO formDTO) {
String extJson = codeService.getExtJson(formDTO);
return new Result<String>().ok(extJson);
}
/**
* 代码上传
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/9 14:23
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
*/
@PostMapping("upload")
public Result upload(@RequestBody CodeUploadFormDTO formDTO) {
codeService.upload(formDTO);
return new Result<>();
}
/**
* 已上传代码列表
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result<java.util.List < com.epmet.dto.result.UploadListResultDTO>>
* @author zhaoqifeng
* @date 2020/7/14 16:30
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<java.util.List<com.epmet.dto.result.UploadListResultDTO>>
*/
@PostMapping("uploadlist")
public Result<List<UploadListResultDTO>> uploadList(@RequestBody UploadListFormDTO formDTO) {
return new Result<>();
public Result<PageData> uploadList(@RequestBody UploadListFormDTO formDTO) {
PageData pageData = codeService.uploadList(formDTO);
return new Result<PageData>().ok(pageData);
}
/**
* 提交审核
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/14 16:40
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
*/
@PostMapping("audit")
public Result submitAudit(@RequestBody SubmitAuditFormDTO formDTO) {
codeService.submitAudit(formDTO);
return new Result<>();
}
/**
* 审核撤回
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/14 17:52
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
*/
@PostMapping("undo")
public Result undo(@RequestBody CodeCommonFormDTO formDTO) {
codeService.undo(formDTO);
return new Result<>();
}
/**
* 发布
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/14 17:52
*/
@PostMapping("release")
public Result release(@RequestBody CodeCommonFormDTO formDTO) {
codeService.release(formDTO);
return new Result<>();
}
/**
* 审核失败原因
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/14 17:52
*/
@PostMapping("reason")
public Result<ReasonResultDTO> reason(@RequestBody CodeCommonFormDTO formDTO) {
ReasonResultDTO resultDTO = codeService.reason(formDTO);
return new Result<ReasonResultDTO>().ok(resultDTO);
}
/**
* 获取体验版二维码
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result
* @author zhaoqifeng
* @date 2020/7/14 17:52
*/
@PostMapping("qrcode")
public Result<QrCodeResultDTO> qrCode(@RequestBody CodeCommonFormDTO formDTO) {
QrCodeResultDTO resultDTO = codeService.qrCode(formDTO);
return new Result<QrCodeResultDTO>().ok(resultDTO);
}
/**
* 操作历史
*
* @param formDTO 参数
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.CodeHistoryResultDTO>
* @author zhaoqifeng
* @date 2020/7/16 10:16
*/
@PostMapping("history")
public Result<PageData> history(@RequestBody CodeCommonFormDTO formDTO) {
PageData result = codeService.history(formDTO);
return new Result<PageData>().ok(result);
}
/**
* 上传临时素材
*
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<java.util.List < com.epmet.dto.result.MediaUploadResultDTO>>
* @author zhaoqifeng
* @date 2020/7/17 11:20
*/
@PostMapping("mediaupload")
public Result<String> mediaUpload(@RequestBody MediaUploadFormDTO formDTO) {
String result = codeService.mediaUpload(formDTO);
return new Result<String>().ok(result);
}
}

84
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CodeExtController.java

@ -0,0 +1,84 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.controller;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.AssertUtils;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.commons.tools.validator.group.AddGroup;
import com.epmet.commons.tools.validator.group.DefaultGroup;
import com.epmet.commons.tools.validator.group.UpdateGroup;
import com.epmet.dto.CodeExtDTO;
import com.epmet.service.CodeExtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-17
*/
@RestController
@RequestMapping("codeext")
public class CodeExtController {
@Autowired
private CodeExtService codeExtService;
@GetMapping("page")
public Result<PageData<CodeExtDTO>> page(@RequestParam Map<String, Object> params){
PageData<CodeExtDTO> page = codeExtService.page(params);
return new Result<PageData<CodeExtDTO>>().ok(page);
}
@GetMapping("{id}")
public Result<CodeExtDTO> get(@PathVariable("id") String id){
CodeExtDTO data = codeExtService.get(id);
return new Result<CodeExtDTO>().ok(data);
}
@PostMapping
public Result save(@RequestBody CodeExtDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
codeExtService.save(dto);
return new Result();
}
@PutMapping
public Result update(@RequestBody CodeExtDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
codeExtService.update(dto);
return new Result();
}
@DeleteMapping
public Result delete(@RequestBody String[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
codeExtService.delete(ids);
return new Result();
}
}

32
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CustomerCodeOperationHistoryController.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CodeOperationHistoryController.java

@ -24,8 +24,8 @@ import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.commons.tools.validator.group.AddGroup;
import com.epmet.commons.tools.validator.group.UpdateGroup;
import com.epmet.commons.tools.validator.group.DefaultGroup;
import com.epmet.dto.CustomerCodeOperationHistoryDTO;
import com.epmet.service.CustomerCodeOperationHistoryService;
import com.epmet.dto.CodeOperationHistoryDTO;
import com.epmet.service.CodeOperationHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -39,37 +39,37 @@ import java.util.Map;
* @since v1.0.0 2020-07-09
*/
@RestController
@RequestMapping("customercodeoperationhistory")
public class CustomerCodeOperationHistoryController {
@RequestMapping("codeoperationhistory")
public class CodeOperationHistoryController {
@Autowired
private CustomerCodeOperationHistoryService customerCodeOperationHistoryService;
private CodeOperationHistoryService codeOperationHistoryService;
@GetMapping("page")
public Result<PageData<CustomerCodeOperationHistoryDTO>> page(@RequestParam Map<String, Object> params){
PageData<CustomerCodeOperationHistoryDTO> page = customerCodeOperationHistoryService.page(params);
return new Result<PageData<CustomerCodeOperationHistoryDTO>>().ok(page);
public Result<PageData<CodeOperationHistoryDTO>> page(@RequestParam Map<String, Object> params){
PageData<CodeOperationHistoryDTO> page = codeOperationHistoryService.page(params);
return new Result<PageData<CodeOperationHistoryDTO>>().ok(page);
}
@GetMapping("{id}")
public Result<CustomerCodeOperationHistoryDTO> get(@PathVariable("id") String id){
CustomerCodeOperationHistoryDTO data = customerCodeOperationHistoryService.get(id);
return new Result<CustomerCodeOperationHistoryDTO>().ok(data);
public Result<CodeOperationHistoryDTO> get(@PathVariable("id") String id){
CodeOperationHistoryDTO data = codeOperationHistoryService.get(id);
return new Result<CodeOperationHistoryDTO>().ok(data);
}
@PostMapping
public Result save(@RequestBody CustomerCodeOperationHistoryDTO dto){
public Result save(@RequestBody CodeOperationHistoryDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
customerCodeOperationHistoryService.save(dto);
codeOperationHistoryService.save(dto);
return new Result();
}
@PutMapping
public Result update(@RequestBody CustomerCodeOperationHistoryDTO dto){
public Result update(@RequestBody CodeOperationHistoryDTO dto){
//效验数据
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
customerCodeOperationHistoryService.update(dto);
codeOperationHistoryService.update(dto);
return new Result();
}
@ -77,7 +77,7 @@ public class CustomerCodeOperationHistoryController {
public Result delete(@RequestBody String[] ids){
//效验数据
AssertUtils.isArrayEmpty(ids, "id");
customerCodeOperationHistoryService.delete(ids);
codeOperationHistoryService.delete(ids);
return new Result();
}

2
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/ComponentVerifyTicketController.java

@ -22,7 +22,7 @@ public class ComponentVerifyTicketController {
private ComponentVerifyTicketService componentVerifyTicketService;
/**
* @Description 获取验证票据3
* @Description 获取验证票据
* @author zxc
*/
@PostMapping(value = "/callback")

27
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/CustomerMpController.java

@ -23,9 +23,12 @@ import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.AssertUtils;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.commons.tools.validator.group.AddGroup;
import com.epmet.commons.tools.validator.group.UpdateGroup;
import com.epmet.commons.tools.validator.group.DefaultGroup;
import com.epmet.commons.tools.validator.group.UpdateGroup;
import com.epmet.dto.CustomerMpDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.WxLoginFormDTO;
import com.epmet.dto.result.PublicCustomerResultDTO;
import com.epmet.excel.CustomerMpExcel;
import com.epmet.service.CustomerMpService;
import org.springframework.beans.factory.annotation.Autowired;
@ -91,4 +94,26 @@ public class CustomerMpController {
ExcelUtils.exportExcelToTarget(response, null, list, CustomerMpExcel.class);
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
**/
@PostMapping("resiandworklogin")
public Result<UserWechatDTO> resiAndWorkLogin(@RequestBody WxLoginFormDTO formDTO) {
return new Result<UserWechatDTO>().ok(customerMpService.resiAndWorkLogin(formDTO));
}
/**
* @param appId
* @return
* @Author sun
* @Description 根据appId查询公众号注册的客户信息
**/
@PostMapping("getcustomermsg/{appId}")
public Result<PublicCustomerResultDTO> getCustomerMsg(@PathVariable("appId") String appId) {
return new Result<PublicCustomerResultDTO>().ok(customerMpService.getCustomerMsg(appId));
}
}

37
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/PaCustomerController.java

@ -7,18 +7,15 @@ import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.commons.tools.validator.group.DefaultGroup;
import com.epmet.dto.form.CreateAgencyFormDTO;
import com.epmet.dto.form.MyInfoFormDTO;
import com.epmet.dto.form.RegisterFormDTO;
import com.epmet.dto.form.RegisterInfoFormDTO;
import com.epmet.dto.result.AgencyLevelListResultDTO;
import com.epmet.dto.result.CreateAgencyResultDTO;
import com.epmet.dto.result.InitCustomerResultDTO;
import com.epmet.dto.result.MyInfoResultDTO;
import com.epmet.service.*;
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;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -80,16 +77,14 @@ public class PaCustomerController {
}
/**
* @param formDTO
* @param tokenDTO
* @return
* @Author sun
* @Description 公众号-查询我的信息
**/
@PostMapping("myinfo")
public Result<MyInfoResultDTO> myInfo(@LoginUser TokenDto tokenDTO, @RequestBody MyInfoFormDTO formDTO) {
//ValidatorUtils.validateEntity(formDTO, MyInfoFormDTO.AddUserInternalGroup.class);
ValidatorUtils.validateEntity(formDTO);
return new Result<MyInfoResultDTO>().ok(paCustomerService.myInfo(tokenDTO, formDTO));
public Result<MyInfoResultDTO> myInfo(@LoginUser TokenDto tokenDTO) {
return new Result<MyInfoResultDTO>().ok(paCustomerService.myInfo(tokenDTO));
}
/**
@ -104,5 +99,27 @@ public class PaCustomerController {
return new Result<PageData>().ok(paCustomerService.registerInfo(formDTO));
}
/**
* @param customerId
* @return
* @Author sun
* @Description 根据客户Id查询各项注册信息
**/
@PostMapping(value = "getcustomeragencyuser/{customerId}")
public Result<InitCustomerResultDTO> getCustomerAgencyUser(@PathVariable("customerId") String customerId) {
return new Result<InitCustomerResultDTO>().ok(paCustomerService.getCustomerAgencyUser(customerId));
}
/**
* @param customerId
* @return
* @Author sun
* @Description 修改客户数据状态为已完成初始化
**/
@PostMapping(value = "updatecustomer/{customerId}")
public Result updateCustomer(@PathVariable("customerId") String customerId) {
paCustomerService.updateCustomer(customerId);
return new Result();
}
}

2
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/WarrantController.java

@ -1,6 +1,6 @@
package com.epmet.controller;
import com.epmet.exception.AesException;
import com.epmet.mpaes.AesException;
import com.epmet.service.WarrantService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;

4
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/controller/WeChatNotifyController.java

@ -1,6 +1,7 @@
package com.epmet.controller;
import com.epmet.commons.tools.utils.Result;
import com.epmet.constant.ModuleConstant;
import com.epmet.service.ComponentVerifyTicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -27,7 +28,8 @@ public class WeChatNotifyController {
@PostMapping("componentaccesstoken")
public Result getComponentAccessToken() {
log.info("开始获取【component_access_token】......");
componentVerifyTicketService.getComponentAccessToken();
String accessTokenCountFlag = ModuleConstant.ACCOUNT_TOKEN_FLAG_TWO;
componentVerifyTicketService.getComponentAccessToken(accessTokenCountFlag);
log.info("已成功获取到【component_access_token】......");
return new Result();
}

20
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CodeCustomerDao.java

@ -18,6 +18,7 @@
package com.epmet.dao;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.dto.CodeCustomerDTO;
import com.epmet.dto.form.UploadListFormDTO;
import com.epmet.dto.result.UploadListResultDTO;
import com.epmet.dto.form.CodeAuditRecordFormDTO;
@ -61,4 +62,23 @@ public interface CodeCustomerDao extends BaseDao<CodeCustomerEntity> {
*/
String selectCodeCustomerId(CodeAuditRecordFormDTO codeAuditRecord);
/**
* 删除旧的上传记录
* @author zhaoqifeng
* @date 2020/7/15 18:06
* @param customerId
* @param clientType
* @return void
*/
void deleteCode(@Param("customerId") String customerId, @Param("clientType") String clientType);
/**
* 获取审核中代码列表
* @author zhaoqifeng
* @date 2020/7/15 18:17
* @param
* @return java.util.List<com.epmet.dto.CodeCustomerDTO>
*/
List<CodeCustomerDTO> selectAuditingCodeList();
}

54
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CodeExtDao.java

@ -0,0 +1,54 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.dao;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.dto.CodeExtDTO;
import com.epmet.entity.CodeExtEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-17
*/
@Mapper
public interface CodeExtDao extends BaseDao<CodeExtEntity> {
/**
* 获取第三方配置模板
* @author zhaoqifeng
* @date 2020/7/17 15:25
* @param
* @return java.lang.String
*/
String selectExtTemplate(@Param("clientType") String clientType);
/**
* 获取客户的第三方配置
* @author zhaoqifeng
* @date 2020/7/17 15:26
* @param customerId
* @param clientType
* @return java.lang.String
*/
CodeExtDTO selectExtByCustomerId(@Param("customerId") String customerId, @Param("clientType") String clientType);
}

48
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CodeOperationHistoryDao.java

@ -0,0 +1,48 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.dao;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.dto.result.CodeHistoryResultDTO;
import com.epmet.entity.CodeOperationHistoryEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 客户代码操作历史
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-09
*/
@Mapper
public interface CodeOperationHistoryDao extends BaseDao<CodeOperationHistoryEntity> {
List<CodeHistoryResultDTO> selectHistoryList(@Param("customerId") String customerId, @Param("clientType") String clientType);
/**
* 更新描述
* @author zhaoqifeng
* @date 2020/7/16 16:11
* @param codeId
* @param describe
* @return void
*/
void updateDescribeByCodeId(@Param("codeId") String codeId, @Param("describe") String describe);
}

26
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CustomerMpDao.java

@ -19,6 +19,7 @@ package com.epmet.dao;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.dto.CustomerMpDTO;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.form.AuthCodeFormDTO;
import com.epmet.entity.CustomerMpEntity;
import org.apache.ibatis.annotations.Mapper;
@ -81,4 +82,29 @@ public interface CustomerMpDao extends BaseDao<CustomerMpEntity> {
*/
String selectClientTypeByCustomerIdAndAuthId(@Param("customerId")String customerId,@Param("authAppId")String authAppId);
/**
* 获取授权状态
* @param customerId
* @param clientType
* @return java.lang.Boolean
* @author zhaoqifeng
* @date 2020/7/16 15:28
*/
Boolean selectAuthFlag(@Param("customerId")String customerId, @Param("clientType")String clientType);
/**
* @param appId
* @return
* @Author sun
* @Description 根据appId查询小程序信息
**/
CustomerMpDTO selectByAppId(@Param("appId") String appId);
/**
* @param appId
* @return
* @Author sun
* @Description 根据appId查询客户信息
**/
PaCustomerDTO selectCustomerByAppId(@Param("appId") String appId);
}

2
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/FuncInfoDao.java

@ -46,6 +46,6 @@ public interface FuncInfoDao extends BaseDao<FuncInfoEntity> {
* @param customerId
* @author zxc
*/
void updateOldFuncInfo(@Param("customerId")String customerId);
void updateOldFuncInfo(@Param("customerId")String customerId,@Param("authAppId")String authAppId);
}

8
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/PaCustomerAgencyDao.java

@ -46,4 +46,12 @@ public interface PaCustomerAgencyDao extends BaseDao<PaCustomerAgencyEntity> {
* @Description 公众号-查询客户组织信息
**/
PaCustomerAgencyDTO selectCustomerAgency(@Param("customerId") String customerId);
/**
* @param customerId
* @return
* @Author sun
* @Description 公众号-查询客户组织信息
**/
PaCustomerAgencyDTO selectAgency(@Param("customerId") String customerId);
}

8
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/PaCustomerDao.java

@ -50,4 +50,12 @@ public interface PaCustomerDao extends BaseDao<PaCustomerEntity> {
* @Description 查询公众号注册的客户信息列表
**/
List<CustomerAgencyResultDTO> registerInfo();
/**
* @param dto
* @return
* @Author sun
* @Description 修改客户数据状态为已完成初始化
**/
int updateCustomerById(PaCustomerDTO dto);
}

8
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/PaUserDao.java

@ -41,4 +41,12 @@ public interface PaUserDao extends BaseDao<PaUserEntity> {
* @Description 根据手机号查询公众号用户基本信息校验用户是否存在
**/
List<PaUserDTO> selectUserByPhone(@Param("phone") String phone);
/**
* @param customerId
* @return
* @Author sun
* @Description 根据客户Id级联查询客户管理员注册信息
**/
PaUserDTO selectPaUser(@Param("customerId") String customerId);
}

61
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/entity/CodeExtEntity.java

@ -0,0 +1,61 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.epmet.commons.mybatis.entity.BaseEpmetEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-17
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("code_ext")
public class CodeExtEntity extends BaseEpmetEntity {
private static final long serialVersionUID = 1L;
/**
* 客户ID
*/
private String customerId;
/**
* 所属端 居民的resi,工作端work
*/
private String clientType;
/**
* APPID
*/
private String appId;
/**
* 自定义配置
*/
private String extJson;
}

4
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/entity/CustomerCodeOperationHistoryEntity.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/entity/CodeOperationHistoryEntity.java

@ -33,8 +33,8 @@ import java.util.Date;
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("customer_code_operation_history")
public class CustomerCodeOperationHistoryEntity extends BaseEpmetEntity {
@TableName("code_operation_history")
public class CodeOperationHistoryEntity extends BaseEpmetEntity {
private static final long serialVersionUID = 1L;

65
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/exception/AesException.java

@ -1,65 +0,0 @@
package com.epmet.exception;
/**
* @Author zxc
* @CreateTime 2020/7/6 10:03
*/
@SuppressWarnings("serial")
public class AesException extends Exception {
public final static int OK = 0;
public final static int ValidateSignatureError = -40001;
public final static int ParseXmlError = -40002;
public final static int ComputeSignatureError = -40003;
public final static int IllegalAesKey = -40004;
public final static int ValidateCorpidError = -40005;
public final static int EncryptAESError = -40006;
public final static int DecryptAESError = -40007;
public final static int IllegalBuffer = -40008;
public final static int EncodeBase64Error = -40009;
public final static int DecodeBase64Error = -40010;
public final static int GenReturnXmlError = -40011;
private int code;
private static String getMessage(int code) {
switch (code) {
case ValidateSignatureError:
return "签名验证错误";
case ParseXmlError:
return "xml解析失败";
case ComputeSignatureError:
return "sha加密生成签名失败";
case IllegalAesKey:
return "SymmetricKey非法";
case ValidateCorpidError:
return "corpid校验失败";
case EncryptAESError:
return "aes加密失败";
case DecryptAESError:
return "aes解密失败";
case IllegalBuffer:
return "解密后得到的buffer非法";
case EncodeBase64Error:
return "base64加密错误";
case DecodeBase64Error:
return "base64解密错误";
case GenReturnXmlError:
return "xml生成失败";
default:
return null; // cannot be
}
}
public int getCode() {
return code;
}
public AesException(int code) {
super(getMessage(code));
this.code = code;
}
}

96
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/AesDecryptUtil.java

@ -0,0 +1,96 @@
/*
* Copyright (C) 2018 Baidu, Inc. All Rights Reserved.
*/
package com.epmet.mpaes;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* JAVA AES 消息加解密
*/
public class AesDecryptUtil {
private static Charset CHARSET = Charset.forName("utf-8");
private Cipher decCipher;
/**
* 构造函数
*
* @param encodingAesKey encodingAESKey
*
* @throws Exception 异常错误信息
*/
public AesDecryptUtil(String encodingAesKey) throws Exception {
int encodingAesKeyLength = 43;
if (encodingAesKey.length() != encodingAesKeyLength) {
throw new Exception("ILLEGAL_AES_KEY_ERROR");
}
byte[] aesKey = Base64.decodeBase64(encodingAesKey + "=");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
Cipher encCipher = Cipher.getInstance("AES/CBC/NoPadding");
encCipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
decCipher = Cipher.getInstance("AES/CBC/NoPadding");
decCipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
}
/**
* 还原4个字节的网络字节序
*
* @param orderBytes 字节码
*
* @return sourceNumber
*/
private int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
int length = 4;
int number = 8;
for (int i = 0; i < length; i++) {
sourceNumber <<= number;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
/**
* 对密文进行解密
*
* @param text 需要解密的密文
*
* @return 解密得到的明文
*
* @throws Exception 异常错误信息
*/
public String decrypt(String text)
throws Exception {
byte[] original;
try {
byte[] encrypted = Base64.decodeBase64(text);
original = decCipher.doFinal(encrypted);
} catch (Exception e) {
throw new Exception("DECRYPT_AES_ERROR");
}
String xmlContent;
try {
// 去除补位字符
byte[] bytes = PKCS7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和ClientId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
} catch (Exception e) {
throw new Exception("ILLEGAL_BUFFER_ERROR");
}
return xmlContent;
}
}

59
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/AesException.java

@ -0,0 +1,59 @@
package com.epmet.mpaes;
@SuppressWarnings("serial")
public class AesException extends Exception {
/*public final static int OK = 0;
public final static int ValidateSignatureError = -40001;
public final static int ParseXmlError = -40002;
public final static int ComputeSignatureError = -40003;
public final static int IllegalAesKey = -40004;
public final static int ValidateAppidError = -40005;
public final static int EncryptAESError = -40006;
public final static int DecryptAESError = -40007;
public final static int IllegalBuffer = -40008;
//public final static int EncodeBase64Error = -40009;
//public final static int DecodeBase64Error = -40010;
//public final static int GenReturnXmlError = -40011;
private int code;
private static String getMessage(int code) {
switch (code) {
case ValidateSignatureError:
return "签名验证错误";
case ParseXmlError:
return "xml解析失败";
case ComputeSignatureError:
return "sha加密生成签名失败";
case IllegalAesKey:
return "SymmetricKey非法";
case ValidateAppidError:
return "appid校验失败";
case EncryptAESError:
return "aes加密失败";
case DecryptAESError:
return "aes解密失败";
case IllegalBuffer:
return "解密后得到的buffer非法";
// case EncodeBase64Error:
// return "base64加密错误";
// case DecodeBase64Error:
// return "base64解密错误";
// case GenReturnXmlError:
// return "xml生成失败";
default:
return null; // cannot be
}
}
public int getCode() {
return code;
}
AesException(int code) {
super(getMessage(code));
this.code = code;
}*/
}

26
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/ByteGroup.java

@ -0,0 +1,26 @@
package com.epmet.mpaes;
import java.util.ArrayList;
class ByteGroup {
ArrayList<Byte> byteContainer = new ArrayList<Byte>();
public byte[] toBytes() {
byte[] bytes = new byte[byteContainer.size()];
for (int i = 0; i < byteContainer.size(); i++) {
bytes[i] = byteContainer.get(i);
}
return bytes;
}
public ByteGroup addBytes(byte[] bytes) {
for (byte b : bytes) {
byteContainer.add(b);
}
return this;
}
public int size() {
return byteContainer.size();
}
}

67
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/PKCS7Encoder.java

@ -0,0 +1,67 @@
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.epmet.mpaes;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* 提供基于PKCS7算法的加解密接口.
*/
class PKCS7Encoder {
static Charset CHARSET = Charset.forName("utf-8");
static int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
static byte[] encode(int count) {
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE;
}
// 获得补位所用的字符
char padChr = chr(amountToPad);
String tmp = new String();
for (int index = 0; index < amountToPad; index++) {
tmp += padChr;
}
return tmp.getBytes(CHARSET);
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
static byte[] decode(byte[] decrypted) {
int pad = (int) decrypted[decrypted.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符用于对明文进行补码
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}

65
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/SHA1.java

@ -0,0 +1,65 @@
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.epmet.mpaes;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.wxapi.enums.WxMaErrorMsgEnum;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.util.Arrays;
/**
* SHA1 class
*
* 计算公众平台的消息签名接口.
*/
@Component
public class SHA1 {
/**
* 用SHA1算法生成安全签名
* @param token 票据
* @param timestamp 时间戳
* @param nonce 随机字符串
* @param encrypt 密文
* @return 安全签名
* @throws AesException
*/
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
try {
String[] array = new String[]{token, timestamp, nonce, encrypt};
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40003.getMsg());
}
}
}

283
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/WXBizMsgCrypt.java

@ -0,0 +1,283 @@
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
/**
* 针对org.apache.commons.codec.binary.Base64
* 需要导入架包commons-codec-1.9或commons-codec-1.8等其他版本
* 官方下载地址http://commons.apache.org/proper/commons-codec/download_codec.cgi
*/
package com.epmet.mpaes;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.wxapi.enums.WxMaErrorMsgEnum;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
/**
* 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).
* <ol>
* <li>第三方回复加密消息给公众平台</li>
* <li>第三方收到公众平台发送的消息验证消息的安全性并对消息进行解密</li>
* </ol>
* 说明异常java.security.InvalidKeyException:illegal Key Size的解决方案
* <ol>
* <li>在官方网站下载JCE无限制权限策略文件JDK7的下载地址
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li>
* <li>下载后解压可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>
* <li>如果安装了JRE将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li>
* <li>如果安装了JDK将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li>
* </ol>
*/
public class WXBizMsgCrypt {
static Charset CHARSET = Charset.forName("utf-8");
Base64 base64 = new Base64();
byte[] aesKey;
String token;
String appId;
/**
* 构造函数
* @param token 公众平台上开发者设置的token
* @param encodingAesKey 公众平台上开发者设置的EncodingAESKey
* @param appId 公众平台appid
*
* @throws AesException 执行失败请查看该异常的错误码和具体的错误信息
*/
public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException {
if (encodingAesKey.length() != 43) {
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40004.getMsg());
}
this.token = token;
this.appId = appId;
aesKey = Base64.decodeBase64(encodingAesKey + "=");
}
// 生成4个字节的网络字节序
byte[] getNetworkBytesOrder(int sourceNumber) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (sourceNumber & 0xFF);
orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
return orderBytes;
}
// 还原4个字节的网络字节序
int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
// 随机生成16位字符串
String getRandomStr() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 对明文进行加密.
*
* @param text 需要加密的明文
* @return 加密后base64编码的字符串
* @throws AesException aes加密失败
*/
String encrypt(String randomStr, String text) throws AesException {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] appidBytes = appId.getBytes(CHARSET);
// randomStr + networkBytesOrder + text + appid
byteCollector.addBytes(randomStrBytes);
byteCollector.addBytes(networkBytesOrder);
byteCollector.addBytes(textBytes);
byteCollector.addBytes(appidBytes);
// ... + pad: 使用自定义的填充方式对明文进行补位填充
byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
byteCollector.addBytes(padBytes);
// 获得最终的字节流, 未加密
byte[] unencrypted = byteCollector.toBytes();
try {
// 设置加密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// 加密
byte[] encrypted = cipher.doFinal(unencrypted);
// 使用BASE64对加密后的字符串进行编码
String base64Encrypted = base64.encodeToString(encrypted);
return base64Encrypted;
} catch (Exception e) {
e.printStackTrace();
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40006.getMsg());
}
}
/**
* 对密文进行解密.
*
* @param text 需要解密的密文
* @return 解密得到的明文
* @throws AesException aes解密失败
*/
String decrypt(String text) throws AesException {
byte[] original;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40007.getMsg());
}
String xmlContent, from_appid;
try {
// 去除补位字符
byte[] bytes = PKCS7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和AppId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
CHARSET);
} catch (Exception e) {
e.printStackTrace();
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40008.getMsg());
}
// appid不相同的情况
if (!from_appid.equals(appId)) {
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40005.getMsg());
}
return xmlContent;
}
/**
* 将公众平台回复用户的消息加密打包.
* <ol>
* <li>对要发送的消息进行AES-CBC加密</li>
* <li>生成安全签名</li>
* <li>将消息密文和安全签名打包成xml格式</li>
* </ol>
*
* @param replyMsg 公众平台待回复用户的消息xml格式的字符串
* @param timeStamp 时间戳可以自己生成也可以用URL参数的timestamp
* @param nonce 随机串可以自己生成也可以用URL参数的nonce
*
* @return 加密后的可以直接回复用户的密文包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
* @throws AesException 执行失败请查看该异常的错误码和具体的错误信息
*/
public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
// 加密
String encrypt = encrypt(getRandomStr(), replyMsg);
// 生成安全签名
if (timeStamp == "") {
timeStamp = Long.toString(System.currentTimeMillis());
}
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
// System.out.println("发送给平台的签名是: " + signature[1].toString());
// 生成发送的xml
String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
return result;
}
/**
* 检验消息的真实性并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名进行签名验证</li>
* <li>若验证通过则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @param msgSignature 签名串对应URL参数的msg_signature
* @param timeStamp 时间戳对应URL参数的timestamp
* @param nonce 随机串对应URL参数的nonce
* @param postData 密文对应POST请求的数据
*
* @return 解密后的原文
* @throws AesException 执行失败请查看该异常的错误码和具体的错误信息
*/
public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
throws AesException {
// 提取密文
String encrypt = XMLParse.extract(postData);
// 验证安全签名
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
if (!signature.equals(msgSignature)) {
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40001.getMsg());
}
// 解密
String result = decrypt(encrypt);
return result;
}
/**
* 验证URL
* @param msgSignature 签名串对应URL参数的msg_signature
* @param timeStamp 时间戳对应URL参数的timestamp
* @param nonce 随机串对应URL参数的nonce
* @param echoStr 随机串对应URL参数的echostr
*
* @return 解密之后的echostr
* @throws AesException 执行失败请查看该异常的错误码和具体的错误信息
*/
public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr)
throws AesException {
String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);
if (!signature.equals(msgSignature)) {
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40001.getMsg());
}
String result = decrypt(echoStr);
return result;
}
}

41
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/WXXmlToMapUtil.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/WXXmlToMapUtil.java

@ -1,5 +1,8 @@
package com.epmet.util;
package com.epmet.mpaes;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
@ -16,6 +19,7 @@ import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -226,5 +230,40 @@ public class WXXmlToMapUtil {
return null;
}
}
/**
* 以格式化的方式输出XML
*
* @param obj
* @return
*/
public static String toXml(Object obj) {
XStream xstream = getXStream();
// 识别obj类中的注解
xstream.processAnnotations(obj.getClass());
// 设置JavaBean的类别名
xstream.aliasType("xml", obj.getClass());
return xstream.toXML(obj);
}
/**
* 转换不带CDDATA的XML
*
* @return
* @
*/
private static XStream getXStream() {
// 实例化XStream基本对象
XStream xstream = new XStream(new DomDriver(StandardCharsets.UTF_8.name(), new NoNameCoder() {
// 不对特殊字符进行转换,避免出现重命名字段时的“双下划线”
@Override
public String encodeNode(String name) {
return name;
}
}));
// 忽视XML与JAVABEAN转换时,XML中的字段在JAVABEAN中不存在的部分
xstream.ignoreUnknownElements();
return xstream;
}
}

73
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/mpaes/XMLParse.java

@ -0,0 +1,73 @@
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.epmet.mpaes;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.wxapi.enums.WxMaErrorMsgEnum;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
/**
* XMLParse class
*
* 提供提取消息格式中的密文及生成回复消息格式的接口.
*/
public class XMLParse {
/**
* 提取出xml数据包中的加密消息
* @param xmltext 待提取的xml字符串
* @return 提取出的加密消息字符串
* @throws AesException
*/
public static String extract(String xmltext) throws AesException {
// Object[] result = new Object[3];
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(xmltext);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
NodeList nodelist2 = root.getElementsByTagName("ToUserName");
// result[0] = 0;
String result = nodelist1.item(0).getTextContent();
// result[2] = nodelist2.item(0).getTextContent();
return result;
} catch (Exception e) {
e.printStackTrace();
throw new RenException(WxMaErrorMsgEnum.CODE_MINUS_40002.getMsg());
}
}
/**
* 生成xml消息
* @param encrypt 加密后的消息密文
* @param signature 安全签名
* @param timestamp 时间戳
* @param nonce 随机字符串
* @return 生成的xml字符串
*/
public static String generate(String encrypt, String signature, String timestamp, String nonce) {
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
return String.format(format, encrypt, signature, timestamp, nonce);
}
}

32
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/dao/CustomerCodeOperationHistoryDao.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/CodeExtRedis.java

@ -15,19 +15,33 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.dao;
package com.epmet.redis;
import com.epmet.commons.mybatis.dao.BaseDao;
import com.epmet.entity.CustomerCodeOperationHistoryEntity;
import org.apache.ibatis.annotations.Mapper;
import com.epmet.commons.tools.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 客户代码操作历史
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-09
* @since v1.0.0 2020-07-17
*/
@Mapper
public interface CustomerCodeOperationHistoryDao extends BaseDao<CustomerCodeOperationHistoryEntity> {
@Component
public class CodeExtRedis {
@Autowired
private RedisUtils redisUtils;
public void delete(Object[] ids) {
}
public void set(){
}
public String get(String id){
return null;
}
}

2
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/CustomerCodeOperationHistoryRedis.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/CodeOperationHistoryRedis.java

@ -28,7 +28,7 @@ import org.springframework.stereotype.Component;
* @since v1.0.0 2020-07-09
*/
@Component
public class CustomerCodeOperationHistoryRedis {
public class CodeOperationHistoryRedis {
@Autowired
private RedisUtils redisUtils;

30
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/redis/RedisThird.java

@ -1,19 +1,15 @@
package com.epmet.redis;
import com.epmet.commons.tools.redis.RedisUtils;
import com.epmet.constant.ModuleConstant;
import com.epmet.constant.ThirdRedisKeyConstant;
import com.epmet.dto.form.AuthCodeFormDTO;
import com.epmet.dto.form.AuthorizationInfoFormDTO;
import com.epmet.dto.form.AuthorizerAccessTokenFormDTO;
import com.epmet.dto.result.AuthorizationInfoResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @Author zxc
* @CreateTime 2020/7/7 9:33
@ -73,9 +69,8 @@ public class RedisThird {
/**
* @Description 缓存 刷新令牌 授权信息不包括 授权给开发者的权限集列表
* 在授权的公众号具备API权限时才有此返回值刷新令牌主要用于第三方平台获取和刷新已授权用户的 authorizer_access_token
* 一旦丢失只能让用户重新授权才能再次拿到新的刷新令牌用户重新授权后之前的刷新令牌会失效
* @param authInfoDTO
* key = 前缀+客户ID+客户端类型
* @author zxc
*/
public void setAuthorizerRefreshToken(AuthorizationInfoFormDTO authInfoDTO){
@ -85,7 +80,7 @@ public class RedisThird {
/**
* @Description 获取刷新
* @param key = epmet:wechartthird:authorizerrefreshtoken:customerId:clientType
* @param key = epmet:wechartthird:authorizerrefreshtoken:customerId:clientType 前缀+客户ID+客户端类型
* @author zxc
*/
public String getAuthorizerRefreshToken(String key){
@ -94,7 +89,7 @@ public class RedisThird {
/**
* @Description 缓存授权码 auth_Code
* @param
* key = ""前缀+客户ID+客户端类型
* @author zxc
*/
public void setAuthCode(AuthCodeFormDTO formDTO){
@ -105,7 +100,7 @@ public class RedisThird {
/**
* @Description 获取授权码
* 授权码, 会在授权成功时回调url返回给第三方平台codeexpiresIn
* @param key
* @param key = "epmet:wechartthird:authcode:customerId:clientType"前缀+客户ID+客户端类型
* @author zxc
*/
public String getAuthCode(String key){
@ -115,21 +110,12 @@ public class RedisThird {
/**
* @Description 缓存授权信息完整的包括 授权给开发者的权限集列表
* @param authInfo
* key = "epmet:wechartthird:authinfo:customerId:clientType"前缀+客户ID+客户端类型
* @author zxc
*/
public void setAuthInfo(AuthorizationInfoResultDTO authInfo){
redisUtils.set(ThirdRedisKeyConstant.AUTH_INFO_REDIS_KEY,authInfo,-1);
public void setAuthInfo(AuthorizationInfoResultDTO authInfo,String customerId,String clientType){
String key = ThirdRedisKeyConstant.AUTH_INFO_REDIS_KEY+ThirdRedisKeyConstant.COLON+customerId+ThirdRedisKeyConstant.COLON+clientType;
redisUtils.set(key,authInfo,-1);
}
/**
* @Description 缓存 刷新后的 授权方令牌 authorizer_access_token 刷新令牌 authorizer_refresh_token
* @param refreshAccessToken
* @param clientType
* @author zxc
*/
/*public void setAuthorizerRefreshToken(AuthorizerAccessTokenFormDTO refreshAccessToken,String clientType){
String key = ThirdRedisKeyConstant.AUTHORIZER_REFRESH_TOKEN_REDIS_KEY + ThirdRedisKeyConstant.COLON + refreshAccessToken.getCustomerId()+ThirdRedisKeyConstant.COLON+clientType;
redisUtils.set(key,refreshAccessToken,-1);
}*/
}

19
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeCustomerService.java

@ -102,4 +102,23 @@ public interface CodeCustomerService extends BaseService<CodeCustomerEntity> {
* @return com.epmet.commons.tools.page.PageData
*/
PageData getCodeList(UploadListFormDTO formDTO);
/**
* 获取审核中代码列表
* @author zhaoqifeng
* @date 2020/7/15 18:16
* @param
* @return java.util.List<com.epmet.dto.CodeCustomerDTO>
*/
List<CodeCustomerDTO> getAuditingCodeList();
/**
* 删除旧代码记录
* @author zhaoqifeng
* @date 2020/7/15 18:10
* @param customerId
* @param clientType
* @return void
*/
void deleteCode(String customerId, String clientType);
}

116
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeExtService.java

@ -0,0 +1,116 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service;
import com.epmet.commons.mybatis.service.BaseService;
import com.epmet.commons.tools.page.PageData;
import com.epmet.dto.CodeExtDTO;
import com.epmet.entity.CodeExtEntity;
import java.util.List;
import java.util.Map;
/**
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-17
*/
public interface CodeExtService extends BaseService<CodeExtEntity> {
/**
* 默认分页
*
* @param params
* @return PageData<CodeExtDTO>
* @author generator
* @date 2020-07-17
*/
PageData<CodeExtDTO> page(Map<String, Object> params);
/**
* 默认查询
*
* @param params
* @return java.util.List<CodeExtDTO>
* @author generator
* @date 2020-07-17
*/
List<CodeExtDTO> list(Map<String, Object> params);
/**
* 单条查询
*
* @param id
* @return CodeExtDTO
* @author generator
* @date 2020-07-17
*/
CodeExtDTO get(String id);
/**
* 默认保存
*
* @param dto
* @return void
* @author generator
* @date 2020-07-17
*/
void save(CodeExtDTO dto);
/**
* 默认更新
*
* @param dto
* @return void
* @author generator
* @date 2020-07-17
*/
void update(CodeExtDTO dto);
/**
* 批量删除
*
* @param ids
* @return void
* @author generator
* @date 2020-07-17
*/
void delete(String[] ids);
/**
* 获取配置模板
*
* @param clientType
* @return java.lang.String
* @author zhaoqifeng
* @date 2020/7/17 15:29
*/
String getExtTemplate(String clientType);
/**
* 获取客户第三方配置
*
* @param customerId
* @param clientType
* @return java.lang.String
* @author zhaoqifeng
* @date 2020/7/17 15:29
*/
CodeExtDTO getExtByCustomer(String customerId, String clientType);
}

37
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CustomerCodeOperationHistoryService.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeOperationHistoryService.java

@ -19,8 +19,9 @@ package com.epmet.service;
import com.epmet.commons.mybatis.service.BaseService;
import com.epmet.commons.tools.page.PageData;
import com.epmet.dto.CustomerCodeOperationHistoryDTO;
import com.epmet.entity.CustomerCodeOperationHistoryEntity;
import com.epmet.dto.CodeOperationHistoryDTO;
import com.epmet.dto.result.CodeHistoryResultDTO;
import com.epmet.entity.CodeOperationHistoryEntity;
import java.util.List;
import java.util.Map;
@ -31,7 +32,7 @@ import java.util.Map;
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-09
*/
public interface CustomerCodeOperationHistoryService extends BaseService<CustomerCodeOperationHistoryEntity> {
public interface CodeOperationHistoryService extends BaseService<CodeOperationHistoryEntity> {
/**
* 默认分页
@ -41,7 +42,7 @@ public interface CustomerCodeOperationHistoryService extends BaseService<Custome
* @author generator
* @date 2020-07-09
*/
PageData<CustomerCodeOperationHistoryDTO> page(Map<String, Object> params);
PageData<CodeOperationHistoryDTO> page(Map<String, Object> params);
/**
* 默认查询
@ -51,7 +52,7 @@ public interface CustomerCodeOperationHistoryService extends BaseService<Custome
* @author generator
* @date 2020-07-09
*/
List<CustomerCodeOperationHistoryDTO> list(Map<String, Object> params);
List<CodeOperationHistoryDTO> list(Map<String, Object> params);
/**
* 单条查询
@ -61,7 +62,7 @@ public interface CustomerCodeOperationHistoryService extends BaseService<Custome
* @author generator
* @date 2020-07-09
*/
CustomerCodeOperationHistoryDTO get(String id);
CodeOperationHistoryDTO get(String id);
/**
* 默认保存
@ -71,7 +72,7 @@ public interface CustomerCodeOperationHistoryService extends BaseService<Custome
* @author generator
* @date 2020-07-09
*/
void save(CustomerCodeOperationHistoryDTO dto);
void save(CodeOperationHistoryDTO dto);
/**
* 默认更新
@ -81,7 +82,7 @@ public interface CustomerCodeOperationHistoryService extends BaseService<Custome
* @author generator
* @date 2020-07-09
*/
void update(CustomerCodeOperationHistoryDTO dto);
void update(CodeOperationHistoryDTO dto);
/**
* 批量删除
@ -92,4 +93,24 @@ public interface CustomerCodeOperationHistoryService extends BaseService<Custome
* @date 2020-07-09
*/
void delete(String[] ids);
/**
* 获取操作历史记录
* @author zhaoqifeng
* @date 2020/7/16 16:53
* @param customerId
* @param clientType
* @return com.epmet.dto.result.CodeHistoryResultDTO
*/
List<CodeHistoryResultDTO> getHistoryList(String customerId, String clientType);
/**
* 更新描述
* @author zhaoqifeng
* @date 2020/7/16 16:10
* @param codeId
* @param describe
* @return void
*/
void updateDescribe(String codeId, String describe);
}

76
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CodeService.java

@ -1,12 +1,9 @@
package com.epmet.service;
import com.epmet.commons.tools.page.PageData;
import com.epmet.dto.form.CodeCommonFormDTO;
import com.epmet.dto.form.CodeUploadFormDTO;
import com.epmet.dto.form.SubmitAuditFormDTO;
import com.epmet.dto.form.UploadListFormDTO;
import com.epmet.dto.result.TemplateListResultDTO;
import com.epmet.dto.result.UploadListResultDTO;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import java.util.List;
@ -26,10 +23,20 @@ public interface CodeService {
*/
List<TemplateListResultDTO> templateList();
/**
* 获取第三方配置
*
* @param formDTO 参数
* @return java.lang.String
* @author zhaoqifeng
* @date 2020/7/17 16:04
*/
String getExtJson(CodeUploadFormDTO formDTO);
/**
* 代码上传
*
* @param formDTO
* @param formDTO 参数
* @author zhaoqifeng
* @date 2020/7/14 18:15
*/
@ -38,7 +45,7 @@ public interface CodeService {
/**
* 已上传代码列表
*
* @param formDTO
* @param formDTO 参数
* @return java.util.List < com.epmet.dto.result.UploadListResultDTO>
* @author zhaoqifeng
* @date 2020/7/14 18:15
@ -48,7 +55,7 @@ public interface CodeService {
/**
* 提交审核
*
* @param formDTO
* @param formDTO 参数
* @author zhaoqifeng
* @date 2020/7/14 18:15
*/
@ -57,9 +64,58 @@ public interface CodeService {
/**
* 审核撤回
*
* @param formDTO
* @param formDTO 参数
* @author zhaoqifeng
* @date 2020/7/14 18:15
*/
void undo(CodeCommonFormDTO formDTO);
/**
* 发布
*
* @param formDTO 参数
* @author zhaoqifeng
* @date 2020/7/14 18:15
*/
void release(CodeCommonFormDTO formDTO);
/**
* 审核失败原因
*
* @param formDTO 参数
* @return com.epmet.dto.result.ReasonResultDTO
* @author zhaoqifeng
* @date 2020/7/16 9:38
*/
ReasonResultDTO reason(CodeCommonFormDTO formDTO);
/**
* 获取体验版二维码
*
* @param formDTO 参数
* @return com.epmet.dto.result.QrCodeResultDTO
* @author zhaoqifeng
* @date 2020/7/16 9:49
*/
QrCodeResultDTO qrCode(CodeCommonFormDTO formDTO);
/**
* 操作历史
*
* @param formDTO 参数
* @return com.epmet.dto.result.CodeHistoryResultDTO
* @author zhaoqifeng
* @date 2020/7/16 10:16
*/
PageData history(CodeCommonFormDTO formDTO);
/**
* 上传临时素材
*
* @param formDTO 参数
* @return java.util.List<com.epmet.dto.result.MediaUploadResultDTO>
* @author zhaoqifeng
* @date 2020/7/17 11:20
*/
String mediaUpload(MediaUploadFormDTO formDTO);
}

5
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/ComponentVerifyTicketService.java

@ -2,6 +2,7 @@ package com.epmet.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author zxc
@ -21,7 +22,7 @@ public interface ComponentVerifyTicketService {
* 令牌component_access_token是第三方平台接口的调用凭据令牌的获取是有限制的每个令牌的有效期为 2 小时
* @author zxc
*/
void getComponentAccessToken();
void getComponentAccessToken(String accessTokenCountFlag);
/**
* @Description 每个预授权码有效期为 10 分钟需要先获取令牌才能调用 获取预授权码
@ -41,6 +42,6 @@ public interface ComponentVerifyTicketService {
* @param
* @author zxc
*/
void redirectUri(HttpServletRequest request, HttpServletResponse response);
void redirectUri(HttpServletRequest request, HttpServletResponse response,String customerId, String clientType) throws IOException;
}

29
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/CustomerMpService.java

@ -20,6 +20,9 @@ package com.epmet.service;
import com.epmet.commons.mybatis.service.BaseService;
import com.epmet.commons.tools.page.PageData;
import com.epmet.dto.CustomerMpDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.WxLoginFormDTO;
import com.epmet.dto.result.PublicCustomerResultDTO;
import com.epmet.entity.CustomerMpEntity;
import java.util.List;
@ -92,4 +95,30 @@ public interface CustomerMpService extends BaseService<CustomerMpEntity> {
* @date 2020-07-09
*/
void delete(String[] ids);
/**
* 获取授权状态
* @author zhaoqifeng
* @date 2020/7/16 15:34
* @param customerId
* @param clientType
* @return java.lang.Boolean
*/
Boolean getAuthFlag(String customerId, String clientType);
/**
* @param formDTO
* @return
* @Author sun
* @Description 校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
**/
UserWechatDTO resiAndWorkLogin(WxLoginFormDTO formDTO);
/**
* @param appId
* @return
* @Author sun
* @Description 根据appId查询公众号注册的客户信息
**/
PublicCustomerResultDTO getCustomerMsg(String appId);
}

22
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/PaCustomerService.java

@ -22,11 +22,11 @@ import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.form.CreateAgencyFormDTO;
import com.epmet.dto.form.MyInfoFormDTO;
import com.epmet.dto.form.RegisterFormDTO;
import com.epmet.dto.form.RegisterInfoFormDTO;
import com.epmet.dto.result.AgencyLevelListResultDTO;
import com.epmet.dto.result.CreateAgencyResultDTO;
import com.epmet.dto.result.InitCustomerResultDTO;
import com.epmet.dto.result.MyInfoResultDTO;
import com.epmet.entity.PaCustomerEntity;
@ -125,12 +125,12 @@ public interface PaCustomerService extends BaseService<PaCustomerEntity> {
CreateAgencyResultDTO createAgency(TokenDto tokenDTO, CreateAgencyFormDTO formDTO);
/**
* @param formDTO
* @param tokenDTO
* @return
* @Author sun
* @Description 公众号-查询我的信息
**/
MyInfoResultDTO myInfo(TokenDto tokenDTO, MyInfoFormDTO formDTO);
MyInfoResultDTO myInfo(TokenDto tokenDTO);
/**
* @param formDTO
@ -139,4 +139,20 @@ public interface PaCustomerService extends BaseService<PaCustomerEntity> {
* @Description 查询公众号注册的客户信息列表
**/
PageData registerInfo(RegisterInfoFormDTO formDTO);
/**
* @param customerId
* @return
* @Author sun
* @Description 根据客户Id查询各项注册信息
**/
InitCustomerResultDTO getCustomerAgencyUser(String customerId);
/**
* @param customerId
* @return
* @Author sun
* @Description 修改客户数据状态为已完成初始化
**/
void updateCustomer(String customerId);
}

3
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/WarrantService.java

@ -1,8 +1,7 @@
package com.epmet.service;
import com.epmet.exception.AesException;
import com.epmet.mpaes.AesException;
import org.dom4j.DocumentException;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

19
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/AppLetAuthorizationServiceImpl.java

@ -1,26 +1,17 @@
package com.epmet.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.HttpClientManager;
import com.epmet.constant.ModuleConstant;
import com.epmet.constant.ThirdApiConstant;
import com.epmet.dao.ComponentAccessTokenDao;
import com.epmet.dao.PaCustomerAgencyDao;
import com.epmet.dto.form.GoToAuthFormDTO;
import com.epmet.dto.result.GoToAuthResultDTO;
import com.epmet.redis.RedisThird;
import com.epmet.service.AppLetAuthorizationService;
import com.epmet.service.ComponentVerifyTicketService;
import com.google.gson.JsonObject;
import com.epmet.wxapi.constant.WxMaCodeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @Author zxc
* @CreateTime 2020/7/10 15:52
@ -33,10 +24,6 @@ public class AppLetAuthorizationServiceImpl implements AppLetAuthorizationServic
private PaCustomerAgencyDao paCustomerAgencyDao;
@Autowired
private ComponentVerifyTicketService componentVerifyTicketService;
@Autowired
private ComponentAccessTokenDao componentAccessTokenDao;
@Autowired
private RedisThird redisThird;
@Value("${third.platform.appId}")
private String componentAppId;
@ -52,8 +39,8 @@ public class AppLetAuthorizationServiceImpl implements AppLetAuthorizationServic
String customerId = paCustomerAgencyDao.getCustomerIdByUserId(userId);
//获取预授权码
String preAuthCode = componentVerifyTicketService.preAuthCode();
String redirectUrl = String.format(ThirdApiConstant.API_RETURN_REDIRECT_URL, formDTO.getClientType(), customerId);
String authUrl = String.format(ThirdApiConstant.API_AUTH_REGISTER_URL, componentAppId, preAuthCode, redirectUrl);
String redirectUrl = String.format(WxMaCodeConstant.API_RETURN_REDIRECT_URL, customerId,formDTO.getClientType());
String authUrl = String.format(WxMaCodeConstant.API_AUTH_REGISTER_URL, componentAppId, preAuthCode, redirectUrl);
result.setUrl(authUrl);
return result;
}

10
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeCustomerServiceImpl.java

@ -113,4 +113,14 @@ public class CodeCustomerServiceImpl extends BaseServiceImpl<CodeCustomerDao, Co
return new PageData<>(list, pageInfo.getTotal());
}
@Override
public List<CodeCustomerDTO> getAuditingCodeList() {
return baseDao.selectAuditingCodeList();
}
@Override
public void deleteCode(String customerId, String clientType) {
baseDao.deleteCode(customerId, clientType);
}
}

58
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CustomerCodeOperationHistoryServiceImpl.java → epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeExtServiceImpl.java

@ -23,11 +23,11 @@ import com.epmet.commons.mybatis.service.impl.BaseServiceImpl;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.constant.FieldConstant;
import com.epmet.dao.CustomerCodeOperationHistoryDao;
import com.epmet.dto.CustomerCodeOperationHistoryDTO;
import com.epmet.entity.CustomerCodeOperationHistoryEntity;
import com.epmet.redis.CustomerCodeOperationHistoryRedis;
import com.epmet.service.CustomerCodeOperationHistoryService;
import com.epmet.dao.CodeExtDao;
import com.epmet.dto.CodeExtDTO;
import com.epmet.entity.CodeExtEntity;
import com.epmet.redis.CodeExtRedis;
import com.epmet.service.CodeExtService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -38,59 +38,59 @@ import java.util.List;
import java.util.Map;
/**
* 客户代码操作历史
* 代码第三方配置
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-09
* @since v1.0.0 2020-07-17
*/
@Service
public class CustomerCodeOperationHistoryServiceImpl extends BaseServiceImpl<CustomerCodeOperationHistoryDao, CustomerCodeOperationHistoryEntity> implements CustomerCodeOperationHistoryService {
public class CodeExtServiceImpl extends BaseServiceImpl<CodeExtDao, CodeExtEntity> implements CodeExtService {
@Autowired
private CustomerCodeOperationHistoryRedis customerCodeOperationHistoryRedis;
private CodeExtRedis codeExtRedis;
@Override
public PageData<CustomerCodeOperationHistoryDTO> page(Map<String, Object> params) {
IPage<CustomerCodeOperationHistoryEntity> page = baseDao.selectPage(
public PageData<CodeExtDTO> page(Map<String, Object> params) {
IPage<CodeExtEntity> page = baseDao.selectPage(
getPage(params, FieldConstant.CREATED_TIME, false),
getWrapper(params)
);
return getPageData(page, CustomerCodeOperationHistoryDTO.class);
return getPageData(page, CodeExtDTO.class);
}
@Override
public List<CustomerCodeOperationHistoryDTO> list(Map<String, Object> params) {
List<CustomerCodeOperationHistoryEntity> entityList = baseDao.selectList(getWrapper(params));
public List<CodeExtDTO> list(Map<String, Object> params) {
List<CodeExtEntity> entityList = baseDao.selectList(getWrapper(params));
return ConvertUtils.sourceToTarget(entityList, CustomerCodeOperationHistoryDTO.class);
return ConvertUtils.sourceToTarget(entityList, CodeExtDTO.class);
}
private QueryWrapper<CustomerCodeOperationHistoryEntity> getWrapper(Map<String, Object> params){
private QueryWrapper<CodeExtEntity> getWrapper(Map<String, Object> params){
String id = (String)params.get(FieldConstant.ID_HUMP);
QueryWrapper<CustomerCodeOperationHistoryEntity> wrapper = new QueryWrapper<>();
QueryWrapper<CodeExtEntity> wrapper = new QueryWrapper<>();
wrapper.eq(StringUtils.isNotBlank(id), FieldConstant.ID, id);
return wrapper;
}
@Override
public CustomerCodeOperationHistoryDTO get(String id) {
CustomerCodeOperationHistoryEntity entity = baseDao.selectById(id);
return ConvertUtils.sourceToTarget(entity, CustomerCodeOperationHistoryDTO.class);
public CodeExtDTO get(String id) {
CodeExtEntity entity = baseDao.selectById(id);
return ConvertUtils.sourceToTarget(entity, CodeExtDTO.class);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(CustomerCodeOperationHistoryDTO dto) {
CustomerCodeOperationHistoryEntity entity = ConvertUtils.sourceToTarget(dto, CustomerCodeOperationHistoryEntity.class);
public void save(CodeExtDTO dto) {
CodeExtEntity entity = ConvertUtils.sourceToTarget(dto, CodeExtEntity.class);
insert(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(CustomerCodeOperationHistoryDTO dto) {
CustomerCodeOperationHistoryEntity entity = ConvertUtils.sourceToTarget(dto, CustomerCodeOperationHistoryEntity.class);
public void update(CodeExtDTO dto) {
CodeExtEntity entity = ConvertUtils.sourceToTarget(dto, CodeExtEntity.class);
updateById(entity);
}
@ -101,4 +101,14 @@ public class CustomerCodeOperationHistoryServiceImpl extends BaseServiceImpl<Cus
baseDao.deleteBatchIds(Arrays.asList(ids));
}
@Override
public String getExtTemplate(String clientType) {
return baseDao.selectExtTemplate(clientType);
}
@Override
public CodeExtDTO getExtByCustomer(String customerId, String clientType) {
return baseDao.selectExtByCustomerId(customerId, clientType);
}
}

115
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeOperationHistoryServiceImpl.java

@ -0,0 +1,115 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.epmet.commons.mybatis.service.impl.BaseServiceImpl;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.constant.FieldConstant;
import com.epmet.dao.CodeOperationHistoryDao;
import com.epmet.dto.CodeOperationHistoryDTO;
import com.epmet.dto.result.CodeHistoryResultDTO;
import com.epmet.entity.CodeOperationHistoryEntity;
import com.epmet.redis.CodeOperationHistoryRedis;
import com.epmet.service.CodeOperationHistoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 客户代码操作历史
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-07-09
*/
@Service
public class CodeOperationHistoryServiceImpl extends BaseServiceImpl<CodeOperationHistoryDao, CodeOperationHistoryEntity> implements CodeOperationHistoryService {
@Autowired
private CodeOperationHistoryRedis customerCodeOperationHistoryRedis;
@Override
public PageData<CodeOperationHistoryDTO> page(Map<String, Object> params) {
IPage<CodeOperationHistoryEntity> page = baseDao.selectPage(
getPage(params, FieldConstant.CREATED_TIME, false),
getWrapper(params)
);
return getPageData(page, CodeOperationHistoryDTO.class);
}
@Override
public List<CodeOperationHistoryDTO> list(Map<String, Object> params) {
List<CodeOperationHistoryEntity> entityList = baseDao.selectList(getWrapper(params));
return ConvertUtils.sourceToTarget(entityList, CodeOperationHistoryDTO.class);
}
private QueryWrapper<CodeOperationHistoryEntity> getWrapper(Map<String, Object> params){
String id = (String)params.get(FieldConstant.ID_HUMP);
QueryWrapper<CodeOperationHistoryEntity> wrapper = new QueryWrapper<>();
wrapper.eq(StringUtils.isNotBlank(id), FieldConstant.ID, id);
return wrapper;
}
@Override
public CodeOperationHistoryDTO get(String id) {
CodeOperationHistoryEntity entity = baseDao.selectById(id);
return ConvertUtils.sourceToTarget(entity, CodeOperationHistoryDTO.class);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(CodeOperationHistoryDTO dto) {
CodeOperationHistoryEntity entity = ConvertUtils.sourceToTarget(dto, CodeOperationHistoryEntity.class);
insert(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(CodeOperationHistoryDTO dto) {
CodeOperationHistoryEntity entity = ConvertUtils.sourceToTarget(dto, CodeOperationHistoryEntity.class);
updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(String[] ids) {
// 逻辑删除(@TableLogic 注解)
baseDao.deleteBatchIds(Arrays.asList(ids));
}
@Override
public List<CodeHistoryResultDTO> getHistoryList(String customerId, String clientType) {
return baseDao.selectHistoryList(customerId, clientType);
}
@Override
public void updateDescribe(String codeId, String describe) {
baseDao.updateDescribeByCodeId(codeId, describe);
}
}

291
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CodeServiceImpl.java

@ -1,38 +1,38 @@
package com.epmet.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.epmet.commons.tools.constant.NumConstant;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.utils.DateUtils;
import com.epmet.commons.tools.utils.MultipartFileToFileUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.constant.CodeConstant;
import com.epmet.dao.AuthorizationInfoDao;
import com.epmet.dao.ComponentAccessTokenDao;
import com.epmet.dto.AuthorizationInfoDTO;
import com.epmet.dto.CodeAuditResultDTO;
import com.epmet.dto.CodeCustomerDTO;
import com.epmet.dto.CustomerDTO;
import com.epmet.dto.form.CodeCommonFormDTO;
import com.epmet.dto.form.CodeUploadFormDTO;
import com.epmet.dto.form.SubmitAuditFormDTO;
import com.epmet.dto.form.UploadListFormDTO;
import com.epmet.dto.result.TemplateListResultDTO;
import com.epmet.dto.*;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import com.epmet.feign.OperCrmOpenFeignClient;
import com.epmet.service.CodeAuditResultService;
import com.epmet.service.CodeCustomerService;
import com.epmet.service.CodeService;
import com.epmet.service.*;
import com.epmet.wxapi.param.WxMaCodeAuditStatusReq;
import com.epmet.wxapi.param.WxMaCodeCommitReq;
import com.epmet.wxapi.param.WxMaCodeSubmitAuditRequest;
import com.epmet.wxapi.result.WxMaAuditStatusResult;
import com.epmet.wxapi.result.WxMaTemplateResult;
import com.epmet.wxapi.result.WxResult;
import com.epmet.wxapi.param.WxMaNewsReq;
import com.epmet.wxapi.result.*;
import com.epmet.wxapi.service.WxMaCodeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
@ -55,6 +55,14 @@ public class CodeServiceImpl implements CodeService {
private OperCrmOpenFeignClient operCrmOpenFeignClient;
@Autowired
private CodeAuditResultService codeAuditResultService;
@Autowired
private CustomerMpService customerMpService;
@Autowired
private CodeOperationHistoryService codeOperationHistoryService;
@Autowired
private CodeMediaService codeMediaService;
@Autowired
private CodeExtService codeExtService;
@Override
public List<TemplateListResultDTO> templateList() {
@ -71,7 +79,7 @@ public class CodeServiceImpl implements CodeService {
}
wxResult.getData().forEach(temp -> {
TemplateListResultDTO dto = new TemplateListResultDTO();
dto.setTemplateId(temp.getTemplateId());
dto.setId(temp.getTemplateId());
dto.setUserVersion(temp.getUserVersion());
dto.setUserDesc(temp.getUserDesc());
dto.setCreateTime(DateUtils.formatTimestamp(temp.getCreateTime(), DateUtils.DATE_PATTERN));
@ -81,21 +89,49 @@ public class CodeServiceImpl implements CodeService {
}
@Override
public String getExtJson(CodeUploadFormDTO formDTO) {
CodeExtDTO codeExtDTO = codeExtService.getExtByCustomer(formDTO.getCustomerId(), formDTO.getClientType());
if (null == codeExtDTO) {
return codeExtService.getExtTemplate(formDTO.getClientType());
}
return codeExtDTO.getExtJson();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void upload(CodeUploadFormDTO formDTO) {
//是否授权
if (customerMpService.getAuthFlag(formDTO.getCustomerId(), formDTO.getClientType())) {
throw new RenException("未授权");
}
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(formDTO.getCustomerId(), formDTO.getClientType());
if (null == authInfo) {
throw new RenException("未授权");
}
//TODO 获取第三方自定义配置
String extJson = "{}";
if (!isJson(formDTO.getExtJson())) {
throw new RenException("第三方配置不是有效的Json");
}
CodeExtDTO codeExtDTO = codeExtService.getExtByCustomer(formDTO.getCustomerId(), formDTO.getClientType());
if (null == codeExtDTO) {
codeExtDTO = new CodeExtDTO();
codeExtDTO.setCustomerId(formDTO.getCustomerId());
codeExtDTO.setClientType(formDTO.getClientType());
codeExtDTO.setAppId(authInfo.getAuthorizerAppid());
codeExtDTO.setExtJson(formDTO.getExtJson());
codeExtService.save(codeExtDTO);
}
codeExtDTO.setExtJson(formDTO.getExtJson());
codeExtService.update(codeExtDTO);
WxMaCodeCommitReq request = ConvertUtils.sourceToTarget(formDTO, WxMaCodeCommitReq.class);
request.setExtJson(extJson);
request.setExtJson(formDTO.getExtJson());
//调用微信API上传代码
WxResult wxResult = wxMaCodeService.commit(authInfo.getAuthorizerAccessToken(), request);
//上传失败,抛出异常
if (!wxResult.success()) {
saveOperation(formDTO.getCustomerId(), null, formDTO.getUserVersion(), CodeConstant.OPER_UPLOAD, wxResult.getErrorMsg());
throw new RenException(wxResult.getErrorCode(), wxResult.getErrorMsg());
}
//获取客户信息
@ -105,19 +141,54 @@ public class CodeServiceImpl implements CodeService {
if (!customerInfo.success()) {
throw new RenException(customerInfo.getCode(), customerInfo.getMsg());
}
//TODO 将之前上传信息删除
//将之前上传信息删除
codeCustomerService.deleteCode(formDTO.getCustomerId(), formDTO.getClientType());
//将上传信息存入表中
CodeCustomerDTO codeCustomerDTO = ConvertUtils.sourceToTarget(formDTO, CodeCustomerDTO.class);
codeCustomerDTO.setCustomerName(customerInfo.getData().getCustomerName());
codeCustomerDTO.setExtJson(extJson);
codeCustomerDTO.setExtJson(formDTO.getExtJson());
codeCustomerDTO.setStatus(CodeConstant.UNAUDITED);
codeCustomerService.save(codeCustomerDTO);
saveOperation(formDTO.getCustomerId(), codeCustomerDTO.getId(), formDTO.getUserVersion(), CodeConstant.OPER_UPLOAD, "上传成功");
}
@Override
public PageData uploadList(UploadListFormDTO formDTO) {
//TODO 更新审核状态
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(formDTO.getCustomerId(), formDTO.getClientType());
if (null == authInfo) {
throw new RenException("未授权");
}
List<CodeCustomerDTO> auditingList = codeCustomerService.getAuditingCodeList();
auditingList.forEach(code -> {
//获取审核结果信息
CodeAuditResultDTO auditResult = codeAuditResultService.getAuditResultByCodeId(code.getId());
//调用微信API获取最新审核状态
WxMaCodeAuditStatusReq request = new WxMaCodeAuditStatusReq();
request.setAuditId(auditResult.getAuditId());
WxResult<WxMaAuditStatusResult> wxAuditResult = wxMaCodeService.getAuditStatus(authInfo.getAuthorizerAccessToken(), request);
if (wxAuditResult.success()) {
WxMaAuditStatusResult result = wxAuditResult.getData();
if (result.getStatus() == NumConstant.ZERO) {
code.setStatus(CodeConstant.AUDIT_SUCCESS);
auditResult.setResult(CodeConstant.AUDIT_SUCCESS);
codeOperationHistoryService.updateDescribe(code.getId(), "审核成功");
} else if (result.getStatus() == NumConstant.ONE) {
code.setStatus(CodeConstant.AUDIT_FAILED);
auditResult.setResult(CodeConstant.AUDIT_FAILED);
auditResult.setReason(result.getReason());
codeOperationHistoryService.updateDescribe(code.getId(), result.getReason());
} else if (result.getStatus() == NumConstant.FOUR) {
code.setStatus(CodeConstant.DELAY);
auditResult.setResult(CodeConstant.DELAY);
codeOperationHistoryService.updateDescribe(code.getId(), "审核延后");
}
codeCustomerService.update(code);
codeAuditResultService.update(auditResult);
}
});
return codeCustomerService.getCodeList(formDTO);
}
@ -125,12 +196,21 @@ public class CodeServiceImpl implements CodeService {
public void submitAudit(SubmitAuditFormDTO formDTO) {
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
//是否授权
if (customerMpService.getAuthFlag(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType())) {
throw new RenException("未授权");
}
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
if (null == authInfo) {
throw new RenException("未授权");
}
//调用微信API上提交审核
WxMaCodeSubmitAuditRequest request = ConvertUtils.sourceToTarget(formDTO, WxMaCodeSubmitAuditRequest.class);
WxResult<String> wxResult = wxMaCodeService.submitAudit(authInfo.getAuthorizerAccessToken(), request);
if (!wxResult.success()) {
saveOperation(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getId(), codeCustomerDTO.getUserVersion(), CodeConstant.OPER_SUBMIT,
wxResult.getErrorMsg());
throw new RenException(wxResult.getErrorCode(), wxResult.getErrorMsg());
}
//将数据存入代码审核表
@ -143,21 +223,30 @@ public class CodeServiceImpl implements CodeService {
//更新代码表状态
codeCustomerDTO.setStatus(CodeConstant.AUDITING);
codeCustomerService.update(codeCustomerDTO);
saveOperation(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getId(), codeCustomerDTO.getUserVersion(), CodeConstant.OPER_SUBMIT,
"审核中");
}
@Override
public void undo(CodeCommonFormDTO formDTO) {
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
//是否授权
if (customerMpService.getAuthFlag(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType())) {
throw new RenException("未授权");
}
//获取审核结果信息
CodeAuditResultDTO codeAuditResultDTO = codeAuditResultService.getAuditResultByCodeId(formDTO.getCodeId());
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
if (null == authInfo) {
throw new RenException("未授权");
}
//调用微信API获取最新审核状态
WxMaCodeAuditStatusReq request = new WxMaCodeAuditStatusReq();
request.setAuditId(codeAuditResultDTO.getAuditId());
WxResult<WxMaAuditStatusResult> wxAuditResult = wxMaCodeService.getAuditStatus(authInfo.getAuthorizerAccessToken(), request);
if (!wxAuditResult.success() ) {
if (!wxAuditResult.success()) {
throw new RenException(wxAuditResult.getErrorCode(), wxAuditResult.getErrorMsg());
}
if (wxAuditResult.getData().getStatus() != NumConstant.TWO) {
@ -166,6 +255,8 @@ public class CodeServiceImpl implements CodeService {
//调用微信API撤销审核
WxResult wxResult = wxMaCodeService.undoCodeAudit(authInfo.getAuthorizerAccessToken());
if (!wxResult.success()) {
saveOperation(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getId(), codeCustomerDTO.getUserVersion(), CodeConstant.OPER_UNDO,
wxResult.getErrorMsg());
throw new RenException(wxResult.getErrorCode(), wxResult.getErrorMsg());
}
//更新审核结果
@ -174,6 +265,160 @@ public class CodeServiceImpl implements CodeService {
//更新代码表状态
codeCustomerDTO.setStatus(CodeConstant.WITHDRAWN);
codeCustomerService.update(codeCustomerDTO);
//更新审核操作记录描述
codeOperationHistoryService.updateDescribe(codeCustomerDTO.getId(), "已撤回");
saveOperation(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getId(), codeCustomerDTO.getUserVersion(), CodeConstant.OPER_UNDO,
"成功");
}
@Override
public void release(CodeCommonFormDTO formDTO) {
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
//是否授权
if (customerMpService.getAuthFlag(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType())) {
throw new RenException("未授权");
}
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
if (null == authInfo) {
throw new RenException("未授权");
}
//调用微信API发布代码
WxResult wxResult = wxMaCodeService.release(authInfo.getAuthorizerAccessToken());
if (!wxResult.success()) {
//更新代码表状态
codeCustomerDTO.setStatus(CodeConstant.RELEASE_FAILED);
codeCustomerService.update(codeCustomerDTO);
saveOperation(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getId(), codeCustomerDTO.getUserVersion(), CodeConstant.OPER_RELEASE,
wxResult.getErrorMsg());
throw new RenException(wxResult.getErrorCode(), wxResult.getErrorMsg());
}
//更新代码表状态
codeCustomerDTO.setStatus(CodeConstant.RELEASE_SUCCESS);
codeCustomerService.update(codeCustomerDTO);
saveOperation(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getId(), codeCustomerDTO.getUserVersion(), CodeConstant.OPER_RELEASE,
"发布成功");
}
@Override
public ReasonResultDTO reason(CodeCommonFormDTO formDTO) {
ReasonResultDTO result = new ReasonResultDTO();
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
//是否授权
if (customerMpService.getAuthFlag(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType())) {
throw new RenException("未授权");
}
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
if (null == authInfo) {
throw new RenException("未授权");
}
//获取审核结果信息
CodeAuditResultDTO codeAuditResultDTO = codeAuditResultService.getAuditResultByCodeId(formDTO.getCodeId());
result.setReason(codeAuditResultDTO.getReason());
String[] mediaIds = codeAuditResultDTO.getScreenShot().split("[|]");
List<String> mediaIdList = new ArrayList<>(mediaIds.length);
Collections.addAll(mediaIdList, mediaIds);
List<String> urlList = new ArrayList<>();
mediaIdList.forEach(mediaId -> {
//调用微信API获取素材
WxMaCodeAuditStatusReq request = new WxMaCodeAuditStatusReq();
request.setAuditId(codeAuditResultDTO.getAuditId());
WxMaNewsReq wxMaNewsReq = new WxMaNewsReq();
wxMaNewsReq.setMediaId(mediaId);
WxResult<WxMaNewsResult> wxAuditResult = wxMaCodeService.getMaterial(authInfo.getAuthorizerAccessToken(), wxMaNewsReq);
wxAuditResult.getData().getNewsItem().forEach(news -> {
urlList.add(news.getUrl());
});
});
result.setScreenshotUrl(urlList);
return result;
}
@Override
public QrCodeResultDTO qrCode(CodeCommonFormDTO formDTO) {
QrCodeResultDTO result = new QrCodeResultDTO();
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
//是否授权
if (customerMpService.getAuthFlag(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType())) {
throw new RenException("未授权");
}
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
//调用微信API获取获取体验版二维码
WxResult<Byte[]> wxResult = wxMaCodeService.getQrCode(authInfo.getAuthorizerAccessToken(), null);
if (!wxResult.success()) {
throw new RenException(wxResult.getErrorCode(), wxResult.getErrorMsg());
}
result.setQrcode(wxResult.getData());
return result;
}
@Override
public PageData history(CodeCommonFormDTO formDTO) {
PageHelper.startPage(formDTO.getPage(), formDTO.getLimit());
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
List<CodeHistoryResultDTO> list = codeOperationHistoryService.getHistoryList(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
PageInfo<CodeHistoryResultDTO> pageInfo = new PageInfo<>(list);
return new PageData<>(list, pageInfo.getTotal());
}
@Override
public String mediaUpload(MediaUploadFormDTO formDTO) {
try {
File file = MultipartFileToFileUtils.multipartFileToFile(formDTO.getMedia());
//获取上传代码信息
CodeCustomerDTO codeCustomerDTO = codeCustomerService.get(formDTO.getCodeId());
//获取小程序调用令牌
AuthorizationInfoDTO authInfo = authorizationInfoDao.getAuthInfoByCustomer(codeCustomerDTO.getCustomerId(), codeCustomerDTO.getClientType());
WxResult<WxMaUploadMediaResult> wxResult = wxMaCodeService.uploadMedia(authInfo.getAuthorizerAccessToken(), formDTO.getType(), file);
if (!wxResult.success()) {
throw new RenException(wxResult.getErrorCode(), wxResult.getErrorMsg());
}
//将素材信息存入数据库表中
CodeMediaDTO codeMediaDTO = new CodeMediaDTO();
codeMediaDTO.setCodeId(formDTO.getCodeId());
codeMediaDTO.setMediaId(wxResult.getData().getMediaId());
codeMediaDTO.setMediaName(formDTO.getMedia().getName());
codeMediaDTO.setMediaType(wxResult.getData().getType());
codeMediaService.save(codeMediaDTO);
return wxResult.getData().getMediaId();
} catch (Exception e) {
throw new RenException("上传失败");
}
}
private void saveOperation(String customerId, String codeId, String version, String operation, String describe) {
CodeOperationHistoryDTO operationDTO = new CodeOperationHistoryDTO();
operationDTO.setCustomerId(customerId);
operationDTO.setCodeId(codeId);
operationDTO.setVersion(version);
operationDTO.setOperation(operation);
operationDTO.setDescribe(describe);
codeOperationHistoryService.save(operationDTO);
}
/**
* 校验是否是Json
*
* @param content
* @return boolean
* @author zhaoqifeng
* @date 2020/7/17 15:43
*/
private boolean isJson(String content) {
try {
JSONObject jsonStr = JSONObject.parseObject(content);
return true;
} catch (Exception e) {
return false;
}
}
}

185
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/ComponentVerifyTicketServiceImpl.java

@ -7,7 +7,7 @@ import com.epmet.commons.tools.constant.NumConstant;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.utils.HttpClientManager;
import com.epmet.constant.ModuleConstant;
import com.epmet.constant.ThirdApiConstant;
import com.epmet.constant.ThirdRedisKeyConstant;
import com.epmet.constant.ThirdRunTimeInfoConstant;
import com.epmet.dao.*;
import com.epmet.dto.form.*;
@ -15,12 +15,11 @@ import com.epmet.dto.result.AuthCodeResultDTO;
import com.epmet.dto.result.AuthorizationInfoResultDTO;
import com.epmet.dto.result.CreateOpenResultDTO;
import com.epmet.dto.result.WillOverDueResultDTO;
import com.epmet.mpaes.WXBizMsgCrypt;
import com.epmet.mpaes.WXXmlToMapUtil;
import com.epmet.redis.RedisThird;
import com.epmet.service.ComponentVerifyTicketService;
import com.epmet.util.WXBizMsgCrypt;
import com.epmet.util.WXXmlToMapUtil;
import com.epmet.util.XmlUtil;
import com.github.pagehelper.util.StringUtil;
import com.epmet.wxapi.constant.WxMaCodeConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
@ -31,14 +30,13 @@ import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import static com.epmet.constant.ModuleConstant.COMPONENT_ACCESS_TOKEN;
import static com.epmet.constant.ThirdRunTimeInfoConstant.*;
/**
@ -107,27 +105,17 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
String timeStamp = request.getParameter(ModuleConstant.TIMESTAMP);
// 随机数
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));
// 从请求中读取整个post数据
InputStream inputStream;
String postData = null;
inputStream = request.getInputStream();
postData= IOUtils.toString(inputStream,ModuleConstant.UTF8);
//从XML中获取<Encrypt></Encrypt>标签内的密文文本
String encrypt = XmlUtil.toXml(postData);
log.info(String.format(ThirdRunTimeInfoConstant.ENCRYPT,encrypt));
//格式化密文文本,否则没有<ToUserName>标签,会解密失败,参考官方的加解密代码JAVA版本
String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
String fromXML = String.format(format, encrypt);
String msg = ""; //解密后的明文
WXBizMsgCrypt wxcpt;
if(StringUtil.isEmpty(encrypt)) {
msg = fromXML;
} else {
wxcpt = new WXBizMsgCrypt(token,aesKey, componentAppId);
// 解密消息
msg = wxcpt.decryptMsg(msgSignature, timeStamp, nonce, fromXML);
}
log.info("postData = "+postData);
WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token,aesKey,componentAppId);
String msg = wxBizMsgCrypt.decryptMsg(msgSignature, timeStamp, nonce, postData);
log.info(String.format(ThirdRunTimeInfoConstant.MSG,msg));
// 将xml转为map
Map<String, String> result = WXXmlToMapUtil.xmlToMap(msg);
@ -171,7 +159,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
log.info(ThirdRunTimeInfoConstant.END_TICKET);
Integer tokenCount = componentAccessTokenDao.selectAccessTokenCount();
if (tokenCount == NumConstant.ZERO){
this.getComponentAccessToken();
String accessTokenCountFlag = ModuleConstant.ACCOUNT_TOKEN_FLAG_ONE;
this.getComponentAccessToken(accessTokenCountFlag);
}
return ModuleConstant.SUCCESS;
}
@ -179,44 +168,40 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
/**
* @Description 定时获取 (令牌component_access_token) 第三方与微信交互使用的component_access_token
* 每十分钟执行一次,判断是否有马上超时的15分钟以内算马上超时
* @param
* @param accessTokenCountFlag 表里的 component_access_token的数量
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void getComponentAccessToken() {
public void getComponentAccessToken(String accessTokenCountFlag) {
log.info(ThirdRunTimeInfoConstant.START_GET_COMPONENT_ACCESS_TOKEN);
Map<String, String> reMap;
//距离超时时间小于15分钟的数量
Integer tokenCount = componentAccessTokenDao.selectWillOverTokenCount();
if (tokenCount > NumConstant.ZERO) {
try {
String componentVerifyTicket = redisThird.getComponentVerifyTicket();
JSONObject jsonObject = new JSONObject();
jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId);
jsonObject.put(ModuleConstant.COMPONENT_APPSECRET, appSecret);
jsonObject.put(ModuleConstant.TICKET_UNDERLINE_KEY, componentVerifyTicket);
String post = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_COMPONENT_TOKEN_URL, JSON.toJSONString(jsonObject)).getData();
HashMap<String, String> hashMap = JSON.parseObject(post, HashMap.class);
String componentAccessToken = hashMap.get(ModuleConstant.COMPONENT_ACCESS_TOKEN);
String expiresIn = hashMap.get(ModuleConstant.EXPIRES_IN);
Date expiresInTime = this.countExpirationTime(expiresIn);
if (StringUtils.isNotEmpty(componentAccessToken)) {
//令牌信息存DB
ComponentAccessTokenFormDTO formDTO = new ComponentAccessTokenFormDTO();
formDTO.setComponentAccessToken(componentAccessToken);
formDTO.setExpiresInTime(expiresInTime);
//先逻辑删,在插入
log.info(ThirdRunTimeInfoConstant.START_DELETE_COMPONENT_ACCESS_TOKEN);
componentAccessTokenDao.updateOldComponentAccessToken();
componentAccessTokenDao.insertComponentAccessToken(formDTO);
//存缓存
redisThird.setComponentAccessToken(componentAccessToken);
} else {
throw new RenException(ThirdRunTimeInfoConstant.FAILURE_ACCESS_TOKEN);
}
} catch (Exception e) {
e.printStackTrace();
if ((tokenCount > NumConstant.ZERO && accessTokenCountFlag.equals(ModuleConstant.ACCOUNT_TOKEN_FLAG_TWO)) || accessTokenCountFlag.equals(ModuleConstant.ACCOUNT_TOKEN_FLAG_ONE)) {
String componentVerifyTicket = redisThird.getComponentVerifyTicket();
JSONObject jsonObject = new JSONObject();
jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId);
jsonObject.put(ModuleConstant.COMPONENT_APPSECRET, appSecret);
jsonObject.put(ModuleConstant.TICKET_UNDERLINE_KEY, componentVerifyTicket);
String post = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_COMPONENT_TOKEN_URL, JSON.toJSONString(jsonObject)).getData();
Map hashMap = JSON.parseObject(post, Map.class);
String componentAccessToken = hashMap.get(COMPONENT_ACCESS_TOKEN).toString();
Integer expiresIn = (Integer) hashMap.get(ModuleConstant.EXPIRES_IN);
Date expiresInTime = this.countExpirationTime(expiresIn.toString());
if (StringUtils.isNotEmpty(componentAccessToken)) {
//令牌信息存DB
ComponentAccessTokenFormDTO formDTO = new ComponentAccessTokenFormDTO();
formDTO.setComponentAccessToken(componentAccessToken);
formDTO.setExpiresInTime(expiresInTime);
//先逻辑删,在插入
log.info(ThirdRunTimeInfoConstant.START_DELETE_COMPONENT_ACCESS_TOKEN);
componentAccessTokenDao.updateOldComponentAccessToken();
componentAccessTokenDao.insertComponentAccessToken(formDTO);
//存缓存
redisThird.setComponentAccessToken(componentAccessToken);
} else {
throw new RenException(ThirdRunTimeInfoConstant.FAILURE_ACCESS_TOKEN);
}
log.info(ThirdRunTimeInfoConstant.SUCCESS_ACCESS_TOKEN);
}
@ -236,12 +221,12 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
String accessToken = redisThird.getComponentAccessToken();
JSONObject jsonObject = new JSONObject();
jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId);
String post = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_CREATE_PREAUTHCODE_URL + accessToken, JSON.toJSONString(jsonObject)).getData();
String post = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_CREATE_PREAUTHCODE_URL + accessToken, JSON.toJSONString(jsonObject)).getData();
log.info(String.format(POST_RESULT,post));
HashMap<String, String> hashMap = JSON.parseObject(post, HashMap.class);
preAuthCode = hashMap.get(ModuleConstant.PRE_AUTH_CODE);
String expiresIn = hashMap.get(ModuleConstant.EXPIRES_IN);
Date expiresInTime = this.countExpirationTime(expiresIn);
Map hashMap = JSON.parseObject(post, Map.class);
preAuthCode = hashMap.get(ModuleConstant.PRE_AUTH_CODE).toString();
Integer expiresIn = (Integer) hashMap.get(ModuleConstant.EXPIRES_IN);
Date expiresInTime = this.countExpirationTime(expiresIn.toString());
if (StringUtils.isNotEmpty(preAuthCode)) {
//预授权码 存DB
PreAuthTokenFormDTO formDTO = new PreAuthTokenFormDTO();
@ -276,16 +261,18 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
JSONObject jsonObject = new JSONObject();
jsonObject.put(ModuleConstant.COMPONENT_APPID, componentAppId);
jsonObject.put(ModuleConstant.AUTHORIZATION_CODE, authCode);
String authInfo = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_QUERY_AUTH_URL + accessToken, JSON.toJSONString(jsonObject)).getData();
String authInfo = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_QUERY_AUTH_URL + accessToken, JSON.toJSONString(jsonObject)).getData();
HashMap<String,Map> hashMap = JSON.parseObject(authInfo, HashMap.class);
Map map = hashMap.get(ModuleConstant.AUTHORIZATION_INFO);
authorizationInfoResultDTO = mapToEntity(map, AuthorizationInfoResultDTO.class);
String authAppId = authorizationInfoResultDTO.getAuthorizer_appid();
log.info("授权信息:"+map);
String expiresIn = authorizationInfoResultDTO.getExpires_in();
Date expiresInTime = this.countExpirationTime(expiresIn);
//授权信息分为两张表,基础信息authorization_info,授权列表func_info
// 1. 基础信息
AuthorizationInfoFormDTO authInfoDTO = new AuthorizationInfoFormDTO();
authInfoDTO.setAuthorizerAppid(authorizationInfoResultDTO.getAuthorizer_appid());
authInfoDTO.setAuthorizerAppid(authAppId);
authInfoDTO.setAuthorizerAccessToken(authorizationInfoResultDTO.getAuthorizer_access_token());
authInfoDTO.setAuthorizerRefreshToken(authorizationInfoResultDTO.getAuthorizer_refresh_token());
authInfoDTO.setExpiresInTime(expiresInTime);
@ -298,23 +285,23 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
log.info(START_INSERT_FUNC_INFO);
List<FuncInfoFormDTO> funcInfos = new ArrayList<>();
List<Map> func_info = authorizationInfoResultDTO.getFunc_info();
for (Map map1 : func_info) {
List key = (List)map1.keySet();
FuncInfoFormDTO fu = new FuncInfoFormDTO();
String funcscopeCategory = key.get(NumConstant.ZERO).toString();
fu.setFuncscopeCategory(funcscopeCategory);
Map funcscope = (Map) map1.get(funcscopeCategory);
String funcscopeId = funcscope.get("id").toString();
fu.setFuncscopeId(funcscopeId);
fu.setAuthorizationInfoAppid(authorizationInfoResultDTO.getAuthorizer_appid());
fu.setCustomerId(customerId);
funcInfos.add(fu);
}
log.info("权限列表信息:"+func_info);
func_info.forEach(func -> {
func.forEach((key,value) -> {
FuncInfoFormDTO fu = new FuncInfoFormDTO();
fu.setFuncscopeCategory((String) key);
Map funcScope = (Map) value;
fu.setFuncscopeId(funcScope.get(ModuleConstant.ID).toString());
fu.setAuthorizationInfoAppid(authAppId);
fu.setCustomerId(customerId);
funcInfos.add(fu);
});
});
//先逻辑删除,在插入
funcInfoDao.updateOldFuncInfo(customerId);
funcInfoDao.updateOldFuncInfo(customerId,authAppId);
funcInfoDao.insertFuncInfo(funcInfos);
// 授权信息放入缓存
redisThird.setAuthInfo(authorizationInfoResultDTO);
redisThird.setAuthInfo(authorizationInfoResultDTO,customerId,clientType);
//authorizer_refresh_token 放入缓存
redisThird.setAuthorizerRefreshToken(authInfoDTO);
log.info(END_GET_AUTH_INFO);
@ -332,6 +319,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
//查询 即将过期的 authorizer_access_token
List<WillOverDueResultDTO> willOverDueResultDTOS = authorizationInfoDao.checkWillOverDue();
if (willOverDueResultDTOS.size() != NumConstant.ZERO && null != willOverDueResultDTOS){
log.info("查询到即将过期的authorizer_access_token");
willOverDueResultDTOS.forEach(willOverDueDTO -> {
String authAppId = willOverDueDTO.getAuthAppId();
String customerId = willOverDueDTO.getCustomerId();
@ -342,7 +330,8 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
//第三方平台AppId
jsonObject.put(ModuleConstant.COMPONENT_APPID,componentAppId);
jsonObject.put(ModuleConstant.AUTHORIZER_REFRESH_TOKEN,willOverDueDTO.getAuthorizerRefreshToken());
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_AUTHORIZER_TOKEN_URL, JSON.toJSONString(jsonObject)).getData();
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);
//authorizer_access_token
String authorizerAccessToken = map.get(ModuleConstant.AUTHORIZER_ACCESS_TOKEN).toString();
@ -366,6 +355,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
//缓存 refreshAuthorizerAccessToken
redisThird.setAuthorizerRefreshToken(authorizationInfo);
});
log.info("更新authorizer_access_token成功");
}
}
@ -377,18 +367,22 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void redirectUri(HttpServletRequest request, HttpServletResponse response) {
public void redirectUri(HttpServletRequest request, HttpServletResponse response,String customerId, String client) throws IOException{
log.info("开始执行回调URL");
try {
request.setCharacterEncoding(ModuleConstant.UTF8);
response.setCharacterEncoding(ModuleConstant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String customerId = request.getParameter(ModuleConstant.CUSTOMER_ID);
String client = request.getParameter(ModuleConstant.CLIENT);
/*String customerId = request.getParameter(ModuleConstant.CUSTOMER_ID);
String client = request.getParameter(ModuleConstant.CLIENT);*/
String authCode = request.getParameter(ModuleConstant.AUTH_CODE);
String expiresIn = request.getParameter(ModuleConstant.EXPIRES_IN);
Date expiresInTime = this.countExpirationTime(expiresIn);
if (StringUtils.isBlank(customerId)||StringUtils.isBlank(client)||StringUtils.isBlank(authCode)||StringUtils.isBlank(expiresIn)){
log.info("客户ID = "+customerId+", 客户端类型为 = "+client+", 授权码为 = "+authCode+", 有效期 = "+expiresIn);
}
// AuthorizationInfoResultDTO authorizationInfo = this.authInfoByAuthCode(authCode, customerId,client);
//authCode存数据库
AuthCodeFormDTO formDTO = new AuthCodeFormDTO();
@ -398,11 +392,13 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
//授权方AppId
// formDTO.setAuthAppId(authorizationInfo.getAuthorizer_appid());
formDTO.setCustomerId(customerId);
log.info(formDTO.toString());
// this.updateCustomerMpAppIdAndCreateOpenPlatform(customerId,authorizationInfo.getAuthorizer_appid(),client);
authCodeDao.insertRedirectAuthCode(formDTO);
//authCode存缓存
redisThird.setAuthCode(formDTO);
log.info("回调结束");
response.sendRedirect(WxMaCodeConstant.WEB_URL);
}
/**
@ -413,15 +409,19 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
*/
@Transactional(rollbackFor = Exception.class)
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);
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_GET_AUTHORIZER_INFO, JSON.toJSONString(jsonObject)).getData();
String componentAccessToken = redisThird.getComponentAccessToken();
String data = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_GET_AUTHORIZER_INFO + componentAccessToken , JSON.toJSONString(jsonObject)).getData();
Map<String,Map> map = JSON.parseObject(data, Map.class);
Map authorizerInfo = map.get(ModuleConstant.AUTHORIZER_INFO);
log.info("授权信息:"+authorizerInfo);
// 存在 “miniprograminfo” 字段为小程序,不存在为公众号
boolean keyExist = authorizerInfo.containsKey(ModuleConstant.MINI_PROGRAM_INFO);
if (keyExist == true){
log.info("授权方为小程序 并 开始插入信息");
MiniInfoFormDTO miniInfoFormDTO = this.mapToEntity(authorizerInfo, MiniInfoFormDTO.class);
miniInfoFormDTO.setCustomerId(customerId);
miniInfoFormDTO.setClientType(clientType);
@ -471,6 +471,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
});
miniCategoryInfoDao.insertCategoryInfo(categoryInfoList);
}else {
log.info("授权方为公众号 并 开始插入信息");
PaInfoFormDTO paInfoFormDTO = this.mapToEntity(authorizerInfo, PaInfoFormDTO.class);
//公众号基本信息插入
paInfoDao.insertPaInfo(paInfoFormDTO);
@ -489,7 +490,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
});
businessInfoDao.insertBusinessInfo(businessInfoList);
}
log.info("保存授权方基本信息结束");
}
@ -500,13 +501,17 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
*/
@Transactional(rollbackFor = Exception.class)
public void updateCustomerMpAppIdAndCreateOpenPlatform(String customerId,String authAppId,String clientType){
log.info("开始创建开放平台账号并绑定");
Integer authCount = customerMpDao.selectAuthCount(customerId);
String openPlatformId = null;
String authorizerRefreshToken = redisThird.getAuthorizerRefreshToken(customerId + ThirdRedisKeyConstant.COLON + clientType);
if (authCount==NumConstant.ZERO){
log.info("未查询到该客户授权信息,先创建开放平台账号,再绑定");
//没有任何一个小程序/公众号授权,【先创建,再绑定】
JSONObject jsonObject = new JSONObject();
jsonObject.put(ModuleConstant.APP_ID,authAppId);
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_CREATE_OPEN, JSON.toJSONString(jsonObject)).getData();
// 此处的 access_token 为 【authorizer_access_token】
String data = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_CREATE_OPEN + authorizerRefreshToken, JSON.toJSONString(jsonObject)).getData();
Map<String,String> map = JSON.parseObject(data, Map.class);
CreateOpenResultDTO createOpen = new CreateOpenResultDTO();
createOpen.setErrCode(Integer.valueOf(map.get(ModuleConstant.ERR_CODE)));
@ -530,11 +535,12 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
openPlatformAccountDao.insertOpenPlatFormAccount(coForm);
openPlatformId = coForm.getId();
}else if (authCount>NumConstant.ZERO){
log.info("该客户已创建过开放平台账号,直接绑定");
String openAppId = openPlatformAccountDao.selectOpenAppIdByCustomerId(customerId);
JSONObject jsonObject = new JSONObject();
jsonObject.put(ModuleConstant.LOW_APP_ID,componentAppId);
jsonObject.put(ModuleConstant.OPEN_APP_ID,openAppId);
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.API_BIND_OPEN, JSON.toJSONString(jsonObject)).getData();
String data = HttpClientManager.getInstance().sendPostByJSON(WxMaCodeConstant.API_BIND_OPEN + authorizerRefreshToken, JSON.toJSONString(jsonObject)).getData();
Map<String,String> map = JSON.parseObject(data, Map.class);
CreateOpenResultDTO createOpen = new CreateOpenResultDTO();
createOpen.setErrCode(Integer.valueOf(map.get(ModuleConstant.ERR_CODE)));
@ -570,6 +576,7 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
bindingAccount.setClientType(clientType);
bindingAccount.setCustomerId(customerId);
bindingAccountDao.insertBindingAccount(bindingAccount);
log.info("创建绑定账号结束");
}
/**
@ -608,10 +615,10 @@ public class ComponentVerifyTicketServiceImpl implements ComponentVerifyTicketSe
* @author zxc
*/
public Date countExpirationTime(String expiresIn){
long now = LocalDateTime.now().toEpochSecond(ZoneOffset.of(NumConstant.POSITIVE_EIGHT_STR));
long expiresInTime = now + Long.valueOf(expiresIn);
LocalDateTime localDateTime = Instant.ofEpochMilli(expiresInTime).atZone(ZoneOffset.ofHours(NumConstant.EIGHT)).toLocalDateTime();
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(NumConstant.EIGHT)).toInstant());
expiresIn = expiresIn + "000";
Date date = new Date();
long l = date.getTime() + Long.valueOf(expiresIn);
date.setTime(l);
return date;
}
}

66
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/CustomerMpServiceImpl.java

@ -20,15 +20,26 @@ package com.epmet.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.epmet.commons.mybatis.service.impl.BaseServiceImpl;
import com.epmet.commons.tools.constant.FieldConstant;
import com.epmet.commons.tools.constant.NumConstant;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.page.PageData;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.constant.FieldConstant;
import com.epmet.constant.PaConstant;
import com.epmet.dao.CustomerMpDao;
import com.epmet.dto.CustomerMpDTO;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.WxLoginFormDTO;
import com.epmet.dto.result.PublicCustomerResultDTO;
import com.epmet.entity.CustomerMpEntity;
import com.epmet.redis.CustomerMpRedis;
import com.epmet.service.CustomerMpService;
import com.epmet.wxapi.service.WxLoginService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -46,8 +57,11 @@ import java.util.Map;
@Service
public class CustomerMpServiceImpl extends BaseServiceImpl<CustomerMpDao, CustomerMpEntity> implements CustomerMpService {
private static final Logger logger = LoggerFactory.getLogger(CustomerMpServiceImpl.class);
@Autowired
private CustomerMpRedis customerMpRedis;
@Autowired
private WxLoginService wxLoginService;
@Override
public PageData<CustomerMpDTO> page(Map<String, Object> params) {
@ -101,4 +115,54 @@ public class CustomerMpServiceImpl extends BaseServiceImpl<CustomerMpDao, Custom
baseDao.deleteBatchIds(Arrays.asList(ids));
}
@Override
public Boolean getAuthFlag(String customerId, String clientType) {
return baseDao.selectAuthFlag(customerId, clientType);
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
**/
@Override
public UserWechatDTO resiAndWorkLogin(WxLoginFormDTO formDTO) {
//1.校验appId是否有效以及对应小程序是否已授权
CustomerMpDTO mpDTO = baseDao.selectByAppId(formDTO.getAppId());
if (null == mpDTO) {
logger.error("无效的appId->根据appId未查询到对应的小程序信息,appId:" + formDTO.getAppId());
throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode());
}
if (NumConstant.ONE != mpDTO.getAuthorizationFlag()) {
logger.error("当前appId对应的小程序未完成第三方平台授权不允许使用,appId:" + formDTO.getAppId());
throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode());
}
//2.调用微信API获取用户信息
UserWechatDTO resultMap = wxLoginService.resiAndWorkLogin(formDTO.getAppId(), formDTO.getWxCode(), mpDTO.getCustomerId(), mpDTO.getClient());
return resultMap;
}
/**
* @param appId
* @return
* @Author sun
* @Description 根据appId查询公众号注册的客户信息
**/
@Override
public PublicCustomerResultDTO getCustomerMsg(String appId) {
PublicCustomerResultDTO resultDTO = new PublicCustomerResultDTO();
//1.根据appid查询客户信息
PaCustomerDTO paCustomerDTO = baseDao.selectCustomerByAppId(appId);
if (null == paCustomerDTO) {
logger.error("根据小程序appId未查询到已授权并且已完成客户初始化的客户信息,appId->" + appId);
throw new RenException(PaConstant.SELECT_CUSTOMER_EXCEPTION);
}
resultDTO.setCustomer(paCustomerDTO);
return resultDTO;
}
}

91
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PaCustomerServiceImpl.java

@ -35,13 +35,9 @@ import com.epmet.constant.PaConstant;
import com.epmet.dao.*;
import com.epmet.dto.*;
import com.epmet.dto.form.CreateAgencyFormDTO;
import com.epmet.dto.form.MyInfoFormDTO;
import com.epmet.dto.form.RegisterFormDTO;
import com.epmet.dto.form.RegisterInfoFormDTO;
import com.epmet.dto.result.AgencyLevelListResultDTO;
import com.epmet.dto.result.CreateAgencyResultDTO;
import com.epmet.dto.result.CustomerAgencyResultDTO;
import com.epmet.dto.result.MyInfoResultDTO;
import com.epmet.dto.result.*;
import com.epmet.entity.*;
import com.epmet.redis.PaCustomerRedis;
import com.epmet.service.CustomerMpService;
@ -207,22 +203,31 @@ public class PaCustomerServiceImpl extends BaseServiceImpl<PaCustomerDao, PaCust
@Override
public List<AgencyLevelListResultDTO> agencyLevelList() {
List<AgencyLevelListResultDTO> list = new ArrayList<>();
//省级
AgencyLevelListResultDTO dto1 = new AgencyLevelListResultDTO();
dto1.setLevelKey(PaConstant.PROVINCE_KEY);
dto1.setLevelName(PaConstant.PROVINCE_NAME);
list.add(dto1);
//市级
AgencyLevelListResultDTO dto2 = new AgencyLevelListResultDTO();
dto2.setLevelKey(PaConstant.CITY_KEY);
dto2.setLevelName(PaConstant.CITY_NAME);
list.add(dto2);
//区县级
AgencyLevelListResultDTO dto3 = new AgencyLevelListResultDTO();
dto3.setLevelKey(PaConstant.STREET_KEY);
dto3.setLevelName(PaConstant.STREET_NAME);
dto3.setLevelKey(PaConstant.DISTRICT_KEY);
dto3.setLevelName(PaConstant.DISTRICT_NAME);
list.add(dto3);
//乡镇级
AgencyLevelListResultDTO dto4 = new AgencyLevelListResultDTO();
dto4.setLevelKey(PaConstant.COMMUNITY_KEY);
dto4.setLevelName(PaConstant.COMMUNITY_NAME);
dto4.setLevelKey(PaConstant.STREET_KEY);
dto4.setLevelName(PaConstant.STREET_NAME);
list.add(dto4);
//社区级
AgencyLevelListResultDTO dto5 = new AgencyLevelListResultDTO();
dto5.setLevelKey(PaConstant.COMMUNITY_KEY);
dto5.setLevelName(PaConstant.COMMUNITY_NAME);
list.add(dto5);
return list;
}
@ -284,27 +289,27 @@ public class PaCustomerServiceImpl extends BaseServiceImpl<PaCustomerDao, PaCust
//获取key的剩余过期时间
String key = RedisKeys.getCpUserKey(LoginConstant.APP_PUBLIC, LoginConstant.CLIENT_MP, tokenDTO.getUserId());
long expire = redisUtils.getExpire(key);
//存入redis
cpUserDetailRedis.set(redisTokenDTO, expire);
//6.接口返参
CreateAgencyResultDTO resultDTO = new CreateAgencyResultDTO();
resultDTO.setCustomerId(entity.getId());
resultDTO.setToken(redisTokenDTO.getToken());
return resultDTO;
}
/**
* @param formDTO
* @param tokenDTO
* @return
* @Author sun
* @Description 公众号-查询我的信息
**/
@Override
public MyInfoResultDTO myInfo(TokenDto tokenDTO, MyInfoFormDTO formDTO) {
public MyInfoResultDTO myInfo(TokenDto tokenDTO) {
//0.根据token中userId查询对应的客户Id,客户Id没有则表示用户没有填写过组织信息,需要继续完善信息
PaCustomerUserAgencyDTO dto = paCustomerUserAgencyDao.selectByUserId(tokenDTO.getUserId());
if(null==dto||null==dto.getCustomerId()){
if (null == dto || null == dto.getCustomerId()) {
return new MyInfoResultDTO();
}
String customerId = dto.getCustomerId();
@ -340,7 +345,7 @@ public class PaCustomerServiceImpl extends BaseServiceImpl<PaCustomerDao, PaCust
* @param formDTO
* @return
* @Author sun
* @Description 查询公众号注册的客户信息列表
* @Description 查询公众号注册的客户信息列表
**/
@Override
public PageData registerInfo(RegisterInfoFormDTO formDTO) {
@ -365,10 +370,66 @@ public class PaCustomerServiceImpl extends BaseServiceImpl<PaCustomerDao, PaCust
}
});
});
PageInfo<CustomerAgencyResultDTO> pageInfo = new PageInfo<>();
PageInfo<CustomerAgencyResultDTO> pageInfo = new PageInfo<>(list);
return new PageData<>(list, pageInfo.getTotal());
}
/**
* @param customerId
* @return
* @Author sun
* @Description 根据客户Id查询各项注册信息
**/
@Override
public InitCustomerResultDTO getCustomerAgencyUser(String customerId) {
InitCustomerResultDTO result = new InitCustomerResultDTO();
//1.查询注册客户信息,并判断是否已完成初始化
PaCustomerEntity entity = baseDao.selectById(customerId);
//未查询到注册客户信息
if (null == entity) {
throw new RenException(EpmetErrorCode.SELECT_CUSTOMER_ERROR.getCode());
}
//客户已完成初始化
if (NumConstant.ONE == entity.getIsInitialize()) {
throw new RenException(EpmetErrorCode.OPER_CUSTOMER_EXISTS.getCode());
}
PaCustomerDTO paCustomer = ConvertUtils.sourceToTarget(entity, PaCustomerDTO.class);
result.setPaCustomer(paCustomer);
//2.查询注册客户对应的组织信息
PaCustomerAgencyDTO paAgency = paCustomerAgencyDao.selectAgency(customerId);
if (null == paAgency) {
throw new RenException(EpmetErrorCode.SELECT_AGENCY_ERROR.getCode());
}
result.setPaAgency(paAgency);
//3.查询组织客户对应的管理员信息
PaUserDTO paUser = paUserDao.selectPaUser(customerId);
if (null == paUser) {
throw new RenException(EpmetErrorCode.SELECT_USER_ERROR.getCode());
}
result.setPaUser(paUser);
return result;
}
/**
* @param customerId
* @return
* @Author sun
* @Description 修改客户数据状态为已完成初始化
**/
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCustomer(String customerId) {
//更新pa_customer表数据状态
PaCustomerDTO dto = new PaCustomerDTO();
dto.setId(customerId);
dto.setIsInitialize(NumConstant.ONE);
if (baseDao.updateCustomerById(dto) < NumConstant.ONE) {
logger.error(EpmetErrorCode.UPDATE_CUSTOMER_ERROR.getMsg());
throw new RenException(EpmetErrorCode.UPDATE_CUSTOMER_ERROR.getCode());
}
}
}

11
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/PaUserServiceImpl.java

@ -26,6 +26,7 @@ import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.constant.FieldConstant;
import com.epmet.dao.PaCustomerDao;
import com.epmet.dao.PaUserDao;
import com.epmet.dao.PaUserWechatDao;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.PaUserDTO;
import com.epmet.dto.PaUserWechatDTO;
@ -61,6 +62,8 @@ public class PaUserServiceImpl extends BaseServiceImpl<PaUserDao, PaUserEntity>
private PaUserWechatService paUserWechatService;
@Autowired
private PaCustomerDao paCustomerDao;
@Autowired
private PaUserWechatDao paUserWechatDao;
@Override
public PageData<PaUserDTO> page(Map<String, Object> params) {
@ -175,17 +178,25 @@ public class PaUserServiceImpl extends BaseServiceImpl<PaUserDao, PaUserEntity>
@Override
public CustomerUserResultDTO checkPaUser(String phone) {
CustomerUserResultDTO resultDTO = new CustomerUserResultDTO();
//1.根据手机号查询用户信息
List<PaUserDTO> userList = baseDao.selectUserByPhone(phone);
if (null == userList || userList.size() < NumConstant.ONE) {
resultDTO.setPaUserResult(null);
resultDTO.setPaCustomerResult(null);
resultDTO.setPaUserWechatResult(null);
return resultDTO;
}
PaUserDTO dto = userList.get(NumConstant.ZERO);
//2.根据用户Id查询对应的客户信息
List<PaCustomerDTO> customerList = paCustomerDao.selectCustomerByUserId(dto.getId());
//3.根据用户Id查询对应的微信基本信息
PaUserWechatDTO wechatDTO = new PaUserWechatDTO();
wechatDTO.setUserId(dto.getId());
PaUserWechatEntity wechatEntity = paUserWechatDao.selectWechatByUserId(wechatDTO);
resultDTO.setPaUserResult(dto);
resultDTO.setPaCustomerResult(customerList.size() > NumConstant.ZERO ? customerList.get(NumConstant.ZERO) : null);
resultDTO.setPaUserWechatResult(ConvertUtils.sourceToTarget(wechatEntity, PaUserWechatDTO.class));
return resultDTO;
}

42
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/service/impl/WarrantServiceImpl.java

@ -10,12 +10,10 @@ import com.epmet.dao.MiniInfoDao;
import com.epmet.dto.form.CodeAuditRecordFormDTO;
import com.epmet.dto.result.CustomerIdAndClientResultDTO;
import com.epmet.dto.result.TemplateAndAppIdResultDTO;
import com.epmet.exception.AesException;
import com.epmet.mpaes.AesException;
import com.epmet.mpaes.WXBizMsgCrypt;
import com.epmet.mpaes.WXXmlToMapUtil;
import com.epmet.service.WarrantService;
import com.epmet.util.WXBizMsgCrypt;
import com.epmet.util.WXXmlToMapUtil;
import com.epmet.util.XmlUtil;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
@ -26,9 +24,9 @@ import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
/**
@ -61,13 +59,14 @@ public class WarrantServiceImpl implements WarrantService {
/**
* @Description 1.保存代码审核结果 2.更新代码上传结果
* @param request
* @param appid
* @param appId
* @param response
* @author zxc
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void acceptMessageAndEvent(HttpServletRequest request, String appid, HttpServletResponse response)throws IOException, DocumentException, AesException {
public void acceptMessageAndEvent(HttpServletRequest request, String appId, HttpServletResponse response)throws IOException, DocumentException, AesException {
log.info("appId:"+ appId);
request.setCharacterEncoding(ModuleConstant.UTF8);
String msgSignature = request.getParameter(ModuleConstant.MSG_SIGNATURE);
String timeStamp = request.getParameter(ModuleConstant.TIMESTAMP);
@ -79,26 +78,21 @@ public class WarrantServiceImpl implements WarrantService {
String postData = null;
inputStream = request.getInputStream();
postData= IOUtils.toString(inputStream,ModuleConstant.UTF8);
//从XML中获取<Encrypt></Encrypt>标签内的密文文本
String encrypt = XmlUtil.toXml(postData);
log.info(String.format(ThirdRunTimeInfoConstant.ENCRYPT,encrypt));
//格式化密文文本,否则没有<ToUserName>标签,会解密失败,参考官方的加解密代码JAVA版本
String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
String fromXML = String.format(format, encrypt);
String msg = ""; //解密后的明文
WXBizMsgCrypt wxcpt;
if(StringUtil.isEmpty(encrypt)) {
msg = fromXML;
} else {
wxcpt = new WXBizMsgCrypt(token,aesKey, componentAppId);
// 解密消息
msg = wxcpt.decryptMsg(msgSignature, timeStamp, nonce, fromXML);
WXBizMsgCrypt wxBizMsgCrypt = null;
String msg = null;
try {
wxBizMsgCrypt = new WXBizMsgCrypt(token,aesKey,componentAppId);
msg = wxBizMsgCrypt.decryptMsg(msgSignature, timeStamp, nonce, postData);
} catch (AesException e) {
e.printStackTrace();
}
log.info(String.format(ThirdRunTimeInfoConstant.MSG,msg));
// 将xml转为map
Map<String, Object> result = WXXmlToMapUtil.multilayerXmlToMap(msg);
CodeAuditRecordFormDTO codeAuditRecord = componentVerifyTicketService.mapToEntity(result, CodeAuditRecordFormDTO.class);
Map<String,Object> xml = (Map<String, Object>) result.get(ModuleConstant.XML);
Long createTime = Long.valueOf(xml.get(ModuleConstant.CREATE_TIME).toString());
CodeAuditRecordFormDTO codeAuditRecord = componentVerifyTicketService.mapToEntity(xml, CodeAuditRecordFormDTO.class);
codeAuditRecord.setWechatCreateTime(new Date(createTime));
String toUserName = codeAuditRecord.getToUserName();//小程序原始ID
CustomerIdAndClientResultDTO customerIdAndClientResultDTO = miniInfoDao.selectCustomerIdAndClientByToUserName(toUserName);
String clientType = customerIdAndClientResultDTO.getClientType();

30
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/OkHttpHelper.java

@ -1,30 +0,0 @@
package com.epmet.util;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @Author zxc
* @CreateTime 2020/7/7 17:39
*/
@Component
public class OkHttpHelper {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
public String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}

63
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/PKCS7EncoderUtil.java

@ -1,63 +0,0 @@
package com.epmet.util;
import com.epmet.commons.tools.constant.NumConstant;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* @Author zxc
* @CreateTime 2020/7/6 10:45
*/
public class PKCS7EncoderUtil {
static Charset CHARSET = Charset.forName("utf-8");
static int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
static byte[] encode(int count) {
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
if (amountToPad == NumConstant.ZERO) {
amountToPad = BLOCK_SIZE;
}
// 获得补位所用的字符
char padChr = chr(amountToPad);
String tmp = new String();
for (int index = NumConstant.ZERO; index < amountToPad; index++) {
tmp += padChr;
}
return tmp.getBytes(CHARSET);
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
static byte[] decode(byte[] decrypted) {
int pad = (int) decrypted[decrypted.length - 1];
if (pad < NumConstant.ONE || pad > 32) {
pad = NumConstant.ZERO;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符用于对明文进行补码
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}

246
epmet-module/epmet-third/epmet-third-server/src/main/java/com/epmet/util/WXBizMsgCrypt.java

@ -1,246 +0,0 @@
package com.epmet.util;
import com.epmet.exception.AesException;
import me.chanjar.weixin.common.util.crypto.PKCS7Encoder;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).
* <ol> * <li>第三方回复加密消息给公众平台</li> * <li>第三方收到公众平台发送的消息验证消息的安全性并对消息进行解密</li>
* </ol>
* 说明异常java.security.InvalidKeyException:illegal Key Size的解决方案
* <ol>
* <li>在官方网站下载JCE无限制权限策略文件JDK7的下载地址 *
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li>
* <li>下载后解压可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>
* <li>如果安装了JRE将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li>
* <li>如果安装了JDK将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li>
*
* </ol>
*/
/**
* @Author zxc
* @CreateTime 2020/7/6 9:51
*/
public class WXBizMsgCrypt {
static Charset CHARSET = Charset.forName("utf-8");
Base64 base64 = new Base64();
byte[] aesKey;
String token;
String appId;
/**
* 构造函数
* @param token 公众平台上开发者设置的token
* @param encodingAesKey 公众平台上开发者设置的EncodingAESKey
* @param appId 公众平台appid
*
* @throws AesException 执行失败请查看该异常的错误码和具体的错误信息
*/
public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException {
if (encodingAesKey.length() != 43) {
throw new AesException(AesException.IllegalAesKey);
}
this.token = token;
this.appId = appId;
aesKey = Base64.decodeBase64(encodingAesKey + "=");
}
// 还原4个字节的网络字节序
int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
/**
* 对密文进行解密.
* @param text 需要解密的密文
* @return 解密得到的明文
* @throws AesException aes解密失败
*/
String decrypt(String text) throws AesException {
byte[] original;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.DecryptAESError);
}
String xmlContent, from_appid;
try {
// 去除补位字符
byte[] bytes = PKCS7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和AppId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
from_appid =
new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET);
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.IllegalBuffer);
}
// appid不相同的情况
if (!from_appid.equals(appId)) {
throw new AesException(AesException.ValidateSignatureError);
}
return xmlContent;
}
/**
* * 检验消息的真实性并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名进行签名验证</li>
* <li>若验证通过则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @param msgSignature 签名串对应URL参数的msg_signature
* @param timeStamp 时间戳对应URL参数的timestamp
* @param nonce 随机串对应URL参数的nonce
* @param postData 密文对应POST请求的数据
* @return 解密后的原文
* @throws AesException 执行失败请查看该异常的错误码和具体的错误信息
*/
public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
throws AesException {
// 密钥,公众账号的app secret
// 提取密文
Object[] encrypt = extract(postData);
// 验证安全签名
String signature = getSHA1(token, timeStamp, nonce, encrypt[1].toString());
// 和URL中的签名比较是否相等
// System.out.println("第三方收到URL中的签名:" + msg_sign);
// System.out.println("第三方校验签名:" + signature);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
// 解密
String result = decrypt(encrypt[1].toString());
return result;
}
/**
* 提取出xml数据包中的加密消息
* @param xmltext 待提取的xml字符串
* @return 提取出的加密消息字符串
* @throws AesException
*/
public static Object[] extract(String xmltext) throws AesException {
Object[] result = new Object[3];
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(xmltext);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
NodeList nodelist2 = root.getElementsByTagName("ToUserName");
result[0] = 0;
result[1] = nodelist1.item(0).getTextContent();
//注意这里,获取ticket中的xml里面没有ToUserName这个元素,官网原示例代码在这里会报空
//空指针,所以需要处理一下
if (nodelist2 != null) {
if (nodelist2.item(0) != null) {
result[2] = nodelist2.item(0).getTextContent();
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ParseXmlError);
}
}
/**
* 用SHA1算法生成安全签名
* @param token 票据
* @param timestamp 时间戳
* @param nonce 随机字符串
* @param encrypt 密文
* @return 安全签名
* @throws
* AesException
*/
public static String getSHA1(String token, String timestamp, String nonce, String encrypt)
throws AesException {
try {
String[] array = new String[]{token, timestamp, nonce, encrypt};
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ComputeSignatureError);
}
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save