diff --git a/pom.xml b/pom.xml index 14c7ecf..f8d92cf 100644 --- a/pom.xml +++ b/pom.xml @@ -6,13 +6,13 @@ pom - cloudutil util - wechatutil + util_cloud + util_wechat ptos_tall ptos_diplomatist ptos_open - tall_sdk + ptos_sdk @@ -112,7 +112,7 @@ cn.hutool hutool-all - 4.1.21 + 5.8.0.M4 diff --git a/ptos_diplomatist/pom.xml b/ptos_diplomatist/pom.xml index 966a78c..ad39990 100644 --- a/ptos_diplomatist/pom.xml +++ b/ptos_diplomatist/pom.xml @@ -22,7 +22,7 @@ - cloudutil + util_cloud com.ccsensptos 1.0-SNAPSHOT @@ -41,7 +41,7 @@ - wechatutil + util_wechat com.ccsensptos 1.0-SNAPSHOT diff --git a/ptos_open/pom.xml b/ptos_open/pom.xml index 677a4fe..cdb71a3 100644 --- a/ptos_open/pom.xml +++ b/ptos_open/pom.xml @@ -22,13 +22,13 @@ - tallsdk + ptos_sdk com.ccsensptos 0.0.1-SNAPSHOT - cloudutil + util_cloud com.ccsensptos 1.0-SNAPSHOT @@ -41,7 +41,7 @@ - wechatutil + util_wechat com.ccsensptos 1.0-SNAPSHOT diff --git a/tall_sdk/.gitignore b/ptos_sdk/.gitignore similarity index 100% rename from tall_sdk/.gitignore rename to ptos_sdk/.gitignore diff --git a/tall_sdk/mvnw b/ptos_sdk/mvnw similarity index 100% rename from tall_sdk/mvnw rename to ptos_sdk/mvnw diff --git a/tall_sdk/mvnw.cmd b/ptos_sdk/mvnw.cmd similarity index 100% rename from tall_sdk/mvnw.cmd rename to ptos_sdk/mvnw.cmd diff --git a/tall_sdk/pom.xml b/ptos_sdk/pom.xml similarity index 97% rename from tall_sdk/pom.xml rename to ptos_sdk/pom.xml index a55aaba..068fd34 100644 --- a/tall_sdk/pom.xml +++ b/ptos_sdk/pom.xml @@ -8,11 +8,11 @@ 1.0-SNAPSHOT - tallsdk + ptos_sdk 0.0.1-SNAPSHOT - tallsdk + ptos_sdk Demo project for Spring Boot diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/TallSdkApplication.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/TallSdkApplication.java similarity index 100% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/TallSdkApplication.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/TallSdkApplication.java diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/HeartbeatController.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/HeartbeatController.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/HeartbeatController.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/HeartbeatController.java index dba32a7..d145af0 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/HeartbeatController.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/HeartbeatController.java @@ -1,28 +1,28 @@ -package com.ccsensptos.tallsdk.api; - -import com.ccsens.util.JsonResponse; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author 逗 - */ -@Api(tags = "heartbeat" , description = "域信息相关接口") -@RestController -@RequestMapping("/tall") -@Slf4j -public class HeartbeatController { - - @ApiOperation(value = "接收私域的心跳", notes = "") - @RequestMapping(value = "/heart", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse receiveHeartbeat() throws Exception { - log.info("接受PTOS_TALL心跳后正确返回"); - return JsonResponse.newInstance().ok(); - } - - -} +package com.ccsensptos.tallsdk.api; + +import com.ccsens.util.JsonResponse; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author 逗 + */ +@Api(tags = "heartbeat" , description = "域信息相关接口") +@RestController +@RequestMapping("/tall") +@Slf4j +public class HeartbeatController { + + @ApiOperation(value = "接收私域的心跳", notes = "") + @RequestMapping(value = "/heart", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse receiveHeartbeat() throws Exception { + log.info("接受PTOS_TALL心跳后正确返回"); + return JsonResponse.newInstance().ok(); + } + + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/ProjectController.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/ProjectController.java similarity index 98% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/ProjectController.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/ProjectController.java index 4774d1a..7c553a7 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/ProjectController.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/ProjectController.java @@ -1,94 +1,94 @@ -package com.ccsensptos.tallsdk.api; - -import com.ccsens.util.WebConstant; -import com.ccsens.util.bean.dto.QueryDto; -import com.ccsensptos.tallsdk.bean.dto.TallProjectDto; -import com.ccsensptos.tallsdk.bean.vo.TallWbsVo; -import com.ccsensptos.tallsdk.service.ITallService; -import com.ccsensptos.tallsdk.bean.vo.TallProjectVo; -import com.ccsens.util.JsonResponse; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * @author 逗 - */ -@Api(tags = "project" , description = "项目相关接口") -@RestController -@RequestMapping("/tall/project") -@Slf4j -public class ProjectController { - - @Resource - private ITallService tallService; - - @ApiOperation(value = "日历页获取项目列表", notes = "") - @RequestMapping(value = "/query", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> queryProjectByUser(HttpServletRequest request, @ApiParam @Validated @RequestBody TallProjectDto.QueryProjectDto params) throws Exception{ - log.info("查询用户所有域下所有业务内的所有项目:{}",params); - List projectInfoList = tallService.queryProjectByUser(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params); - log.info("返回用户所有域下所有业务内的所有项目"); - return JsonResponse.newInstance().ok(projectInfoList); - } - - - @ApiOperation(value = "导入Wbs", notes = "") - @RequestMapping(value = "/wbs", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse importWbs(HttpServletRequest request, QueryDto params,Long parentId) throws Exception{ - log.info("导入Wbs:{}",params); - TallProjectVo.ProjectInfo projectInfoList = tallService.importWbs(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam(),parentId); - log.info("导入Wbs"); - return JsonResponse.newInstance().ok(projectInfoList); - } - - - @ApiOperation(value = "导出Wbs", notes = "") - @RequestMapping(value = "/exportWbs", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse exportWbs(HttpServletRequest request,@ApiParam @Validated @RequestBody QueryDto params) throws Exception{ - log.info("导出Wbs:{}",params); - TallWbsVo.WbsPath wbsPath = tallService.exportWbs(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("Wbs的路径:{}",wbsPath); - return JsonResponse.newInstance().ok(wbsPath); - } - - @ApiOperation(value = "根据id查询项目信息", notes = "根据id查询项目信息") - @RequestMapping(value = "/findProjectById", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse findProjectById(HttpServletRequest request,@ApiParam @Validated @RequestBody QueryDto params) throws Exception{ - TallProjectVo.ProjectInfo projectById = tallService.findProjectById(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - return JsonResponse.newInstance().ok(projectById); - } - - - - @ApiOperation(value = "删除项目", notes = "") - @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> deleteProject(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) throws Exception{ - log.info("删除项目:{}",params); - tallService.deleteProject(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("删除项目成功"); - return JsonResponse.newInstance().ok(); - } - - - @ApiOperation(value = "拖拽项目", notes = "") - @RequestMapping(value = "/drag", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse dragProject(HttpServletRequest request, @ApiParam @Validated @RequestBody TallProjectDto.MoveProject params) throws Exception{ - log.info("删除项目:{}",params); - tallService.dragProject(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params); - log.info("删除项目成功"); - return JsonResponse.newInstance().ok(); - } - -} +package com.ccsensptos.tallsdk.api; + +import com.ccsens.util.WebConstant; +import com.ccsens.util.bean.dto.QueryDto; +import com.ccsensptos.tallsdk.bean.dto.TallProjectDto; +import com.ccsensptos.tallsdk.bean.vo.TallWbsVo; +import com.ccsensptos.tallsdk.service.ITallService; +import com.ccsensptos.tallsdk.bean.vo.TallProjectVo; +import com.ccsens.util.JsonResponse; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * @author 逗 + */ +@Api(tags = "project" , description = "项目相关接口") +@RestController +@RequestMapping("/tall/project") +@Slf4j +public class ProjectController { + + @Resource + private ITallService tallService; + + @ApiOperation(value = "日历页获取项目列表", notes = "") + @RequestMapping(value = "/query", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> queryProjectByUser(HttpServletRequest request, @ApiParam @Validated @RequestBody TallProjectDto.QueryProjectDto params) throws Exception{ + log.info("查询用户所有域下所有业务内的所有项目:{}",params); + List projectInfoList = tallService.queryProjectByUser(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params); + log.info("返回用户所有域下所有业务内的所有项目"); + return JsonResponse.newInstance().ok(projectInfoList); + } + + + @ApiOperation(value = "导入Wbs", notes = "") + @RequestMapping(value = "/wbs", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse importWbs(HttpServletRequest request, QueryDto params,Long parentId) throws Exception{ + log.info("导入Wbs:{}",params); + TallProjectVo.ProjectInfo projectInfoList = tallService.importWbs(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam(),parentId); + log.info("导入Wbs"); + return JsonResponse.newInstance().ok(projectInfoList); + } + + + @ApiOperation(value = "导出Wbs", notes = "") + @RequestMapping(value = "/exportWbs", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse exportWbs(HttpServletRequest request,@ApiParam @Validated @RequestBody QueryDto params) throws Exception{ + log.info("导出Wbs:{}",params); + TallWbsVo.WbsPath wbsPath = tallService.exportWbs(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("Wbs的路径:{}",wbsPath); + return JsonResponse.newInstance().ok(wbsPath); + } + + @ApiOperation(value = "根据id查询项目信息", notes = "根据id查询项目信息") + @RequestMapping(value = "/findProjectById", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse findProjectById(HttpServletRequest request,@ApiParam @Validated @RequestBody QueryDto params) throws Exception{ + TallProjectVo.ProjectInfo projectById = tallService.findProjectById(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + return JsonResponse.newInstance().ok(projectById); + } + + + + @ApiOperation(value = "删除项目", notes = "") + @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> deleteProject(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) throws Exception{ + log.info("删除项目:{}",params); + tallService.deleteProject(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("删除项目成功"); + return JsonResponse.newInstance().ok(); + } + + + @ApiOperation(value = "拖拽项目", notes = "") + @RequestMapping(value = "/drag", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse dragProject(HttpServletRequest request, @ApiParam @Validated @RequestBody TallProjectDto.MoveProject params) throws Exception{ + log.info("删除项目:{}",params); + tallService.dragProject(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params); + log.info("删除项目成功"); + return JsonResponse.newInstance().ok(); + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/RoleController.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/RoleController.java similarity index 97% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/RoleController.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/RoleController.java index d299b2b..aa039ad 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/RoleController.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/RoleController.java @@ -1,45 +1,45 @@ -package com.ccsensptos.tallsdk.api; - -import com.ccsens.util.WebConstant; -import com.ccsens.util.bean.dto.QueryDto; -import com.ccsensptos.tallsdk.bean.dto.TallRoleDto; -import com.ccsensptos.tallsdk.bean.vo.TallRoleVo; -import com.ccsensptos.tallsdk.service.ITallService; -import com.ccsens.util.JsonResponse; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; - -/** - * @author 逗 - */ -@Api(tags = "角色相关" , description = "DebugController | ") -@RestController -@RequestMapping("/tall/role") -@Slf4j -public class RoleController { - - @Resource - private ITallService tallService; - - - - @ApiOperation(value = "根据项目id查找角色", notes = "") - @RequestMapping(value = "/show", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse queryByProjectId(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { - log.info("根据项目id查找角色{}",params); - TallRoleVo.QueryRole queryRole = tallService.queryShowRole(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("项目id查找角色列表{}",queryRole); - return JsonResponse.newInstance().ok(queryRole); - } - -} +package com.ccsensptos.tallsdk.api; + +import com.ccsens.util.WebConstant; +import com.ccsens.util.bean.dto.QueryDto; +import com.ccsensptos.tallsdk.bean.dto.TallRoleDto; +import com.ccsensptos.tallsdk.bean.vo.TallRoleVo; +import com.ccsensptos.tallsdk.service.ITallService; +import com.ccsens.util.JsonResponse; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; + +/** + * @author 逗 + */ +@Api(tags = "角色相关" , description = "DebugController | ") +@RestController +@RequestMapping("/tall/role") +@Slf4j +public class RoleController { + + @Resource + private ITallService tallService; + + + + @ApiOperation(value = "根据项目id查找角色", notes = "") + @RequestMapping(value = "/show", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse queryByProjectId(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { + log.info("根据项目id查找角色{}",params); + TallRoleVo.QueryRole queryRole = tallService.queryShowRole(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("项目id查找角色列表{}",queryRole); + return JsonResponse.newInstance().ok(queryRole); + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/TaskController.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/TaskController.java similarity index 98% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/TaskController.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/TaskController.java index 433ab40..3a2734e 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/api/TaskController.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/api/TaskController.java @@ -1,93 +1,93 @@ -package com.ccsensptos.tallsdk.api; - -import com.ccsens.util.WebConstant; -import com.ccsens.util.bean.dto.QueryDto; -import com.ccsensptos.tallsdk.service.ITallService; -import com.ccsensptos.tallsdk.bean.dto.TallTaskDto; -import com.ccsensptos.tallsdk.bean.vo.TallTaskVo; -import com.ccsens.util.JsonResponse; -import com.github.pagehelper.PageHelper; -import com.github.pagehelper.PageInfo; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * @author 逗 - */ -@Api(tags = "任务相关" , description = "DebugController | ") -@RestController -@RequestMapping("/tall/task") -@Slf4j -public class TaskController { - - @Resource - private ITallService tallService; - - - @ApiOperation(value = "查找永久日常任务", notes = "") - @RequestMapping(value = "/permanent", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> queryPermanentGlobalTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { - log.info("查找永久日常任务:{}",params); - List queryTasks = tallService.queryPermanentGlobalTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("返回日常任务"); - return JsonResponse.newInstance().ok(queryTasks); - } - - - @ApiOperation(value = "查找带时间的日常任务", notes = "") - @RequestMapping(value = "/global", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> queryGlobalTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { - log.info("查找带时间的日常任务:{}",params); - List queryTasks = tallService.queryGlobalTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("返回带时间的日常任务"); - return JsonResponse.newInstance().ok(queryTasks); - } - - - @ApiOperation(value = "查找定期任务", notes = "") - @RequestMapping(value = "/regular", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> queryRegularTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { - log.info("查找定期任务:{}",params); - List queryTasks = tallService.queryRegularTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("返回定期任务"); - return JsonResponse.newInstance().ok(queryTasks); - } - -// @ApiOperation(value = "查找定期任务和相应的插件展示信息", notes = "") -// @RequestMapping(value = "/regular/plugin", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse> queryRegularTaskAndPlugin(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { -// log.info("查找定期任务和相应的插件展示信息:{}",params); -// List queryTasks = tallService.queryRegularTaskAndPlugin(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); -// log.info("返回定期任务和相应的插件展示信息"); -// return JsonResponse.newInstance().ok(queryTasks); -// } - - @ApiOperation(value = "分页查找定期任务", notes = "") - @RequestMapping(value = "/regular/page", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> pageQueryRegularTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { - log.info("分页查找定期任务:{}",params); - PageInfo queryTasks = tallService.pageQueryRegularTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); - log.info("返回分页查找定期任务"); - return JsonResponse.newInstance().ok(queryTasks); - } - - @ApiOperation(value = "查看用户所有的任务", notes = "") - @RequestMapping(value = "/allTask", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse> queryAllTask(HttpServletRequest request, @ApiParam @Validated @RequestBody TallTaskDto.QueryAllTask params) { - log.info("查看用户所有的任务:{}",params); - List queryTasks = tallService.queryAllTask(params); - log.info("返回用户所有的任务"); - return JsonResponse.newInstance().ok(queryTasks); - } -} +package com.ccsensptos.tallsdk.api; + +import com.ccsens.util.WebConstant; +import com.ccsens.util.bean.dto.QueryDto; +import com.ccsensptos.tallsdk.service.ITallService; +import com.ccsensptos.tallsdk.bean.dto.TallTaskDto; +import com.ccsensptos.tallsdk.bean.vo.TallTaskVo; +import com.ccsens.util.JsonResponse; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * @author 逗 + */ +@Api(tags = "任务相关" , description = "DebugController | ") +@RestController +@RequestMapping("/tall/task") +@Slf4j +public class TaskController { + + @Resource + private ITallService tallService; + + + @ApiOperation(value = "查找永久日常任务", notes = "") + @RequestMapping(value = "/permanent", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> queryPermanentGlobalTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { + log.info("查找永久日常任务:{}",params); + List queryTasks = tallService.queryPermanentGlobalTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("返回日常任务"); + return JsonResponse.newInstance().ok(queryTasks); + } + + + @ApiOperation(value = "查找带时间的日常任务", notes = "") + @RequestMapping(value = "/global", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> queryGlobalTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { + log.info("查找带时间的日常任务:{}",params); + List queryTasks = tallService.queryGlobalTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("返回带时间的日常任务"); + return JsonResponse.newInstance().ok(queryTasks); + } + + + @ApiOperation(value = "查找定期任务", notes = "") + @RequestMapping(value = "/regular", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> queryRegularTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { + log.info("查找定期任务:{}",params); + List queryTasks = tallService.queryRegularTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("返回定期任务"); + return JsonResponse.newInstance().ok(queryTasks); + } + +// @ApiOperation(value = "查找定期任务和相应的插件展示信息", notes = "") +// @RequestMapping(value = "/regular/plugin", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse> queryRegularTaskAndPlugin(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { +// log.info("查找定期任务和相应的插件展示信息:{}",params); +// List queryTasks = tallService.queryRegularTaskAndPlugin(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); +// log.info("返回定期任务和相应的插件展示信息"); +// return JsonResponse.newInstance().ok(queryTasks); +// } + + @ApiOperation(value = "分页查找定期任务", notes = "") + @RequestMapping(value = "/regular/page", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> pageQueryRegularTask(HttpServletRequest request, @ApiParam @Validated @RequestBody QueryDto params) { + log.info("分页查找定期任务:{}",params); + PageInfo queryTasks = tallService.pageQueryRegularTask(request.getHeader(WebConstant.HEADER_KEY_TOKEN),params.getParam()); + log.info("返回分页查找定期任务"); + return JsonResponse.newInstance().ok(queryTasks); + } + + @ApiOperation(value = "查看用户所有的任务", notes = "") + @RequestMapping(value = "/allTask", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) + public JsonResponse> queryAllTask(HttpServletRequest request, @ApiParam @Validated @RequestBody TallTaskDto.QueryAllTask params) { + log.info("查看用户所有的任务:{}",params); + List queryTasks = tallService.queryAllTask(params); + log.info("返回用户所有的任务"); + return JsonResponse.newInstance().ok(queryTasks); + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallPluginDto.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallPluginDto.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallPluginDto.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallPluginDto.java index 882d33b..9be8c2b 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallPluginDto.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallPluginDto.java @@ -1,29 +1,29 @@ -package com.ccsensptos.tallsdk.bean.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class TallPluginDto { - @Data - @ApiModel("通过业务code和插件名查找插件信息") - public static class BusinessPluginByName { - @ApiModelProperty("业务插件关联id") - private String code; - @ApiModelProperty("业务插件关联id") - private String pluginName; - - public BusinessPluginByName(String code, String pluginName) { - this.code = code; - this.pluginName = pluginName; - } - - public BusinessPluginByName() { - } - } - -} +package com.ccsensptos.tallsdk.bean.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class TallPluginDto { + @Data + @ApiModel("通过业务code和插件名查找插件信息") + public static class BusinessPluginByName { + @ApiModelProperty("业务插件关联id") + private String code; + @ApiModelProperty("业务插件关联id") + private String pluginName; + + public BusinessPluginByName(String code, String pluginName) { + this.code = code; + this.pluginName = pluginName; + } + + public BusinessPluginByName() { + } + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallProjectDto.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallProjectDto.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallProjectDto.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallProjectDto.java index fdf713b..6e87d3b 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallProjectDto.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallProjectDto.java @@ -1,55 +1,55 @@ -package com.ccsensptos.tallsdk.bean.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import javax.validation.constraints.NotNull; - -/** - * @author 逗 - */ -@Data -public class TallProjectDto { - - @Data - @ApiModel("根据id查找项目信息") - public static class ProjectById { - @NotNull(message = "请选择项目") - @ApiModelProperty("项目id") - private Long projectId; - private Long userId; - } - - @Data - @ApiModel("用户查询可见的项目") - public static class QueryProjectDto{ - @ApiModelProperty("开始时间") - private Long startTime; - @ApiModelProperty("结束时间") - private Long endTime; - } - - - @Data - @ApiModel("查询日历是否有项目") - public static class QueryHaveProject { - @NotNull(message = "开始时间不能为空") - @ApiModelProperty("开始时间") - private Long startTime; - @NotNull(message = "结束时间不能为空") - @ApiModelProperty("结束时间") - private Long endTime; - } - - @Data - @ApiModel("移动项目位置(修改项目层级关系)") - public static class MoveProject{ - @ApiModelProperty("需要移动的项目id") - private Long moveProjectId; - @ApiModelProperty("目标项目的id") - private Long targetProjectId; - @ApiModelProperty("业务code") - private String businessCode; - } -} +package com.ccsensptos.tallsdk.bean.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; + +/** + * @author 逗 + */ +@Data +public class TallProjectDto { + + @Data + @ApiModel("根据id查找项目信息") + public static class ProjectById { + @NotNull(message = "请选择项目") + @ApiModelProperty("项目id") + private Long projectId; + private Long userId; + } + + @Data + @ApiModel("用户查询可见的项目") + public static class QueryProjectDto{ + @ApiModelProperty("开始时间") + private Long startTime; + @ApiModelProperty("结束时间") + private Long endTime; + } + + + @Data + @ApiModel("查询日历是否有项目") + public static class QueryHaveProject { + @NotNull(message = "开始时间不能为空") + @ApiModelProperty("开始时间") + private Long startTime; + @NotNull(message = "结束时间不能为空") + @ApiModelProperty("结束时间") + private Long endTime; + } + + @Data + @ApiModel("移动项目位置(修改项目层级关系)") + public static class MoveProject{ + @ApiModelProperty("需要移动的项目id") + private Long moveProjectId; + @ApiModelProperty("目标项目的id") + private Long targetProjectId; + @ApiModelProperty("业务code") + private String businessCode; + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallRoleDto.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallRoleDto.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallRoleDto.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallRoleDto.java index 63c5484..3fec4b4 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallRoleDto.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallRoleDto.java @@ -1,20 +1,20 @@ -package com.ccsensptos.tallsdk.bean.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import javax.validation.constraints.NotNull; - -@Data -public class TallRoleDto { - @Data - @ApiModel("查看角色栏展示") - public static class QueryRoleById{ - @NotNull(message = "项目id不能为空") - @ApiModelProperty("项目id") - private Long projectId; - @ApiModelProperty("展示的角色数量") - private int num = 5; - } -} +package com.ccsensptos.tallsdk.bean.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; + +@Data +public class TallRoleDto { + @Data + @ApiModel("查看角色栏展示") + public static class QueryRoleById{ + @NotNull(message = "项目id不能为空") + @ApiModelProperty("项目id") + private Long projectId; + @ApiModelProperty("展示的角色数量") + private int num = 5; + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTaskDto.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTaskDto.java similarity index 97% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTaskDto.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTaskDto.java index 6c5b113..b619b04 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTaskDto.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTaskDto.java @@ -1,102 +1,102 @@ -package com.ccsensptos.tallsdk.bean.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import javax.validation.constraints.NotNull; -import java.util.List; - -@Data -public class TallTaskDto { - @Data - @ApiModel("查看永久日常任务") - public static class QueryPermanentGlobalTask{ - @NotNull(message = "角色id不能为空") - @ApiModelProperty("角色id") - private Long roleId; - } - - @Data - @ApiModel("查看带时间的日常任务") - public static class QueryGlobalTask{ - @NotNull(message = "角色id不能为空") - @ApiModelProperty("角色id") - private Long roleId; - @ApiModelProperty("时间基准点 默认当前") - private Long timeNode = System.currentTimeMillis(); - @ApiModelProperty("时间颗粒度单位 默认天") - private int timeUnit = 4; - } - - @Data - @ApiModel("查看定期任务") - public static class QueryRegularTask{ - @NotNull(message = "角色id不能为空") - @ApiModelProperty("角色id") - private Long roleId; - @ApiModelProperty("时间基准点 默认当前") - private Long timeNode = System.currentTimeMillis(); - @ApiModelProperty("时间颗粒度 默认天") - private int timeUnit = 4; - @ApiModelProperty("0向上查找 1向下查找(默认) 下查包含自己,上查不包含") - private int queryType = 1; - @ApiModelProperty("查找颗粒度数量 默认3个") - private int queryNum = 3; - } - - @Data - @ApiModel("分期查看定期任务") - public static class PageQueryRegularTask{ -// @NotNull(message = "角色id不能为空") - @ApiModelProperty("角色id") - private Long roleId; - @ApiModelProperty("项目id") - private Long projectId; - @ApiModelProperty("任务id") - private Long taskId; - @ApiModelProperty("时间基准点 默认当前") - private Long timeNode = System.currentTimeMillis(); - @ApiModelProperty("时间颗粒度 默认天") - private int timeUnit = 4; - @ApiModelProperty("0向上查找 1向下查找(默认) 下查包含自己,上查不包含") - private int queryType = 1; - @ApiModelProperty("第几页") - private Integer pageNum = 1; - @ApiModelProperty("每页几条信息") - private Integer pageSize = 10; - - @ApiModelProperty("任务所属的服务code") - private String businessCode; - @ApiModelProperty("触发类型 0翻页查找 1双击小红点触发") - private int triggerType = 0; - @ApiModelProperty("服务codes") - private List codes; - } - - @Data - @ApiModel("查找用户的所有任务") - public static class QueryAllTask { - @ApiModelProperty("userId") - private Long userId; - @ApiModelProperty("手机号") - private String phone; - @ApiModelProperty("服务codes") - private List codes; - @ApiModelProperty("时间基准点 默认当前") - private Long timeNode = System.currentTimeMillis(); - @ApiModelProperty("时间颗粒度 默认天") - private int timeUnit = 4; - @ApiModelProperty("0向上查找 1向下查找(默认) 下查包含自己,上查不包含") - private int queryType = 1; - @ApiModelProperty("第几页") - private Integer pageNum = 1; - @ApiModelProperty("每页几条信息") - private Integer pageSize = 10; - - @ApiModelProperty("任务id") - private String taskId; - @ApiModelProperty("任务所属的服务code") - private String businessCode; - } -} +package com.ccsensptos.tallsdk.bean.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotNull; +import java.util.List; + +@Data +public class TallTaskDto { + @Data + @ApiModel("查看永久日常任务") + public static class QueryPermanentGlobalTask{ + @NotNull(message = "角色id不能为空") + @ApiModelProperty("角色id") + private Long roleId; + } + + @Data + @ApiModel("查看带时间的日常任务") + public static class QueryGlobalTask{ + @NotNull(message = "角色id不能为空") + @ApiModelProperty("角色id") + private Long roleId; + @ApiModelProperty("时间基准点 默认当前") + private Long timeNode = System.currentTimeMillis(); + @ApiModelProperty("时间颗粒度单位 默认天") + private int timeUnit = 4; + } + + @Data + @ApiModel("查看定期任务") + public static class QueryRegularTask{ + @NotNull(message = "角色id不能为空") + @ApiModelProperty("角色id") + private Long roleId; + @ApiModelProperty("时间基准点 默认当前") + private Long timeNode = System.currentTimeMillis(); + @ApiModelProperty("时间颗粒度 默认天") + private int timeUnit = 4; + @ApiModelProperty("0向上查找 1向下查找(默认) 下查包含自己,上查不包含") + private int queryType = 1; + @ApiModelProperty("查找颗粒度数量 默认3个") + private int queryNum = 3; + } + + @Data + @ApiModel("分期查看定期任务") + public static class PageQueryRegularTask{ +// @NotNull(message = "角色id不能为空") + @ApiModelProperty("角色id") + private Long roleId; + @ApiModelProperty("项目id") + private Long projectId; + @ApiModelProperty("任务id") + private Long taskId; + @ApiModelProperty("时间基准点 默认当前") + private Long timeNode = System.currentTimeMillis(); + @ApiModelProperty("时间颗粒度 默认天") + private int timeUnit = 4; + @ApiModelProperty("0向上查找 1向下查找(默认) 下查包含自己,上查不包含") + private int queryType = 1; + @ApiModelProperty("第几页") + private Integer pageNum = 1; + @ApiModelProperty("每页几条信息") + private Integer pageSize = 10; + + @ApiModelProperty("任务所属的服务code") + private String businessCode; + @ApiModelProperty("触发类型 0翻页查找 1双击小红点触发") + private int triggerType = 0; + @ApiModelProperty("服务codes") + private List codes; + } + + @Data + @ApiModel("查找用户的所有任务") + public static class QueryAllTask { + @ApiModelProperty("userId") + private Long userId; + @ApiModelProperty("手机号") + private String phone; + @ApiModelProperty("服务codes") + private List codes; + @ApiModelProperty("时间基准点 默认当前") + private Long timeNode = System.currentTimeMillis(); + @ApiModelProperty("时间颗粒度 默认天") + private int timeUnit = 4; + @ApiModelProperty("0向上查找 1向下查找(默认) 下查包含自己,上查不包含") + private int queryType = 1; + @ApiModelProperty("第几页") + private Integer pageNum = 1; + @ApiModelProperty("每页几条信息") + private Integer pageSize = 10; + + @ApiModelProperty("任务id") + private String taskId; + @ApiModelProperty("任务所属的服务code") + private String businessCode; + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTokenDto.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTokenDto.java similarity index 95% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTokenDto.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTokenDto.java index e2bd7da..1672d5b 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTokenDto.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/dto/TallTokenDto.java @@ -1,49 +1,49 @@ -package com.ccsensptos.tallsdk.bean.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class TallTokenDto { - - - @Data - public static class GetAccessToken{ - //"appId" - private String appId; - //"secret" - private String secret; - - public GetAccessToken(String appId, String secret) { - this.appId = appId; - this.secret = secret; - } - - public GetAccessToken() { - } - } - - @Data - public static class GetUserByToken{ - //"token") - private String token; - //"appId") - private String appId; - //"secret") - private String secret; - - public GetUserByToken() { - } - - public GetUserByToken(String token, String appId, String secret) { - this.token = token; - this.appId = appId; - this.secret = secret; - } - } - -} +package com.ccsensptos.tallsdk.bean.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class TallTokenDto { + + + @Data + public static class GetAccessToken{ + //"appId" + private String appId; + //"secret" + private String secret; + + public GetAccessToken(String appId, String secret) { + this.appId = appId; + this.secret = secret; + } + + public GetAccessToken() { + } + } + + @Data + public static class GetUserByToken{ + //"token") + private String token; + //"appId") + private String appId; + //"secret") + private String secret; + + public GetUserByToken() { + } + + public GetUserByToken(String token, String appId, String secret) { + this.token = token; + this.appId = appId; + this.secret = secret; + } + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallPluginVo.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallPluginVo.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallPluginVo.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallPluginVo.java index 8433230..30d9b32 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallPluginVo.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallPluginVo.java @@ -1,25 +1,25 @@ -package com.ccsensptos.tallsdk.bean.vo; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class TallPluginVo { - - @Data - @ApiModel("查找插件信息,通过服务code和插件名") - public static class BusinessPluginInfo{ - @ApiModelProperty("插件id") - private Long pluginId; - @ApiModelProperty("业务插件关联id") - private Long businessPluginId; - @ApiModelProperty("插件在业务下的唯一code") - private String code; - @ApiModelProperty("是否是内置组件 0否 1是") - private Byte inner; - } -} +package com.ccsensptos.tallsdk.bean.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class TallPluginVo { + + @Data + @ApiModel("查找插件信息,通过服务code和插件名") + public static class BusinessPluginInfo{ + @ApiModelProperty("插件id") + private Long pluginId; + @ApiModelProperty("业务插件关联id") + private Long businessPluginId; + @ApiModelProperty("插件在业务下的唯一code") + private String code; + @ApiModelProperty("是否是内置组件 0否 1是") + private Byte inner; + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallProjectVo.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallProjectVo.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallProjectVo.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallProjectVo.java index 37d6ee9..c998852 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallProjectVo.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallProjectVo.java @@ -1,103 +1,103 @@ -package com.ccsensptos.tallsdk.bean.vo; - -import cn.hutool.core.util.ObjectUtil; -import com.ccsens.util.WebConstant; -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import java.util.List; - -/** - * @author 逗 - */ -@Data -public class TallProjectVo { - - @Data - @ApiModel("域信息") - public static class DomainInfo{ - @ApiModelProperty("id") - private Long id; - @ApiModelProperty("域名") - private String name; - @ApiModelProperty("域code") - private String code; - @ApiModelProperty("域访问前缀") - private String url; - @ApiModelProperty("是否是自身 0否 1是") - private byte self; - @ApiModelProperty("业务列表") - private List businessList; - } - @Data - @ApiModel("业务信息") - public static class BusinessInfo{ - @ApiModelProperty("业务id") - private Long businessId; - @ApiModelProperty("业务名") - private String businessName; - @ApiModelProperty("业务code") - private String businessCode; - @ApiModelProperty("业务访问前缀") - private String url; - @ApiModelProperty("项目列表") - private List projectList; - } - - @Data - @ApiModel("日历下项目列表信息") - public static class ProjectInfo{ - @ApiModelProperty("id") - private Long id; - @ApiModelProperty("项目名") - private String name; - @ApiModelProperty("开始时间") - private Long startTime; - @ApiModelProperty("结束时间") - private Long endTime; - @ApiModelProperty("项目完成状态(0-未开始,1-进行中,2-已完成,3-暂停)") - private byte status; - @ApiModelProperty("访问路径)") - private String url; - @ApiModelProperty("所属域code") - private String domainCode; - @ApiModelProperty("所属业务code") - private String businessCode; - @ApiModelProperty("子项目") - private List sonProjectList; - @JsonIgnore - @ApiModelProperty("父级id") - private Long parentId; - - public Byte getStatus() { - long current = System.currentTimeMillis(); - if(ObjectUtil.isNull(getStartTime()) || ObjectUtil.isNull(getEndTime())) { - return null; - } - if(getStartTime() > current){ - this.status = (byte) WebConstant.EVENT_PROCESS.Pending.value; - }else if(getEndTime() < current){ - this.status = (byte) WebConstant.EVENT_PROCESS.Expired.value; - }else{ - this.status = (byte) WebConstant.EVENT_PROCESS.Processing.value; - } - return this.status; - } - - public ProjectInfo() { - } - - public ProjectInfo(Long id, String name, Long startTime, Long endTime, String url, String domainCode, String businessCode) { - this.id = id; - this.name = name; - this.startTime = startTime; - this.endTime = endTime; - this.url = url; - this.domainCode = domainCode; - this.businessCode = businessCode; - } - } - -} +package com.ccsensptos.tallsdk.bean.vo; + +import cn.hutool.core.util.ObjectUtil; +import com.ccsens.util.WebConstant; +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author 逗 + */ +@Data +public class TallProjectVo { + + @Data + @ApiModel("域信息") + public static class DomainInfo{ + @ApiModelProperty("id") + private Long id; + @ApiModelProperty("域名") + private String name; + @ApiModelProperty("域code") + private String code; + @ApiModelProperty("域访问前缀") + private String url; + @ApiModelProperty("是否是自身 0否 1是") + private byte self; + @ApiModelProperty("业务列表") + private List businessList; + } + @Data + @ApiModel("业务信息") + public static class BusinessInfo{ + @ApiModelProperty("业务id") + private Long businessId; + @ApiModelProperty("业务名") + private String businessName; + @ApiModelProperty("业务code") + private String businessCode; + @ApiModelProperty("业务访问前缀") + private String url; + @ApiModelProperty("项目列表") + private List projectList; + } + + @Data + @ApiModel("日历下项目列表信息") + public static class ProjectInfo{ + @ApiModelProperty("id") + private Long id; + @ApiModelProperty("项目名") + private String name; + @ApiModelProperty("开始时间") + private Long startTime; + @ApiModelProperty("结束时间") + private Long endTime; + @ApiModelProperty("项目完成状态(0-未开始,1-进行中,2-已完成,3-暂停)") + private byte status; + @ApiModelProperty("访问路径)") + private String url; + @ApiModelProperty("所属域code") + private String domainCode; + @ApiModelProperty("所属业务code") + private String businessCode; + @ApiModelProperty("子项目") + private List sonProjectList; + @JsonIgnore + @ApiModelProperty("父级id") + private Long parentId; + + public Byte getStatus() { + long current = System.currentTimeMillis(); + if(ObjectUtil.isNull(getStartTime()) || ObjectUtil.isNull(getEndTime())) { + return null; + } + if(getStartTime() > current){ + this.status = (byte) WebConstant.EVENT_PROCESS.Pending.value; + }else if(getEndTime() < current){ + this.status = (byte) WebConstant.EVENT_PROCESS.Expired.value; + }else{ + this.status = (byte) WebConstant.EVENT_PROCESS.Processing.value; + } + return this.status; + } + + public ProjectInfo() { + } + + public ProjectInfo(Long id, String name, Long startTime, Long endTime, String url, String domainCode, String businessCode) { + this.id = id; + this.name = name; + this.startTime = startTime; + this.endTime = endTime; + this.url = url; + this.domainCode = domainCode; + this.businessCode = businessCode; + } + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallRoleVo.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallRoleVo.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallRoleVo.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallRoleVo.java index 4b1a120..d47ecfd 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallRoleVo.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallRoleVo.java @@ -1,36 +1,36 @@ -package com.ccsensptos.tallsdk.bean.vo; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import java.util.List; - -@Data -public class TallRoleVo { - - @Data - @ApiModel("查看角色栏展示的角色信息") - public static class QueryRole { - @ApiModelProperty("展示的角色信息") - private List visibleList; - @ApiModelProperty("不展示的角色信息") - private List invisibleList; - } - - @Data - @ApiModel("角色信息") - public static class RoleInfo { - @ApiModelProperty("角色id") - private Long id; - @ApiModelProperty("是否是项目经理 0否 1是") - private int pm; - @ApiModelProperty("是否是自己所属的角色 0否 1是") - private int mine; - @ApiModelProperty("角色名") - private String name; - @ApiModelProperty("排序") - private int sequence; - } - -} +package com.ccsensptos.tallsdk.bean.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +@Data +public class TallRoleVo { + + @Data + @ApiModel("查看角色栏展示的角色信息") + public static class QueryRole { + @ApiModelProperty("展示的角色信息") + private List visibleList; + @ApiModelProperty("不展示的角色信息") + private List invisibleList; + } + + @Data + @ApiModel("角色信息") + public static class RoleInfo { + @ApiModelProperty("角色id") + private Long id; + @ApiModelProperty("是否是项目经理 0否 1是") + private int pm; + @ApiModelProperty("是否是自己所属的角色 0否 1是") + private int mine; + @ApiModelProperty("角色名") + private String name; + @ApiModelProperty("排序") + private int sequence; + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTaskVo.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTaskVo.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTaskVo.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTaskVo.java index 43d8059..1634b20 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTaskVo.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTaskVo.java @@ -1,117 +1,117 @@ -package com.ccsensptos.tallsdk.bean.vo; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import java.util.List; - -/** - * @author 逗 - */ -@Data -public class TallTaskVo { - - @Data - @ApiModel("查看定期任务返回值") - public static class QueryTask{ - @ApiModelProperty("任务id(任务分解id)") - private Long id; - @ApiModelProperty("详情id") - private Long detailId; - @ApiModelProperty("任务名") - private String name; - @ApiModelProperty("任务详情") - private String description; - @ApiModelProperty("计划开始时间") - private Long planStart; - @ApiModelProperty("计划时长") - private Long planDuration; - @ApiModelProperty("计划结束时长") - private Long planEnd; - @ApiModelProperty("实际开始时间") - private Long realStart; - @ApiModelProperty("实际时长") - private Long realDuration; - @ApiModelProperty("实际结束时长") - private Long realEnd; - @ApiModelProperty("任务状态 0未开始 1进行中 2暂停中 3已完成") - private int process; - @ApiModelProperty("任务流转策略 -1不跳转 0直接跳转 如果是其他正整数 就是多少毫秒后跳转 ") - private Long skip; - @ApiModelProperty("跳转的任务id") - private Long skipTaskId; - @ApiModelProperty("任务面板") - private PanelInfo panel; - @ApiModelProperty("检查人列表") - private List checkerList; - @ApiModelProperty("插件") - private List> plugins; - - @ApiModelProperty("项目id") - private Long projectId; - @ApiModelProperty("负责人id") - private Long executorRoleId; - @ApiModelProperty("所属服务的code") - private String businessCode; - @ApiModelProperty("服务的url") - private String businessUrl; - } - @Data - @ApiModel("任务下的检查人") - public static class CheckerOfTask { - @ApiModelProperty("角色id") - private Long roleId; - @ApiModelProperty("名字") - private String name; - } - - @Data - @ApiModel("任务面板信息") - public static class PanelInfo{ - @ApiModelProperty("背景色") - private String backgroundColor; - @ApiModelProperty("圆角") - private String borderRadius; - @ApiModelProperty("边框") - private String border; - @ApiModelProperty("阴影") - private String shadow; - @ApiModelProperty("宽") - private String width; - @ApiModelProperty("高") - private String height; - @ApiModelProperty("行") - private int row; - @ApiModelProperty("列") - private int col; - } - - @Data - @ApiModel("任务下的插件信息") - public static class TaskPluginInfo{ - @ApiModelProperty("插件任务关联id") - private Long pluginTaskId; - @ApiModelProperty("插件id") - private Long pluginId; - @ApiModelProperty("插件和服务关联的id") - private Long businessPluginId; - @ApiModelProperty("插件code") - private String pluginCode; - @ApiModelProperty("是否是内置组件 0否 1是") - private Byte inner; - @ApiModelProperty("参数") - private String param; - @ApiModelProperty("行") - private int row; - @ApiModelProperty("列") - private int col; - @ApiModelProperty("跨行") - private int rowspan; - @ApiModelProperty("跨列") - private int colspan; - @ApiModelProperty("插件在时间轴的展示信息") - private String data; - } - -} +package com.ccsensptos.tallsdk.bean.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author 逗 + */ +@Data +public class TallTaskVo { + + @Data + @ApiModel("查看定期任务返回值") + public static class QueryTask{ + @ApiModelProperty("任务id(任务分解id)") + private Long id; + @ApiModelProperty("详情id") + private Long detailId; + @ApiModelProperty("任务名") + private String name; + @ApiModelProperty("任务详情") + private String description; + @ApiModelProperty("计划开始时间") + private Long planStart; + @ApiModelProperty("计划时长") + private Long planDuration; + @ApiModelProperty("计划结束时长") + private Long planEnd; + @ApiModelProperty("实际开始时间") + private Long realStart; + @ApiModelProperty("实际时长") + private Long realDuration; + @ApiModelProperty("实际结束时长") + private Long realEnd; + @ApiModelProperty("任务状态 0未开始 1进行中 2暂停中 3已完成") + private int process; + @ApiModelProperty("任务流转策略 -1不跳转 0直接跳转 如果是其他正整数 就是多少毫秒后跳转 ") + private Long skip; + @ApiModelProperty("跳转的任务id") + private Long skipTaskId; + @ApiModelProperty("任务面板") + private PanelInfo panel; + @ApiModelProperty("检查人列表") + private List checkerList; + @ApiModelProperty("插件") + private List> plugins; + + @ApiModelProperty("项目id") + private Long projectId; + @ApiModelProperty("负责人id") + private Long executorRoleId; + @ApiModelProperty("所属服务的code") + private String businessCode; + @ApiModelProperty("服务的url") + private String businessUrl; + } + @Data + @ApiModel("任务下的检查人") + public static class CheckerOfTask { + @ApiModelProperty("角色id") + private Long roleId; + @ApiModelProperty("名字") + private String name; + } + + @Data + @ApiModel("任务面板信息") + public static class PanelInfo{ + @ApiModelProperty("背景色") + private String backgroundColor; + @ApiModelProperty("圆角") + private String borderRadius; + @ApiModelProperty("边框") + private String border; + @ApiModelProperty("阴影") + private String shadow; + @ApiModelProperty("宽") + private String width; + @ApiModelProperty("高") + private String height; + @ApiModelProperty("行") + private int row; + @ApiModelProperty("列") + private int col; + } + + @Data + @ApiModel("任务下的插件信息") + public static class TaskPluginInfo{ + @ApiModelProperty("插件任务关联id") + private Long pluginTaskId; + @ApiModelProperty("插件id") + private Long pluginId; + @ApiModelProperty("插件和服务关联的id") + private Long businessPluginId; + @ApiModelProperty("插件code") + private String pluginCode; + @ApiModelProperty("是否是内置组件 0否 1是") + private Byte inner; + @ApiModelProperty("参数") + private String param; + @ApiModelProperty("行") + private int row; + @ApiModelProperty("列") + private int col; + @ApiModelProperty("跨行") + private int rowspan; + @ApiModelProperty("跨列") + private int colspan; + @ApiModelProperty("插件在时间轴的展示信息") + private String data; + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTokenVo.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTokenVo.java similarity index 95% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTokenVo.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTokenVo.java index a60f396..11f6859 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTokenVo.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallTokenVo.java @@ -1,40 +1,40 @@ -package com.ccsensptos.tallsdk.bean.vo; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class TallTokenVo { - - @Data - public static class UserIdByToken { - //"用户id" - private Long id; - //"用户名" - private String userName; - //"头像" - private String avatarUrl; - //"手机号" - private String phone; - //"用户类型 0未认证 1已认证" - private byte authType; - //"token" - private String token; - //"刷新token" - private String refreshToken; - } - - @Data - public static class AccessToken{ - //"accessToken" - private String accessToken; - //"存放时间" - private Long time; - } - -} +package com.ccsensptos.tallsdk.bean.vo; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class TallTokenVo { + + @Data + public static class UserIdByToken { + //"用户id" + private Long id; + //"用户名" + private String userName; + //"头像" + private String avatarUrl; + //"手机号" + private String phone; + //"用户类型 0未认证 1已认证" + private byte authType; + //"token" + private String token; + //"刷新token" + private String refreshToken; + } + + @Data + public static class AccessToken{ + //"accessToken" + private String accessToken; + //"存放时间" + private Long time; + } + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallWbsVo.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallWbsVo.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallWbsVo.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallWbsVo.java index c1718e3..02dd101 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallWbsVo.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/bean/vo/TallWbsVo.java @@ -1,145 +1,145 @@ -package com.ccsensptos.tallsdk.bean.vo; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import java.util.List; - -/** - * @author 逗 - */ -@Data -public class TallWbsVo { - - @Data - @ApiModel("wbs文件下载链接") - public static class WbsPath{ - @ApiModelProperty("下载链接") - private String url; - } - - /** - * 项目信息 - */ - @Data - public static class WbsProjectInfo{ - //项目id - private String projectId; - //项目名称 - private String projectName; - //描述 - private String description; - //地点 - private String address; - //开始时间(yyyy/MM/dd HH:mm) - private String startTime; - //结束时间(yyyy/MM/dd HH:mm) - private String endTime; - //版本号 - private String version; - } - - /** - * 任务信息 - */ - @Data - public static class WbsTaskInfo{ - //一级任务id - private String firstId; - //一级任务名称 - private String firstName; - //二级任务信息 - private List secondTaskList; - } - - /** - * 二级任务信息 - */ - @Data - public static class WbsSecondTask{ - //二级任务id - private String detailId; - //分解后的任务id - private String subId; - //二级任务名称 - private String taskName; - //任务描述 - private String description; - //开始时间(yyyy/MM/dd HH:mm) 如果有实际时间则以实际时间为准 - private String startTime; - //结束时间(yyyy/MM/dd HH:mm) 如果有实际时间则以实际时间为准 - private String endTime; - //任务时长 - private String duration; - //重要性标签 - private String label; - //负责人 - private String executor; - //检查人 - private String checker; - //交付物id - private String deliverId; - //交付物名称 - private String deliverName; - //绩效/即使奖惩 - private String reward; - //任务插件1关联id - private String pluginOneId; - //插件1名称 - private String pluginOneName; - //任务插件2关联id - private String pluginTwoId; - //插件2名称 - private String pluginTwoName; - //任务插件3关联id - private String pluginThreeId; - //插件3名称 - private String pluginThreeName; - } - - /** - * 角色成员表信息 - */ - @Data - public static class WbsRoleInfo{ - //项目经理 - private List pmList; - //项目成员 - private List roleList; - } - - /** - * 角色信息 - */ - @Data - public static class WbsRole{ - //角色id - private String roleId; - //角色名 - private String roleName; - //对谁不可见 - private String repulsion; - //成员信息 - private List memberList; - } - - /** - * 成员信息 - */ - @Data - public static class WbsMember{ - //成员id - private String memberId; - //成员名 - private String memberName; - //成员手机号 - private String memberPhone; - //奖惩干系人id - private String stakeholderId; - //奖惩干系人名 - private String stakeholderName; - //奖惩干系人手机号 - private String stakeholderPhone; - } -} +package com.ccsensptos.tallsdk.bean.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author 逗 + */ +@Data +public class TallWbsVo { + + @Data + @ApiModel("wbs文件下载链接") + public static class WbsPath{ + @ApiModelProperty("下载链接") + private String url; + } + + /** + * 项目信息 + */ + @Data + public static class WbsProjectInfo{ + //项目id + private String projectId; + //项目名称 + private String projectName; + //描述 + private String description; + //地点 + private String address; + //开始时间(yyyy/MM/dd HH:mm) + private String startTime; + //结束时间(yyyy/MM/dd HH:mm) + private String endTime; + //版本号 + private String version; + } + + /** + * 任务信息 + */ + @Data + public static class WbsTaskInfo{ + //一级任务id + private String firstId; + //一级任务名称 + private String firstName; + //二级任务信息 + private List secondTaskList; + } + + /** + * 二级任务信息 + */ + @Data + public static class WbsSecondTask{ + //二级任务id + private String detailId; + //分解后的任务id + private String subId; + //二级任务名称 + private String taskName; + //任务描述 + private String description; + //开始时间(yyyy/MM/dd HH:mm) 如果有实际时间则以实际时间为准 + private String startTime; + //结束时间(yyyy/MM/dd HH:mm) 如果有实际时间则以实际时间为准 + private String endTime; + //任务时长 + private String duration; + //重要性标签 + private String label; + //负责人 + private String executor; + //检查人 + private String checker; + //交付物id + private String deliverId; + //交付物名称 + private String deliverName; + //绩效/即使奖惩 + private String reward; + //任务插件1关联id + private String pluginOneId; + //插件1名称 + private String pluginOneName; + //任务插件2关联id + private String pluginTwoId; + //插件2名称 + private String pluginTwoName; + //任务插件3关联id + private String pluginThreeId; + //插件3名称 + private String pluginThreeName; + } + + /** + * 角色成员表信息 + */ + @Data + public static class WbsRoleInfo{ + //项目经理 + private List pmList; + //项目成员 + private List roleList; + } + + /** + * 角色信息 + */ + @Data + public static class WbsRole{ + //角色id + private String roleId; + //角色名 + private String roleName; + //对谁不可见 + private String repulsion; + //成员信息 + private List memberList; + } + + /** + * 成员信息 + */ + @Data + public static class WbsMember{ + //成员id + private String memberId; + //成员名 + private String memberName; + //成员手机号 + private String memberPhone; + //奖惩干系人id + private String stakeholderId; + //奖惩干系人名 + private String stakeholderName; + //奖惩干系人手机号 + private String stakeholderPhone; + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/config/BeanConfig.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/config/BeanConfig.java similarity index 100% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/config/BeanConfig.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/config/BeanConfig.java diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/config/SpringConfig.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/config/SpringConfig.java similarity index 100% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/config/SpringConfig.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/config/SpringConfig.java diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/config/SwaggerConfigure.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/config/SwaggerConfigure.java similarity index 100% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/config/SwaggerConfigure.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/config/SwaggerConfigure.java diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/intercept/MybatisInterceptor.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/intercept/MybatisInterceptor.java similarity index 100% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/intercept/MybatisInterceptor.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/intercept/MybatisInterceptor.java diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/service/ITallService.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/service/ITallService.java similarity index 96% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/service/ITallService.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/service/ITallService.java index c24621d..3fbc3cb 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/service/ITallService.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/service/ITallService.java @@ -1,111 +1,111 @@ -package com.ccsensptos.tallsdk.service; - -import com.ccsens.util.bean.dto.QueryDto; -import com.ccsensptos.tallsdk.bean.dto.TallProjectDto; -import com.ccsensptos.tallsdk.bean.dto.TallRoleDto; -import com.ccsensptos.tallsdk.bean.dto.TallTaskDto; -import com.ccsensptos.tallsdk.bean.vo.TallProjectVo; -import com.ccsensptos.tallsdk.bean.vo.TallRoleVo; -import com.ccsensptos.tallsdk.bean.vo.TallTaskVo; -import com.ccsensptos.tallsdk.bean.vo.TallWbsVo; -import com.github.pagehelper.PageInfo; -import org.springframework.web.multipart.MultipartFile; - -import java.util.List; - -/** - * @author 逗 - */ -public interface ITallService { - /** - * 查询用户可见的项目 - * @param param 开始结束时间 - * @return 返回项目列表 - */ - List queryProjectByUser(String token, TallProjectDto.QueryProjectDto param); - - /** - * 查询项目下的角色列表 - * @param param 项目id - * @return 返回角色列表 - */ - TallRoleVo.QueryRole queryShowRole(String token, TallRoleDto.QueryRoleById param); - - /** - * 查询没有时间的日常任务 - * @param param 角色id等。。。 - * @return 返回任务列表 - */ - List queryPermanentGlobalTask(String token, TallTaskDto.QueryPermanentGlobalTask param); - - /** - * 查询有时间的日常任务 - * @param param 角色id和时间 - * @return 返回任务列表 - */ - List queryGlobalTask(String token, TallTaskDto.QueryGlobalTask param); - - /** - * 查询定期任务 - * @param param 角色id和时间 - * @return 返回任务列表 - */ - List queryRegularTask(String token, TallTaskDto.QueryRegularTask param); - - /** - * 导入wbs - * @param params wbs文件 - * @return 返回项目信息 - */ - TallProjectVo.ProjectInfo importWbs(String token, MultipartFile params,Long parentId); - - /** - * 根据id查询项目信息 - */ - TallProjectVo.ProjectInfo findProjectById(String token, TallProjectDto.ProjectById params); - -// /** -// * 查询定期任务包括插件展示的信息 -// * @param token token -// * @param param 任务id信息 -// * @return 返回任务洗洗和插件展示的信息 -// */ -// List queryRegularTaskAndPlugin(String token, TallTaskDto.QueryRegularTask param); - - /** - * 分页查找定期任务 - * @param token token - * @param param 角色时间分页等信息 - * @return 任务列表 - */ - PageInfo pageQueryRegularTask(String token, TallTaskDto.PageQueryRegularTask param); - - /** - * 导出wbs - * @param token token - * @param param 项目id - * @return 返回wbs的下载路径 - */ - TallWbsVo.WbsPath exportWbs(String token, TallProjectDto.ProjectById param); - - /** - * 查找用户所有的任务 - * @param param 用户信息和查询条件 - * @return 返回任务信息 - */ - List queryAllTask(TallTaskDto.QueryAllTask param); - - /** - * 删除项目 - * @param token token - * @param params 项目id - */ - void deleteProject(String token, TallProjectDto.ProjectById params); - - /** - * 移动项目,修改项目层级关系 - * @param token token - * @param params 项目id等信息 - */ - void dragProject(String token, TallProjectDto.MoveProject params); -} +package com.ccsensptos.tallsdk.service; + +import com.ccsens.util.bean.dto.QueryDto; +import com.ccsensptos.tallsdk.bean.dto.TallProjectDto; +import com.ccsensptos.tallsdk.bean.dto.TallRoleDto; +import com.ccsensptos.tallsdk.bean.dto.TallTaskDto; +import com.ccsensptos.tallsdk.bean.vo.TallProjectVo; +import com.ccsensptos.tallsdk.bean.vo.TallRoleVo; +import com.ccsensptos.tallsdk.bean.vo.TallTaskVo; +import com.ccsensptos.tallsdk.bean.vo.TallWbsVo; +import com.github.pagehelper.PageInfo; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * @author 逗 + */ +public interface ITallService { + /** + * 查询用户可见的项目 + * @param param 开始结束时间 + * @return 返回项目列表 + */ + List queryProjectByUser(String token, TallProjectDto.QueryProjectDto param); + + /** + * 查询项目下的角色列表 + * @param param 项目id + * @return 返回角色列表 + */ + TallRoleVo.QueryRole queryShowRole(String token, TallRoleDto.QueryRoleById param); + + /** + * 查询没有时间的日常任务 + * @param param 角色id等。。。 + * @return 返回任务列表 + */ + List queryPermanentGlobalTask(String token, TallTaskDto.QueryPermanentGlobalTask param); + + /** + * 查询有时间的日常任务 + * @param param 角色id和时间 + * @return 返回任务列表 + */ + List queryGlobalTask(String token, TallTaskDto.QueryGlobalTask param); + + /** + * 查询定期任务 + * @param param 角色id和时间 + * @return 返回任务列表 + */ + List queryRegularTask(String token, TallTaskDto.QueryRegularTask param); + + /** + * 导入wbs + * @param params wbs文件 + * @return 返回项目信息 + */ + TallProjectVo.ProjectInfo importWbs(String token, MultipartFile params,Long parentId); + + /** + * 根据id查询项目信息 + */ + TallProjectVo.ProjectInfo findProjectById(String token, TallProjectDto.ProjectById params); + +// /** +// * 查询定期任务包括插件展示的信息 +// * @param token token +// * @param param 任务id信息 +// * @return 返回任务洗洗和插件展示的信息 +// */ +// List queryRegularTaskAndPlugin(String token, TallTaskDto.QueryRegularTask param); + + /** + * 分页查找定期任务 + * @param token token + * @param param 角色时间分页等信息 + * @return 任务列表 + */ + PageInfo pageQueryRegularTask(String token, TallTaskDto.PageQueryRegularTask param); + + /** + * 导出wbs + * @param token token + * @param param 项目id + * @return 返回wbs的下载路径 + */ + TallWbsVo.WbsPath exportWbs(String token, TallProjectDto.ProjectById param); + + /** + * 查找用户所有的任务 + * @param param 用户信息和查询条件 + * @return 返回任务信息 + */ + List queryAllTask(TallTaskDto.QueryAllTask param); + + /** + * 删除项目 + * @param token token + * @param params 项目id + */ + void deleteProject(String token, TallProjectDto.ProjectById params); + + /** + * 移动项目,修改项目层级关系 + * @param token token + * @param params 项目id等信息 + */ + void dragProject(String token, TallProjectDto.MoveProject params); +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/Constant.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/Constant.java similarity index 97% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/Constant.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/Constant.java index d2b59b4..4204ad4 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/Constant.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/Constant.java @@ -1,30 +1,30 @@ -package com.ccsensptos.tallsdk.util; - -/** - * @author 逗 - */ -public class Constant { - - /**域内gateway请求前缀*/ - public static final String GATEWAY_URL = "http://101.201.226.163/gateway/"; - - /**tall-查询所有任务的接口路径*/ - public static final String QUERY_ALL_TASK = "ptostall/task/allTask"; - /**tall-请求的用户信息的接口路径*/ - public static final String TALL_USER_TOKEN = "ptostall/users/businessToken"; - /**tall-获取accessToken*/ - public static final String TALL_GET_ACCESS_TOKEN = "ptostall/business/accessToken"; - /**tall-通过手机号获取userId*/ - public static final String TALL_GET_USER_ID = "ptostall/users/userIdByPhone"; - /**开放平台-获取插件信息*/ - public static final String OPEN_GET_PLUGIN = "opt/business/businessPluginByName"; - /**消息系统-发送消息*/ - public static final String MESSAGE_SEND_TO = "http://101.201.226.163:8194/message/v4.0/message/send"; - - /**请求头--accessToken*/ - public static final String ACCESS_TOKEN = "accessToken"; - - /**token过期时间 100分钟*/ - public static final Long EXPIRATION_TIME = 60 * 1000L * 100; - -} +package com.ccsensptos.tallsdk.util; + +/** + * @author 逗 + */ +public class Constant { + + /**域内gateway请求前缀*/ + public static final String GATEWAY_URL = "http://101.201.226.163/gateway/"; + + /**tall-查询所有任务的接口路径*/ + public static final String QUERY_ALL_TASK = "ptostall/task/allTask"; + /**tall-请求的用户信息的接口路径*/ + public static final String TALL_USER_TOKEN = "ptostall/users/businessToken"; + /**tall-获取accessToken*/ + public static final String TALL_GET_ACCESS_TOKEN = "ptostall/business/accessToken"; + /**tall-通过手机号获取userId*/ + public static final String TALL_GET_USER_ID = "ptostall/users/userIdByPhone"; + /**开放平台-获取插件信息*/ + public static final String OPEN_GET_PLUGIN = "opt/business/businessPluginByName"; + /**消息系统-发送消息*/ + public static final String MESSAGE_SEND_TO = "http://101.201.226.163:8194/message/v4.0/message/send"; + + /**请求头--accessToken*/ + public static final String ACCESS_TOKEN = "accessToken"; + + /**token过期时间 100分钟*/ + public static final Long EXPIRATION_TIME = 60 * 1000L * 100; + +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/MessageUtil.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/MessageUtil.java similarity index 97% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/MessageUtil.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/MessageUtil.java index b7bd9e6..a3ca7a7 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/MessageUtil.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/MessageUtil.java @@ -1,94 +1,94 @@ -package com.ccsensptos.tallsdk.util; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpUtil; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.ccsens.util.RestTemplateUtil; -import com.ccsens.util.bean.message.common.InMessage; -import com.ccsens.util.bean.message.common.MessageConstant; -import com.ccsens.util.bean.message.common.MessageRule; -import com.ccsens.util.exception.BaseException; -import com.ccsensptos.tallsdk.bean.dto.TallTokenDto; -import com.ccsensptos.tallsdk.bean.vo.TallTokenVo; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author 逗 - */ -@Component -@Slf4j -public class MessageUtil { - - public static void sendToUser(List phoneList, Set userIdSet,Object data,MessageConstant.DomainType toDomain,MessageRule rule){ - if(userIdSet == null){ - userIdSet = new HashSet<>(); - } - //通过手机号获取接收者的userId - if(CollectionUtil.isNotEmpty(phoneList)) { - String getUserIdByPhoneUrl = Constant.GATEWAY_URL + Constant.TALL_GET_USER_ID; - log.info("调用获取userId接口:{}--{}", getUserIdByPhoneUrl, phoneList); - String strBody = null; - try { - strBody = HttpUtil.post(getUserIdByPhoneUrl, JSON.toJSONString(phoneList)); - log.info("接口返回信息:{}",strBody); - } catch (Exception e) { - log.error("消息发送失败--" + e); - } - JSONObject jsonObject = JSONObject.parseObject(strBody); - if(ObjectUtil.isNotNull(jsonObject)){ - //请求正确返回则,否则无操作 - Integer code = jsonObject.getInteger("code"); - if (code == null || code != 200) { - throw new BaseException("返回参数异常"); - } - //userId - JSONArray dataArray = jsonObject.getJSONArray("data"); - if (CollectionUtil.isNotEmpty(dataArray)) { - for (Object object : dataArray) { - userIdSet.add(object.toString()); - } - } - } - } - //创建InMessage对象 - InMessage inMessage = new InMessage(); - if(ObjectUtil.isNull(toDomain)){ - toDomain = MessageConstant.DomainType.User; - } - inMessage.setToDomain(toDomain); - inMessage.setTos(userIdSet); - //如果 - if(ObjectUtil.isNull(rule)){ - switch (toDomain){ - case Server: - rule = new MessageRule((byte) 1, MessageRule.AckRule.ALWAYS, 10, (byte) 1,0L); - break; - case User: - rule = new MessageRule((byte)0, MessageRule.AckRule.ALWAYS,100,(byte)0,0L); - break; - default: - rule = new MessageRule((byte)0, MessageRule.AckRule.ALWAYS,10,(byte)1,0L); - break; - } - } - inMessage.setRule(rule); - inMessage.setData(JSONObject.toJSONString(data)); - - String url = Constant.MESSAGE_SEND_TO; - log.info("调用发送消息接口:{}--{}", url, inMessage); - try{ - RestTemplateUtil.postBody(url,inMessage); - }catch (Exception e){ - log.error("消息发送失败--" + e); - } - } -} +package com.ccsensptos.tallsdk.util; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.ccsens.util.RestTemplateUtil; +import com.ccsens.util.bean.message.common.InMessage; +import com.ccsens.util.bean.message.common.MessageConstant; +import com.ccsens.util.bean.message.common.MessageRule; +import com.ccsens.util.exception.BaseException; +import com.ccsensptos.tallsdk.bean.dto.TallTokenDto; +import com.ccsensptos.tallsdk.bean.vo.TallTokenVo; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @author 逗 + */ +@Component +@Slf4j +public class MessageUtil { + + public static void sendToUser(List phoneList, Set userIdSet,Object data,MessageConstant.DomainType toDomain,MessageRule rule){ + if(userIdSet == null){ + userIdSet = new HashSet<>(); + } + //通过手机号获取接收者的userId + if(CollectionUtil.isNotEmpty(phoneList)) { + String getUserIdByPhoneUrl = Constant.GATEWAY_URL + Constant.TALL_GET_USER_ID; + log.info("调用获取userId接口:{}--{}", getUserIdByPhoneUrl, phoneList); + String strBody = null; + try { + strBody = HttpUtil.post(getUserIdByPhoneUrl, JSON.toJSONString(phoneList)); + log.info("接口返回信息:{}",strBody); + } catch (Exception e) { + log.error("消息发送失败--" + e); + } + JSONObject jsonObject = JSONObject.parseObject(strBody); + if(ObjectUtil.isNotNull(jsonObject)){ + //请求正确返回则,否则无操作 + Integer code = jsonObject.getInteger("code"); + if (code == null || code != 200) { + throw new BaseException("返回参数异常"); + } + //userId + JSONArray dataArray = jsonObject.getJSONArray("data"); + if (CollectionUtil.isNotEmpty(dataArray)) { + for (Object object : dataArray) { + userIdSet.add(object.toString()); + } + } + } + } + //创建InMessage对象 + InMessage inMessage = new InMessage(); + if(ObjectUtil.isNull(toDomain)){ + toDomain = MessageConstant.DomainType.User; + } + inMessage.setToDomain(toDomain); + inMessage.setTos(userIdSet); + //如果 + if(ObjectUtil.isNull(rule)){ + switch (toDomain){ + case Server: + rule = new MessageRule((byte) 1, MessageRule.AckRule.ALWAYS, 10, (byte) 1,0L); + break; + case User: + rule = new MessageRule((byte)0, MessageRule.AckRule.ALWAYS,100,(byte)0,0L); + break; + default: + rule = new MessageRule((byte)0, MessageRule.AckRule.ALWAYS,10,(byte)1,0L); + break; + } + } + inMessage.setRule(rule); + inMessage.setData(JSONObject.toJSONString(data)); + + String url = Constant.MESSAGE_SEND_TO; + log.info("调用发送消息接口:{}--{}", url, inMessage); + try{ + RestTemplateUtil.postBody(url,inMessage); + }catch (Exception e){ + log.error("消息发送失败--" + e); + } + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/PluginUtil.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/PluginUtil.java similarity index 97% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/PluginUtil.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/PluginUtil.java index 2d37f05..5c45afc 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/PluginUtil.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/PluginUtil.java @@ -1,61 +1,61 @@ -package com.ccsensptos.tallsdk.util; - -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.ccsens.util.RestTemplateUtil; -import com.ccsensptos.tallsdk.bean.dto.TallPluginDto; -import com.ccsensptos.tallsdk.bean.dto.TallTokenDto; -import com.ccsensptos.tallsdk.bean.vo.TallPluginVo; -import com.ccsensptos.tallsdk.bean.vo.TallTokenVo; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -@Slf4j -public class PluginUtil { - - /** - * 通过业务code和插件名获取插件信息 - * @return 返回accessToken - */ - public static TallPluginVo.BusinessPluginInfo getPluginByCodeAndName(String businessCode,String pluginName){ - TallPluginVo.BusinessPluginInfo businessPluginInfo; - TallPluginDto.BusinessPluginByName businessPluginByName = new TallPluginDto.BusinessPluginByName(businessCode,pluginName); - - //发送请求 - String url = Constant.GATEWAY_URL + Constant.OPEN_GET_PLUGIN; - log.info("调用接口:{}--{}", url, businessPluginByName); - String postBody = null; - try{ - postBody = RestTemplateUtil.postBody(url, businessPluginByName); - }catch (Exception e){ - log.error("请求开放品台失败--" + e); - } - if(StrUtil.isBlank(postBody)){ - return null; - } - JSONObject jsonObject = JSONObject.parseObject(postBody); - log.info("接口返回:{}", jsonObject); - //请求正确返回则,否则无操作 - Integer code = jsonObject.getInteger("code"); - if (code == null || code != 200) { - return null; - } - String data = jsonObject.getString("data"); - if(ObjectUtil.isNull(data)){ - return null; - } - try { - businessPluginInfo = JSON.parseObject(data, TallPluginVo.BusinessPluginInfo.class); - }catch (Exception e){ - log.info("返回值转换失败"); - return null; - } - return businessPluginInfo; - } -} +package com.ccsensptos.tallsdk.util; + +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.ccsens.util.RestTemplateUtil; +import com.ccsensptos.tallsdk.bean.dto.TallPluginDto; +import com.ccsensptos.tallsdk.bean.dto.TallTokenDto; +import com.ccsensptos.tallsdk.bean.vo.TallPluginVo; +import com.ccsensptos.tallsdk.bean.vo.TallTokenVo; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +@Slf4j +public class PluginUtil { + + /** + * 通过业务code和插件名获取插件信息 + * @return 返回accessToken + */ + public static TallPluginVo.BusinessPluginInfo getPluginByCodeAndName(String businessCode,String pluginName){ + TallPluginVo.BusinessPluginInfo businessPluginInfo; + TallPluginDto.BusinessPluginByName businessPluginByName = new TallPluginDto.BusinessPluginByName(businessCode,pluginName); + + //发送请求 + String url = Constant.GATEWAY_URL + Constant.OPEN_GET_PLUGIN; + log.info("调用接口:{}--{}", url, businessPluginByName); + String postBody = null; + try{ + postBody = RestTemplateUtil.postBody(url, businessPluginByName); + }catch (Exception e){ + log.error("请求开放品台失败--" + e); + } + if(StrUtil.isBlank(postBody)){ + return null; + } + JSONObject jsonObject = JSONObject.parseObject(postBody); + log.info("接口返回:{}", jsonObject); + //请求正确返回则,否则无操作 + Integer code = jsonObject.getInteger("code"); + if (code == null || code != 200) { + return null; + } + String data = jsonObject.getString("data"); + if(ObjectUtil.isNull(data)){ + return null; + } + try { + businessPluginInfo = JSON.parseObject(data, TallPluginVo.BusinessPluginInfo.class); + }catch (Exception e){ + log.info("返回值转换失败"); + return null; + } + return businessPluginInfo; + } +} diff --git a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/TokenUtil.java b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/TokenUtil.java similarity index 97% rename from tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/TokenUtil.java rename to ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/TokenUtil.java index 293bb5c..ca3b882 100644 --- a/tall_sdk/src/main/java/com/ccsensptos/tallsdk/util/TokenUtil.java +++ b/ptos_sdk/src/main/java/com/ccsensptos/tallsdk/util/TokenUtil.java @@ -1,158 +1,158 @@ -package com.ccsensptos.tallsdk.util; - -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.ccsens.util.RedisUtil; -import com.ccsens.util.RestTemplateUtil; -import com.ccsensptos.tallsdk.bean.dto.TallTokenDto; -import com.ccsensptos.tallsdk.bean.vo.TallTokenVo; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.Resource; -import java.util.HashMap; -import java.util.Map; - -/** - * @author 逗 - */ -@Component -@Slf4j -public class TokenUtil { - /**缓存token或用户信息*/ - public static Map accessTokenMap = new HashMap<>(); - - public static String openRedis; - @Value("${spring.application.sdk-cache-redis:}") - public void setApplication(String redis) { - openRedis = redis; - } - - @Resource - private RedisUtil redisUtil; - private static TokenUtil util; - - @PostConstruct - public void init(){ - util = this; - util.redisUtil = this.redisUtil; - } - - - /** - * 通过AppId获取accessToken - * @return 返回accessToken - */ - public static String getAccessToken(String appId, String secret){ - //查看业务是否开启redis缓存 -// if(REDIS_IS_OPEN.equals(openRedis)){ -// //redis开启则通过appId去redis内查询 -// util.redisUtil.get(appId); -// } - - //否则查找Map内是否存在 - //如果map内存在,则判断数据的时间是否到期,到期了就删掉 - //如果redis内未查到,或map内未查到,或map内时间到期,则调用tall的接口获取accessToken - //在redis内缓存,或存在map内 - - //调用tall的接口生成accessToken - - //查找map内的数据 - long now = System.currentTimeMillis(); - TallTokenVo.AccessToken accessToken = (TallTokenVo.AccessToken) accessTokenMap.get(appId); - if(ObjectUtil.isNotNull(accessToken)){ - if(accessToken.getTime() + Constant.EXPIRATION_TIME > now){ - return accessToken.getAccessToken(); - }else { - //如果过期,就删掉数据 - accessTokenMap.remove(appId); - } - } - //map内查不到,则去请求tall获取新的accessToken -// String url = "http://127.0.0.1:7290/" + Constant.TALL_GET_ACCESS_TOKEN; - String url = Constant.GATEWAY_URL + Constant.TALL_GET_ACCESS_TOKEN; - TallTokenDto.GetAccessToken get = new TallTokenDto.GetAccessToken(appId,secret); - log.info("调用接口:{}--{}", url, get); - String postBody = null; - try{ - postBody = RestTemplateUtil.postBody(url,get); - }catch (Exception e){ - log.error("获取accessToken异常--" + e); - } - if(StrUtil.isBlank(postBody)){ - return null; - } - JSONObject jsonObject = JSONObject.parseObject(postBody); - log.info("接口返回:{}", jsonObject); - //请求正确返回则,否则无操作 - Integer code = jsonObject.getInteger("code"); - if (code == null || code != 200) { - return null; - } - String data = jsonObject.getString("data"); - if(ObjectUtil.isNull(data)){ - return null; - } - TallTokenVo.AccessToken t = new TallTokenVo.AccessToken(); - t.setAccessToken(data); - t.setTime(System.currentTimeMillis()); - accessTokenMap.put(get.getAppId(),t); - return data; - } - - /** - * 通过token获取用户信息 - * @return 返回accessToken - */ - public static TallTokenVo.UserIdByToken getUserByToken(TallTokenDto.GetUserByToken getUserByToken){ - //查看业务是否开启redis缓存 -// if(REDIS_IS_OPEN.equals(openRedis)){ -// //查询token是否存在 -// util.redisUtil.get(token); -// } - //没开启redis则去map内查找,如果 - - //调用tall的接口生成查询项目信息 - - //发送请求 - String url = Constant.GATEWAY_URL + Constant.TALL_USER_TOKEN; -// String url = "http://127.0.0.1:7290/" + Constant.TALL_USER_TOKEN; - log.info("调用接口:{}--{}", url, getUserByToken); - String postBody = null; - try{ - Map map = new HashMap<>(); - map.put(Constant.ACCESS_TOKEN,getAccessToken(getUserByToken.getAppId(),getUserByToken.getSecret())); - postBody = RestTemplateUtil.postBodySpecialHeader(url, getUserByToken,map); - }catch (Exception e){ - log.error("获取accessToken异常--" + e); - } - if(StrUtil.isBlank(postBody)){ - return null; - } - JSONObject jsonObject = JSONObject.parseObject(postBody); - log.info("接口返回:{}", jsonObject); - //请求正确返回则,否则无操作 - Integer code = jsonObject.getInteger("code"); - if (code == null || code != 200) { - return null; - } - String data = jsonObject.getString("data"); - if(ObjectUtil.isNull(data)){ - return null; - } - TallTokenVo.UserIdByToken userIdByToken; - try { - userIdByToken = JSON.parseObject(data, TallTokenVo.UserIdByToken.class); - }catch (Exception e){ - log.info("返回值转换失败"); - return null; - } - - return userIdByToken; - } - -} +package com.ccsensptos.tallsdk.util; + +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.ccsens.util.RedisUtil; +import com.ccsens.util.RestTemplateUtil; +import com.ccsensptos.tallsdk.bean.dto.TallTokenDto; +import com.ccsensptos.tallsdk.bean.vo.TallTokenVo; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; + +/** + * @author 逗 + */ +@Component +@Slf4j +public class TokenUtil { + /**缓存token或用户信息*/ + public static Map accessTokenMap = new HashMap<>(); + + public static String openRedis; + @Value("${spring.application.sdk-cache-redis:}") + public void setApplication(String redis) { + openRedis = redis; + } + + @Resource + private RedisUtil redisUtil; + private static TokenUtil util; + + @PostConstruct + public void init(){ + util = this; + util.redisUtil = this.redisUtil; + } + + + /** + * 通过AppId获取accessToken + * @return 返回accessToken + */ + public static String getAccessToken(String appId, String secret){ + //查看业务是否开启redis缓存 +// if(REDIS_IS_OPEN.equals(openRedis)){ +// //redis开启则通过appId去redis内查询 +// util.redisUtil.get(appId); +// } + + //否则查找Map内是否存在 + //如果map内存在,则判断数据的时间是否到期,到期了就删掉 + //如果redis内未查到,或map内未查到,或map内时间到期,则调用tall的接口获取accessToken + //在redis内缓存,或存在map内 + + //调用tall的接口生成accessToken + + //查找map内的数据 + long now = System.currentTimeMillis(); + TallTokenVo.AccessToken accessToken = (TallTokenVo.AccessToken) accessTokenMap.get(appId); + if(ObjectUtil.isNotNull(accessToken)){ + if(accessToken.getTime() + Constant.EXPIRATION_TIME > now){ + return accessToken.getAccessToken(); + }else { + //如果过期,就删掉数据 + accessTokenMap.remove(appId); + } + } + //map内查不到,则去请求tall获取新的accessToken +// String url = "http://127.0.0.1:7290/" + Constant.TALL_GET_ACCESS_TOKEN; + String url = Constant.GATEWAY_URL + Constant.TALL_GET_ACCESS_TOKEN; + TallTokenDto.GetAccessToken get = new TallTokenDto.GetAccessToken(appId,secret); + log.info("调用接口:{}--{}", url, get); + String postBody = null; + try{ + postBody = RestTemplateUtil.postBody(url,get); + }catch (Exception e){ + log.error("获取accessToken异常--" + e); + } + if(StrUtil.isBlank(postBody)){ + return null; + } + JSONObject jsonObject = JSONObject.parseObject(postBody); + log.info("接口返回:{}", jsonObject); + //请求正确返回则,否则无操作 + Integer code = jsonObject.getInteger("code"); + if (code == null || code != 200) { + return null; + } + String data = jsonObject.getString("data"); + if(ObjectUtil.isNull(data)){ + return null; + } + TallTokenVo.AccessToken t = new TallTokenVo.AccessToken(); + t.setAccessToken(data); + t.setTime(System.currentTimeMillis()); + accessTokenMap.put(get.getAppId(),t); + return data; + } + + /** + * 通过token获取用户信息 + * @return 返回accessToken + */ + public static TallTokenVo.UserIdByToken getUserByToken(TallTokenDto.GetUserByToken getUserByToken){ + //查看业务是否开启redis缓存 +// if(REDIS_IS_OPEN.equals(openRedis)){ +// //查询token是否存在 +// util.redisUtil.get(token); +// } + //没开启redis则去map内查找,如果 + + //调用tall的接口生成查询项目信息 + + //发送请求 + String url = Constant.GATEWAY_URL + Constant.TALL_USER_TOKEN; +// String url = "http://127.0.0.1:7290/" + Constant.TALL_USER_TOKEN; + log.info("调用接口:{}--{}", url, getUserByToken); + String postBody = null; + try{ + Map map = new HashMap<>(); + map.put(Constant.ACCESS_TOKEN,getAccessToken(getUserByToken.getAppId(),getUserByToken.getSecret())); + postBody = RestTemplateUtil.postBodySpecialHeader(url, getUserByToken,map); + }catch (Exception e){ + log.error("获取accessToken异常--" + e); + } + if(StrUtil.isBlank(postBody)){ + return null; + } + JSONObject jsonObject = JSONObject.parseObject(postBody); + log.info("接口返回:{}", jsonObject); + //请求正确返回则,否则无操作 + Integer code = jsonObject.getInteger("code"); + if (code == null || code != 200) { + return null; + } + String data = jsonObject.getString("data"); + if(ObjectUtil.isNull(data)){ + return null; + } + TallTokenVo.UserIdByToken userIdByToken; + try { + userIdByToken = JSON.parseObject(data, TallTokenVo.UserIdByToken.class); + }catch (Exception e){ + log.info("返回值转换失败"); + return null; + } + + return userIdByToken; + } + +} diff --git a/tall_sdk/src/main/resources/application-common.yml b/ptos_sdk/src/main/resources/application-common.yml similarity index 100% rename from tall_sdk/src/main/resources/application-common.yml rename to ptos_sdk/src/main/resources/application-common.yml diff --git a/tall_sdk/src/main/resources/application-dev.yml b/ptos_sdk/src/main/resources/application-dev.yml similarity index 100% rename from tall_sdk/src/main/resources/application-dev.yml rename to ptos_sdk/src/main/resources/application-dev.yml diff --git a/tall_sdk/src/main/resources/application-prod.yml b/ptos_sdk/src/main/resources/application-prod.yml similarity index 100% rename from tall_sdk/src/main/resources/application-prod.yml rename to ptos_sdk/src/main/resources/application-prod.yml diff --git a/tall_sdk/src/main/resources/application-test.yml b/ptos_sdk/src/main/resources/application-test.yml similarity index 100% rename from tall_sdk/src/main/resources/application-test.yml rename to ptos_sdk/src/main/resources/application-test.yml diff --git a/tall_sdk/src/main/resources/application.yml b/ptos_sdk/src/main/resources/application.yml similarity index 100% rename from tall_sdk/src/main/resources/application.yml rename to ptos_sdk/src/main/resources/application.yml diff --git a/tall_sdk/src/main/resources/druid-dev.yml b/ptos_sdk/src/main/resources/druid-dev.yml similarity index 100% rename from tall_sdk/src/main/resources/druid-dev.yml rename to ptos_sdk/src/main/resources/druid-dev.yml diff --git a/tall_sdk/src/main/resources/druid-prod.yml b/ptos_sdk/src/main/resources/druid-prod.yml similarity index 100% rename from tall_sdk/src/main/resources/druid-prod.yml rename to ptos_sdk/src/main/resources/druid-prod.yml diff --git a/tall_sdk/src/main/resources/druid-test.yml b/ptos_sdk/src/main/resources/druid-test.yml similarity index 100% rename from tall_sdk/src/main/resources/druid-test.yml rename to ptos_sdk/src/main/resources/druid-test.yml diff --git a/tall_sdk/src/main/resources/logback-spring.xml b/ptos_sdk/src/main/resources/logback-spring.xml similarity index 100% rename from tall_sdk/src/main/resources/logback-spring.xml rename to ptos_sdk/src/main/resources/logback-spring.xml diff --git a/ptos_tall/pom.xml b/ptos_tall/pom.xml index f754f5d..cba9d41 100644 --- a/ptos_tall/pom.xml +++ b/ptos_tall/pom.xml @@ -22,7 +22,7 @@ - cloudutil + util_cloud com.ccsensptos 1.0-SNAPSHOT @@ -34,7 +34,7 @@ - wechatutil + util_wechat com.ccsensptos 1.0-SNAPSHOT diff --git a/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/BusinessService.java b/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/BusinessService.java index 3c6adfd..b1d820a 100644 --- a/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/BusinessService.java +++ b/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/BusinessService.java @@ -1,6 +1,7 @@ package com.ccsens.ptos_tall.service; import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSONObject; @@ -36,7 +37,7 @@ public class BusinessService implements IBusinessService { //TODO 是否是正确的域(pt使用零号的appId也可以成功) //生成accessToken - Map payLoads = CollectionUtil.newHashMap(); + Map payLoads = MapUtil.newHashMap(); payLoads.put("secret", params.getSecret()); //生成过期时间 long tokenExpired = 3600 * 1000L * 2; diff --git a/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/ProjectService.java b/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/ProjectService.java index 422b4dc..6b869ce 100644 --- a/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/ProjectService.java +++ b/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/ProjectService.java @@ -3,6 +3,7 @@ package com.ccsens.ptos_tall.service; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DateUtil; +import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSONArray; @@ -147,7 +148,7 @@ public class ProjectService implements IProjectService { //根据手机号查询用户信息 SysAuth sysAuth = sysAuthDao.getByPhone(param.getPhone().get(0)); //生成token - Map theMap = CollectionUtil.newHashMap(); + Map theMap = MapUtil.newHashMap(); theMap.put("authId", String.valueOf(sysAuth.getId())); UserVo.TokenBean tokenBean = userService.generateToken(sysAuth.getUserId(), sysAuth.getId()); //查找所有在线的业务的项目 diff --git a/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/UserService.java b/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/UserService.java index fa0e5d2..a6e24c7 100644 --- a/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/UserService.java +++ b/ptos_tall/src/main/java/com/ccsens/ptos_tall/service/UserService.java @@ -3,6 +3,7 @@ package com.ccsens.ptos_tall.service; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; +import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; @@ -149,7 +150,7 @@ public class UserService implements IUserService { */ @Override public UserVo.TokenBean generateToken(Long userId, Object authId) { - Map payLoads = CollectionUtil.newHashMap(); + Map payLoads = MapUtil.newHashMap(); payLoads.put(WebConstant.PARAMETER_KEY_TOKEN_AUTH_ID, String.valueOf(authId)); UserVo.TokenBean tokenBean = new UserVo.TokenBean(); @@ -511,7 +512,7 @@ public class UserService implements IUserService { throw new BaseException(PtOsCodeError.NOT_REFRESH_TOKEN); } //重新生成token - Map payLoads = CollectionUtil.newHashMap(); + Map payLoads = MapUtil.newHashMap(); payLoads.put(WebConstant.PARAMETER_KEY_TOKEN_AUTH_ID, String.valueOf(authId)); //生成过期时间 long tokenExpired = 3600 * 1000L * 2; diff --git a/util/src/test/java/com/ccsens/util/OtherTest.java b/util/src/test/java/com/ccsens/util/OtherTest.java index 05f49dc..641bddf 100644 --- a/util/src/test/java/com/ccsens/util/OtherTest.java +++ b/util/src/test/java/com/ccsens/util/OtherTest.java @@ -2,10 +2,10 @@ package com.ccsens.util; import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.img.ImgUtil; import cn.hutool.core.lang.Filter; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.HexUtil; -import cn.hutool.core.util.ImageUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; @@ -171,9 +171,9 @@ public class OtherTest { File file1 = new File("C:\\Users\\逗\\Desktop\\1.jpg"); File file2 = new File("C:\\Users\\逗\\Desktop\\2.jpg"); System.out.println(file.length()); - ImageUtil.scale(file, file1, 0.5f); + ImgUtil.scale(file, file1, 0.5f); System.out.println(file1); - ImageUtil.scale(file1, file2, 2); + ImgUtil.scale(file1, file2, 2); } @Test diff --git a/cloudutil/pom.xml b/util_cloud/pom.xml similarity index 97% rename from cloudutil/pom.xml rename to util_cloud/pom.xml index a4b8766..e1be20f 100644 --- a/cloudutil/pom.xml +++ b/util_cloud/pom.xml @@ -9,7 +9,7 @@ 4.0.0 - cloudutil + util_cloud diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/annotation/CacheMd5.java b/util_cloud/src/main/java/com/ccsens/cloudutil/annotation/CacheMd5.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/annotation/CacheMd5.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/annotation/CacheMd5.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/annotation/Login.java b/util_cloud/src/main/java/com/ccsens/cloudutil/annotation/Login.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/annotation/Login.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/annotation/Login.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/annotation/MustLogin.java b/util_cloud/src/main/java/com/ccsens/cloudutil/annotation/MustLogin.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/annotation/MustLogin.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/annotation/MustLogin.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/aspect/CacheMd5Aspect.java b/util_cloud/src/main/java/com/ccsens/cloudutil/aspect/CacheMd5Aspect.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/aspect/CacheMd5Aspect.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/aspect/CacheMd5Aspect.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/aspect/LogAspect.java b/util_cloud/src/main/java/com/ccsens/cloudutil/aspect/LogAspect.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/aspect/LogAspect.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/aspect/LogAspect.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/aspect/MustLoginAspect.java b/util_cloud/src/main/java/com/ccsens/cloudutil/aspect/MustLoginAspect.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/aspect/MustLoginAspect.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/aspect/MustLoginAspect.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/bean/QueryParam.java b/util_cloud/src/main/java/com/ccsens/cloudutil/bean/QueryParam.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/bean/QueryParam.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/bean/QueryParam.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignProjectDto.java b/util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignProjectDto.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignProjectDto.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignProjectDto.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignUserDto.java b/util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignUserDto.java similarity index 96% rename from cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignUserDto.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignUserDto.java index 43be217..0b2c742 100644 --- a/cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignUserDto.java +++ b/util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/dto/FeignUserDto.java @@ -1,34 +1,34 @@ -package com.ccsens.cloudutil.bean.ptos.dto; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class FeignUserDto { - @Data - @ApiModel("通过token获取用户信息") - public static class UserInfoByToken{ - @ApiModelProperty("token") - private String token; - @ApiModelProperty("设备id") - private String deviceId; - @ApiModelProperty("ip地址") - private String clientIp; - @ApiModelProperty("客户端类型 0-H5 1-App") - private Byte clientType; - - public UserInfoByToken() { - } - - public UserInfoByToken(String token, String deviceId, String clientIp, Byte clientType) { - this.token = token; - this.deviceId = deviceId; - this.clientIp = clientIp; - this.clientType = clientType; - } - } -} +package com.ccsens.cloudutil.bean.ptos.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class FeignUserDto { + @Data + @ApiModel("通过token获取用户信息") + public static class UserInfoByToken{ + @ApiModelProperty("token") + private String token; + @ApiModelProperty("设备id") + private String deviceId; + @ApiModelProperty("ip地址") + private String clientIp; + @ApiModelProperty("客户端类型 0-H5 1-App") + private Byte clientType; + + public UserInfoByToken() { + } + + public UserInfoByToken(String token, String deviceId, String clientIp, Byte clientType) { + this.token = token; + this.deviceId = deviceId; + this.clientIp = clientIp; + this.clientType = clientType; + } + } +} diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignProjectVo.java b/util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignProjectVo.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignProjectVo.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignProjectVo.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignUserVo.java b/util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignUserVo.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignUserVo.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/bean/ptos/vo/FeignUserVo.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/config/FeignTokenConfig.java b/util_cloud/src/main/java/com/ccsens/cloudutil/config/FeignTokenConfig.java similarity index 97% rename from cloudutil/src/main/java/com/ccsens/cloudutil/config/FeignTokenConfig.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/config/FeignTokenConfig.java index 6590f50..84e7b8f 100644 --- a/cloudutil/src/main/java/com/ccsens/cloudutil/config/FeignTokenConfig.java +++ b/util_cloud/src/main/java/com/ccsens/cloudutil/config/FeignTokenConfig.java @@ -1,45 +1,45 @@ -package com.ccsens.cloudutil.config; - -import cn.hutool.json.JSONObject; -import cn.hutool.json.JSONUtil; -import feign.RequestInterceptor; -import feign.RequestTemplate; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpHeaders; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; - - -/** - * @author 逗 - */ -@Configuration -public class FeignTokenConfig implements RequestInterceptor { - @Override - public void apply(RequestTemplate template) { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - System.out.println("attributes:"+attributes); - if (attributes != null) { - HttpServletRequest request = attributes.getRequest(); - System.out.println("token:" + request.getHeader(HttpHeaders.AUTHORIZATION)); - //添加token - template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION)); - return; - } - - byte[] body = template.body(); - if (body == null) { - return; - } - String json = new String(body); - JSONObject jsonObject = JSONUtil.parseObj(json); - - //添加token - template.header("Authorization", jsonObject.getStr("token")); - - - } -} +package com.ccsens.cloudutil.config; + +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import feign.RequestInterceptor; +import feign.RequestTemplate; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + + +/** + * @author 逗 + */ +@Configuration +public class FeignTokenConfig implements RequestInterceptor { + @Override + public void apply(RequestTemplate template) { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + System.out.println("attributes:"+attributes); + if (attributes != null) { + HttpServletRequest request = attributes.getRequest(); + System.out.println("token:" + request.getHeader(HttpHeaders.AUTHORIZATION)); + //添加token + template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION)); + return; + } + + byte[] body = template.body(); + if (body == null) { + return; + } + String json = new String(body); + JSONObject jsonObject = JSONUtil.parseObj(json); + + //添加token + template.header("Authorization", jsonObject.getStr("token")); + + + } +} diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/feign/DiplomatistFeignClient.java b/util_cloud/src/main/java/com/ccsens/cloudutil/feign/DiplomatistFeignClient.java similarity index 97% rename from cloudutil/src/main/java/com/ccsens/cloudutil/feign/DiplomatistFeignClient.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/feign/DiplomatistFeignClient.java index 568fc66..90419cc 100644 --- a/cloudutil/src/main/java/com/ccsens/cloudutil/feign/DiplomatistFeignClient.java +++ b/util_cloud/src/main/java/com/ccsens/cloudutil/feign/DiplomatistFeignClient.java @@ -1,44 +1,44 @@ -package com.ccsens.cloudutil.feign; - - -import com.ccsens.cloudutil.bean.ptos.dto.FeignProjectDto; -import com.ccsens.cloudutil.bean.ptos.vo.FeignProjectVo; -import com.ccsens.cloudutil.config.FeignTokenConfig; -import com.ccsens.util.JsonResponse; -import feign.hystrix.FallbackFactory; -import lombok.extern.slf4j.Slf4j; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.GetMapping; - -import java.util.List; - -/** - * @author 逗 - */ -@FeignClient(name = "diplomatist", path = "",fallbackFactory = DiplomatistFeignClientFallBack.class,configuration = FeignTokenConfig.class) -public interface DiplomatistFeignClient { - /** - * 查询用户关联的其他域的项目信息 - */ - @GetMapping("domain/ptDomainProject") - JsonResponse> queryDomainProject(FeignProjectDto.QueryProjectByPhone params); - -} - -@Slf4j -@Component -class DiplomatistFeignClientFallBack implements FallbackFactory { - - @Override - public DiplomatistFeignClient create(Throwable cause) { - log.error("访问传达室异常", cause); - return new DiplomatistFeignClient() { - @Override - public JsonResponse> queryDomainProject(FeignProjectDto.QueryProjectByPhone params) { - return null; - } - - }; - } +package com.ccsens.cloudutil.feign; + + +import com.ccsens.cloudutil.bean.ptos.dto.FeignProjectDto; +import com.ccsens.cloudutil.bean.ptos.vo.FeignProjectVo; +import com.ccsens.cloudutil.config.FeignTokenConfig; +import com.ccsens.util.JsonResponse; +import feign.hystrix.FallbackFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; + +import java.util.List; + +/** + * @author 逗 + */ +@FeignClient(name = "diplomatist", path = "",fallbackFactory = DiplomatistFeignClientFallBack.class,configuration = FeignTokenConfig.class) +public interface DiplomatistFeignClient { + /** + * 查询用户关联的其他域的项目信息 + */ + @GetMapping("domain/ptDomainProject") + JsonResponse> queryDomainProject(FeignProjectDto.QueryProjectByPhone params); + +} + +@Slf4j +@Component +class DiplomatistFeignClientFallBack implements FallbackFactory { + + @Override + public DiplomatistFeignClient create(Throwable cause) { + log.error("访问传达室异常", cause); + return new DiplomatistFeignClient() { + @Override + public JsonResponse> queryDomainProject(FeignProjectDto.QueryProjectByPhone params) { + return null; + } + + }; + } } \ No newline at end of file diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/feign/PtosTallFeignClient.java b/util_cloud/src/main/java/com/ccsens/cloudutil/feign/PtosTallFeignClient.java similarity index 97% rename from cloudutil/src/main/java/com/ccsens/cloudutil/feign/PtosTallFeignClient.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/feign/PtosTallFeignClient.java index a2079ce..eddf36d 100644 --- a/cloudutil/src/main/java/com/ccsens/cloudutil/feign/PtosTallFeignClient.java +++ b/util_cloud/src/main/java/com/ccsens/cloudutil/feign/PtosTallFeignClient.java @@ -1,60 +1,60 @@ -package com.ccsens.cloudutil.feign; - - -import com.ccsens.cloudutil.bean.ptos.dto.FeignProjectDto; -import com.ccsens.cloudutil.bean.ptos.dto.FeignUserDto; -import com.ccsens.cloudutil.bean.ptos.vo.FeignProjectVo; -import com.ccsens.cloudutil.bean.ptos.vo.FeignUserVo; -import com.ccsens.cloudutil.config.FeignTokenConfig; -import com.ccsens.util.JsonResponse; -import feign.hystrix.FallbackFactory; -import lombok.extern.slf4j.Slf4j; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -import java.util.List; - -/** - * @author 逗 - */ -@FeignClient(name = "ptostall", path = "",fallbackFactory = PtosTallFeignClientFallBack.class,configuration = FeignTokenConfig.class) -public interface PtosTallFeignClient { - - /** - * 根据token获取userId - */ - @PostMapping("users/token") - JsonResponse getUserIdByToken(FeignUserDto.UserInfoByToken params); - - /** - * 根据手机号获取用户在本域的业务项目列表 - */ - @PostMapping("project/byPhone") - JsonResponse> queryProjectByPhone(FeignProjectDto.QueryProjectByPhone params); - -} - -@Slf4j -@Component -class PtosTallFeignClientFallBack implements FallbackFactory { - - @Override - public PtosTallFeignClient create(Throwable cause) { - log.error("访问ptosTall异常", cause); - return new PtosTallFeignClient() { - @Override - public JsonResponse getUserIdByToken(FeignUserDto.UserInfoByToken params) { - return null; - } - - @Override - public JsonResponse> queryProjectByPhone(FeignProjectDto.QueryProjectByPhone params) { - return null; - } - - }; - } +package com.ccsens.cloudutil.feign; + + +import com.ccsens.cloudutil.bean.ptos.dto.FeignProjectDto; +import com.ccsens.cloudutil.bean.ptos.dto.FeignUserDto; +import com.ccsens.cloudutil.bean.ptos.vo.FeignProjectVo; +import com.ccsens.cloudutil.bean.ptos.vo.FeignUserVo; +import com.ccsens.cloudutil.config.FeignTokenConfig; +import com.ccsens.util.JsonResponse; +import feign.hystrix.FallbackFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.List; + +/** + * @author 逗 + */ +@FeignClient(name = "ptostall", path = "",fallbackFactory = PtosTallFeignClientFallBack.class,configuration = FeignTokenConfig.class) +public interface PtosTallFeignClient { + + /** + * 根据token获取userId + */ + @PostMapping("users/token") + JsonResponse getUserIdByToken(FeignUserDto.UserInfoByToken params); + + /** + * 根据手机号获取用户在本域的业务项目列表 + */ + @PostMapping("project/byPhone") + JsonResponse> queryProjectByPhone(FeignProjectDto.QueryProjectByPhone params); + +} + +@Slf4j +@Component +class PtosTallFeignClientFallBack implements FallbackFactory { + + @Override + public PtosTallFeignClient create(Throwable cause) { + log.error("访问ptosTall异常", cause); + return new PtosTallFeignClient() { + @Override + public JsonResponse getUserIdByToken(FeignUserDto.UserInfoByToken params) { + return null; + } + + @Override + public JsonResponse> queryProjectByPhone(FeignProjectDto.QueryProjectByPhone params) { + return null; + } + + }; + } } \ No newline at end of file diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/interceptor/LogInterceptor.java b/util_cloud/src/main/java/com/ccsens/cloudutil/interceptor/LogInterceptor.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/interceptor/LogInterceptor.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/interceptor/LogInterceptor.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/RibbonClientConfig.java b/util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/RibbonClientConfig.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/RibbonClientConfig.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/RibbonClientConfig.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/RibbonConfiguration.java b/util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/RibbonConfiguration.java similarity index 100% rename from cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/RibbonConfiguration.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/RibbonConfiguration.java diff --git a/cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/WpsBalanceRule.java b/util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/WpsBalanceRule.java similarity index 96% rename from cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/WpsBalanceRule.java rename to util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/WpsBalanceRule.java index 569c13b..f53b21c 100644 --- a/cloudutil/src/main/java/com/ccsens/cloudutil/ribbon/WpsBalanceRule.java +++ b/util_cloud/src/main/java/com/ccsens/cloudutil/ribbon/WpsBalanceRule.java @@ -1,28 +1,28 @@ -//package com.ccsens.cloudutil.ribbon; -// -//import com.netflix.client.config.IClientConfig; -//import com.netflix.loadbalancer.AbstractLoadBalancerRule; -//import com.netflix.loadbalancer.ILoadBalancer; -//import com.netflix.loadbalancer.Server; -//import org.springframework.context.annotation.Primary; -// -////@Primary -//public class WpsBalanceRule extends AbstractLoadBalancerRule { -// -// @Override -// public void initWithNiwsConfig(IClientConfig clientConfig) { -// -// } -// -// @Override -// public Server choose(Object key) { -// return choose(getLoadBalancer(), key); -// } -// -// private Server choose(ILoadBalancer loadBalancer, Object key) { -// System.out.println(key); -// return null; -// } -// -// -//} +//package com.ccsens.cloudutil.ribbon; +// +//import com.netflix.client.config.IClientConfig; +//import com.netflix.loadbalancer.AbstractLoadBalancerRule; +//import com.netflix.loadbalancer.ILoadBalancer; +//import com.netflix.loadbalancer.Server; +//import org.springframework.context.annotation.Primary; +// +////@Primary +//public class WpsBalanceRule extends AbstractLoadBalancerRule { +// +// @Override +// public void initWithNiwsConfig(IClientConfig clientConfig) { +// +// } +// +// @Override +// public Server choose(Object key) { +// return choose(getLoadBalancer(), key); +// } +// +// private Server choose(ILoadBalancer loadBalancer, Object key) { +// System.out.println(key); +// return null; +// } +// +// +//} diff --git a/cloudutil/src/main/resources/application-util-dev.yml b/util_cloud/src/main/resources/application-util-dev.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-dev.yml rename to util_cloud/src/main/resources/application-util-dev.yml diff --git a/cloudutil/src/main/resources/application-util-green.yml b/util_cloud/src/main/resources/application-util-green.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-green.yml rename to util_cloud/src/main/resources/application-util-green.yml diff --git a/cloudutil/src/main/resources/application-util-greenvalley.yml b/util_cloud/src/main/resources/application-util-greenvalley.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-greenvalley.yml rename to util_cloud/src/main/resources/application-util-greenvalley.yml diff --git a/cloudutil/src/main/resources/application-util-pre.yml b/util_cloud/src/main/resources/application-util-pre.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-pre.yml rename to util_cloud/src/main/resources/application-util-pre.yml diff --git a/cloudutil/src/main/resources/application-util-prod.yml b/util_cloud/src/main/resources/application-util-prod.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-prod.yml rename to util_cloud/src/main/resources/application-util-prod.yml diff --git a/cloudutil/src/main/resources/application-util-prodsd.yml b/util_cloud/src/main/resources/application-util-prodsd.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-prodsd.yml rename to util_cloud/src/main/resources/application-util-prodsd.yml diff --git a/cloudutil/src/main/resources/application-util-test.yml b/util_cloud/src/main/resources/application-util-test.yml similarity index 100% rename from cloudutil/src/main/resources/application-util-test.yml rename to util_cloud/src/main/resources/application-util-test.yml diff --git a/wechatutil/.gitignore b/util_wechat/.gitignore similarity index 100% rename from wechatutil/.gitignore rename to util_wechat/.gitignore diff --git a/wechatutil/mvnw b/util_wechat/mvnw similarity index 100% rename from wechatutil/mvnw rename to util_wechat/mvnw diff --git a/wechatutil/mvnw.cmd b/util_wechat/mvnw.cmd similarity index 100% rename from wechatutil/mvnw.cmd rename to util_wechat/mvnw.cmd diff --git a/wechatutil/pom.xml b/util_wechat/pom.xml similarity index 98% rename from wechatutil/pom.xml rename to util_wechat/pom.xml index ffc039f..44f8b29 100644 --- a/wechatutil/pom.xml +++ b/util_wechat/pom.xml @@ -9,7 +9,7 @@ 4.0.0 - wechatutil + util_wechat 1.8 diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/WechatutilApplication.java b/util_wechat/src/main/java/com/ccsens/wechatutil/WechatutilApplication.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/WechatutilApplication.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/WechatutilApplication.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/api/DebugController.java b/util_wechat/src/main/java/com/ccsens/wechatutil/api/DebugController.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/api/DebugController.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/api/DebugController.java index 3ca4eb2..79ed8ab 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/api/DebugController.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/api/DebugController.java @@ -1,68 +1,68 @@ -//package com.ccsens.wechatutil.api; -// -//import cn.hutool.core.date.DateUtil; -//import com.ccsens.util.JsonResponse; -//import com.ccsens.util.PropUtil; -//import com.ccsens.util.WebConstant; -//import com.ccsens.util.wx.WxXcxUtil; -//import com.ccsens.wechatutil.bean.dto.WechatCode; -//import com.ccsens.wechatutil.wxmini.MiniCodeUtil; -//import com.ccsens.wechatutil.wxofficial.OfficialAccountMessageUtil; -//import io.swagger.annotations.Api; -//import io.swagger.annotations.ApiImplicitParams; -//import io.swagger.annotations.ApiOperation; -//import lombok.extern.slf4j.Slf4j; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.RequestMethod; -//import org.springframework.web.bind.annotation.RestController; -// -//import javax.servlet.http.HttpServletRequest; -// -//@Api(tags = "DEBUG" , description = "DebugController | ") -//@RestController -//@RequestMapping("/debug") -//@Slf4j -//public class DebugController { -// -// -// -// @ApiOperation(value = "/测试",notes = "") -// @ApiImplicitParams({ -// }) -// @RequestMapping(value="",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) -// public JsonResponse debug(HttpServletRequest request) throws Exception { -// -// return JsonResponse.newInstance().ok("测试"); -// } -// -// @ApiOperation(value = "/测试",notes = "") -// @ApiImplicitParams({ -// }) -// @RequestMapping(value="code",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) -// public JsonResponse debugWxCode(HttpServletRequest request) throws Exception { -// //生成二维码 -// String fileName = "/gameQrCode/" + DateUtil.today() + "/" + System.currentTimeMillis() + ".png"; -// String path = WebConstant.UPLOAD_PATH_BASE + fileName; -// -// WechatCode.WechatCodeB wechatCodeB = new WechatCode.WechatCodeB(); -// wechatCodeB.setPage(WebConstant.QRCODE_GAME); -// wechatCodeB.setScene("id=1&type=SQ"); -// MiniCodeUtil.getWxCodeB(wechatCodeB, path); -//// WxXcxUtil.getWxCodeC(WebConstant.QRCODE_GAME+"?id=" + gameRecord.getId() + "&type=" + gameType.getCode(), path, gameType.getCode()); -// -//// gameRecord.setQrCodeUrl(PropUtil.qrCode + fileName); -// log.info("调用微信生成二维码"); -// return JsonResponse.newInstance().ok("测试"); -// } -// -// @ApiOperation(value = "/测试公众号消息",notes = "") -// @ApiImplicitParams({ -// }) -// @RequestMapping(value="message",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) -// public JsonResponse debugWxMessage(HttpServletRequest request) throws Exception { -//// OfficialAccountMessageUtil.officialMessage(); -// log.info("发送公众号消息"); -// return JsonResponse.newInstance().ok("测试"); -// } -// -//} +//package com.ccsens.wechatutil.api; +// +//import cn.hutool.core.date.DateUtil; +//import com.ccsens.util.JsonResponse; +//import com.ccsens.util.PropUtil; +//import com.ccsens.util.WebConstant; +//import com.ccsens.util.wx.WxXcxUtil; +//import com.ccsens.wechatutil.bean.dto.WechatCode; +//import com.ccsens.wechatutil.wxmini.MiniCodeUtil; +//import com.ccsens.wechatutil.wxofficial.OfficialAccountMessageUtil; +//import io.swagger.annotations.Api; +//import io.swagger.annotations.ApiImplicitParams; +//import io.swagger.annotations.ApiOperation; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RequestMethod; +//import org.springframework.web.bind.annotation.RestController; +// +//import javax.servlet.http.HttpServletRequest; +// +//@Api(tags = "DEBUG" , description = "DebugController | ") +//@RestController +//@RequestMapping("/debug") +//@Slf4j +//public class DebugController { +// +// +// +// @ApiOperation(value = "/测试",notes = "") +// @ApiImplicitParams({ +// }) +// @RequestMapping(value="",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) +// public JsonResponse debug(HttpServletRequest request) throws Exception { +// +// return JsonResponse.newInstance().ok("测试"); +// } +// +// @ApiOperation(value = "/测试",notes = "") +// @ApiImplicitParams({ +// }) +// @RequestMapping(value="code",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) +// public JsonResponse debugWxCode(HttpServletRequest request) throws Exception { +// //生成二维码 +// String fileName = "/gameQrCode/" + DateUtil.today() + "/" + System.currentTimeMillis() + ".png"; +// String path = WebConstant.UPLOAD_PATH_BASE + fileName; +// +// WechatCode.WechatCodeB wechatCodeB = new WechatCode.WechatCodeB(); +// wechatCodeB.setPage(WebConstant.QRCODE_GAME); +// wechatCodeB.setScene("id=1&type=SQ"); +// MiniCodeUtil.getWxCodeB(wechatCodeB, path); +//// WxXcxUtil.getWxCodeC(WebConstant.QRCODE_GAME+"?id=" + gameRecord.getId() + "&type=" + gameType.getCode(), path, gameType.getCode()); +// +//// gameRecord.setQrCodeUrl(PropUtil.qrCode + fileName); +// log.info("调用微信生成二维码"); +// return JsonResponse.newInstance().ok("测试"); +// } +// +// @ApiOperation(value = "/测试公众号消息",notes = "") +// @ApiImplicitParams({ +// }) +// @RequestMapping(value="message",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) +// public JsonResponse debugWxMessage(HttpServletRequest request) throws Exception { +//// OfficialAccountMessageUtil.officialMessage(); +// log.info("发送公众号消息"); +// return JsonResponse.newInstance().ok("测试"); +// } +// +//} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java b/util_wechat/src/main/java/com/ccsens/wechatutil/api/WxController.java similarity index 98% rename from wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/api/WxController.java index 9960a76..32c68ae 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/api/WxController.java @@ -1,80 +1,80 @@ -//package com.ccsens.wechatutil.api; -// -//import com.ccsens.util.JsonResponse; -//import com.ccsens.wechatutil.bean.dto.WxMessageDto; -//import com.ccsens.wechatutil.service.IWxMessageService; -//import com.ccsens.wechatutil.service.IWxService; -//import com.ccsens.wechatutil.bean.po.MiniProgramUser; -//import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; -//import com.ccsens.wechatutil.bean.dto.WechatCode; -//import io.swagger.annotations.Api; -//import io.swagger.annotations.ApiOperation; -//import io.swagger.annotations.ApiParam; -//import lombok.extern.slf4j.Slf4j; -//import org.springframework.validation.annotation.Validated; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.RequestMethod; -//import org.springframework.web.bind.annotation.RestController; -// -//import javax.annotation.Resource; -// -///** -// * @author 逗 -// */ -//@Api(tags = "DEBUG" , description = "DebugController | ") -//@RestController -//@RequestMapping("/wx") -//@Slf4j -//public class WxController { -// -// @Resource -// private IWxService miniProgramService; -// @Resource -// private IWxMessageService wxMessageService; -// -// @ApiOperation(value = "小程序根据code获取appId", notes = "小程序") -// @RequestMapping(value = "/signinByMini", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse signinByMini(@ApiParam @Validated String code) throws Exception{ -// MiniProgramUser wxUser = miniProgramService.signinByMini(code); -// return JsonResponse.newInstance().ok(); -// } -// -// @ApiOperation(value = "公众号/网页二维码登录", notes = "公众号/网页二维码") -// @RequestMapping(value = "/signinByH5", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse signinByH5(@ApiParam @Validated String code) throws Exception{ -// WxOauth2UserInfo wxUser = miniProgramService.signinByH5(code); -// return JsonResponse.newInstance().ok(); -// } -// -// @ApiOperation(value = "生成小程序码-方案A", notes = "") -// @RequestMapping(value = "/getWxCodeA", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse getWxCodeA(@ApiParam @Validated WechatCode.WechatCodeA wechatCodeA, String path) throws Exception{ -// miniProgramService.getWxCodeA(wechatCodeA, path); -// return JsonResponse.newInstance().ok(); -// } -// -// -// @ApiOperation(value = "生成小程序码-方案B", notes = "") -// @RequestMapping(value = "/getWxCodeB", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse getWxCodeB(@ApiParam @Validated WechatCode.WechatCodeB wechatCodeB,String path) throws Exception{ -// wechatCodeB = new WechatCode.WechatCodeB(); -// wechatCodeB.setScene("id=1&type=SQ"); -// wechatCodeB.setPage("pages/index/index"); -// miniProgramService.getWxCodeB(wechatCodeB,path); -// return JsonResponse.newInstance().ok(); -// } -// -// @ApiOperation(value = "生成小程序码-方案B", notes = "") -// @RequestMapping(value = "/getWxCodeC", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse getWxCodeC(@ApiParam @Validated WechatCode.WechatCodeC wechatCodeC,String path) throws Exception{ -// miniProgramService.getWxCodeC(wechatCodeC,path); -// return JsonResponse.newInstance().ok(); -// } -// -// @ApiOperation(value = "群机器人发送消息", notes = "") -// @RequestMapping(value = "/robotMessage", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) -// public JsonResponse robotMessage(@ApiParam @Validated WxMessageDto.RobotMessage robotMessage) throws Exception{ -// wxMessageService.sendRobotInfo(robotMessage); -// return JsonResponse.newInstance().ok(); -// } -//} +//package com.ccsens.wechatutil.api; +// +//import com.ccsens.util.JsonResponse; +//import com.ccsens.wechatutil.bean.dto.WxMessageDto; +//import com.ccsens.wechatutil.service.IWxMessageService; +//import com.ccsens.wechatutil.service.IWxService; +//import com.ccsens.wechatutil.bean.po.MiniProgramUser; +//import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; +//import com.ccsens.wechatutil.bean.dto.WechatCode; +//import io.swagger.annotations.Api; +//import io.swagger.annotations.ApiOperation; +//import io.swagger.annotations.ApiParam; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.validation.annotation.Validated; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RequestMethod; +//import org.springframework.web.bind.annotation.RestController; +// +//import javax.annotation.Resource; +// +///** +// * @author 逗 +// */ +//@Api(tags = "DEBUG" , description = "DebugController | ") +//@RestController +//@RequestMapping("/wx") +//@Slf4j +//public class WxController { +// +// @Resource +// private IWxService miniProgramService; +// @Resource +// private IWxMessageService wxMessageService; +// +// @ApiOperation(value = "小程序根据code获取appId", notes = "小程序") +// @RequestMapping(value = "/signinByMini", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse signinByMini(@ApiParam @Validated String code) throws Exception{ +// MiniProgramUser wxUser = miniProgramService.signinByMini(code); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "公众号/网页二维码登录", notes = "公众号/网页二维码") +// @RequestMapping(value = "/signinByH5", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse signinByH5(@ApiParam @Validated String code) throws Exception{ +// WxOauth2UserInfo wxUser = miniProgramService.signinByH5(code); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "生成小程序码-方案A", notes = "") +// @RequestMapping(value = "/getWxCodeA", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse getWxCodeA(@ApiParam @Validated WechatCode.WechatCodeA wechatCodeA, String path) throws Exception{ +// miniProgramService.getWxCodeA(wechatCodeA, path); +// return JsonResponse.newInstance().ok(); +// } +// +// +// @ApiOperation(value = "生成小程序码-方案B", notes = "") +// @RequestMapping(value = "/getWxCodeB", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse getWxCodeB(@ApiParam @Validated WechatCode.WechatCodeB wechatCodeB,String path) throws Exception{ +// wechatCodeB = new WechatCode.WechatCodeB(); +// wechatCodeB.setScene("id=1&type=SQ"); +// wechatCodeB.setPage("pages/index/index"); +// miniProgramService.getWxCodeB(wechatCodeB,path); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "生成小程序码-方案B", notes = "") +// @RequestMapping(value = "/getWxCodeC", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse getWxCodeC(@ApiParam @Validated WechatCode.WechatCodeC wechatCodeC,String path) throws Exception{ +// miniProgramService.getWxCodeC(wechatCodeC,path); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "群机器人发送消息", notes = "") +// @RequestMapping(value = "/robotMessage", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse robotMessage(@ApiParam @Validated WxMessageDto.RobotMessage robotMessage) throws Exception{ +// wxMessageService.sendRobotInfo(robotMessage); +// return JsonResponse.newInstance().ok(); +// } +//} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WechatCode.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WechatCode.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WechatCode.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WechatCode.java index 37ce38b..effed26 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WechatCode.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WechatCode.java @@ -1,67 +1,67 @@ -package com.ccsens.wechatutil.bean.dto; - -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class WechatCode { - /** - * 获取小程序码--方案A - */ - @Data - public static class WechatCodeA{ - // 扫码进入的小程序页面路径,最大长度 128 字节,不能为空; - public String path; - //二维码的宽度,单位 px,最小 280px,最大 1280px 默认430 - public Integer width; - //默认false 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false - public Boolean auto_color; - //auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示 - public LineColor line_color; - //默认false 是否需要透明底色,为 true 时,生成透明底色的小程序 - public Boolean is_hyaline; - } - - /** - * 获取小程序码--方案B - */ - @Data - public static class WechatCodeB{ - //参数 --最大32个可见字符 - public String scene; - //小程序地址 - public String page; - //二维码的宽度,单位 px,最小 280px,最大 1280px 默认430 - public Integer width; - //默认false 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false - public Boolean auto_color; - //auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示 - public LineColor line_color; - //默认false 是否需要透明底色,为 true 时,生成透明底色的小程序 - public Boolean is_hyaline; - } - - /** - * rgb颜色 - */ - @Data - public static class LineColor{ - public String r; - public String g; - public String b; - } - - /** - * 获取小程序码--方案C - */ - @Data - public static class WechatCodeC{ - // 扫码进入的小程序页面路径,最大长度 128 字节,不能为空; - public String path; - //二维码的宽度,单位 px,最小 280px,最大 1280px 默认430 - public Integer width; - } - -} +package com.ccsens.wechatutil.bean.dto; + +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class WechatCode { + /** + * 获取小程序码--方案A + */ + @Data + public static class WechatCodeA{ + // 扫码进入的小程序页面路径,最大长度 128 字节,不能为空; + public String path; + //二维码的宽度,单位 px,最小 280px,最大 1280px 默认430 + public Integer width; + //默认false 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false + public Boolean auto_color; + //auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示 + public LineColor line_color; + //默认false 是否需要透明底色,为 true 时,生成透明底色的小程序 + public Boolean is_hyaline; + } + + /** + * 获取小程序码--方案B + */ + @Data + public static class WechatCodeB{ + //参数 --最大32个可见字符 + public String scene; + //小程序地址 + public String page; + //二维码的宽度,单位 px,最小 280px,最大 1280px 默认430 + public Integer width; + //默认false 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调,默认 false + public Boolean auto_color; + //auto_color 为 false 时生效,使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示 + public LineColor line_color; + //默认false 是否需要透明底色,为 true 时,生成透明底色的小程序 + public Boolean is_hyaline; + } + + /** + * rgb颜色 + */ + @Data + public static class LineColor{ + public String r; + public String g; + public String b; + } + + /** + * 获取小程序码--方案C + */ + @Data + public static class WechatCodeC{ + // 扫码进入的小程序页面路径,最大长度 128 字节,不能为空; + public String path; + //二维码的宽度,单位 px,最小 280px,最大 1280px 默认430 + public Integer width; + } + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java similarity index 96% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java index dd7c3eb..012807e 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java @@ -1,115 +1,115 @@ -package com.ccsens.wechatutil.bean.dto; - -import cn.hutool.core.collection.CollectionUtil; -import com.ccsens.wechatutil.payutil.WxMessageUtil; -import lombok.Data; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; - -/** - * @author 逗 - */ -@Data -public class WxMessageDto { - /** - * 微信机器人发送消息 - */ - @Data - public static class RobotMessage{ - //机器人地址 - public String webHook; - //消息的内容 - public String content; - //消息格式 - public String msgType; - //通过id@群内人员 - public List mentionedList; - //通过手机号@群内人员 - public List mentionedMobileList; - } - - @Data - public static class WxRobotVo{ - private String msgtype; - private WxRobotText text; - private WxRobotMarkdown markdown; - } - @Data - public static class WxRobotText{ - private String content; - private List mentioned_list; - private List mentioned_mobile_list; - } - @Data - public static class WxRobotMarkdown{ - private String content; - } - - /*** -----------------小程序订阅消息相关---------------------- */ - @Getter - @Setter - private static class CommonEntity { - private String value; - } - - @Getter - @Setter - public static class SubscribeEntity { - private String touser; - private String template_id; - private String page; - private T data; - } - - @Getter - @Setter - public static class ReceiveSubscriBuyData { - public ReceiveSubscriBuyData(List params) { - if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { - character_string1 = new CommonEntity(); - amount3 = new CommonEntity(); - thing4 = new CommonEntity(); - time2 = new CommonEntity(); - number11 = new CommonEntity(); - character_string1.setValue(params.get(0)); - amount3.setValue(params.get(1)); - thing4.setValue(params.get(2)); - time2.setValue(params.get(3)); - number11.setValue(params.get(4)); - } - } - - private CommonEntity character_string1;//订单编号 - private CommonEntity amount3;//订单金额 - private CommonEntity thing4;//商品名称 - private CommonEntity time2;//支付时间 - private CommonEntity number11;//购买数量 - } - - @Getter - @Setter - public static class ReceiveSubscriOrderSendData { - public ReceiveSubscriOrderSendData(List params) { - if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { - thing1 = new CommonEntity(); - character_string2 = new CommonEntity(); - date3 = new CommonEntity(); - thing4 = new CommonEntity(); - character_string5 = new CommonEntity(); - thing1.setValue(params.get(0)); - character_string2.setValue(params.get(1)); - date3.setValue(params.get(2)); - thing4.setValue(params.get(3)); - character_string5.setValue(params.get(4)); - } - } - - private CommonEntity thing1;//商品名称 - private CommonEntity character_string2;//订单号 - private CommonEntity date3;//发货时间 - private CommonEntity thing4;//快递公司 - private CommonEntity character_string5;//快递单号 - } -} +package com.ccsens.wechatutil.bean.dto; + +import cn.hutool.core.collection.CollectionUtil; +import com.ccsens.wechatutil.payutil.WxMessageUtil; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * @author 逗 + */ +@Data +public class WxMessageDto { + /** + * 微信机器人发送消息 + */ + @Data + public static class RobotMessage{ + //机器人地址 + public String webHook; + //消息的内容 + public String content; + //消息格式 + public String msgType; + //通过id@群内人员 + public List mentionedList; + //通过手机号@群内人员 + public List mentionedMobileList; + } + + @Data + public static class WxRobotVo{ + private String msgtype; + private WxRobotText text; + private WxRobotMarkdown markdown; + } + @Data + public static class WxRobotText{ + private String content; + private List mentioned_list; + private List mentioned_mobile_list; + } + @Data + public static class WxRobotMarkdown{ + private String content; + } + + /*** -----------------小程序订阅消息相关---------------------- */ + @Getter + @Setter + private static class CommonEntity { + private String value; + } + + @Getter + @Setter + public static class SubscribeEntity { + private String touser; + private String template_id; + private String page; + private T data; + } + + @Getter + @Setter + public static class ReceiveSubscriBuyData { + public ReceiveSubscriBuyData(List params) { + if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { + character_string1 = new CommonEntity(); + amount3 = new CommonEntity(); + thing4 = new CommonEntity(); + time2 = new CommonEntity(); + number11 = new CommonEntity(); + character_string1.setValue(params.get(0)); + amount3.setValue(params.get(1)); + thing4.setValue(params.get(2)); + time2.setValue(params.get(3)); + number11.setValue(params.get(4)); + } + } + + private CommonEntity character_string1;//订单编号 + private CommonEntity amount3;//订单金额 + private CommonEntity thing4;//商品名称 + private CommonEntity time2;//支付时间 + private CommonEntity number11;//购买数量 + } + + @Getter + @Setter + public static class ReceiveSubscriOrderSendData { + public ReceiveSubscriOrderSendData(List params) { + if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { + thing1 = new CommonEntity(); + character_string2 = new CommonEntity(); + date3 = new CommonEntity(); + thing4 = new CommonEntity(); + character_string5 = new CommonEntity(); + thing1.setValue(params.get(0)); + character_string2.setValue(params.get(1)); + date3.setValue(params.get(2)); + thing4.setValue(params.get(3)); + character_string5.setValue(params.get(4)); + } + } + + private CommonEntity thing1;//商品名称 + private CommonEntity character_string2;//订单号 + private CommonEntity date3;//发货时间 + private CommonEntity thing4;//快递公司 + private CommonEntity character_string5;//快递单号 + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxTemplateMessage.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WxTemplateMessage.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxTemplateMessage.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/WxTemplateMessage.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/wxmini/NoticeDto.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/wxmini/NoticeDto.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/wxmini/NoticeDto.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/wxmini/NoticeDto.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/wxofficial/WxQrCodeDto.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/wxofficial/WxQrCodeDto.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/wxofficial/WxQrCodeDto.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/dto/wxofficial/WxQrCodeDto.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/MiniProgramUser.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/MiniProgramUser.java similarity index 94% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/MiniProgramUser.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/MiniProgramUser.java index cd3bd1c..1bb968f 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/MiniProgramUser.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/MiniProgramUser.java @@ -1,14 +1,14 @@ -package com.ccsens.wechatutil.bean.po; - -import lombok.Data; - -/** - * @author 逗 - */ -@Data -public class MiniProgramUser extends WxBaseEntity { - - public String openid; - public String session_key; - public String unionid; -} +package com.ccsens.wechatutil.bean.po; + +import lombok.Data; + +/** + * @author 逗 + */ +@Data +public class MiniProgramUser extends WxBaseEntity { + + public String openid; + public String session_key; + public String unionid; +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxAccessToken.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxAccessToken.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxAccessToken.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxAccessToken.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxBaseEntity.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxBaseEntity.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxBaseEntity.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxBaseEntity.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2AccessToken.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2AccessToken.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2AccessToken.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2AccessToken.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2UserInfo.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2UserInfo.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2UserInfo.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxOauth2UserInfo.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxPhoneDecryptInfo.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxPhoneDecryptInfo.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/WxPhoneDecryptInfo.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/WxPhoneDecryptInfo.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSignin.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSignin.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSignin.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSignin.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSigninResponse.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSigninResponse.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSigninResponse.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/FiotSigninResponse.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/ResponseInfo.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/ResponseInfo.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/ResponseInfo.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/po/wxfiotexplorer/ResponseInfo.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/vo/wxmini/Custom.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/vo/wxmini/Custom.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/vo/wxmini/Custom.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/vo/wxmini/Custom.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/vo/wxofficial/WxQrCodeVo.java b/util_wechat/src/main/java/com/ccsens/wechatutil/bean/vo/wxofficial/WxQrCodeVo.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/bean/vo/wxofficial/WxQrCodeVo.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/bean/vo/wxofficial/WxQrCodeVo.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/config/BeanConfig.java b/util_wechat/src/main/java/com/ccsens/wechatutil/config/BeanConfig.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/config/BeanConfig.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/config/BeanConfig.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/config/SpringConfig.java b/util_wechat/src/main/java/com/ccsens/wechatutil/config/SpringConfig.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/config/SpringConfig.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/config/SpringConfig.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/config/SwaggerConfigure.java b/util_wechat/src/main/java/com/ccsens/wechatutil/config/SwaggerConfigure.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/config/SwaggerConfigure.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/config/SwaggerConfigure.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/exception/PayException.java b/util_wechat/src/main/java/com/ccsens/wechatutil/exception/PayException.java similarity index 95% rename from wechatutil/src/main/java/com/ccsens/wechatutil/exception/PayException.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/exception/PayException.java index 73434ff..2f93c31 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/exception/PayException.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/exception/PayException.java @@ -1,14 +1,14 @@ -package com.ccsens.wechatutil.exception; - -public class PayException extends RuntimeException{ - private int code; - public PayException(int code,String message){ - super(message); - this.code = code; - } - - public PayException(String message){ - super(message); - this.code = -1; - } -} +package com.ccsens.wechatutil.exception; + +public class PayException extends RuntimeException{ + private int code; + public PayException(int code,String message){ + super(message); + this.code = code; + } + + public PayException(String message){ + super(message); + this.code = -1; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/intercept/MybatisInterceptor.java b/util_wechat/src/main/java/com/ccsens/wechatutil/intercept/MybatisInterceptor.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/intercept/MybatisInterceptor.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/intercept/MybatisInterceptor.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/AesUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/AesUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/AesUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/AesUtil.java index 8e09e57..15562a5 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/AesUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/AesUtil.java @@ -1,67 +1,67 @@ -package com.ccsens.wechatutil.payutil; - -import lombok.extern.slf4j.Slf4j; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import javax.crypto.Cipher; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -/** - * @author :mr.zhangsan - * @date :Created in 2021/6/21 21:17 - * @version v1.0: - */ -@Slf4j -public class AesUtil { - - static final int KEY_LENGTH_BYTE = 32; - static final int TAG_LENGTH_BIT = 128; - private final byte[] aesKey; - - public AesUtil(byte[] key) { - if (key.length != KEY_LENGTH_BYTE) { - throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节"); - } - this.aesKey = key; - } - - /** - * 对加密的授权/解除授权结果进行解密 - * @param associatedData - * @param nonce - * @param ciphertext - * @return - * @throws GeneralSecurityException - * @throws IOException - */ - public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext) - throws GeneralSecurityException, IOException { - try { - log.info("---------1111"); - log.info("cipher" + Cipher.getInstance("AES/GCM/NoPadding")); - Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); - - log.info("key" + new SecretKeySpec(aesKey, "AES")); - SecretKeySpec key = new SecretKeySpec(aesKey, "AES"); - log.info("spec" + new GCMParameterSpec(TAG_LENGTH_BIT, nonce)); - GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce); - log.info("------------1"); - cipher.init(Cipher.DECRYPT_MODE, key, spec); - log.info("------------2"); - cipher.updateAAD(associatedData); - log.info("------------3"); - return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8"); - } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new IllegalStateException(e); - } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { - throw new IllegalArgumentException(e); - } - } +package com.ccsens.wechatutil.payutil; + +import lombok.extern.slf4j.Slf4j; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import javax.crypto.Cipher; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + * @author :mr.zhangsan + * @date :Created in 2021/6/21 21:17 + * @version v1.0: + */ +@Slf4j +public class AesUtil { + + static final int KEY_LENGTH_BYTE = 32; + static final int TAG_LENGTH_BIT = 128; + private final byte[] aesKey; + + public AesUtil(byte[] key) { + if (key.length != KEY_LENGTH_BYTE) { + throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节"); + } + this.aesKey = key; + } + + /** + * 对加密的授权/解除授权结果进行解密 + * @param associatedData + * @param nonce + * @param ciphertext + * @return + * @throws GeneralSecurityException + * @throws IOException + */ + public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext) + throws GeneralSecurityException, IOException { + try { + log.info("---------1111"); + log.info("cipher" + Cipher.getInstance("AES/GCM/NoPadding")); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + + log.info("key" + new SecretKeySpec(aesKey, "AES")); + SecretKeySpec key = new SecretKeySpec(aesKey, "AES"); + log.info("spec" + new GCMParameterSpec(TAG_LENGTH_BIT, nonce)); + GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce); + log.info("------------1"); + cipher.init(Cipher.DECRYPT_MODE, key, spec); + log.info("------------2"); + cipher.updateAAD(associatedData); + log.info("------------3"); + return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8"); + } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { + throw new IllegalStateException(e); + } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { + throw new IllegalArgumentException(e); + } + } } \ No newline at end of file diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/HttpsUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/HttpsUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/HttpsUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/HttpsUtil.java index 0a4bffc..98f4771 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/HttpsUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/HttpsUtil.java @@ -1,132 +1,132 @@ -package com.ccsens.wechatutil.payutil; - -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContexts; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; - -import javax.net.ssl.*; -import java.io.*; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.security.KeyStore; - -/** - * @author :mr.zhangsan - * @date :Created in 2021/6/21 23:21 - * @version v1.0: - */ -public class HttpsUtil { - - /** - * 发送https请求 使用PKCS12类型证书 - * - * @param requestUrl 请求地址 - * @param requestMethod 请求方式(GET、POST) - * @param postStr 提交的数据 - * @return String(Json) - */ - public static String httpsRequest(String requestUrl, String requestMethod, String postStr,String pKCS12Path,String pKCS12Pwd) throws Exception { - SSLContext sc = null; - FileInputStream instream = null; - KeyStore keyStore = null; - - keyStore = KeyStore.getInstance("PKCS12"); - instream = new FileInputStream(new File(pKCS12Path)); - keyStore.load(instream,pKCS12Pwd.toCharArray()); - instream.close(); - - SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial( - keyStore, pKCS12Pwd.toCharArray()).build(); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( - sslcontext, - new String[] { "TLSv1" }, - null, - SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER - ); - CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .build(); - HttpPost httpost = new HttpPost(requestUrl); - httpost.addHeader("Connection", "keep-alive"); - httpost.addHeader("Accept", "*/*"); - httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); - httpost.addHeader("Host", "api.mch.weixin.qq.com"); - httpost.addHeader("X-Requested-With", "XMLHttpRequest"); - httpost.addHeader("Cache-Control", "max-age=0"); - httpost.addHeader("User-Agent", - "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); - httpost.setEntity(new StringEntity(postStr, "UTF-8")); - CloseableHttpResponse response = httpclient.execute(httpost); - HttpEntity entity = response.getEntity(); - String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8"); - EntityUtils.consume(entity); - - return jsonStr; - } - - /** - * 设置信任自签名证书 - * - * @param keyStorePath 密钥库路径 - * @param keyStorepass 密钥库密码 - * @return - */ - - public static SSLContext custom(String keyStorePath, String keyStorepass) { - SSLContext sc = null; - FileInputStream instream = null; - KeyStore trustStore = null; - try { - trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - instream = new FileInputStream(new File(keyStorePath)); - trustStore.load(instream, keyStorepass.toCharArray()); - // 相信自己的CA和所有自签名的证书 - sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); - // 构造 javax.net.ssl.TrustManager 对象 - TrustManagerFactory tmf = - TrustManagerFactory.getInstance("SunX509", "SunJSSE"); - tmf.init(trustStore); - TrustManager tms [] = tmf.getTrustManagers(); - // 使用构造好的 TrustManager 访问相应的 https 站点 - SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); - sslContext.init(null, tms, new java.security.SecureRandom()); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - instream.close(); - } catch (IOException e) { - } - } - return sc; - } - - public static String sendGet(String url, String charset, int timeout) { - String result = ""; - try { - URL u = new URL(url); - try { - URLConnection conn = u.openConnection(); - conn.connect(); - conn.setConnectTimeout(timeout); - BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); - String line = ""; - while ((line = in.readLine()) != null) { - result = result + line; - } - in.close(); - } catch (IOException e) { - return result; - } - } catch (MalformedURLException e) { - return result; - } - return result; - } -} +package com.ccsens.wechatutil.payutil; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContexts; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.*; +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.security.KeyStore; + +/** + * @author :mr.zhangsan + * @date :Created in 2021/6/21 23:21 + * @version v1.0: + */ +public class HttpsUtil { + + /** + * 发送https请求 使用PKCS12类型证书 + * + * @param requestUrl 请求地址 + * @param requestMethod 请求方式(GET、POST) + * @param postStr 提交的数据 + * @return String(Json) + */ + public static String httpsRequest(String requestUrl, String requestMethod, String postStr,String pKCS12Path,String pKCS12Pwd) throws Exception { + SSLContext sc = null; + FileInputStream instream = null; + KeyStore keyStore = null; + + keyStore = KeyStore.getInstance("PKCS12"); + instream = new FileInputStream(new File(pKCS12Path)); + keyStore.load(instream,pKCS12Pwd.toCharArray()); + instream.close(); + + SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial( + keyStore, pKCS12Pwd.toCharArray()).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( + sslcontext, + new String[] { "TLSv1" }, + null, + SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER + ); + CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .build(); + HttpPost httpost = new HttpPost(requestUrl); + httpost.addHeader("Connection", "keep-alive"); + httpost.addHeader("Accept", "*/*"); + httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); + httpost.addHeader("Host", "api.mch.weixin.qq.com"); + httpost.addHeader("X-Requested-With", "XMLHttpRequest"); + httpost.addHeader("Cache-Control", "max-age=0"); + httpost.addHeader("User-Agent", + "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); + httpost.setEntity(new StringEntity(postStr, "UTF-8")); + CloseableHttpResponse response = httpclient.execute(httpost); + HttpEntity entity = response.getEntity(); + String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8"); + EntityUtils.consume(entity); + + return jsonStr; + } + + /** + * 设置信任自签名证书 + * + * @param keyStorePath 密钥库路径 + * @param keyStorepass 密钥库密码 + * @return + */ + + public static SSLContext custom(String keyStorePath, String keyStorepass) { + SSLContext sc = null; + FileInputStream instream = null; + KeyStore trustStore = null; + try { + trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + instream = new FileInputStream(new File(keyStorePath)); + trustStore.load(instream, keyStorepass.toCharArray()); + // 相信自己的CA和所有自签名的证书 + sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); + // 构造 javax.net.ssl.TrustManager 对象 + TrustManagerFactory tmf = + TrustManagerFactory.getInstance("SunX509", "SunJSSE"); + tmf.init(trustStore); + TrustManager tms [] = tmf.getTrustManagers(); + // 使用构造好的 TrustManager 访问相应的 https 站点 + SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); + sslContext.init(null, tms, new java.security.SecureRandom()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + instream.close(); + } catch (IOException e) { + } + } + return sc; + } + + public static String sendGet(String url, String charset, int timeout) { + String result = ""; + try { + URL u = new URL(url); + try { + URLConnection conn = u.openConnection(); + conn.connect(); + conn.setConnectTimeout(timeout); + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); + String line = ""; + while ((line = in.readLine()) != null) { + result = result + line; + } + in.close(); + } catch (IOException e) { + return result; + } + } catch (MalformedURLException e) { + return result; + } + return result; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/JacksonUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/JacksonUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/JacksonUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/JacksonUtil.java index 362ce8a..346a757 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/JacksonUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/JacksonUtil.java @@ -1,163 +1,163 @@ -package com.ccsens.wechatutil.payutil; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - -/** - * @author :mr.zhangsan - * @date :Created in 2021/6/21 22:41 - * @version v1.0: - */ -public class JacksonUtil { - private static ObjectMapper getDefaultObjectMapper() { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); - return objectMapper; - } - - private static XmlMapper getDefaultXmlMapper() { - XmlMapper xmlMapper = new XmlMapper(); - xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); - - return xmlMapper; - } - - public static String getJsonValue(String json,String key) throws IOException{ - JsonNode jsonNode = getDefaultObjectMapper().readTree(json); - return jsonNode.get(key).toString(); - } - - public static T jsonToBean(String json, Class clazz, boolean isSet) throws IOException { - T t = null; - if (!isSet) { - t = getDefaultObjectMapper().readValue(json, clazz); - } - else { - t = getDefaultObjectMapper().readValue(json, new TypeReference() { - }); - } - return t; - } - - - /** - * 获取泛型的Collection Type - * @param collectionClass 泛型的Collection - * @param elementClasses 元素类 - * @return JavaType Java类型 - * @since 1.0 - */ - public static JavaType getCollectionType(ObjectMapper mapper, Class collectionClass, Class... elementClasses) { - return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); - } - - //------------------------------------ Json and Bean ----------------------------0 - public static List jsonToBean(String json, Class clazz, Class setClazz) throws IOException { - List tList = null; - ObjectMapper mapper = getDefaultObjectMapper(); - JavaType javaType = getCollectionType(mapper,setClazz,clazz); - tList = getDefaultObjectMapper().readValue(json, javaType); - return tList; - } - - public static String beanToJson(T bean) throws JsonProcessingException { - String json = null; - json = getDefaultObjectMapper().writeValueAsString(bean); - return json; - } - - public static String beanToJson(T bean, boolean pretty) throws JsonProcessingException { - String json = null; - if (!pretty) { - json = getDefaultObjectMapper().writeValueAsString(bean); - } else { - json = getDefaultObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(bean); - } - return json; - } - - //------------------------------------ Json and Map ----------------------------0 - public static Map jsonToMap(String json) throws IOException { - Map map = null; - ObjectMapper mapper = getDefaultObjectMapper(); - map = getDefaultObjectMapper().readValue(json,Map.class); - return map; - } - - public static String mapToJson(Map map) throws JsonProcessingException { - String json = null; - json = getDefaultObjectMapper().writeValueAsString(map); - return json; - } - - public static T mapToBean(Map map,Class clazz) { - - try { - return jsonToBean(mapToJson(map),clazz,false); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - //------------------------------------ Xml and Bean ----------------------------0 - public static T xmlToBean(InputStream xmlInStream, Class clazz) throws IOException { - T t = null; - t = getDefaultXmlMapper().readValue(xmlInStream, clazz); - return t; - } - - public static String beanToXml(T bean) throws JsonProcessingException { - String xmlString = null; - xmlString = getDefaultXmlMapper().writeValueAsString(bean); - return xmlString; - } - - //这个方法可能有点问题,必须配合其他jar包才能使用 -// -// org.codehaus.woodstox -// woodstox-core-asl -// 4.4.1 -// -// public static String beanToXml(T bean, boolean pretty) throws JsonProcessingException { -// -// String xmlString = null; -// if (!pretty) -// xmlString = getDefaultXmlMapper().writeValueAsString(bean); -// else -// xmlString = getDefaultXmlMapper().writerWithDefaultPrettyPrinter().writeValueAsString(bean); -// return xmlString; -// } - - public static String beanToXml(T bean,String root) throws JsonProcessingException { - String xmlString = null; - xmlString = getDefaultXmlMapper().writer().with(SerializationFeature.WRAP_ROOT_VALUE) - .withRootName(root).writeValueAsString(bean); - return xmlString; - } - - //------------------------------------ Xml and Map ---------------------------- - public static Map xmlToMap(InputStream xmlInStream) throws IOException { - Map map = getDefaultXmlMapper().readValue(xmlInStream, Map.class); - return map; - } - - public static String mapToXml(Map map,String root) throws JsonProcessingException { - String xmlString = null; - xmlString = getDefaultXmlMapper().writer().with(SerializationFeature.WRAP_ROOT_VALUE) - .withRootName(root).writeValueAsString(map); - return xmlString; - } -} +package com.ccsens.wechatutil.payutil; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +/** + * @author :mr.zhangsan + * @date :Created in 2021/6/21 22:41 + * @version v1.0: + */ +public class JacksonUtil { + private static ObjectMapper getDefaultObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); + return objectMapper; + } + + private static XmlMapper getDefaultXmlMapper() { + XmlMapper xmlMapper = new XmlMapper(); + xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + + return xmlMapper; + } + + public static String getJsonValue(String json,String key) throws IOException{ + JsonNode jsonNode = getDefaultObjectMapper().readTree(json); + return jsonNode.get(key).toString(); + } + + public static T jsonToBean(String json, Class clazz, boolean isSet) throws IOException { + T t = null; + if (!isSet) { + t = getDefaultObjectMapper().readValue(json, clazz); + } + else { + t = getDefaultObjectMapper().readValue(json, new TypeReference() { + }); + } + return t; + } + + + /** + * 获取泛型的Collection Type + * @param collectionClass 泛型的Collection + * @param elementClasses 元素类 + * @return JavaType Java类型 + * @since 1.0 + */ + public static JavaType getCollectionType(ObjectMapper mapper, Class collectionClass, Class... elementClasses) { + return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); + } + + //------------------------------------ Json and Bean ----------------------------0 + public static List jsonToBean(String json, Class clazz, Class setClazz) throws IOException { + List tList = null; + ObjectMapper mapper = getDefaultObjectMapper(); + JavaType javaType = getCollectionType(mapper,setClazz,clazz); + tList = getDefaultObjectMapper().readValue(json, javaType); + return tList; + } + + public static String beanToJson(T bean) throws JsonProcessingException { + String json = null; + json = getDefaultObjectMapper().writeValueAsString(bean); + return json; + } + + public static String beanToJson(T bean, boolean pretty) throws JsonProcessingException { + String json = null; + if (!pretty) { + json = getDefaultObjectMapper().writeValueAsString(bean); + } else { + json = getDefaultObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(bean); + } + return json; + } + + //------------------------------------ Json and Map ----------------------------0 + public static Map jsonToMap(String json) throws IOException { + Map map = null; + ObjectMapper mapper = getDefaultObjectMapper(); + map = getDefaultObjectMapper().readValue(json,Map.class); + return map; + } + + public static String mapToJson(Map map) throws JsonProcessingException { + String json = null; + json = getDefaultObjectMapper().writeValueAsString(map); + return json; + } + + public static T mapToBean(Map map,Class clazz) { + + try { + return jsonToBean(mapToJson(map),clazz,false); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + //------------------------------------ Xml and Bean ----------------------------0 + public static T xmlToBean(InputStream xmlInStream, Class clazz) throws IOException { + T t = null; + t = getDefaultXmlMapper().readValue(xmlInStream, clazz); + return t; + } + + public static String beanToXml(T bean) throws JsonProcessingException { + String xmlString = null; + xmlString = getDefaultXmlMapper().writeValueAsString(bean); + return xmlString; + } + + //这个方法可能有点问题,必须配合其他jar包才能使用 +// +// org.codehaus.woodstox +// woodstox-core-asl +// 4.4.1 +// +// public static String beanToXml(T bean, boolean pretty) throws JsonProcessingException { +// +// String xmlString = null; +// if (!pretty) +// xmlString = getDefaultXmlMapper().writeValueAsString(bean); +// else +// xmlString = getDefaultXmlMapper().writerWithDefaultPrettyPrinter().writeValueAsString(bean); +// return xmlString; +// } + + public static String beanToXml(T bean,String root) throws JsonProcessingException { + String xmlString = null; + xmlString = getDefaultXmlMapper().writer().with(SerializationFeature.WRAP_ROOT_VALUE) + .withRootName(root).writeValueAsString(bean); + return xmlString; + } + + //------------------------------------ Xml and Map ---------------------------- + public static Map xmlToMap(InputStream xmlInStream) throws IOException { + Map map = getDefaultXmlMapper().readValue(xmlInStream, Map.class); + return map; + } + + public static String mapToXml(Map map,String root) throws JsonProcessingException { + String xmlString = null; + xmlString = getDefaultXmlMapper().writer().with(SerializationFeature.WRAP_ROOT_VALUE) + .withRootName(root).writeValueAsString(map); + return xmlString; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java index c561108..4a739bb 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java @@ -1,155 +1,155 @@ -package com.ccsens.wechatutil.payutil; - -import cn.hutool.core.collection.CollectionUtil; -import com.ccsens.util.HttpsUtil; -import lombok.Getter; -import lombok.Setter; -import lombok.extern.slf4j.Slf4j; - -import java.util.List; - - -/** - * @author :mr.zhangsan - * @date :Created in 2021/4/15 21:11 - * @version v1.0: - */ -@Slf4j -public class WxMessageUtil { - /** - * 微信发送订阅消息 - */ - private static final String URL_SEND_SUBSCRIBE_MESSAGE - = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%1$s"; - - private static String SUBSCRIBE_MSG_ID_BUY = "bqdx4FW51G-JLU6HjL6LyvUbjpo4rFK6CPor2-w3VwM"; - private static String SUBSCRIBE_MSG_ID_ORDERSEND = "5-rhM8h3x1W82tHCt18g9iXyGELyUKQtBDZiFjgItOo"; - - public enum Packet_Notify_Type { - /** - * 消息类型 - */ - Buy(1, "购买"), - ReceiveSubscriBuyData(2, "订单发货"); - - public int value; - public String phase; - - Packet_Notify_Type(int value, String thePhase) { - this.value = value; - this.phase = thePhase; - } - } - - @Getter - @Setter - private static class CommonEntity { - private String value; - } - - @Getter - @Setter - public static class SubscribeEntity { - private String touser; - private String template_id; - private String page; - private T data; - } - - @Getter - @Setter - public static class ReceiveSubscriBuyData { - public ReceiveSubscriBuyData(List params) { - if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { - character_string1 = new CommonEntity(); - amount3 = new CommonEntity(); - thing4 = new CommonEntity(); - time2 = new CommonEntity(); - number11 = new CommonEntity(); - character_string1.setValue(params.get(0)); - amount3.setValue(params.get(1)); - thing4.setValue(params.get(2)); - time2.setValue(params.get(3)); - number11.setValue(params.get(4)); - } - } - - private CommonEntity character_string1;//订单编号 - private CommonEntity amount3;//订单金额 - private CommonEntity thing4;//商品名称 - private CommonEntity time2;//支付时间 - private CommonEntity number11;//购买数量 - } - - @Getter - @Setter - public static class ReceiveSubscriOrderSendData { - public ReceiveSubscriOrderSendData(List params) { - if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { - thing1 = new CommonEntity(); - character_string2 = new CommonEntity(); - date3 = new CommonEntity(); - thing4 = new CommonEntity(); - character_string5 = new CommonEntity(); - thing1.setValue(params.get(0)); - character_string2.setValue(params.get(1)); - date3.setValue(params.get(2)); - thing4.setValue(params.get(3)); - character_string5.setValue(params.get(4)); - } - } - - private CommonEntity thing1;//商品名称 - private CommonEntity character_string2;//订单号 - private CommonEntity date3;//发货时间 - private CommonEntity thing4;//快递公司 - private CommonEntity character_string5;//快递单号 - } - - /** - * 发送微信订阅消息 - * - * @param notifyType 通知类型 - * @param toUser 用户openid - * @param page 小程序页面路径 - * @param params 小程序模板数据 - * @return - * @throws Exception -// */ - public static boolean sendSubcribeMsg(Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { - String ret = null; - String url = String.format(URL_SEND_SUBSCRIBE_MESSAGE, WxTokenUtil.getToken()); - switch (notifyType) { - //订单支付成功通知 - case Buy: { - SubscribeEntity t = new SubscribeEntity<>(); - t.setTouser(toUser); - t.setTemplate_id(SUBSCRIBE_MSG_ID_BUY); - t.setPage(page); - t.setData(new ReceiveSubscriBuyData(params)); - System.out.println(JacksonUtil.beanToJson(t)); - ret = HttpsUtil.httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); - break; - } - //订单发货 - case ReceiveSubscriBuyData: { - SubscribeEntity t = new SubscribeEntity<>(); - t.setTouser(toUser); - t.setTemplate_id(SUBSCRIBE_MSG_ID_ORDERSEND); - t.setData(new ReceiveSubscriOrderSendData(params)); - System.out.println(JacksonUtil.beanToJson(t)); - ret = HttpsUtil.httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); - break; - } - default: { - break; - } - } - //ok: {"errcode":0,"errmsg":"ok"} - //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} - System.out.println("Send Subscribe Message:" + ret); - String errCode = JacksonUtil.getJsonValue(ret, "errcode"); - System.out.println(errCode); - return errCode.equals("0"); - } -} +package com.ccsens.wechatutil.payutil; + +import cn.hutool.core.collection.CollectionUtil; +import com.ccsens.util.HttpsUtil; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; + +import java.util.List; + + +/** + * @author :mr.zhangsan + * @date :Created in 2021/4/15 21:11 + * @version v1.0: + */ +@Slf4j +public class WxMessageUtil { + /** + * 微信发送订阅消息 + */ + private static final String URL_SEND_SUBSCRIBE_MESSAGE + = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%1$s"; + + private static String SUBSCRIBE_MSG_ID_BUY = "bqdx4FW51G-JLU6HjL6LyvUbjpo4rFK6CPor2-w3VwM"; + private static String SUBSCRIBE_MSG_ID_ORDERSEND = "5-rhM8h3x1W82tHCt18g9iXyGELyUKQtBDZiFjgItOo"; + + public enum Packet_Notify_Type { + /** + * 消息类型 + */ + Buy(1, "购买"), + ReceiveSubscriBuyData(2, "订单发货"); + + public int value; + public String phase; + + Packet_Notify_Type(int value, String thePhase) { + this.value = value; + this.phase = thePhase; + } + } + + @Getter + @Setter + private static class CommonEntity { + private String value; + } + + @Getter + @Setter + public static class SubscribeEntity { + private String touser; + private String template_id; + private String page; + private T data; + } + + @Getter + @Setter + public static class ReceiveSubscriBuyData { + public ReceiveSubscriBuyData(List params) { + if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { + character_string1 = new CommonEntity(); + amount3 = new CommonEntity(); + thing4 = new CommonEntity(); + time2 = new CommonEntity(); + number11 = new CommonEntity(); + character_string1.setValue(params.get(0)); + amount3.setValue(params.get(1)); + thing4.setValue(params.get(2)); + time2.setValue(params.get(3)); + number11.setValue(params.get(4)); + } + } + + private CommonEntity character_string1;//订单编号 + private CommonEntity amount3;//订单金额 + private CommonEntity thing4;//商品名称 + private CommonEntity time2;//支付时间 + private CommonEntity number11;//购买数量 + } + + @Getter + @Setter + public static class ReceiveSubscriOrderSendData { + public ReceiveSubscriOrderSendData(List params) { + if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { + thing1 = new CommonEntity(); + character_string2 = new CommonEntity(); + date3 = new CommonEntity(); + thing4 = new CommonEntity(); + character_string5 = new CommonEntity(); + thing1.setValue(params.get(0)); + character_string2.setValue(params.get(1)); + date3.setValue(params.get(2)); + thing4.setValue(params.get(3)); + character_string5.setValue(params.get(4)); + } + } + + private CommonEntity thing1;//商品名称 + private CommonEntity character_string2;//订单号 + private CommonEntity date3;//发货时间 + private CommonEntity thing4;//快递公司 + private CommonEntity character_string5;//快递单号 + } + + /** + * 发送微信订阅消息 + * + * @param notifyType 通知类型 + * @param toUser 用户openid + * @param page 小程序页面路径 + * @param params 小程序模板数据 + * @return + * @throws Exception +// */ + public static boolean sendSubcribeMsg(Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { + String ret = null; + String url = String.format(URL_SEND_SUBSCRIBE_MESSAGE, WxTokenUtil.getToken()); + switch (notifyType) { + //订单支付成功通知 + case Buy: { + SubscribeEntity t = new SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(SUBSCRIBE_MSG_ID_BUY); + t.setPage(page); + t.setData(new ReceiveSubscriBuyData(params)); + System.out.println(JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); + break; + } + //订单发货 + case ReceiveSubscriBuyData: { + SubscribeEntity t = new SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(SUBSCRIBE_MSG_ID_ORDERSEND); + t.setData(new ReceiveSubscriOrderSendData(params)); + System.out.println(JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); + break; + } + default: { + break; + } + } + //ok: {"errcode":0,"errmsg":"ok"} + //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} + System.out.println("Send Subscribe Message:" + ret); + String errCode = JacksonUtil.getJsonValue(ret, "errcode"); + System.out.println(errCode); + return errCode.equals("0"); + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxPayDirectUtils.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxPayDirectUtils.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxPayDirectUtils.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxPayDirectUtils.java index c4039a1..ea17d0e 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxPayDirectUtils.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxPayDirectUtils.java @@ -1,322 +1,322 @@ -package com.ccsens.wechatutil.payutil; - -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSONObject; -import com.ccsens.wechatutil.exception.PayException; -import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder; -import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier; -import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner; -import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials; -import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator; -import com.wechat.pay.contrib.apache.httpclient.util.PemUtil; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.StringEntity; -import org.apache.http.util.EntityUtils; - -import javax.servlet.http.HttpServletRequest; -import java.io.*; -import java.math.BigInteger; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.security.PrivateKey; -import java.security.Signature; -import java.util.Base64; -import java.util.UUID; - -/** - * 微信直连商户支付 - * @author :mr.zhangsan - * @date :Created in 2021/6/18 23:58 - * @version v1.0: - */ -@Slf4j -public class WxPayDirectUtils { - - //商户支付URL - private static final String URL_TRANSACTIONS - = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"; - //测试小程序号appid - public static final String TK_APPID = "wxa26bb3e3f1d2d998"; - //测试商户号 - public static final String TK_MCHID = "1603930405"; - //测试小程序秘钥secret - public static final String TK_SECRET = "162cc6eb70bc341bc67fea210796be21"; - //商户私钥 - private static PrivateKey privateKey; - //版本>=0.1.5可使用 AutoUpdateCertificatesVerifier 类替代默认的验签器。 - // 它会在构造时自动下载商户对应的微信支付平台证书,并每隔一段时间(默认为1个小时)更新证书。 - private static AutoUpdateCertificatesVerifier verifier = null; - //WechatPayHttpClient - private static HttpClient httpClient = null; - //测试商户证书存放路径 - private static final String Client_Key_Path = "C:\\home\\fxxt\\cert_tk\\apiclient_key.pem"; - //测试商户v3key - private static final String DIRECT_V3_Key = "5IDIy173oyjSGPZHuP0lc2V3UqFBO55M"; - //测试证书序列号 - private static final String DIRECT_CERT_SERIAL_NO = "368344414C13EA2ABF3A59A8CF3F31E99ACE0058"; - - - /** - * 支付订单状态 - */ - public enum PayOrderStatus { - SUCCESS, NOTPAY, CLOSED, REVOKED, USERPAYING, PAYERROR, FAILED, UNKNOWN - } - - - /** - * 商户统一下单支付 - * - * 应用ID appid string[1,32] 是 body 由微信生成的应用ID,全局唯一。请求基础下单接口时请注意APPID的应用属性,例如公众号场景下,需使用应用属性为公众号的APPID - * 示例值:wxd678efh567hg6787 - * 直连商户号 mchid string[1,32] 是 body 直连商户的商户号,由微信支付生成并下发。 - * 示例值:1230000109 - * 商品描述 description string[1,127] 是 body 商品描述 - * 示例值:Image形象店-深圳腾大-QQ公仔 - * 商户订单号 out_trade_no string[6,32] 是 body 商户系统内部订单号,只能是数字、大小写字母_-*且在同一个商户号下唯一 - * 示例值:1217752501201407033233368018 - * 交易结束时间 time_expire string[1,64] 否 body 订单失效时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示,北京时间2015年5月20日 13点29分35秒。 - * 示例值:2018-06-08T10:34:56+08:00 - * 附加数据 attach string[1,128] 否 body 附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用 - * 示例值:自定义数据 - * 通知地址 notify_url string[1,256] 是 - */ - public static JSONObject transactions(String openid, String outTradeNo, String description, String notifyUrl, int totalFee) throws Exception { - HttpPost httpPost = new HttpPost(URL_TRANSACTIONS); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Content-type", "application/json; charset=utf-8"); - - JSONObject params = new JSONObject(); - JSONObject amount = new JSONObject(); - JSONObject payer = new JSONObject(); - payer.put("openid", openid); - - amount.put("total", totalFee); - amount.put("currency", "CNY"); - - params.put("appid", TK_APPID); - params.put("mchid", TK_MCHID); - params.put("out_trade_no", outTradeNo); - params.put("description", description); - params.put("notify_url", notifyUrl); - params.put("amount", amount); - params.put("payer", payer); - - httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); - CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpPost); - String bodyAsString = EntityUtils.toString(response.getEntity()); - JSONObject respJson = JSONObject.parseObject(bodyAsString); - - Object prepayId = respJson.get("prepay_id"); - Object code = respJson.get("code"); - - if (code != null) { - throw new Exception(respJson.get("message").toString()); - } - JSONObject result = new JSONObject(); - //根据返回的prepay_id生成发起支付需要的参数签名返回前端 - - result.put("appId", TK_APPID); - result.put("timeStamp", System.currentTimeMillis() / 1000); - result.put("nonceStr", createNonceStr()); - result.put("package", "prepay_id=" + prepayId); - result.put("signType", "RSA"); - - String message = TK_APPID + "\n" - + result.get("timeStamp") + "\n" - + result.get("nonceStr") + "\n" - + result.get("package") + "\n"; - String sign = wxPayReqSign(message.getBytes("utf-8")); - result.put("paySign", sign); - return result; - } - - /** - * 解析支付完毕微信通知参数 - * - * signature 头部签名 Wechatpay-Signature - * body json消息 - * @return - * @throws IOException 参数名 变量 类型[长度限制] 必填 描述 - */ - public static JSONObject rechargeResult(HttpServletRequest request) throws Exception { - log.info("解析支付完毕微信通知参数"); - //一、验证签名 - //1.1获取平台证书 - getVerifier(); - //1.2检查平台证书序列号 - String wepaySerial = request.getHeader("Wechatpay-Serial"); - if (wepaySerial == null) { - throw new PayException(-9, "平台证书序列号为空"); - } - log.info("获取平台证书序列号"); - //获取平台证书序列号 - BigInteger currentSerial = getVerifier().getValidCertificate().getSerialNumber(); - if (StrUtil.isEmpty(wepaySerial) || !wepaySerial.equalsIgnoreCase(currentSerial.toString(16))) { - throw new PayException(-9, "证书序列号不一致"); - } - log.info("3构造验签名串"); - //1.3构造验签名串 - String wepayNonce = request.getHeader("Wechatpay-Nonce"); - String wepayTimestamp = request.getHeader("Wechatpay-Timestamp"); - String wepayBody = null; - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); - String line = null; - StringBuilder body = new StringBuilder(); - while ((line = br.readLine()) != null) { - body.append(line); - } - if (StrUtil.isEmpty(body.toString())) { - throw new PayException(-9, "body is null"); - } - wepayBody = body.toString(); - - - String message = wepayTimestamp + "\n" - + wepayNonce + "\n" - + body.toString() + "\n"; - log.info("获取应答签名"); - //1.4获取应答签名 - String wepySignature = request.getHeader("Wechatpay-Signature"); - - //1.5验证签名 - boolean rr = getVerifier().verify(wepaySerial, - message.getBytes(StandardCharsets.UTF_8),wepySignature); - if (!rr){ - //TODO 签名验证失败抛异常 - } -// String sign = wxPayRespSign(message.getBytes("utf-8")); -// if (!wepySignature.equals(sign)) { -// throw new PayException(-9, "验证签名不一致"); -// } - log.info("解密数据"); - //二、解密数据 - JSONObject jsonObject = JSONObject.parseObject(wepayBody); - JSONObject resource = (JSONObject) jsonObject.get("resource"); - AesUtil aesUtil = new AesUtil(DIRECT_V3_Key.getBytes("utf-8")); - //解密 - String decryptToString = aesUtil.decryptToString( - resource.get("associated_data").toString().getBytes(), - resource.get("nonce").toString().getBytes(), - resource.get("ciphertext").toString()); - JSONObject parseObject = JSONObject.parseObject(decryptToString); - return parseObject; - } - - private static PayOrderStatus getPayOrderStatus(URIBuilder uriBuilder) throws URISyntaxException, IOException { - HttpGet httpGet = new HttpGet(uriBuilder.build()); - httpGet.addHeader("Accept", "application/json"); - - CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpGet); - - String bodyAsString = EntityUtils.toString(response.getEntity()); - - JSONObject jsonObject = JSONObject.parseObject(bodyAsString); - log.info("json:{}", jsonObject); - Object trade_state = jsonObject.get("trade_state"); - if (trade_state != null) { - String tradeState = trade_state.toString(); - log.info("PayOrderStatus:{}",tradeState); - if ("SUCCESS".equals(tradeState)) { - return PayOrderStatus.SUCCESS; - } else if ("USERPAYING".equals(tradeState)) { - return PayOrderStatus.USERPAYING; - } else { - return PayOrderStatus.FAILED; - } - } - return PayOrderStatus.UNKNOWN; - } - - /** - * 商户订单号查询 - * - * @param transactionId 微信订单号 - * @return - * @throws IOException - * @throws URISyntaxException - */ - public static PayOrderStatus wechatOrder(String transactionId) throws IOException, URISyntaxException { - URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/" + transactionId + "?mchid=" + TK_MCHID); - return getPayOrderStatus(uriBuilder); - } - - /** - * 根据商户证书,获取私钥 - * - * @return - * @throws FileNotFoundException - */ - public static PrivateKey getPrivateKey() throws FileNotFoundException { - if (privateKey == null) { - privateKey = PemUtil.loadPrivateKey( - new FileInputStream(Client_Key_Path)); - } - return privateKey; - } - - /** - * 依据商户证书私钥进行签名 - * - * @param message - * @return - * @throws Exception - */ - public static String wxPayReqSign(byte[] message) throws Exception { - Signature sign = Signature.getInstance("SHA256withRSA"); - sign.initSign(getPrivateKey()); - sign.update(message); - - return Base64.getEncoder().encodeToString(sign.sign()); - } - - /** - * 根据微信平台证书获取httpclient - * - * @return - * @throws FileNotFoundException - * @throws UnsupportedEncodingException - */ - public static HttpClient getWechatPayHttpClient() throws FileNotFoundException, UnsupportedEncodingException { - if (httpClient == null) { - //构造WechatPayHttpClientBuilder - WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create() - .withMerchant(TK_MCHID, DIRECT_CERT_SERIAL_NO, getPrivateKey()) - .withValidator(new WechatPay2Validator(getVerifier())); - - // 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签,并进行证书自动更新 - httpClient = builder.build(); - } - return httpClient; - } - - /** - * 自动获取微信平台证书 - * - * @throws UnsupportedEncodingException - */ - public static AutoUpdateCertificatesVerifier getVerifier() throws FileNotFoundException { - //不需要传入微信支付证书了 - if (verifier == null) { - verifier = new AutoUpdateCertificatesVerifier( - new WechatPay2Credentials(TK_MCHID, new PrivateKeySigner(DIRECT_CERT_SERIAL_NO, getPrivateKey())), - DIRECT_V3_Key.getBytes(StandardCharsets.UTF_8)); - } - return verifier; - } - - - /** - * 生成随机字符串 - * - * @return - */ - public static String createNonceStr() { - return UUID.randomUUID().toString().replace("-", ""); - } -} +package com.ccsens.wechatutil.payutil; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import com.ccsens.wechatutil.exception.PayException; +import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder; +import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier; +import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner; +import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials; +import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator; +import com.wechat.pay.contrib.apache.httpclient.util.PemUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.math.BigInteger; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.security.PrivateKey; +import java.security.Signature; +import java.util.Base64; +import java.util.UUID; + +/** + * 微信直连商户支付 + * @author :mr.zhangsan + * @date :Created in 2021/6/18 23:58 + * @version v1.0: + */ +@Slf4j +public class WxPayDirectUtils { + + //商户支付URL + private static final String URL_TRANSACTIONS + = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"; + //测试小程序号appid + public static final String TK_APPID = "wxa26bb3e3f1d2d998"; + //测试商户号 + public static final String TK_MCHID = "1603930405"; + //测试小程序秘钥secret + public static final String TK_SECRET = "162cc6eb70bc341bc67fea210796be21"; + //商户私钥 + private static PrivateKey privateKey; + //版本>=0.1.5可使用 AutoUpdateCertificatesVerifier 类替代默认的验签器。 + // 它会在构造时自动下载商户对应的微信支付平台证书,并每隔一段时间(默认为1个小时)更新证书。 + private static AutoUpdateCertificatesVerifier verifier = null; + //WechatPayHttpClient + private static HttpClient httpClient = null; + //测试商户证书存放路径 + private static final String Client_Key_Path = "C:\\home\\fxxt\\cert_tk\\apiclient_key.pem"; + //测试商户v3key + private static final String DIRECT_V3_Key = "5IDIy173oyjSGPZHuP0lc2V3UqFBO55M"; + //测试证书序列号 + private static final String DIRECT_CERT_SERIAL_NO = "368344414C13EA2ABF3A59A8CF3F31E99ACE0058"; + + + /** + * 支付订单状态 + */ + public enum PayOrderStatus { + SUCCESS, NOTPAY, CLOSED, REVOKED, USERPAYING, PAYERROR, FAILED, UNKNOWN + } + + + /** + * 商户统一下单支付 + * + * 应用ID appid string[1,32] 是 body 由微信生成的应用ID,全局唯一。请求基础下单接口时请注意APPID的应用属性,例如公众号场景下,需使用应用属性为公众号的APPID + * 示例值:wxd678efh567hg6787 + * 直连商户号 mchid string[1,32] 是 body 直连商户的商户号,由微信支付生成并下发。 + * 示例值:1230000109 + * 商品描述 description string[1,127] 是 body 商品描述 + * 示例值:Image形象店-深圳腾大-QQ公仔 + * 商户订单号 out_trade_no string[6,32] 是 body 商户系统内部订单号,只能是数字、大小写字母_-*且在同一个商户号下唯一 + * 示例值:1217752501201407033233368018 + * 交易结束时间 time_expire string[1,64] 否 body 订单失效时间,遵循rfc3339标准格式,格式为YYYY-MM-DDTHH:mm:ss+TIMEZONE,YYYY-MM-DD表示年月日,T出现在字符串中,表示time元素的开头,HH:mm:ss表示时分秒,TIMEZONE表示时区(+08:00表示东八区时间,领先UTC 8小时,即北京时间)。例如:2015-05-20T13:29:35+08:00表示,北京时间2015年5月20日 13点29分35秒。 + * 示例值:2018-06-08T10:34:56+08:00 + * 附加数据 attach string[1,128] 否 body 附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用 + * 示例值:自定义数据 + * 通知地址 notify_url string[1,256] 是 + */ + public static JSONObject transactions(String openid, String outTradeNo, String description, String notifyUrl, int totalFee) throws Exception { + HttpPost httpPost = new HttpPost(URL_TRANSACTIONS); + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-type", "application/json; charset=utf-8"); + + JSONObject params = new JSONObject(); + JSONObject amount = new JSONObject(); + JSONObject payer = new JSONObject(); + payer.put("openid", openid); + + amount.put("total", totalFee); + amount.put("currency", "CNY"); + + params.put("appid", TK_APPID); + params.put("mchid", TK_MCHID); + params.put("out_trade_no", outTradeNo); + params.put("description", description); + params.put("notify_url", notifyUrl); + params.put("amount", amount); + params.put("payer", payer); + + httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); + CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpPost); + String bodyAsString = EntityUtils.toString(response.getEntity()); + JSONObject respJson = JSONObject.parseObject(bodyAsString); + + Object prepayId = respJson.get("prepay_id"); + Object code = respJson.get("code"); + + if (code != null) { + throw new Exception(respJson.get("message").toString()); + } + JSONObject result = new JSONObject(); + //根据返回的prepay_id生成发起支付需要的参数签名返回前端 + + result.put("appId", TK_APPID); + result.put("timeStamp", System.currentTimeMillis() / 1000); + result.put("nonceStr", createNonceStr()); + result.put("package", "prepay_id=" + prepayId); + result.put("signType", "RSA"); + + String message = TK_APPID + "\n" + + result.get("timeStamp") + "\n" + + result.get("nonceStr") + "\n" + + result.get("package") + "\n"; + String sign = wxPayReqSign(message.getBytes("utf-8")); + result.put("paySign", sign); + return result; + } + + /** + * 解析支付完毕微信通知参数 + * + * signature 头部签名 Wechatpay-Signature + * body json消息 + * @return + * @throws IOException 参数名 变量 类型[长度限制] 必填 描述 + */ + public static JSONObject rechargeResult(HttpServletRequest request) throws Exception { + log.info("解析支付完毕微信通知参数"); + //一、验证签名 + //1.1获取平台证书 + getVerifier(); + //1.2检查平台证书序列号 + String wepaySerial = request.getHeader("Wechatpay-Serial"); + if (wepaySerial == null) { + throw new PayException(-9, "平台证书序列号为空"); + } + log.info("获取平台证书序列号"); + //获取平台证书序列号 + BigInteger currentSerial = getVerifier().getValidCertificate().getSerialNumber(); + if (StrUtil.isEmpty(wepaySerial) || !wepaySerial.equalsIgnoreCase(currentSerial.toString(16))) { + throw new PayException(-9, "证书序列号不一致"); + } + log.info("3构造验签名串"); + //1.3构造验签名串 + String wepayNonce = request.getHeader("Wechatpay-Nonce"); + String wepayTimestamp = request.getHeader("Wechatpay-Timestamp"); + String wepayBody = null; + BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); + String line = null; + StringBuilder body = new StringBuilder(); + while ((line = br.readLine()) != null) { + body.append(line); + } + if (StrUtil.isEmpty(body.toString())) { + throw new PayException(-9, "body is null"); + } + wepayBody = body.toString(); + + + String message = wepayTimestamp + "\n" + + wepayNonce + "\n" + + body.toString() + "\n"; + log.info("获取应答签名"); + //1.4获取应答签名 + String wepySignature = request.getHeader("Wechatpay-Signature"); + + //1.5验证签名 + boolean rr = getVerifier().verify(wepaySerial, + message.getBytes(StandardCharsets.UTF_8),wepySignature); + if (!rr){ + //TODO 签名验证失败抛异常 + } +// String sign = wxPayRespSign(message.getBytes("utf-8")); +// if (!wepySignature.equals(sign)) { +// throw new PayException(-9, "验证签名不一致"); +// } + log.info("解密数据"); + //二、解密数据 + JSONObject jsonObject = JSONObject.parseObject(wepayBody); + JSONObject resource = (JSONObject) jsonObject.get("resource"); + AesUtil aesUtil = new AesUtil(DIRECT_V3_Key.getBytes("utf-8")); + //解密 + String decryptToString = aesUtil.decryptToString( + resource.get("associated_data").toString().getBytes(), + resource.get("nonce").toString().getBytes(), + resource.get("ciphertext").toString()); + JSONObject parseObject = JSONObject.parseObject(decryptToString); + return parseObject; + } + + private static PayOrderStatus getPayOrderStatus(URIBuilder uriBuilder) throws URISyntaxException, IOException { + HttpGet httpGet = new HttpGet(uriBuilder.build()); + httpGet.addHeader("Accept", "application/json"); + + CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpGet); + + String bodyAsString = EntityUtils.toString(response.getEntity()); + + JSONObject jsonObject = JSONObject.parseObject(bodyAsString); + log.info("json:{}", jsonObject); + Object trade_state = jsonObject.get("trade_state"); + if (trade_state != null) { + String tradeState = trade_state.toString(); + log.info("PayOrderStatus:{}",tradeState); + if ("SUCCESS".equals(tradeState)) { + return PayOrderStatus.SUCCESS; + } else if ("USERPAYING".equals(tradeState)) { + return PayOrderStatus.USERPAYING; + } else { + return PayOrderStatus.FAILED; + } + } + return PayOrderStatus.UNKNOWN; + } + + /** + * 商户订单号查询 + * + * @param transactionId 微信订单号 + * @return + * @throws IOException + * @throws URISyntaxException + */ + public static PayOrderStatus wechatOrder(String transactionId) throws IOException, URISyntaxException { + URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/" + transactionId + "?mchid=" + TK_MCHID); + return getPayOrderStatus(uriBuilder); + } + + /** + * 根据商户证书,获取私钥 + * + * @return + * @throws FileNotFoundException + */ + public static PrivateKey getPrivateKey() throws FileNotFoundException { + if (privateKey == null) { + privateKey = PemUtil.loadPrivateKey( + new FileInputStream(Client_Key_Path)); + } + return privateKey; + } + + /** + * 依据商户证书私钥进行签名 + * + * @param message + * @return + * @throws Exception + */ + public static String wxPayReqSign(byte[] message) throws Exception { + Signature sign = Signature.getInstance("SHA256withRSA"); + sign.initSign(getPrivateKey()); + sign.update(message); + + return Base64.getEncoder().encodeToString(sign.sign()); + } + + /** + * 根据微信平台证书获取httpclient + * + * @return + * @throws FileNotFoundException + * @throws UnsupportedEncodingException + */ + public static HttpClient getWechatPayHttpClient() throws FileNotFoundException, UnsupportedEncodingException { + if (httpClient == null) { + //构造WechatPayHttpClientBuilder + WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create() + .withMerchant(TK_MCHID, DIRECT_CERT_SERIAL_NO, getPrivateKey()) + .withValidator(new WechatPay2Validator(getVerifier())); + + // 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签,并进行证书自动更新 + httpClient = builder.build(); + } + return httpClient; + } + + /** + * 自动获取微信平台证书 + * + * @throws UnsupportedEncodingException + */ + public static AutoUpdateCertificatesVerifier getVerifier() throws FileNotFoundException { + //不需要传入微信支付证书了 + if (verifier == null) { + verifier = new AutoUpdateCertificatesVerifier( + new WechatPay2Credentials(TK_MCHID, new PrivateKeySigner(DIRECT_CERT_SERIAL_NO, getPrivateKey())), + DIRECT_V3_Key.getBytes(StandardCharsets.UTF_8)); + } + return verifier; + } + + + /** + * 生成随机字符串 + * + * @return + */ + public static String createNonceStr() { + return UUID.randomUUID().toString().replace("-", ""); + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxPayProviderUtils.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxPayProviderUtils.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxPayProviderUtils.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxPayProviderUtils.java index 908f21f..6fe155d 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxPayProviderUtils.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxPayProviderUtils.java @@ -1,687 +1,687 @@ -package com.ccsens.wechatutil.payutil; - -import cn.hutool.core.util.StrUtil; -import com.alibaba.fastjson.JSONObject; -import com.ccsens.util.HttpsUtil; -import com.ccsens.wechatutil.exception.PayException; -import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder; -import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier; -import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner; -import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials; -import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator; -import com.wechat.pay.contrib.apache.httpclient.util.PemUtil; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.StringEntity; -import org.apache.http.util.EntityUtils; -import javax.servlet.http.HttpServletRequest; -import java.io.*; -import java.math.BigInteger; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.security.PrivateKey; -import java.security.Signature; -import java.util.*; - -/** - * 微信服务商支付 - * @author :mr.zhangsan - * @date :Created in 2021/5/15 22:24 - * @version v1.0: - */ -@Slf4j -public class WxPayProviderUtils { - - /** - * 支付订单状态 - */ - public enum PayOrderStatus { - SUCCESS, NOTPAY, CLOSED, REVOKED, USERPAYING, PAYERROR, FAILED, UNKNOWN - } - - private static final String URL_MERCHANT_PAY - = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi"; - //退款url - private static final String URL_REFUND_PAY - = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"; - //查询退款url - private static final String SEL_URL_REFUND_PAY - = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"; - //付款到零钱url - private static final String URL_PAYTO_USER - = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"; - //商户支付URL - private static final String URL_TRANSACTIONS - = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"; - //测试小程序APPID - private static final String appid = "wxf30402e727f0840a"; - //测试小程序secret - private static final String secret = "70402290ac83857c7324b0ee881b544a"; - //商户支付 - //服务商API秘钥key - private static final String KEY = "5a689a2d6b8c4ff499c23d998fde0941"; - // 服务商应用ID(公众号appid) - private static final String SPAPPID = "wx65d45856040e9a4a"; - // 服务商户号 - private static final String SPMECHID = "1610985721"; - //子商户应用ID - private static final String SUBAPPID = appid; - // 子商户号 - private static final String SUBMCHID = "1611259929"; - //服务商证书序列号 - private static final String CERT_SERIAL_NO = "1251E728C5B765190B641C9B45B2A18A4DDEC553"; - //微信提现url - private static final String URL_PAY_TO_USR_WX - = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; - //服务商证书存放路径 - private static final String Client_Key_Path = "C:\\home\\fxxt\\cert_fws\\apiclient_key.pem"; - //服务商APIv3Key - private static final String API_V3_Key = "gRcJ8bpi5imIm4qbbRch5iSSD77DFCKY"; - //测试商户证书存放路径 - public static final String PATH_WX_CRET = "C:\\home\\fxxt\\cert_zyc\\apiclient_key.pem"; - //测试商户私钥 - private static PrivateKey privateKey; - //版本>=0.1.5可使用 AutoUpdateCertificatesVerifier 类替代默认的验签器。 - // 它会在构造时自动下载商户对应的微信支付平台证书,并每隔一段时间(默认为1个小时)更新证书。 - private static AutoUpdateCertificatesVerifier verifier = null; - //WechatPayHttpClient - private static HttpClient httpClient = null; - //加密方式 - private static final String schema = "WECHATPAY2-SHA256-RSA2048"; - - /** - * 私有构造 不允许生成实例, 只允许调用静态方法 - */ - private WxPayProviderUtils() { - - } - - /** - * 生成随机字符串 - * - * @return - */ - public static String createNonceStr() { - return UUID.randomUUID().toString().replace("-", ""); - } - - - /** - * 依据商户证书私钥进行签名 - * - * @param message - * @return - * @throws Exception - */ - private static String wxPayReqSign(byte[] message) throws Exception { - Signature sign = Signature.getInstance("SHA256withRSA"); - sign.initSign(getPrivateKey()); - sign.update(message); - - return Base64.getEncoder().encodeToString(sign.sign()); - } - - /** - * 依据微信支付平台证书(公钥)进行签名 - * - * @param message - * @return - * @throws Exception - */ - private static boolean wxPayRespSign(byte[] message,String signature) throws Exception { - Signature sign = Signature.getInstance("SHA256withRSA"); - sign.initVerify(getVerifier().getValidCertificate()); - sign.update(message); - return sign.verify(Base64.getDecoder().decode(signature)); - } - - /** - * 根据商户证书,获取私钥 - * - * @return - * @throws FileNotFoundException - */ - public static PrivateKey getPrivateKey() throws FileNotFoundException { - if (privateKey == null) { - privateKey = PemUtil.loadPrivateKey( - new FileInputStream(Client_Key_Path)); - } - return privateKey; - } - - /** - * 自动获取微信平台证书 - * - * @throws UnsupportedEncodingException - */ - public static AutoUpdateCertificatesVerifier getVerifier() throws FileNotFoundException { - //不需要传入微信支付证书了 - if (verifier == null) { - verifier = new AutoUpdateCertificatesVerifier( - new WechatPay2Credentials(SPMECHID, new PrivateKeySigner(CERT_SERIAL_NO, getPrivateKey())), - API_V3_Key.getBytes(StandardCharsets.UTF_8)); - } - return verifier; - } - - /** - * 根据微信平台证书获取httpclient - * - * @return - * @throws FileNotFoundException - * @throws UnsupportedEncodingException - */ - public static HttpClient getWechatPayHttpClient() throws FileNotFoundException, UnsupportedEncodingException { - if (httpClient == null) { - //构造WechatPayHttpClientBuilder - WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create() - .withMerchant(SPMECHID, CERT_SERIAL_NO, getPrivateKey()) - .withValidator(new WechatPay2Validator(getVerifier())); - - // 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签,并进行证书自动更新 - httpClient = builder.build(); - } - return httpClient; - } - - /** - * 服务商统一下单支付 - */ - public static JSONObject merchantPreparyPay(String openid, String outTradeNo, String description, String notifyUrl, int totalFee) throws Exception { - HttpPost httpPost = new HttpPost(URL_MERCHANT_PAY); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Content-type", "application/json; charset=utf-8"); - - JSONObject params = new JSONObject(); - JSONObject amount = new JSONObject(); - JSONObject payer = new JSONObject(); - payer.put("sub_openid", openid); - - amount.put("total", totalFee); - amount.put("currency", "CNY"); - - params.put("sp_mchid", SPMECHID); - params.put("sub_mchid", SUBMCHID); - log.info("out_trade_no:{}", outTradeNo); - params.put("out_trade_no", outTradeNo); - params.put("sp_appid", SPAPPID); - params.put("sub_appid", SUBAPPID); - params.put("description", description); - params.put("notify_url", notifyUrl); - params.put("amount", amount); - params.put("payer", payer); - - httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); - CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpPost); - String bodyAsString = EntityUtils.toString(response.getEntity()); - JSONObject respJson = JSONObject.parseObject(bodyAsString); - Object prepayId = respJson.get("prepay_id"); - Object code = respJson.get("code"); - - if (code != null) { - throw new Exception(respJson.get("message").toString()); - } - JSONObject result = new JSONObject(); - //根据返回的prepay_id生成发起支付需要的参数签名返回前端 - - result.put("appId", SUBAPPID); - result.put("timeStamp", System.currentTimeMillis() / 1000); - result.put("nonceStr", createNonceStr()); - result.put("package", "prepay_id=" + prepayId); - result.put("signType", "RSA"); - - log.info("准备签名"); - String message = SUBAPPID + "\n" - + result.get("timeStamp") + "\n" - + result.get("nonceStr") + "\n" - + result.get("package") + "\n"; - String sign = wxPayReqSign(message.getBytes(StandardCharsets.UTF_8)); - log.info("sign:{}", sign); - result.put("paySign", sign); - return result; - } - - /** - * 解析支付完毕微信通知参数 - *

- * signature 头部签名 Wechatpay-Signature - * body json消息 - * - * @return - * @throws IOException 参数名 变量 类型[长度限制] 必填 描述 - */ - public JSONObject rechargeResult(HttpServletRequest request) throws Exception { - //一、验证签名 - //1.1获取平台证书 - getVerifier(); - //1.2检查平台证书序列号 - String wepaySerial = request.getHeader("Wechatpay-Serial"); - if (wepaySerial == null) { - throw new PayException(-9, "平台证书序列号为空"); - } - //获取平台证书序列号 - BigInteger currentSerial = getVerifier().getValidCertificate().getSerialNumber(); - log.info("currentSerial:{} " + currentSerial.toString(16)); - log.info("wepaySerial:{} " + wepaySerial); - if (StrUtil.isEmpty(wepaySerial) || !wepaySerial.equalsIgnoreCase(currentSerial.toString(16))) { - throw new PayException(-9, "证书序列号不一致"); - } - //1.3构造验签名串 - String wepayNonce = request.getHeader("Wechatpay-Nonce"); - String wepayTimestamp = request.getHeader("Wechatpay-Timestamp"); - String wepayBody = null; - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8)); - String line = null; - StringBuilder body = new StringBuilder(); - while ((line = br.readLine()) != null) { - body.append(line); - } - if (StrUtil.isEmpty(body.toString())) { - throw new PayException(-9, "body is null"); - } - wepayBody = body.toString(); - - String message = wepayTimestamp + "\n" - + wepayNonce + "\n" - + body.toString() + "\n"; - //1.4获取应答签名 - String wepySignature = request.getHeader("Wechatpay-Signature"); - log.info("----------------1,{}\n----{}", wepySignature, message); - - - //1.5验证签名 - boolean rr = getVerifier().verify(wepaySerial, - message.getBytes(StandardCharsets.UTF_8), wepySignature); - -// boolean rr = wxPayRespSign(message.getBytes("utf-8"), wepySignature); - if (!rr) { - //TODO 签名验证失败抛异常 - throw new PayException(-9, "验证签名不一致"); - } - log.info("+++++++++++zzc 签名调用+++++++++++++++++++++ "); - //二、解密数据 - JSONObject jsonObject = JSONObject.parseObject(wepayBody); - JSONObject resource = (JSONObject) jsonObject.get("resource"); - AesUtil aesUtil = new AesUtil(API_V3_Key.getBytes("utf-8")); - //解密 - String decryptToString = aesUtil.decryptToString( - resource.get("associated_data").toString().getBytes(), - resource.get("nonce").toString().getBytes(), - resource.get("ciphertext").toString()); - JSONObject parseObject = JSONObject.parseObject(decryptToString); - return parseObject; - } - - private static PayOrderStatus getPayOrderStatus(URIBuilder uriBuilder) throws URISyntaxException, IOException { - HttpGet httpGet = new HttpGet(uriBuilder.build()); - httpGet.addHeader("Accept", "application/json"); - - CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpGet); - - String bodyAsString = EntityUtils.toString(response.getEntity()); - - JSONObject jsonObject = JSONObject.parseObject(bodyAsString); - log.info("json:{}", jsonObject); - Object trade_state = jsonObject.get("trade_state"); - if (trade_state != null) { - String tradeState = trade_state.toString(); - if ("SUCCESS".equals(tradeState)) { - return PayOrderStatus.SUCCESS; - } else if ("USERPAYING".equals(tradeState)) { - return PayOrderStatus.USERPAYING; - } else { - return PayOrderStatus.FAILED; - } - } - return PayOrderStatus.UNKNOWN; - } - - /** - * 服务商查询订单 - * - * @param orderNo - * @throws Exception - */ - public static PayOrderStatus queryOrder(String orderNo) throws IOException, URISyntaxException { - URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/id/" + orderNo + "?sp_mchid=" + SPMECHID + "&sub_mchid=" + SUBMCHID); - return getPayOrderStatus(uriBuilder); - } - - /** - * 商户订单号查询 - * - * @param transactionId 微信订单号 - * @return - * @throws IOException - * @throws URISyntaxException - */ - public static PayOrderStatus wechatOrder(String transactionId) throws IOException, URISyntaxException { - URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/out-trade-no/" + transactionId + "?sp_mchid=" + SPMECHID + "&sub_mchid=" + SUBMCHID); - return getPayOrderStatus(uriBuilder); - } - - - /** - * 服务商关闭订单 - * - * @param orderNo 商户订单号 - */ - public static void closeOrder(String orderNo) throws IOException { - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/out-trade-no/" + orderNo + "/close"); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Content-type", "application/json; charset=utf-8"); - - JSONObject params = new JSONObject(); - params.put("sp_mchid", SPMECHID); - params.put("sub_mchid", SUBMCHID); - - httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); - getWechatPayHttpClient().execute(httpPost); - //接口响应204,无内容 - } - - - /** - * 服务商退款 - * - * @param refund 退款金额 - * @param outTradeNo 商户订单号 - * @param outRefundNo 商户退款单号 - * @param notifyUrl 退款回调url - * @param total 原订单金额 - * @return - * @throws Exception - */ - public static String refunds(int refund, String outTradeNo, String outRefundNo, String notifyUrl, int total) throws Exception { - HttpPost httpPost = new HttpPost(URL_REFUND_PAY); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Content-type", "application/json; charset=utf-8"); - - JSONObject params = new JSONObject(); - JSONObject amount = new JSONObject(); - - //金额信息 - amount.put("refund", refund); - //原订单金额 - amount.put("total", total); - //退款币种 - amount.put("currency", "CNY"); - //子商户号 否 - params.put("sub_mchid", SUBMCHID); -//// 微信支付订单号 (二选一) -// params.put("transaction_id", SUBMCHID); - //商户订单号 (二选一) - params.put("out_trade_no", outTradeNo); - //商户退款单号 - log.info("商户退款单号----------------------------------------out_trade_no:{}", outRefundNo); - params.put("out_refund_no", outRefundNo); - //退款结果回调url 否 - params.put("notify_url", notifyUrl); - //金额信息 - params.put("amount", amount); - - httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); - CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpPost); - String bodyAsString = EntityUtils.toString(response.getEntity()); - JSONObject respJson = JSONObject.parseObject(bodyAsString); - - log.info("respJson:{}", respJson); - Object result = respJson.get("status"); - String status = result.toString(); - if ("SUCCESS".equals(status) || "PROCESSING".equals(status)) { - return status; - } else { - throw new PayException("[" + respJson.get("err_code") + "]" - + respJson.get("err_code_des")); - } - } - - /** - * 查询单笔退款 - */ - public static JSONObject selRechargeResult(String out_refund_no) throws Exception { - HttpGet httpGet = new HttpGet(SEL_URL_REFUND_PAY + "/" + out_refund_no + "?sub_mchid=" + SUBMCHID); - httpGet.addHeader("Accept", "application/json"); - httpGet.addHeader("Content-type", "application/json; charset=utf-8"); - httpGet.addHeader("Wechatpay-Serial", getVerifier().getValidCertificate().getSerialNumber().toString(16)); - - CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpGet); - String bodyAsString = EntityUtils.toString(response.getEntity()); - return JSONObject.parseObject(bodyAsString); - } - - /** - * 微信退款结果通知 - */ - public static JSONObject tuiKuanResult(HttpServletRequest request) throws Exception { - //一、验证签名 - //1.1获取平台证书 - getVerifier(); - //1.2检查平台证书序列号 - String wepaySerial = request.getHeader("Wechatpay-Serial"); - if (wepaySerial == null) { - throw new PayException(-9, "平台证书序列号为空"); - } - //获取平台证书序列号 - BigInteger currentSerial = getVerifier().getValidCertificate().getSerialNumber(); - if (StrUtil.isEmpty(wepaySerial) || !wepaySerial.equalsIgnoreCase(currentSerial.toString(16))) { - throw new PayException(-9, "证书序列号不一致"); - } - String wepayNonce = request.getHeader("Wechatpay-Nonce"); - String wepayTimestamp = request.getHeader("Wechatpay-Timestamp"); - String wepayBody = null; - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),StandardCharsets.UTF_8)); - String line = null; - StringBuilder body = new StringBuilder(); - while ((line = br.readLine()) != null) { - body.append(line); - } - if (StrUtil.isEmpty(body.toString())) { - throw new PayException(-9, "body is null"); - } - wepayBody = body.toString(); - - String message = wepayTimestamp + "\n" - + wepayNonce + "\n" - + body.toString() + "\n"; - //1.4获取应答签名 - String wepySignature = request.getHeader("Wechatpay-Signature"); - - //1.5验证签名 - boolean rr = getVerifier().verify(wepaySerial, - message.getBytes(StandardCharsets.UTF_8),wepySignature); - if (!rr){ - } - JSONObject jsonObject = JSONObject.parseObject(wepayBody); - JSONObject resource = (JSONObject) jsonObject.get("resource"); - AesUtil aesUtil = new AesUtil(API_V3_Key.getBytes("utf-8")); - //解密 - String decryptToString = aesUtil.decryptToString( - resource.get("associated_data").toString().getBytes(),//附加数据 - resource.get("nonce").toString().getBytes(),//随机串 - resource.get("ciphertext").toString());//数据密文 - JSONObject parseObject = JSONObject.parseObject(decryptToString); - return parseObject; - } - - - /** - * 企业付款到零钱 - * - * @param partner_trade_no 商户订单号 - * @param openid 用户openid - * @param total_fee 金额 - * @param desc 付款备注 - * @param spbill_create_ip Ip地址 - * @return - * @throws Exception - */ - public static Map payToUsrWx( - String partner_trade_no, String openid, int total_fee, String desc, String spbill_create_ip) - throws Exception { - //1.构造请求字符串 - Map reqMap = new HashMap(); - reqMap.put("mch_appid", SUBAPPID); - reqMap.put("mchid", SUBMCHID); - //reqMap.put("device_info",null); //不能添加空字段,Jackson会生成闭包xml 导致签名失败 - reqMap.put("nonce_str", createNonceStr()); - reqMap.put("partner_trade_no", partner_trade_no); - reqMap.put("openid", openid); - reqMap.put("check_name", "NO_CHECK"); - //reqMap.put("re_user_name",null); - reqMap.put("amount", total_fee + ""); - reqMap.put("desc", desc); - reqMap.put("spbill_create_ip", spbill_create_ip); - reqMap.put("sign", createSign(reqMap)); - - //2.发送付款请求 - String reqrXml = JacksonUtil.mapToXml(paraFilterEmpty(reqMap), "xml"); - String respXml = HttpsUtil.httpsRequest(URL_PAY_TO_USR_WX, "POST", reqrXml, - PATH_WX_CRET, SUBMCHID); - System.out.println("---------------PayToUsrWx Request Xml-----------------"); - System.out.println(reqrXml); - System.out.println("---------------PayToUsrWx Response Xml-----------------"); - System.out.println(respXml); - System.out.println("---------------PayToUsrWx end-----------------"); - - //3.判断成功失败 - Map respMap = JacksonUtil.xmlToMap(new ByteArrayInputStream(respXml.getBytes(StandardCharsets.UTF_8))); - String return_code, result_code; - return_code = String.valueOf(respMap.get("return_code")); - result_code = String.valueOf(respMap.get("result_code")); - - if (!StrUtil.isEmpty(return_code) && !StrUtil.isEmpty(result_code)) { - if (return_code.equals("SUCCESS") && return_code.equals(result_code)) { - return respMap; - } else { - throw new PayException("[" + respMap.get("err_code") + "]" - + respMap.get("err_code_des")); - } - } else { - throw new PayException(String.valueOf(respMap.get("return_msg"))); - } - //return null; - } - - /** - * Create Sign - * - * @param sParaTemp - * @return - */ - private static String createSign(Map sParaTemp) throws FileNotFoundException { - // 除去数组中的空值和签名参数 - Map sPara = paraFilter(sParaTemp); - String prestr = createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 - //MD5运算生成签名 - String sign = sign(prestr, getPrivateKey().toString(), "utf-8").toUpperCase(); -// return sign; - return sign; - } - - /** - * 签名字符串 - * - * @param text 需要签名的字符串 - * @param key 密钥 - * @param input_charset 编码格式 - * @return 签名结果 - */ - private static String sign(String text, String key, String input_charset) { - text = text + "&key=" + key; - return DigestUtils.md5Hex(getContentBytes(text, input_charset)); - } - - /** - * @param content - * @param charset - * @return - * @throws - * @throws UnsupportedEncodingException - */ - private static byte[] getContentBytes(String content, String charset) { - if (charset == null || "".equals(charset)) { - return content.getBytes(); - } - try { - return content.getBytes(charset); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset); - } - } - - /** - * 除去数组中的空值和签名参数 - * - * @param sArray 签名参数组 - * @return 去掉空值与签名参数后的新签名参数组 - */ - private static Map paraFilter(Map sArray) { - Map result = new HashMap(); - if (sArray == null || sArray.size() <= 0) { - return result; - } - for (String key : sArray.keySet()) { - Object objVal = sArray.get(key); - if (objVal == null) { - continue; - } - String value = String.valueOf(objVal); - if (StrUtil.isEmpty(value) || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) { - continue; - } - result.put(key, value); - } - return result; - } - - /** - * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串 - * - * @param params 需要排序并参与字符拼接的参数组 - * @return 拼接后字符串 - */ - private static String createLinkString(Map params) { - List keys = new ArrayList(params.keySet()); - Collections.sort(keys); - String prestr = ""; - for (int i = 0; i < keys.size(); i++) { - String key = keys.get(i); - String value = params.get(key); - if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符 - prestr = prestr + key + "=" + value; - } else { - prestr = prestr + key + "=" + value + "&"; - } - } - return prestr; - } - - - /** - * 除去数组中的空值和签名参数 - * - * @param sArray 签名参数组 - * @return 去掉空值与签名参数后的新签名参数组 - */ - private static Map paraFilterEmpty(Map sArray) { - Map result = new HashMap(); - if (sArray == null || sArray.size() <= 0) { - return result; - } - for (String key : sArray.keySet()) { - Object objVal = sArray.get(key); - if (objVal == null) { - continue; - } - String value = String.valueOf(objVal); - result.put(key, value); - } - return result; - } +package com.ccsens.wechatutil.payutil; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import com.ccsens.util.HttpsUtil; +import com.ccsens.wechatutil.exception.PayException; +import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder; +import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier; +import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner; +import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials; +import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator; +import com.wechat.pay.contrib.apache.httpclient.util.PemUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.math.BigInteger; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.security.PrivateKey; +import java.security.Signature; +import java.util.*; + +/** + * 微信服务商支付 + * @author :mr.zhangsan + * @date :Created in 2021/5/15 22:24 + * @version v1.0: + */ +@Slf4j +public class WxPayProviderUtils { + + /** + * 支付订单状态 + */ + public enum PayOrderStatus { + SUCCESS, NOTPAY, CLOSED, REVOKED, USERPAYING, PAYERROR, FAILED, UNKNOWN + } + + private static final String URL_MERCHANT_PAY + = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi"; + //退款url + private static final String URL_REFUND_PAY + = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"; + //查询退款url + private static final String SEL_URL_REFUND_PAY + = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"; + //付款到零钱url + private static final String URL_PAYTO_USER + = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"; + //商户支付URL + private static final String URL_TRANSACTIONS + = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"; + //测试小程序APPID + private static final String appid = "wxf30402e727f0840a"; + //测试小程序secret + private static final String secret = "70402290ac83857c7324b0ee881b544a"; + //商户支付 + //服务商API秘钥key + private static final String KEY = "5a689a2d6b8c4ff499c23d998fde0941"; + // 服务商应用ID(公众号appid) + private static final String SPAPPID = "wx65d45856040e9a4a"; + // 服务商户号 + private static final String SPMECHID = "1610985721"; + //子商户应用ID + private static final String SUBAPPID = appid; + // 子商户号 + private static final String SUBMCHID = "1611259929"; + //服务商证书序列号 + private static final String CERT_SERIAL_NO = "1251E728C5B765190B641C9B45B2A18A4DDEC553"; + //微信提现url + private static final String URL_PAY_TO_USR_WX + = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; + //服务商证书存放路径 + private static final String Client_Key_Path = "C:\\home\\fxxt\\cert_fws\\apiclient_key.pem"; + //服务商APIv3Key + private static final String API_V3_Key = "gRcJ8bpi5imIm4qbbRch5iSSD77DFCKY"; + //测试商户证书存放路径 + public static final String PATH_WX_CRET = "C:\\home\\fxxt\\cert_zyc\\apiclient_key.pem"; + //测试商户私钥 + private static PrivateKey privateKey; + //版本>=0.1.5可使用 AutoUpdateCertificatesVerifier 类替代默认的验签器。 + // 它会在构造时自动下载商户对应的微信支付平台证书,并每隔一段时间(默认为1个小时)更新证书。 + private static AutoUpdateCertificatesVerifier verifier = null; + //WechatPayHttpClient + private static HttpClient httpClient = null; + //加密方式 + private static final String schema = "WECHATPAY2-SHA256-RSA2048"; + + /** + * 私有构造 不允许生成实例, 只允许调用静态方法 + */ + private WxPayProviderUtils() { + + } + + /** + * 生成随机字符串 + * + * @return + */ + public static String createNonceStr() { + return UUID.randomUUID().toString().replace("-", ""); + } + + + /** + * 依据商户证书私钥进行签名 + * + * @param message + * @return + * @throws Exception + */ + private static String wxPayReqSign(byte[] message) throws Exception { + Signature sign = Signature.getInstance("SHA256withRSA"); + sign.initSign(getPrivateKey()); + sign.update(message); + + return Base64.getEncoder().encodeToString(sign.sign()); + } + + /** + * 依据微信支付平台证书(公钥)进行签名 + * + * @param message + * @return + * @throws Exception + */ + private static boolean wxPayRespSign(byte[] message,String signature) throws Exception { + Signature sign = Signature.getInstance("SHA256withRSA"); + sign.initVerify(getVerifier().getValidCertificate()); + sign.update(message); + return sign.verify(Base64.getDecoder().decode(signature)); + } + + /** + * 根据商户证书,获取私钥 + * + * @return + * @throws FileNotFoundException + */ + public static PrivateKey getPrivateKey() throws FileNotFoundException { + if (privateKey == null) { + privateKey = PemUtil.loadPrivateKey( + new FileInputStream(Client_Key_Path)); + } + return privateKey; + } + + /** + * 自动获取微信平台证书 + * + * @throws UnsupportedEncodingException + */ + public static AutoUpdateCertificatesVerifier getVerifier() throws FileNotFoundException { + //不需要传入微信支付证书了 + if (verifier == null) { + verifier = new AutoUpdateCertificatesVerifier( + new WechatPay2Credentials(SPMECHID, new PrivateKeySigner(CERT_SERIAL_NO, getPrivateKey())), + API_V3_Key.getBytes(StandardCharsets.UTF_8)); + } + return verifier; + } + + /** + * 根据微信平台证书获取httpclient + * + * @return + * @throws FileNotFoundException + * @throws UnsupportedEncodingException + */ + public static HttpClient getWechatPayHttpClient() throws FileNotFoundException, UnsupportedEncodingException { + if (httpClient == null) { + //构造WechatPayHttpClientBuilder + WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create() + .withMerchant(SPMECHID, CERT_SERIAL_NO, getPrivateKey()) + .withValidator(new WechatPay2Validator(getVerifier())); + + // 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签,并进行证书自动更新 + httpClient = builder.build(); + } + return httpClient; + } + + /** + * 服务商统一下单支付 + */ + public static JSONObject merchantPreparyPay(String openid, String outTradeNo, String description, String notifyUrl, int totalFee) throws Exception { + HttpPost httpPost = new HttpPost(URL_MERCHANT_PAY); + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-type", "application/json; charset=utf-8"); + + JSONObject params = new JSONObject(); + JSONObject amount = new JSONObject(); + JSONObject payer = new JSONObject(); + payer.put("sub_openid", openid); + + amount.put("total", totalFee); + amount.put("currency", "CNY"); + + params.put("sp_mchid", SPMECHID); + params.put("sub_mchid", SUBMCHID); + log.info("out_trade_no:{}", outTradeNo); + params.put("out_trade_no", outTradeNo); + params.put("sp_appid", SPAPPID); + params.put("sub_appid", SUBAPPID); + params.put("description", description); + params.put("notify_url", notifyUrl); + params.put("amount", amount); + params.put("payer", payer); + + httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); + CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpPost); + String bodyAsString = EntityUtils.toString(response.getEntity()); + JSONObject respJson = JSONObject.parseObject(bodyAsString); + Object prepayId = respJson.get("prepay_id"); + Object code = respJson.get("code"); + + if (code != null) { + throw new Exception(respJson.get("message").toString()); + } + JSONObject result = new JSONObject(); + //根据返回的prepay_id生成发起支付需要的参数签名返回前端 + + result.put("appId", SUBAPPID); + result.put("timeStamp", System.currentTimeMillis() / 1000); + result.put("nonceStr", createNonceStr()); + result.put("package", "prepay_id=" + prepayId); + result.put("signType", "RSA"); + + log.info("准备签名"); + String message = SUBAPPID + "\n" + + result.get("timeStamp") + "\n" + + result.get("nonceStr") + "\n" + + result.get("package") + "\n"; + String sign = wxPayReqSign(message.getBytes(StandardCharsets.UTF_8)); + log.info("sign:{}", sign); + result.put("paySign", sign); + return result; + } + + /** + * 解析支付完毕微信通知参数 + *

+ * signature 头部签名 Wechatpay-Signature + * body json消息 + * + * @return + * @throws IOException 参数名 变量 类型[长度限制] 必填 描述 + */ + public JSONObject rechargeResult(HttpServletRequest request) throws Exception { + //一、验证签名 + //1.1获取平台证书 + getVerifier(); + //1.2检查平台证书序列号 + String wepaySerial = request.getHeader("Wechatpay-Serial"); + if (wepaySerial == null) { + throw new PayException(-9, "平台证书序列号为空"); + } + //获取平台证书序列号 + BigInteger currentSerial = getVerifier().getValidCertificate().getSerialNumber(); + log.info("currentSerial:{} " + currentSerial.toString(16)); + log.info("wepaySerial:{} " + wepaySerial); + if (StrUtil.isEmpty(wepaySerial) || !wepaySerial.equalsIgnoreCase(currentSerial.toString(16))) { + throw new PayException(-9, "证书序列号不一致"); + } + //1.3构造验签名串 + String wepayNonce = request.getHeader("Wechatpay-Nonce"); + String wepayTimestamp = request.getHeader("Wechatpay-Timestamp"); + String wepayBody = null; + BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8)); + String line = null; + StringBuilder body = new StringBuilder(); + while ((line = br.readLine()) != null) { + body.append(line); + } + if (StrUtil.isEmpty(body.toString())) { + throw new PayException(-9, "body is null"); + } + wepayBody = body.toString(); + + String message = wepayTimestamp + "\n" + + wepayNonce + "\n" + + body.toString() + "\n"; + //1.4获取应答签名 + String wepySignature = request.getHeader("Wechatpay-Signature"); + log.info("----------------1,{}\n----{}", wepySignature, message); + + + //1.5验证签名 + boolean rr = getVerifier().verify(wepaySerial, + message.getBytes(StandardCharsets.UTF_8), wepySignature); + +// boolean rr = wxPayRespSign(message.getBytes("utf-8"), wepySignature); + if (!rr) { + //TODO 签名验证失败抛异常 + throw new PayException(-9, "验证签名不一致"); + } + log.info("+++++++++++zzc 签名调用+++++++++++++++++++++ "); + //二、解密数据 + JSONObject jsonObject = JSONObject.parseObject(wepayBody); + JSONObject resource = (JSONObject) jsonObject.get("resource"); + AesUtil aesUtil = new AesUtil(API_V3_Key.getBytes("utf-8")); + //解密 + String decryptToString = aesUtil.decryptToString( + resource.get("associated_data").toString().getBytes(), + resource.get("nonce").toString().getBytes(), + resource.get("ciphertext").toString()); + JSONObject parseObject = JSONObject.parseObject(decryptToString); + return parseObject; + } + + private static PayOrderStatus getPayOrderStatus(URIBuilder uriBuilder) throws URISyntaxException, IOException { + HttpGet httpGet = new HttpGet(uriBuilder.build()); + httpGet.addHeader("Accept", "application/json"); + + CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpGet); + + String bodyAsString = EntityUtils.toString(response.getEntity()); + + JSONObject jsonObject = JSONObject.parseObject(bodyAsString); + log.info("json:{}", jsonObject); + Object trade_state = jsonObject.get("trade_state"); + if (trade_state != null) { + String tradeState = trade_state.toString(); + if ("SUCCESS".equals(tradeState)) { + return PayOrderStatus.SUCCESS; + } else if ("USERPAYING".equals(tradeState)) { + return PayOrderStatus.USERPAYING; + } else { + return PayOrderStatus.FAILED; + } + } + return PayOrderStatus.UNKNOWN; + } + + /** + * 服务商查询订单 + * + * @param orderNo + * @throws Exception + */ + public static PayOrderStatus queryOrder(String orderNo) throws IOException, URISyntaxException { + URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/id/" + orderNo + "?sp_mchid=" + SPMECHID + "&sub_mchid=" + SUBMCHID); + return getPayOrderStatus(uriBuilder); + } + + /** + * 商户订单号查询 + * + * @param transactionId 微信订单号 + * @return + * @throws IOException + * @throws URISyntaxException + */ + public static PayOrderStatus wechatOrder(String transactionId) throws IOException, URISyntaxException { + URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/out-trade-no/" + transactionId + "?sp_mchid=" + SPMECHID + "&sub_mchid=" + SUBMCHID); + return getPayOrderStatus(uriBuilder); + } + + + /** + * 服务商关闭订单 + * + * @param orderNo 商户订单号 + */ + public static void closeOrder(String orderNo) throws IOException { + HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/out-trade-no/" + orderNo + "/close"); + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-type", "application/json; charset=utf-8"); + + JSONObject params = new JSONObject(); + params.put("sp_mchid", SPMECHID); + params.put("sub_mchid", SUBMCHID); + + httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); + getWechatPayHttpClient().execute(httpPost); + //接口响应204,无内容 + } + + + /** + * 服务商退款 + * + * @param refund 退款金额 + * @param outTradeNo 商户订单号 + * @param outRefundNo 商户退款单号 + * @param notifyUrl 退款回调url + * @param total 原订单金额 + * @return + * @throws Exception + */ + public static String refunds(int refund, String outTradeNo, String outRefundNo, String notifyUrl, int total) throws Exception { + HttpPost httpPost = new HttpPost(URL_REFUND_PAY); + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-type", "application/json; charset=utf-8"); + + JSONObject params = new JSONObject(); + JSONObject amount = new JSONObject(); + + //金额信息 + amount.put("refund", refund); + //原订单金额 + amount.put("total", total); + //退款币种 + amount.put("currency", "CNY"); + //子商户号 否 + params.put("sub_mchid", SUBMCHID); +//// 微信支付订单号 (二选一) +// params.put("transaction_id", SUBMCHID); + //商户订单号 (二选一) + params.put("out_trade_no", outTradeNo); + //商户退款单号 + log.info("商户退款单号----------------------------------------out_trade_no:{}", outRefundNo); + params.put("out_refund_no", outRefundNo); + //退款结果回调url 否 + params.put("notify_url", notifyUrl); + //金额信息 + params.put("amount", amount); + + httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8")); + CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpPost); + String bodyAsString = EntityUtils.toString(response.getEntity()); + JSONObject respJson = JSONObject.parseObject(bodyAsString); + + log.info("respJson:{}", respJson); + Object result = respJson.get("status"); + String status = result.toString(); + if ("SUCCESS".equals(status) || "PROCESSING".equals(status)) { + return status; + } else { + throw new PayException("[" + respJson.get("err_code") + "]" + + respJson.get("err_code_des")); + } + } + + /** + * 查询单笔退款 + */ + public static JSONObject selRechargeResult(String out_refund_no) throws Exception { + HttpGet httpGet = new HttpGet(SEL_URL_REFUND_PAY + "/" + out_refund_no + "?sub_mchid=" + SUBMCHID); + httpGet.addHeader("Accept", "application/json"); + httpGet.addHeader("Content-type", "application/json; charset=utf-8"); + httpGet.addHeader("Wechatpay-Serial", getVerifier().getValidCertificate().getSerialNumber().toString(16)); + + CloseableHttpResponse response = (CloseableHttpResponse) getWechatPayHttpClient().execute(httpGet); + String bodyAsString = EntityUtils.toString(response.getEntity()); + return JSONObject.parseObject(bodyAsString); + } + + /** + * 微信退款结果通知 + */ + public static JSONObject tuiKuanResult(HttpServletRequest request) throws Exception { + //一、验证签名 + //1.1获取平台证书 + getVerifier(); + //1.2检查平台证书序列号 + String wepaySerial = request.getHeader("Wechatpay-Serial"); + if (wepaySerial == null) { + throw new PayException(-9, "平台证书序列号为空"); + } + //获取平台证书序列号 + BigInteger currentSerial = getVerifier().getValidCertificate().getSerialNumber(); + if (StrUtil.isEmpty(wepaySerial) || !wepaySerial.equalsIgnoreCase(currentSerial.toString(16))) { + throw new PayException(-9, "证书序列号不一致"); + } + String wepayNonce = request.getHeader("Wechatpay-Nonce"); + String wepayTimestamp = request.getHeader("Wechatpay-Timestamp"); + String wepayBody = null; + BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),StandardCharsets.UTF_8)); + String line = null; + StringBuilder body = new StringBuilder(); + while ((line = br.readLine()) != null) { + body.append(line); + } + if (StrUtil.isEmpty(body.toString())) { + throw new PayException(-9, "body is null"); + } + wepayBody = body.toString(); + + String message = wepayTimestamp + "\n" + + wepayNonce + "\n" + + body.toString() + "\n"; + //1.4获取应答签名 + String wepySignature = request.getHeader("Wechatpay-Signature"); + + //1.5验证签名 + boolean rr = getVerifier().verify(wepaySerial, + message.getBytes(StandardCharsets.UTF_8),wepySignature); + if (!rr){ + } + JSONObject jsonObject = JSONObject.parseObject(wepayBody); + JSONObject resource = (JSONObject) jsonObject.get("resource"); + AesUtil aesUtil = new AesUtil(API_V3_Key.getBytes("utf-8")); + //解密 + String decryptToString = aesUtil.decryptToString( + resource.get("associated_data").toString().getBytes(),//附加数据 + resource.get("nonce").toString().getBytes(),//随机串 + resource.get("ciphertext").toString());//数据密文 + JSONObject parseObject = JSONObject.parseObject(decryptToString); + return parseObject; + } + + + /** + * 企业付款到零钱 + * + * @param partner_trade_no 商户订单号 + * @param openid 用户openid + * @param total_fee 金额 + * @param desc 付款备注 + * @param spbill_create_ip Ip地址 + * @return + * @throws Exception + */ + public static Map payToUsrWx( + String partner_trade_no, String openid, int total_fee, String desc, String spbill_create_ip) + throws Exception { + //1.构造请求字符串 + Map reqMap = new HashMap(); + reqMap.put("mch_appid", SUBAPPID); + reqMap.put("mchid", SUBMCHID); + //reqMap.put("device_info",null); //不能添加空字段,Jackson会生成闭包xml 导致签名失败 + reqMap.put("nonce_str", createNonceStr()); + reqMap.put("partner_trade_no", partner_trade_no); + reqMap.put("openid", openid); + reqMap.put("check_name", "NO_CHECK"); + //reqMap.put("re_user_name",null); + reqMap.put("amount", total_fee + ""); + reqMap.put("desc", desc); + reqMap.put("spbill_create_ip", spbill_create_ip); + reqMap.put("sign", createSign(reqMap)); + + //2.发送付款请求 + String reqrXml = JacksonUtil.mapToXml(paraFilterEmpty(reqMap), "xml"); + String respXml = HttpsUtil.httpsRequest(URL_PAY_TO_USR_WX, "POST", reqrXml, + PATH_WX_CRET, SUBMCHID); + System.out.println("---------------PayToUsrWx Request Xml-----------------"); + System.out.println(reqrXml); + System.out.println("---------------PayToUsrWx Response Xml-----------------"); + System.out.println(respXml); + System.out.println("---------------PayToUsrWx end-----------------"); + + //3.判断成功失败 + Map respMap = JacksonUtil.xmlToMap(new ByteArrayInputStream(respXml.getBytes(StandardCharsets.UTF_8))); + String return_code, result_code; + return_code = String.valueOf(respMap.get("return_code")); + result_code = String.valueOf(respMap.get("result_code")); + + if (!StrUtil.isEmpty(return_code) && !StrUtil.isEmpty(result_code)) { + if (return_code.equals("SUCCESS") && return_code.equals(result_code)) { + return respMap; + } else { + throw new PayException("[" + respMap.get("err_code") + "]" + + respMap.get("err_code_des")); + } + } else { + throw new PayException(String.valueOf(respMap.get("return_msg"))); + } + //return null; + } + + /** + * Create Sign + * + * @param sParaTemp + * @return + */ + private static String createSign(Map sParaTemp) throws FileNotFoundException { + // 除去数组中的空值和签名参数 + Map sPara = paraFilter(sParaTemp); + String prestr = createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 + //MD5运算生成签名 + String sign = sign(prestr, getPrivateKey().toString(), "utf-8").toUpperCase(); +// return sign; + return sign; + } + + /** + * 签名字符串 + * + * @param text 需要签名的字符串 + * @param key 密钥 + * @param input_charset 编码格式 + * @return 签名结果 + */ + private static String sign(String text, String key, String input_charset) { + text = text + "&key=" + key; + return DigestUtils.md5Hex(getContentBytes(text, input_charset)); + } + + /** + * @param content + * @param charset + * @return + * @throws + * @throws UnsupportedEncodingException + */ + private static byte[] getContentBytes(String content, String charset) { + if (charset == null || "".equals(charset)) { + return content.getBytes(); + } + try { + return content.getBytes(charset); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset); + } + } + + /** + * 除去数组中的空值和签名参数 + * + * @param sArray 签名参数组 + * @return 去掉空值与签名参数后的新签名参数组 + */ + private static Map paraFilter(Map sArray) { + Map result = new HashMap(); + if (sArray == null || sArray.size() <= 0) { + return result; + } + for (String key : sArray.keySet()) { + Object objVal = sArray.get(key); + if (objVal == null) { + continue; + } + String value = String.valueOf(objVal); + if (StrUtil.isEmpty(value) || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) { + continue; + } + result.put(key, value); + } + return result; + } + + /** + * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串 + * + * @param params 需要排序并参与字符拼接的参数组 + * @return 拼接后字符串 + */ + private static String createLinkString(Map params) { + List keys = new ArrayList(params.keySet()); + Collections.sort(keys); + String prestr = ""; + for (int i = 0; i < keys.size(); i++) { + String key = keys.get(i); + String value = params.get(key); + if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符 + prestr = prestr + key + "=" + value; + } else { + prestr = prestr + key + "=" + value + "&"; + } + } + return prestr; + } + + + /** + * 除去数组中的空值和签名参数 + * + * @param sArray 签名参数组 + * @return 去掉空值与签名参数后的新签名参数组 + */ + private static Map paraFilterEmpty(Map sArray) { + Map result = new HashMap(); + if (sArray == null || sArray.size() <= 0) { + return result; + } + for (String key : sArray.keySet()) { + Object objVal = sArray.get(key); + if (objVal == null) { + continue; + } + String value = String.valueOf(objVal); + result.put(key, value); + } + return result; + } } \ No newline at end of file diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxTokenUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxTokenUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxTokenUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxTokenUtil.java index bd77ea6..fe1e470 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxTokenUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/payutil/WxTokenUtil.java @@ -1,64 +1,64 @@ -package com.ccsens.wechatutil.payutil; - -import com.alibaba.fastjson.JSONObject; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.util.EntityUtils; - -import java.io.FileNotFoundException; -import java.io.IOException; - -/** - * @author :mr.zhangsan - * @date :Created in 2021/4/15 21:11 - * @version v1.0: - */ - -public class WxTokenUtil { - - //测试APPID - private static final String appid = "wxf30402e727f0840a"; - //测试secret - private static final String secret = "70402290ac83857c7324b0ee881b544a"; - // 测试商户号 - private static final String SUBMCHID = "1611259929"; - - /** - * 获取小程序全局唯一后台接口调用凭据(access_token) - */ - private static final String URL_GETTOKEN_PAY - = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; - - public static String getToken() throws Exception{ - - HttpGet httpGet = new HttpGet(URL_GETTOKEN_PAY); - httpGet.addHeader("Accept", "application/json"); - httpGet.addHeader("Content-type", "application/json; charset=utf-8"); - try { - httpGet.addHeader("Wechatpay-Serial", WxPayProviderUtils.getVerifier().getValidCertificate().getSerialNumber().toString(16)); - }catch (FileNotFoundException e) { - e.printStackTrace(); - throw new FileNotFoundException("获取微信平台证书失败"); - } - String bodyAsString = ""; - try { - CloseableHttpResponse response = (CloseableHttpResponse) WxPayProviderUtils.getWechatPayHttpClient().execute(httpGet); - try { - bodyAsString = EntityUtils.toString(response.getEntity()); - }catch (IOException e) { - e.printStackTrace(); - throw new FileNotFoundException("bodyAsString转换错误"); - } - }catch (IOException e) { - e.printStackTrace(); - throw new FileNotFoundException("根据微信平台证书获取httpclient失败"); - } - JSONObject respJson = JSONObject.parseObject(bodyAsString); - Object access_token = respJson.get("access_token"); - if (access_token != null) { - return access_token.toString(); - }else { - throw new Exception("获取WxToken失败"); - } - } -} +package com.ccsens.wechatutil.payutil; + +import com.alibaba.fastjson.JSONObject; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.util.EntityUtils; + +import java.io.FileNotFoundException; +import java.io.IOException; + +/** + * @author :mr.zhangsan + * @date :Created in 2021/4/15 21:11 + * @version v1.0: + */ + +public class WxTokenUtil { + + //测试APPID + private static final String appid = "wxf30402e727f0840a"; + //测试secret + private static final String secret = "70402290ac83857c7324b0ee881b544a"; + // 测试商户号 + private static final String SUBMCHID = "1611259929"; + + /** + * 获取小程序全局唯一后台接口调用凭据(access_token) + */ + private static final String URL_GETTOKEN_PAY + = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; + + public static String getToken() throws Exception{ + + HttpGet httpGet = new HttpGet(URL_GETTOKEN_PAY); + httpGet.addHeader("Accept", "application/json"); + httpGet.addHeader("Content-type", "application/json; charset=utf-8"); + try { + httpGet.addHeader("Wechatpay-Serial", WxPayProviderUtils.getVerifier().getValidCertificate().getSerialNumber().toString(16)); + }catch (FileNotFoundException e) { + e.printStackTrace(); + throw new FileNotFoundException("获取微信平台证书失败"); + } + String bodyAsString = ""; + try { + CloseableHttpResponse response = (CloseableHttpResponse) WxPayProviderUtils.getWechatPayHttpClient().execute(httpGet); + try { + bodyAsString = EntityUtils.toString(response.getEntity()); + }catch (IOException e) { + e.printStackTrace(); + throw new FileNotFoundException("bodyAsString转换错误"); + } + }catch (IOException e) { + e.printStackTrace(); + throw new FileNotFoundException("根据微信平台证书获取httpclient失败"); + } + JSONObject respJson = JSONObject.parseObject(bodyAsString); + Object access_token = respJson.get("access_token"); + if (access_token != null) { + return access_token.toString(); + }else { + throw new Exception("获取WxToken失败"); + } + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/util/TC3Util.java b/util_wechat/src/main/java/com/ccsens/wechatutil/util/TC3Util.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/util/TC3Util.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/util/TC3Util.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WeiXinPropUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/util/WeiXinPropUtil.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/util/WeiXinPropUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/util/WeiXinPropUtil.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxCodeError.java b/util_wechat/src/main/java/com/ccsens/wechatutil/util/WxCodeError.java similarity index 96% rename from wechatutil/src/main/java/com/ccsens/wechatutil/util/WxCodeError.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/util/WxCodeError.java index 0f2a505..f19b4e8 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxCodeError.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/util/WxCodeError.java @@ -1,15 +1,15 @@ -package com.ccsens.wechatutil.util; - -import com.ccsens.util.CodeError; - -/** - * @author 逗 - */ -public class WxCodeError extends CodeError { - - public static final Code WX_HTTP_ERROR = new Code(1,"微信接口请求失败", true); - public static final Code ACCESS_TOKEN_ERROR = new Code(2,"accessToken获取失败", true); - public static final Code OPENID_ERROR = new Code(2,"openId获取失败", true); - - -} +package com.ccsens.wechatutil.util; + +import com.ccsens.util.CodeError; + +/** + * @author 逗 + */ +public class WxCodeError extends CodeError { + + public static final Code WX_HTTP_ERROR = new Code(1,"微信接口请求失败", true); + public static final Code ACCESS_TOKEN_ERROR = new Code(2,"accessToken获取失败", true); + public static final Code OPENID_ERROR = new Code(2,"openId获取失败", true); + + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java b/util_wechat/src/main/java/com/ccsens/wechatutil/util/WxConstant.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/util/WxConstant.java index 8111685..009686c 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/util/WxConstant.java @@ -1,129 +1,129 @@ -package com.ccsens.wechatutil.util; - -import cn.hutool.core.util.StrUtil; -import com.ccsens.util.JacksonUtil; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.bean.po.WxBaseEntity; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * @author 逗 - */ -public class WxConstant { - - /*** 默认小程序 */ - public static final String ANYRING = "anyring"; - - - /*** 公众号获取accessToken */ - public static final String URL_GET_OAUTH2_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%1$s&secret=%2$s&code=%3$s&grant_type=authorization_code"; - /*** 公众号发送订阅消息 */ - public static final String MESSAGE_TEMPLATE_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%1$s"; - /** 创建二维码 */ - public static final String QR_CODE_CREATE = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={}"; - /**根据openId获取用户信息*/ - public static final String USER_INFO = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%1$s&openid=%2$s&lang=zh_CN"; - - - /*** 小程序登录路径 */ - public static final String MINI_PROGRAM_LOGIN = "https://api.weixin.qq.com/sns/jscode2session?appid=%1$s&secret=%2$s&js_code=%3$s&grant_type=%4$s"; - /*** 通过网页授权和openId获取用户信息 */ - public static final String URL_GET_OAUTH2_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%1$s&openid=%2$s"; - /*** 获取小程序码A */ - public static final String URL_GET_WX_CODE_A = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%1$s"; - /*** 获取小程序码B */ - public static final String URL_GET_WX_CODE_B = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%1$s"; - /*** 获取小程序码C */ - public static final String URL_GET_WX_CODE_C = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%1$s"; - /*** 小程序获取accessToken */ - public static final String URL_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%1$s&secret=%2$s"; - /*** 小程序发送订阅消息 */ - public static final String URL_SEND_SUBSCRIBE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%1$s"; - /*** 小程序消息模板--支付 */ - public static String SUBSCRIBE_MSG_ID_BUY = "bqdx4FW51G-JLU6HjL6LyvUbjpo4rFK6CPor2-w3VwM"; - /*** 小程序消息模板--订单发送 */ - public static String SUBSCRIBE_MSG_ID_ORDERSEND = "5-rhM8h3x1W82tHCt18g9iXyGELyUKQtBDZiFjgItOo"; - /*** 小程序登录路径内的type */ - public static final String GRANT_TYPE = "authorization_code"; - - /*** redis内存储AccessToken的Key */ - public static final String ACCESS_TOKEN = "tall_wx_access_token_"; - - /*** 机器人消息类型--文本 */ - public static final String TEXT = "text"; - /*** 机器人消息类型--markdown */ - public static final String MARKDOWN = "markdown"; - - - /** - * 小程序订阅消息类型 - */ - public enum Packet_Notify_Type { - /** - * 消息类型 - */ - Buy(1, "购买"), - ReceiveSubscriBuyData(2, "订单发货"); - - public int value; - public String phase; - - Packet_Notify_Type(int value, String thePhase) { - this.value = value; - this.phase = thePhase; - } - } - - /*** 小程序appId */ - public static final Map APP_ID = new HashMap<>(); - static { - //默认小程序 - APP_ID.put("anyring", "wx356e01c7eb01d55d"); - //tall3小程序 - APP_ID.put("tall", "wxf72a76c2ea24a472"); - //赛跑小程序 - APP_ID.put("SP", "wx2ebb5cf926fe1ddb"); - //数钱小程序 - APP_ID.put("SQ", "wx55fa235267ca11e6"); - //拔河小程序 - APP_ID.put("BH", "wxd06d18fe7c75b498"); - //健康码小程序 - APP_ID.put("health", "wx2f9ef33e08053bbf"); - //企业微信 - APP_ID.put("enterprise", "wx808fa75921bd8f22"); - } - - /*** 小程序secret */ - public static final Map SECRET = new HashMap<>(); - static { - //默认小程序 - SECRET.put("anyring", "353033db85d4b5a35f05d1c0176a0cc6"); - //tall3小程序 - SECRET.put("tall", "5aa3fc421a149ec1e59a4a4f472e1223"); - //赛跑小程序 - SECRET.put("SP", "38e4425b8e3647015b439c6d38172b49"); - //数钱小程序 - SECRET.put("SQ", "d75a5a7538ff9c72f781738850817081"); - //拔河小程序 - SECRET.put("BH", "202ad7f3d95b0532948c667c468c9a56"); - //健康码小程序 - SECRET.put("health", "af90801c26bc177681b2c39a603605b9"); - //企业微信 - SECRET.put("enterprise", "8d2e95462bfeab363ee84776bc807859"); - } - - - public static void pageResult(String result) { - try { - if (StrUtil.isEmpty(result) || null == JacksonUtil.jsonToBean(result, WxBaseEntity.class)) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - } - -} +package com.ccsens.wechatutil.util; + +import cn.hutool.core.util.StrUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.po.WxBaseEntity; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * @author 逗 + */ +public class WxConstant { + + /*** 默认小程序 */ + public static final String ANYRING = "anyring"; + + + /*** 公众号获取accessToken */ + public static final String URL_GET_OAUTH2_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%1$s&secret=%2$s&code=%3$s&grant_type=authorization_code"; + /*** 公众号发送订阅消息 */ + public static final String MESSAGE_TEMPLATE_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%1$s"; + /** 创建二维码 */ + public static final String QR_CODE_CREATE = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={}"; + /**根据openId获取用户信息*/ + public static final String USER_INFO = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%1$s&openid=%2$s&lang=zh_CN"; + + + /*** 小程序登录路径 */ + public static final String MINI_PROGRAM_LOGIN = "https://api.weixin.qq.com/sns/jscode2session?appid=%1$s&secret=%2$s&js_code=%3$s&grant_type=%4$s"; + /*** 通过网页授权和openId获取用户信息 */ + public static final String URL_GET_OAUTH2_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%1$s&openid=%2$s"; + /*** 获取小程序码A */ + public static final String URL_GET_WX_CODE_A = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%1$s"; + /*** 获取小程序码B */ + public static final String URL_GET_WX_CODE_B = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%1$s"; + /*** 获取小程序码C */ + public static final String URL_GET_WX_CODE_C = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%1$s"; + /*** 小程序获取accessToken */ + public static final String URL_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%1$s&secret=%2$s"; + /*** 小程序发送订阅消息 */ + public static final String URL_SEND_SUBSCRIBE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%1$s"; + /*** 小程序消息模板--支付 */ + public static String SUBSCRIBE_MSG_ID_BUY = "bqdx4FW51G-JLU6HjL6LyvUbjpo4rFK6CPor2-w3VwM"; + /*** 小程序消息模板--订单发送 */ + public static String SUBSCRIBE_MSG_ID_ORDERSEND = "5-rhM8h3x1W82tHCt18g9iXyGELyUKQtBDZiFjgItOo"; + /*** 小程序登录路径内的type */ + public static final String GRANT_TYPE = "authorization_code"; + + /*** redis内存储AccessToken的Key */ + public static final String ACCESS_TOKEN = "tall_wx_access_token_"; + + /*** 机器人消息类型--文本 */ + public static final String TEXT = "text"; + /*** 机器人消息类型--markdown */ + public static final String MARKDOWN = "markdown"; + + + /** + * 小程序订阅消息类型 + */ + public enum Packet_Notify_Type { + /** + * 消息类型 + */ + Buy(1, "购买"), + ReceiveSubscriBuyData(2, "订单发货"); + + public int value; + public String phase; + + Packet_Notify_Type(int value, String thePhase) { + this.value = value; + this.phase = thePhase; + } + } + + /*** 小程序appId */ + public static final Map APP_ID = new HashMap<>(); + static { + //默认小程序 + APP_ID.put("anyring", "wx356e01c7eb01d55d"); + //tall3小程序 + APP_ID.put("tall", "wxf72a76c2ea24a472"); + //赛跑小程序 + APP_ID.put("SP", "wx2ebb5cf926fe1ddb"); + //数钱小程序 + APP_ID.put("SQ", "wx55fa235267ca11e6"); + //拔河小程序 + APP_ID.put("BH", "wxd06d18fe7c75b498"); + //健康码小程序 + APP_ID.put("health", "wx2f9ef33e08053bbf"); + //企业微信 + APP_ID.put("enterprise", "wx808fa75921bd8f22"); + } + + /*** 小程序secret */ + public static final Map SECRET = new HashMap<>(); + static { + //默认小程序 + SECRET.put("anyring", "353033db85d4b5a35f05d1c0176a0cc6"); + //tall3小程序 + SECRET.put("tall", "5aa3fc421a149ec1e59a4a4f472e1223"); + //赛跑小程序 + SECRET.put("SP", "38e4425b8e3647015b439c6d38172b49"); + //数钱小程序 + SECRET.put("SQ", "d75a5a7538ff9c72f781738850817081"); + //拔河小程序 + SECRET.put("BH", "202ad7f3d95b0532948c667c468c9a56"); + //健康码小程序 + SECRET.put("health", "af90801c26bc177681b2c39a603605b9"); + //企业微信 + SECRET.put("enterprise", "8d2e95462bfeab363ee84776bc807859"); + } + + + public static void pageResult(String result) { + try { + if (StrUtil.isEmpty(result) || null == JacksonUtil.jsonToBean(result, WxBaseEntity.class)) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + } + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java index 897f7df..07652d5 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java @@ -1,68 +1,68 @@ -package com.ccsens.wechatutil.wxcommon; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpRequest; -import com.ccsens.util.JacksonUtil; -import com.ccsens.util.RedisUtil; -import com.ccsens.util.WebConstant; -import com.ccsens.util.bean.wx.po.WxAccessToken; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.Resource; -import java.io.IOException; -/** - * @author 逗 - */ -@Slf4j -@Component -public class WxCommonUtil { - - @Resource - private RedisUtil redisUtil; - private static WxCommonUtil util; - - @PostConstruct - public void init(){ - util = this; - } - - - - /** - * 小程序获取Access_token - */ - public static String getAccessToken(String appId, String secret) throws BaseException { - log.info("获取accessToken,appid:{}", appId.substring(appId.length() - 4)); - Object obj = util.redisUtil.get(WxConstant.ACCESS_TOKEN + appId); - if (obj == null || StrUtil.isBlank((String) obj)) { - WxAccessToken wxAccessToken; - String url = String.format(WxConstant.URL_GET_ACCESS_TOKEN, appId, secret); - String response = HttpRequest.get(url).execute().body(); - log.info("getAccessToken: {}", response); - try { - if (StrUtil.isEmpty(response) || null == (wxAccessToken = JacksonUtil.jsonToBean(response, WxAccessToken.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - - if (null != wxAccessToken.getErrcode()) { - throw new BaseException(wxAccessToken.getErrcode(), wxAccessToken.getErrmsg()); - } - if (StrUtil.isEmpty(wxAccessToken.getAccessToken())) { - throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); - } - util.redisUtil.set(WebConstant.Wx.ACCESS_TOKEN + appId, wxAccessToken.getAccessToken(), WebConstant.Wx.EXPIRE_TIME); - log.info("存储access_token:{}", wxAccessToken.getAccessToken()); - return wxAccessToken.getAccessToken(); - } - log.info("读取reids的token:{}", obj); - return (String) obj; - } -} +package com.ccsens.wechatutil.wxcommon; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.RedisUtil; +import com.ccsens.util.WebConstant; +import com.ccsens.util.bean.wx.po.WxAccessToken; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.io.IOException; +/** + * @author 逗 + */ +@Slf4j +@Component +public class WxCommonUtil { + + @Resource + private RedisUtil redisUtil; + private static WxCommonUtil util; + + @PostConstruct + public void init(){ + util = this; + } + + + + /** + * 小程序获取Access_token + */ + public static String getAccessToken(String appId, String secret) throws BaseException { + log.info("获取accessToken,appid:{}", appId.substring(appId.length() - 4)); + Object obj = util.redisUtil.get(WxConstant.ACCESS_TOKEN + appId); + if (obj == null || StrUtil.isBlank((String) obj)) { + WxAccessToken wxAccessToken; + String url = String.format(WxConstant.URL_GET_ACCESS_TOKEN, appId, secret); + String response = HttpRequest.get(url).execute().body(); + log.info("getAccessToken: {}", response); + try { + if (StrUtil.isEmpty(response) || null == (wxAccessToken = JacksonUtil.jsonToBean(response, WxAccessToken.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + + if (null != wxAccessToken.getErrcode()) { + throw new BaseException(wxAccessToken.getErrcode(), wxAccessToken.getErrmsg()); + } + if (StrUtil.isEmpty(wxAccessToken.getAccessToken())) { + throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); + } + util.redisUtil.set(WebConstant.Wx.ACCESS_TOKEN + appId, wxAccessToken.getAccessToken(), WebConstant.Wx.EXPIRE_TIME); + log.info("存储access_token:{}", wxAccessToken.getAccessToken()); + return wxAccessToken.getAccessToken(); + } + log.info("读取reids的token:{}", obj); + return (String) obj; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java index c06d0ef..e066a7c 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java @@ -1,83 +1,83 @@ -package com.ccsens.wechatutil.wxenterprise; - -import cn.hutool.core.collection.CollectionUtil; -import com.ccsens.util.JacksonUtil; -import com.ccsens.wechatutil.bean.dto.WxMessageDto; -import com.ccsens.wechatutil.util.WxConstant; -import lombok.extern.slf4j.Slf4j; - -import java.io.*; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.StandardCharsets; - -/** - * @author 逗 - */ -@Slf4j -public class EnterpriseRobotUtil { - /** - * 微信机器人 - * @param robotMessage 机器人消息 - * @throws Exception 异常 - */ - public static void sendRobotInfo(WxMessageDto.RobotMessage robotMessage)throws Exception { - WxMessageDto.WxRobotVo wxRobotVo = new WxMessageDto.WxRobotVo(); - wxRobotVo.setMsgtype(robotMessage.getMsgType()); - if(WxConstant.TEXT.equalsIgnoreCase(robotMessage.getMsgType())){ - WxMessageDto.WxRobotText wxRobotText = new WxMessageDto.WxRobotText(); - wxRobotText.setContent(robotMessage.getContent()); - if(CollectionUtil.isNotEmpty(robotMessage.getMentionedList())){ - wxRobotText.setMentioned_list(robotMessage.getMentionedList()); - } - if(CollectionUtil.isNotEmpty(robotMessage.getMentionedMobileList())){ - wxRobotText.setMentioned_mobile_list(robotMessage.getMentionedMobileList()); - } - wxRobotVo.setText(wxRobotText); - }else if(WxConstant.MARKDOWN.equalsIgnoreCase(robotMessage.getMsgType())){ - WxMessageDto.WxRobotMarkdown wxRobotMarkdown = new WxMessageDto.WxRobotMarkdown(); - wxRobotMarkdown.setContent(robotMessage.getContent()); - wxRobotVo.setMarkdown(wxRobotMarkdown); - } - - String body = JacksonUtil.beanToJson(wxRobotVo); - log.info(body); - sendPost(robotMessage.getWebHook(),body); - } - - - public static void sendPost(String url, String param){ - PrintWriter out = null; - BufferedReader in = null; - try { - URL realUrl = new URL(url); - // 打开和URL之间的连接 - URLConnection conn = realUrl.openConnection(); - // 发送POST请求必须设置如下两行 - conn.setDoOutput(true); - conn.setDoInput(true); - // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8) - out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)); - // 发送请求参数 - out.print(param); - // flush输出流的缓冲 - out.flush(); - // 获取请求返回数据(设置返回数据编码为UTF-8) - in = new BufferedReader( - new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (out != null) { - out.close(); - } - if (in != null) { - in.close(); - } - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } -} +package com.ccsens.wechatutil.wxenterprise; + +import cn.hutool.core.collection.CollectionUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.wechatutil.bean.dto.WxMessageDto; +import com.ccsens.wechatutil.util.WxConstant; +import lombok.extern.slf4j.Slf4j; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; + +/** + * @author 逗 + */ +@Slf4j +public class EnterpriseRobotUtil { + /** + * 微信机器人 + * @param robotMessage 机器人消息 + * @throws Exception 异常 + */ + public static void sendRobotInfo(WxMessageDto.RobotMessage robotMessage)throws Exception { + WxMessageDto.WxRobotVo wxRobotVo = new WxMessageDto.WxRobotVo(); + wxRobotVo.setMsgtype(robotMessage.getMsgType()); + if(WxConstant.TEXT.equalsIgnoreCase(robotMessage.getMsgType())){ + WxMessageDto.WxRobotText wxRobotText = new WxMessageDto.WxRobotText(); + wxRobotText.setContent(robotMessage.getContent()); + if(CollectionUtil.isNotEmpty(robotMessage.getMentionedList())){ + wxRobotText.setMentioned_list(robotMessage.getMentionedList()); + } + if(CollectionUtil.isNotEmpty(robotMessage.getMentionedMobileList())){ + wxRobotText.setMentioned_mobile_list(robotMessage.getMentionedMobileList()); + } + wxRobotVo.setText(wxRobotText); + }else if(WxConstant.MARKDOWN.equalsIgnoreCase(robotMessage.getMsgType())){ + WxMessageDto.WxRobotMarkdown wxRobotMarkdown = new WxMessageDto.WxRobotMarkdown(); + wxRobotMarkdown.setContent(robotMessage.getContent()); + wxRobotVo.setMarkdown(wxRobotMarkdown); + } + + String body = JacksonUtil.beanToJson(wxRobotVo); + log.info(body); + sendPost(robotMessage.getWebHook(),body); + } + + + public static void sendPost(String url, String param){ + PrintWriter out = null; + BufferedReader in = null; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8) + out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)); + // 发送请求参数 + out.print(param); + // flush输出流的缓冲 + out.flush(); + // 获取请求返回数据(设置返回数据编码为UTF-8) + in = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxfiotexplorer/FiotExplorerSigninUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxfiotexplorer/FiotExplorerSigninUtil.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxfiotexplorer/FiotExplorerSigninUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxfiotexplorer/FiotExplorerSigninUtil.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxh5/H5SigninUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxh5/H5SigninUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxh5/H5SigninUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxh5/H5SigninUtil.java index 76b26c2..0032f1a 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxh5/H5SigninUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxh5/H5SigninUtil.java @@ -1,105 +1,105 @@ -package com.ccsens.wechatutil.wxh5; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpRequest; -import com.ccsens.util.DateUtil; -import com.ccsens.util.JacksonUtil; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.bean.po.WxOauth2AccessToken; -import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * @author 逗 - */ -@Slf4j -@Component -public class H5SigninUtil { - - private static String appIdH5; - private static String secretH5; - - @Value("${h5.appId:}") - public void setAppIdOfficial(String appIdOfficial) { - H5SigninUtil.appIdH5 = appIdOfficial; - } - @Value("${h5.secret:}") - public void setApplication(String secretOfficial) { - H5SigninUtil.secretH5 = secretOfficial; - } - - public static WxOauth2UserInfo signinByH5(String code) { - return signinByH5(code, appIdH5, secretH5); - } - - public static WxOauth2UserInfo signinByH5(String code, String appId, String secret) { - //获取accessToken - WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code, appId, secret); - //获取用户信息 - return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(), wxOauth2AccessToken.getOpenId()); - } - - /** - * 获取网页授权凭证 - * @param code OAuth2授权码 - * @return WxOauth2AccessToken - */ - private static WxOauth2AccessToken getOauth2AccessToken(String code, String appId, String secret) { - WxOauth2AccessToken wxOauth2AccessToken; - //拼接访问路径 - String url = String.format(WxConstant.URL_GET_OAUTH2_ACCESS_TOKEN, appId, secret, code); - //调用微信接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response, WxOauth2AccessToken.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2AccessToken.getErrcode()) { - throw new BaseException(wxOauth2AccessToken.getErrcode(), wxOauth2AccessToken.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) { - throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); - } - wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds()); - return wxOauth2AccessToken; - } - - /** - * 通过网页授权accessToken获取用户信息 - * @param accessToken 网页授权接口调用凭证 - * @param openId 用户标识 - * @return SNSUserInfo - */ - private static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) { - WxOauth2UserInfo wxOauth2UserInfo; - //拼接访问路径 - String url = String.format(WxConstant.URL_GET_OAUTH2_USER_INFO, accessToken, openId); - //调用微信接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2UserInfo.getErrcode()) { - throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { - throw new BaseException(WxCodeError.OPENID_ERROR); - } - return wxOauth2UserInfo; - } -} +package com.ccsens.wechatutil.wxh5; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.ccsens.util.DateUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.po.WxOauth2AccessToken; +import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * @author 逗 + */ +@Slf4j +@Component +public class H5SigninUtil { + + private static String appIdH5; + private static String secretH5; + + @Value("${h5.appId:}") + public void setAppIdOfficial(String appIdOfficial) { + H5SigninUtil.appIdH5 = appIdOfficial; + } + @Value("${h5.secret:}") + public void setApplication(String secretOfficial) { + H5SigninUtil.secretH5 = secretOfficial; + } + + public static WxOauth2UserInfo signinByH5(String code) { + return signinByH5(code, appIdH5, secretH5); + } + + public static WxOauth2UserInfo signinByH5(String code, String appId, String secret) { + //获取accessToken + WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code, appId, secret); + //获取用户信息 + return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(), wxOauth2AccessToken.getOpenId()); + } + + /** + * 获取网页授权凭证 + * @param code OAuth2授权码 + * @return WxOauth2AccessToken + */ + private static WxOauth2AccessToken getOauth2AccessToken(String code, String appId, String secret) { + WxOauth2AccessToken wxOauth2AccessToken; + //拼接访问路径 + String url = String.format(WxConstant.URL_GET_OAUTH2_ACCESS_TOKEN, appId, secret, code); + //调用微信接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response, WxOauth2AccessToken.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2AccessToken.getErrcode()) { + throw new BaseException(wxOauth2AccessToken.getErrcode(), wxOauth2AccessToken.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) { + throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); + } + wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds()); + return wxOauth2AccessToken; + } + + /** + * 通过网页授权accessToken获取用户信息 + * @param accessToken 网页授权接口调用凭证 + * @param openId 用户标识 + * @return SNSUserInfo + */ + private static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) { + WxOauth2UserInfo wxOauth2UserInfo; + //拼接访问路径 + String url = String.format(WxConstant.URL_GET_OAUTH2_USER_INFO, accessToken, openId); + //调用微信接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2UserInfo.getErrcode()) { + throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { + throw new BaseException(WxCodeError.OPENID_ERROR); + } + return wxOauth2UserInfo; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCodeUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniCodeUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCodeUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniCodeUtil.java index d2b3060..7a5eb8e 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCodeUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniCodeUtil.java @@ -1,159 +1,159 @@ -package com.ccsens.wechatutil.wxmini; - -import com.ccsens.util.HttpsUtil; -import com.ccsens.util.JacksonUtil; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.bean.dto.WechatCode; -import com.ccsens.wechatutil.bean.po.WxBaseEntity; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import com.ccsens.wechatutil.wxcommon.WxCommonUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.*; - -/** - * @author 逗 - */ -@Slf4j -@Component -public class MiniCodeUtil { - - private static String miniAppId; - private static String miniSecret; - - @Value("${mini.appId:}") - public void setMiniAppId(String miniAppId) { - MiniCodeUtil.miniAppId = miniAppId; - } - @Value("${mini.secret:}") - public void setMiniSecret(String miniSecret) { - MiniCodeUtil.miniSecret = miniSecret; - } - /** - * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * 使用默认appId - * @param wechatCodeA 传入参数 - * @param path 小程序码存储位置 - */ - public static void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path)throws Exception { - getWxCodeA(wechatCodeA,path,miniAppId,miniSecret); - } - - /** - * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * @param wechatCodeA 传入参数 - * @param path 小程序码存储位置 - * @param appId appId - * @param secret secret - */ - public static void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path, String appId, String secret) throws Exception { - String url = String.format(WxConstant.URL_GET_WX_CODE_A, WxCommonUtil.getAccessToken(appId, secret)); - log.info("调用生成二维码路径和accessToken:{}", url); - String postStr = JacksonUtil.beanToJson(wechatCodeA); - log.info("二维码的参数:{}", postStr); - //调用微信接口在指定位置生成图片 - httpWxCode(path, url, postStr); - } - - /** - * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 - * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 - * 使用默认appId - * @param wechatCodeB 传入参数 - * @param path 小程序码存储位置 - */ - public static void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path)throws Exception { - getWxCodeB(wechatCodeB,path,miniAppId, miniSecret); - } - - /** - * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 - * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 - * @param wechatCodeB 传入参数 - * @param path 小程序码存储位置 - * @param appId appId - * @param secret secret - */ - public static void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path, String appId, String secret) throws Exception { - String url = String.format(WxConstant.URL_GET_WX_CODE_B, WxCommonUtil.getAccessToken(appId, secret)); - log.info("调用生成二维码路径和accessToken:{}", url); - String postStr = JacksonUtil.beanToJson(wechatCodeB); - log.info("二维码的参数:{}", postStr); - //调用微信接口在指定位置生成图片 - httpWxCode(path, url, postStr); - } - - /** - * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * 使用默认appId - * @param wechatCodeC 传入参数 - * @param path 小程序码存储位置 - */ - public static void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path) throws Exception { - getWxCodeC(wechatCodeC,path,miniAppId, miniSecret); - } - - /** - * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * @param wechatCodeC 传入参数 - * @param path 小程序码存储位置 - * @param appId appId - * @param secret secret - */ - public static void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path, String appId, String secret) throws Exception { - String url = String.format(WxConstant.URL_GET_WX_CODE_C, WxCommonUtil.getAccessToken(appId, secret)); - log.info("调用生成二维码路径和accessToken:{}", url); - String postStr = JacksonUtil.beanToJson(wechatCodeC); - log.info("二维码的参数:{}", postStr); - //调用微信接口在指定位置生成图片 - httpWxCode(path, url, postStr); - } - - /** - * 调用微信的接口在指定位置生成二维码 - * @param path 图片储存位置 - * @param url 微信接口路径 - * @param postStr 传入参数 - * @throws Exception 异常 - */ - public static void httpWxCode(String path, String url, String postStr) throws Exception { - WxBaseEntity wxBaseEntity; - byte[] response = HttpsUtil.httpsRequestByte(url, "POST", postStr); - - if(response.length == 0){ - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - try { - if (null == (wxBaseEntity = JacksonUtil.jsonToBean(new String(response), WxBaseEntity.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - if (null != wxBaseEntity.getErrcode()) { - throw new BaseException(wxBaseEntity.getErrcode(), wxBaseEntity.getErrmsg()); - } - } catch (IOException e) { - // 从输入流读取返回内容 - File file = new File(path); - if (!file.getParentFile().exists()) { - file.getParentFile().mkdirs(); - } - InputStream inputStream = new ByteArrayInputStream(response); - BufferedInputStream bis = new BufferedInputStream(inputStream); - OutputStream os = new FileOutputStream(file); - int len; - byte[] arr = new byte[1024]; - while ((len = bis.read(arr)) != -1) - { - os.write(arr, 0, len); - os.flush(); - } - os.close(); - } - } -} +package com.ccsens.wechatutil.wxmini; + +import com.ccsens.util.HttpsUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.dto.WechatCode; +import com.ccsens.wechatutil.bean.po.WxBaseEntity; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.io.*; + +/** + * @author 逗 + */ +@Slf4j +@Component +public class MiniCodeUtil { + + private static String miniAppId; + private static String miniSecret; + + @Value("${mini.appId:}") + public void setMiniAppId(String miniAppId) { + MiniCodeUtil.miniAppId = miniAppId; + } + @Value("${mini.secret:}") + public void setMiniSecret(String miniSecret) { + MiniCodeUtil.miniSecret = miniSecret; + } + /** + * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * 使用默认appId + * @param wechatCodeA 传入参数 + * @param path 小程序码存储位置 + */ + public static void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path)throws Exception { + getWxCodeA(wechatCodeA,path,miniAppId,miniSecret); + } + + /** + * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * @param wechatCodeA 传入参数 + * @param path 小程序码存储位置 + * @param appId appId + * @param secret secret + */ + public static void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path, String appId, String secret) throws Exception { + String url = String.format(WxConstant.URL_GET_WX_CODE_A, WxCommonUtil.getAccessToken(appId, secret)); + log.info("调用生成二维码路径和accessToken:{}", url); + String postStr = JacksonUtil.beanToJson(wechatCodeA); + log.info("二维码的参数:{}", postStr); + //调用微信接口在指定位置生成图片 + httpWxCode(path, url, postStr); + } + + /** + * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 + * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 + * 使用默认appId + * @param wechatCodeB 传入参数 + * @param path 小程序码存储位置 + */ + public static void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path)throws Exception { + getWxCodeB(wechatCodeB,path,miniAppId, miniSecret); + } + + /** + * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 + * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 + * @param wechatCodeB 传入参数 + * @param path 小程序码存储位置 + * @param appId appId + * @param secret secret + */ + public static void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path, String appId, String secret) throws Exception { + String url = String.format(WxConstant.URL_GET_WX_CODE_B, WxCommonUtil.getAccessToken(appId, secret)); + log.info("调用生成二维码路径和accessToken:{}", url); + String postStr = JacksonUtil.beanToJson(wechatCodeB); + log.info("二维码的参数:{}", postStr); + //调用微信接口在指定位置生成图片 + httpWxCode(path, url, postStr); + } + + /** + * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * 使用默认appId + * @param wechatCodeC 传入参数 + * @param path 小程序码存储位置 + */ + public static void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path) throws Exception { + getWxCodeC(wechatCodeC,path,miniAppId, miniSecret); + } + + /** + * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * @param wechatCodeC 传入参数 + * @param path 小程序码存储位置 + * @param appId appId + * @param secret secret + */ + public static void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path, String appId, String secret) throws Exception { + String url = String.format(WxConstant.URL_GET_WX_CODE_C, WxCommonUtil.getAccessToken(appId, secret)); + log.info("调用生成二维码路径和accessToken:{}", url); + String postStr = JacksonUtil.beanToJson(wechatCodeC); + log.info("二维码的参数:{}", postStr); + //调用微信接口在指定位置生成图片 + httpWxCode(path, url, postStr); + } + + /** + * 调用微信的接口在指定位置生成二维码 + * @param path 图片储存位置 + * @param url 微信接口路径 + * @param postStr 传入参数 + * @throws Exception 异常 + */ + public static void httpWxCode(String path, String url, String postStr) throws Exception { + WxBaseEntity wxBaseEntity; + byte[] response = HttpsUtil.httpsRequestByte(url, "POST", postStr); + + if(response.length == 0){ + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + try { + if (null == (wxBaseEntity = JacksonUtil.jsonToBean(new String(response), WxBaseEntity.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + if (null != wxBaseEntity.getErrcode()) { + throw new BaseException(wxBaseEntity.getErrcode(), wxBaseEntity.getErrmsg()); + } + } catch (IOException e) { + // 从输入流读取返回内容 + File file = new File(path); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + InputStream inputStream = new ByteArrayInputStream(response); + BufferedInputStream bis = new BufferedInputStream(inputStream); + OutputStream os = new FileOutputStream(file); + int len; + byte[] arr = new byte[1024]; + while ((len = bis.read(arr)) != -1) + { + os.write(arr, 0, len); + os.flush(); + } + os.close(); + } + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCustomSendUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniCustomSendUtil.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCustomSendUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniCustomSendUtil.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniEncryptionAndDecryptionUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniEncryptionAndDecryptionUtil.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniEncryptionAndDecryptionUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniEncryptionAndDecryptionUtil.java diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessageUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessageUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessageUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessageUtil.java index cd071c5..83c07df 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessageUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessageUtil.java @@ -1,91 +1,91 @@ -package com.ccsens.wechatutil.wxmini; - -import com.ccsens.util.HttpsUtil; -import com.ccsens.wechatutil.bean.dto.WxMessageDto; -import com.ccsens.wechatutil.util.WxConstant; -import com.ccsens.wechatutil.wxcommon.WxCommonUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.util.List; - -/** - * @author 逗 - */ -@Slf4j -@Component -public class MiniMessageUtil { - - private static String miniAppId; - private static String miniSecret; - - @Value("${mini.appId:}") - public void setMiniAppId(String miniAppId) { - MiniMessageUtil.miniAppId = miniAppId; - } - @Value("${mini.secret:}") - public void setMiniSecret(String miniSecret) { - MiniMessageUtil.miniSecret = miniSecret; - } - - /** - * 发送微信订阅消息 (使用默认appId) - * - * @param notifyType 通知类型 - * @param toUser 用户openid - * @param page 小程序页面路径 - * @param params 小程序模板数据 - */ - public static boolean sendSubcribeMsg(WxConstant.Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { - return sendSubcribeMsg(notifyType,toUser,page,params,miniAppId,miniSecret); - } - - /** - * 发送微信订阅消息 - * - * @param notifyType 通知类型 - * @param toUser 用户openid - * @param page 小程序页面路径 - * @param params 小程序模板数据 - */ - public static boolean sendSubcribeMsg(WxConstant.Packet_Notify_Type notifyType, String toUser, String page, List params,String appId, String secret) throws Exception { - String ret = null; - String url = String.format(WxConstant.URL_SEND_SUBSCRIBE_MESSAGE, WxCommonUtil.getAccessToken(appId, secret)); - switch (notifyType) { - //订单支付成功通知 - case Buy: { - WxMessageDto.SubscribeEntity t = new WxMessageDto.SubscribeEntity<>(); - t.setTouser(toUser); - t.setTemplate_id(WxConstant.SUBSCRIBE_MSG_ID_BUY); - t.setPage(page); - t.setData(new WxMessageDto.ReceiveSubscriBuyData(params)); - System.out.println(com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); - ret = HttpsUtil.httpsRequest(url, "POST", com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); - break; - } - //订单发货 - case ReceiveSubscriBuyData: { - WxMessageDto.SubscribeEntity t = new WxMessageDto.SubscribeEntity<>(); - t.setTouser(toUser); - t.setTemplate_id(WxConstant.SUBSCRIBE_MSG_ID_ORDERSEND); - t.setData(new WxMessageDto.ReceiveSubscriOrderSendData(params)); - System.out.println(com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); - ret = HttpsUtil.httpsRequest(url, "POST", com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); - break; - } - default: { - break; - } - } - //ok: {"errcode":0,"errmsg":"ok"} - //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} - System.out.println("Send Subscribe Message:" + ret); - String errCode = com.ccsens.wechatutil.payutil.JacksonUtil.getJsonValue(ret, "errcode"); - System.out.println(errCode); - return "0".equals(errCode); - } - - - -} +package com.ccsens.wechatutil.wxmini; + +import com.ccsens.util.HttpsUtil; +import com.ccsens.wechatutil.bean.dto.WxMessageDto; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @author 逗 + */ +@Slf4j +@Component +public class MiniMessageUtil { + + private static String miniAppId; + private static String miniSecret; + + @Value("${mini.appId:}") + public void setMiniAppId(String miniAppId) { + MiniMessageUtil.miniAppId = miniAppId; + } + @Value("${mini.secret:}") + public void setMiniSecret(String miniSecret) { + MiniMessageUtil.miniSecret = miniSecret; + } + + /** + * 发送微信订阅消息 (使用默认appId) + * + * @param notifyType 通知类型 + * @param toUser 用户openid + * @param page 小程序页面路径 + * @param params 小程序模板数据 + */ + public static boolean sendSubcribeMsg(WxConstant.Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { + return sendSubcribeMsg(notifyType,toUser,page,params,miniAppId,miniSecret); + } + + /** + * 发送微信订阅消息 + * + * @param notifyType 通知类型 + * @param toUser 用户openid + * @param page 小程序页面路径 + * @param params 小程序模板数据 + */ + public static boolean sendSubcribeMsg(WxConstant.Packet_Notify_Type notifyType, String toUser, String page, List params,String appId, String secret) throws Exception { + String ret = null; + String url = String.format(WxConstant.URL_SEND_SUBSCRIBE_MESSAGE, WxCommonUtil.getAccessToken(appId, secret)); + switch (notifyType) { + //订单支付成功通知 + case Buy: { + WxMessageDto.SubscribeEntity t = new WxMessageDto.SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(WxConstant.SUBSCRIBE_MSG_ID_BUY); + t.setPage(page); + t.setData(new WxMessageDto.ReceiveSubscriBuyData(params)); + System.out.println(com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + break; + } + //订单发货 + case ReceiveSubscriBuyData: { + WxMessageDto.SubscribeEntity t = new WxMessageDto.SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(WxConstant.SUBSCRIBE_MSG_ID_ORDERSEND); + t.setData(new WxMessageDto.ReceiveSubscriOrderSendData(params)); + System.out.println(com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + break; + } + default: { + break; + } + } + //ok: {"errcode":0,"errmsg":"ok"} + //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} + System.out.println("Send Subscribe Message:" + ret); + String errCode = com.ccsens.wechatutil.payutil.JacksonUtil.getJsonValue(ret, "errcode"); + System.out.println(errCode); + return "0".equals(errCode); + } + + + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java index f744c1f..6c0af31 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java @@ -1,81 +1,81 @@ -package com.ccsens.wechatutil.wxmini; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpRequest; -import com.ccsens.util.HttpsUtil; -import com.ccsens.util.JacksonUtil; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.bean.dto.WechatCode; -import com.ccsens.wechatutil.bean.dto.WxMessageDto; -import com.ccsens.wechatutil.bean.po.MiniProgramUser; -import com.ccsens.wechatutil.bean.po.WxBaseEntity; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import com.ccsens.wechatutil.wxcommon.WxCommonUtil; -import com.ccsens.wechatutil.wxofficial.OfficialAccountSigninUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.*; -import java.util.List; - -/** - * @author 逗 - */ -@Slf4j -@Component -public class MiniSigninUtil { - - private static String miniAppId; - private static String miniSecret; - - @Value("${mini.appId:}") - public void setMiniAppId(String miniAppId) { - MiniSigninUtil.miniAppId = miniAppId; - } - @Value("${mini.secret:}") - public void setMiniSecret(String miniSecret) { - MiniSigninUtil.miniSecret = miniSecret; - } - - - /** - * 小程序登录 - * -- 从配置文件中获取默认appId - * 配置文件内的名称 h5.appId: 和 h5.secret: - * @param code code - * @return 返回当前用户的openId等 - */ - public static MiniProgramUser signinByMini(String code) { - return signinByMini(code, miniAppId, miniSecret); - } - /** - * 小程序登录 -- 传入appId - * @param code code - * @param appId appId - * @param secret secret - * @return 返回当前用户的openId等 - */ - public static MiniProgramUser signinByMini(String code, String appId, String secret) { - MiniProgramUser wxUser; - //拼接wx的访问的路径 - String url = String.format(WxConstant.MINI_PROGRAM_LOGIN, appId, secret, code, WxConstant.GRANT_TYPE); - //调用微信的接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxUser = JacksonUtil.jsonToBean(response, MiniProgramUser.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxUser.getErrcode()) { - throw new BaseException(wxUser.getErrcode(), wxUser.getErrmsg()); - } - return wxUser; - } - - -} +package com.ccsens.wechatutil.wxmini; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.ccsens.util.HttpsUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.dto.WechatCode; +import com.ccsens.wechatutil.bean.dto.WxMessageDto; +import com.ccsens.wechatutil.bean.po.MiniProgramUser; +import com.ccsens.wechatutil.bean.po.WxBaseEntity; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import com.ccsens.wechatutil.wxofficial.OfficialAccountSigninUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.io.*; +import java.util.List; + +/** + * @author 逗 + */ +@Slf4j +@Component +public class MiniSigninUtil { + + private static String miniAppId; + private static String miniSecret; + + @Value("${mini.appId:}") + public void setMiniAppId(String miniAppId) { + MiniSigninUtil.miniAppId = miniAppId; + } + @Value("${mini.secret:}") + public void setMiniSecret(String miniSecret) { + MiniSigninUtil.miniSecret = miniSecret; + } + + + /** + * 小程序登录 + * -- 从配置文件中获取默认appId + * 配置文件内的名称 h5.appId: 和 h5.secret: + * @param code code + * @return 返回当前用户的openId等 + */ + public static MiniProgramUser signinByMini(String code) { + return signinByMini(code, miniAppId, miniSecret); + } + /** + * 小程序登录 -- 传入appId + * @param code code + * @param appId appId + * @param secret secret + * @return 返回当前用户的openId等 + */ + public static MiniProgramUser signinByMini(String code, String appId, String secret) { + MiniProgramUser wxUser; + //拼接wx的访问的路径 + String url = String.format(WxConstant.MINI_PROGRAM_LOGIN, appId, secret, code, WxConstant.GRANT_TYPE); + //调用微信的接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxUser = JacksonUtil.jsonToBean(response, MiniProgramUser.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxUser.getErrcode()) { + throw new BaseException(wxUser.getErrcode(), wxUser.getErrmsg()); + } + return wxUser; + } + + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountMessageUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountMessageUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountMessageUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountMessageUtil.java index 9525d65..7a86829 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountMessageUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountMessageUtil.java @@ -1,123 +1,123 @@ -package com.ccsens.wechatutil.wxofficial; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.util.StrUtil; -import com.ccsens.util.*; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.bean.dto.WxTemplateMessage; -import com.ccsens.wechatutil.bean.po.WxBaseEntity; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import com.ccsens.wechatutil.wxcommon.WxCommonUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.util.List; - -/** - * @author 逗 - */ -@Slf4j -@Component -public class OfficialAccountMessageUtil { - - - private static String appIdOfficial; - private static String secretOfficial; - - @Value("${official.appId:}") - public void setAppIdOfficial(String appIdOfficial) { - OfficialAccountMessageUtil.appIdOfficial = appIdOfficial; - } - @Value("${official.secret:}") - public void setApplication(String secretOfficial) { - OfficialAccountMessageUtil.secretOfficial = secretOfficial; - } - -// public static void officialMessage() { -// WxTemplateMessage message = new WxTemplateMessage(); -// -// String url = String.format(WechatUtil.PROJECT_URL, 123); -//// WxTemplateMessage.MiniProgram miniProgram = new WxTemplateMessage.MiniProgram(WechatUtil.appid,url); -// -//// message.setMiniprogram(miniProgram); -// -// -// message.setTemplate_id(WxGzhUtil.Template.TASK_FINISH.templateId); -//// WxTemplateMessage.TemplateData data = new WxTemplateMessage.TemplateData(); -//// data.setFirst(new WxTemplateMessage.TemplateSettings("测试项目")); -//// data.setKeyword1(new WxTemplateMessage.TemplateSettings("测试任务")); -//// data.setKeyword2(new WxTemplateMessage.TemplateSettings(DateUtil.now())); -// -// Map data = new HashMap<>(); -// data.put("zzz", new WxTemplateMessage.TemplateSettings("测试fzz")); -// data.put("first", new WxTemplateMessage.TemplateSettings("测试first")); -// data.put("keyword1", new WxTemplateMessage.TemplateSettings("测试keyword1")); -// data.put("keyword2", new WxTemplateMessage.TemplateSettings("测试keyword2")); -// data.put("remark", new WxTemplateMessage.TemplateSettings("测试remark")); -// -// message.setData(data); -// -// List openIdList = new ArrayList<>(); -// openIdList.add("oALvgw-_70_fXptB97xJpYDhMJRU"); -// -// officialMessage(message,openIdList); -// } - - /** - * 公众号发送订阅消息(使用默认openId) - * @param templateMessage 消息 - * @param openIdList 推送的用户 - */ - public static void officialMessage(WxTemplateMessage templateMessage, List openIdList) { - officialMessage(templateMessage,openIdList,appIdOfficial, secretOfficial); - } - - /** - * 公众号发送订阅消息(传入openId) - * @param templateMessage 消息 - * @param openIdList 推送的用户 - */ - public static void officialMessage(WxTemplateMessage templateMessage, List openIdList,String appId, String secret) { - //判断是否有openId - if (CollectionUtil.isNotEmpty(openIdList)) { - openIdList.forEach(openid -> { - //拼接访问路径 - sendMsg(appId, secret, templateMessage); - }); - } - } - - /** - * 公众号发送订阅消息(传入openId) - * @param templateMessages 消息 - */ - public static void officialMessage(List templateMessages, String appId, String secret) { - //判断是否有openId - if (CollectionUtil.isEmpty(templateMessages)) { - return; - } - templateMessages.forEach(templateMessage -> sendMsg(appId, secret, templateMessage)); - } - - private static void sendMsg(String appId, String secret, WxTemplateMessage templateMessage) { - //拼接访问路径 - String url = String.format(WxConstant.MESSAGE_TEMPLATE_SEND, WxCommonUtil.getAccessToken(appId, secret)); - //调用微信接口 - String response = RestTemplateUtil.postBody(url, templateMessage); - log.info("url: {}\nresponse: {}", url, response); - WxBaseEntity wxBaseEntity; - try { - if (StrUtil.isEmpty(response) || null == (wxBaseEntity = JacksonUtil.jsonToBean(response, WxBaseEntity.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxBaseEntity.getErrcode()) { - throw new BaseException(wxBaseEntity.getErrcode(), wxBaseEntity.getErrmsg()); - } - } -} +package com.ccsens.wechatutil.wxofficial; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +import com.ccsens.util.*; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.dto.WxTemplateMessage; +import com.ccsens.wechatutil.bean.po.WxBaseEntity; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.List; + +/** + * @author 逗 + */ +@Slf4j +@Component +public class OfficialAccountMessageUtil { + + + private static String appIdOfficial; + private static String secretOfficial; + + @Value("${official.appId:}") + public void setAppIdOfficial(String appIdOfficial) { + OfficialAccountMessageUtil.appIdOfficial = appIdOfficial; + } + @Value("${official.secret:}") + public void setApplication(String secretOfficial) { + OfficialAccountMessageUtil.secretOfficial = secretOfficial; + } + +// public static void officialMessage() { +// WxTemplateMessage message = new WxTemplateMessage(); +// +// String url = String.format(WechatUtil.PROJECT_URL, 123); +//// WxTemplateMessage.MiniProgram miniProgram = new WxTemplateMessage.MiniProgram(WechatUtil.appid,url); +// +//// message.setMiniprogram(miniProgram); +// +// +// message.setTemplate_id(WxGzhUtil.Template.TASK_FINISH.templateId); +//// WxTemplateMessage.TemplateData data = new WxTemplateMessage.TemplateData(); +//// data.setFirst(new WxTemplateMessage.TemplateSettings("测试项目")); +//// data.setKeyword1(new WxTemplateMessage.TemplateSettings("测试任务")); +//// data.setKeyword2(new WxTemplateMessage.TemplateSettings(DateUtil.now())); +// +// Map data = new HashMap<>(); +// data.put("zzz", new WxTemplateMessage.TemplateSettings("测试fzz")); +// data.put("first", new WxTemplateMessage.TemplateSettings("测试first")); +// data.put("keyword1", new WxTemplateMessage.TemplateSettings("测试keyword1")); +// data.put("keyword2", new WxTemplateMessage.TemplateSettings("测试keyword2")); +// data.put("remark", new WxTemplateMessage.TemplateSettings("测试remark")); +// +// message.setData(data); +// +// List openIdList = new ArrayList<>(); +// openIdList.add("oALvgw-_70_fXptB97xJpYDhMJRU"); +// +// officialMessage(message,openIdList); +// } + + /** + * 公众号发送订阅消息(使用默认openId) + * @param templateMessage 消息 + * @param openIdList 推送的用户 + */ + public static void officialMessage(WxTemplateMessage templateMessage, List openIdList) { + officialMessage(templateMessage,openIdList,appIdOfficial, secretOfficial); + } + + /** + * 公众号发送订阅消息(传入openId) + * @param templateMessage 消息 + * @param openIdList 推送的用户 + */ + public static void officialMessage(WxTemplateMessage templateMessage, List openIdList,String appId, String secret) { + //判断是否有openId + if (CollectionUtil.isNotEmpty(openIdList)) { + openIdList.forEach(openid -> { + //拼接访问路径 + sendMsg(appId, secret, templateMessage); + }); + } + } + + /** + * 公众号发送订阅消息(传入openId) + * @param templateMessages 消息 + */ + public static void officialMessage(List templateMessages, String appId, String secret) { + //判断是否有openId + if (CollectionUtil.isEmpty(templateMessages)) { + return; + } + templateMessages.forEach(templateMessage -> sendMsg(appId, secret, templateMessage)); + } + + private static void sendMsg(String appId, String secret, WxTemplateMessage templateMessage) { + //拼接访问路径 + String url = String.format(WxConstant.MESSAGE_TEMPLATE_SEND, WxCommonUtil.getAccessToken(appId, secret)); + //调用微信接口 + String response = RestTemplateUtil.postBody(url, templateMessage); + log.info("url: {}\nresponse: {}", url, response); + WxBaseEntity wxBaseEntity; + try { + if (StrUtil.isEmpty(response) || null == (wxBaseEntity = JacksonUtil.jsonToBean(response, WxBaseEntity.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxBaseEntity.getErrcode()) { + throw new BaseException(wxBaseEntity.getErrcode(), wxBaseEntity.getErrmsg()); + } + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java similarity index 97% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java index c663245..5bbd495 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java +++ b/util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java @@ -1,141 +1,141 @@ -package com.ccsens.wechatutil.wxofficial; - -import cn.hutool.core.lang.Console; -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpRequest; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; -import com.ccsens.util.DateUtil; -import com.ccsens.util.JacksonUtil; -import com.ccsens.util.exception.BaseException; -import com.ccsens.util.exception.BusinessException; -import com.ccsens.util.exception.WxException; -import com.ccsens.wechatutil.bean.po.WxOauth2AccessToken; -import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import com.ccsens.wechatutil.wxcommon.WxCommonUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -/** - * @author 逗 - */ -@Slf4j -@Component -public class OfficialAccountSigninUtil { - - private static String appIdOfficial; - private static String secretOfficial; - - @Value("${official.appId:}") - public void setAppIdOfficial(String appIdOfficial) { - OfficialAccountSigninUtil.appIdOfficial = appIdOfficial; - } - @Value("${official.secret:}") - public void setApplication(String secretOfficial) { - OfficialAccountSigninUtil.secretOfficial = secretOfficial; - } - - public static WxOauth2UserInfo signinByH5(String code) { - return signinByH5(code, appIdOfficial, secretOfficial); - } - - public static WxOauth2UserInfo signinByH5(String code, String appId, String secret) { - //获取accessToken - WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code, appId, secret); - //获取用户信息 - return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(), wxOauth2AccessToken.getOpenId()); - } - - /** - * 获取网页授权凭证 - * @param code OAuth2授权码 - * @return WxOauth2AccessToken - */ - private static WxOauth2AccessToken getOauth2AccessToken(String code, String appId, String secret) { - WxOauth2AccessToken wxOauth2AccessToken; - //拼接访问路径 - String url = String.format(WxConstant.URL_GET_OAUTH2_ACCESS_TOKEN, appId, secret, code); - //调用微信接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response, WxOauth2AccessToken.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2AccessToken.getErrcode()) { - throw new BaseException(wxOauth2AccessToken.getErrcode(), wxOauth2AccessToken.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) { - throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); - } - wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds()); - return wxOauth2AccessToken; - } - - /** - * 通过网页授权accessToken获取用户信息 - * @param accessToken 网页授权接口调用凭证 - * @param openId 用户标识 - * @return SNSUserInfo - */ - private static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) { - WxOauth2UserInfo wxOauth2UserInfo; - //拼接访问路径 - String url = String.format(WxConstant.URL_GET_OAUTH2_USER_INFO, accessToken, openId); - //调用微信接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2UserInfo.getErrcode()) { - throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { - throw new BaseException(WxCodeError.OPENID_ERROR); - } - return wxOauth2UserInfo; - } - - /** - * 根据openid查询用户信息 - * @param openid - * @return - * @throws BaseException - */ - public static WxOauth2UserInfo getUserInfo(String openid,String appId, String secret) throws BaseException, IOException { - WxOauth2UserInfo wxOauth2UserInfo; - - String url = String.format(WxConstant.USER_INFO, WxCommonUtil.getAccessToken(appId,secret),openid); - String response = HttpRequest.get(url).execute().body(); - Console.log("请求路径:{}, 返回结果:{}", url, response); -// pageResponse(response); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2UserInfo.getErrcode()) { - throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { - throw new BaseException(WxCodeError.OPENID_ERROR); - } - return wxOauth2UserInfo; - } -} +package com.ccsens.wechatutil.wxofficial; + +import cn.hutool.core.lang.Console; +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.ccsens.util.DateUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.util.exception.BusinessException; +import com.ccsens.util.exception.WxException; +import com.ccsens.wechatutil.bean.po.WxOauth2AccessToken; +import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +/** + * @author 逗 + */ +@Slf4j +@Component +public class OfficialAccountSigninUtil { + + private static String appIdOfficial; + private static String secretOfficial; + + @Value("${official.appId:}") + public void setAppIdOfficial(String appIdOfficial) { + OfficialAccountSigninUtil.appIdOfficial = appIdOfficial; + } + @Value("${official.secret:}") + public void setApplication(String secretOfficial) { + OfficialAccountSigninUtil.secretOfficial = secretOfficial; + } + + public static WxOauth2UserInfo signinByH5(String code) { + return signinByH5(code, appIdOfficial, secretOfficial); + } + + public static WxOauth2UserInfo signinByH5(String code, String appId, String secret) { + //获取accessToken + WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code, appId, secret); + //获取用户信息 + return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(), wxOauth2AccessToken.getOpenId()); + } + + /** + * 获取网页授权凭证 + * @param code OAuth2授权码 + * @return WxOauth2AccessToken + */ + private static WxOauth2AccessToken getOauth2AccessToken(String code, String appId, String secret) { + WxOauth2AccessToken wxOauth2AccessToken; + //拼接访问路径 + String url = String.format(WxConstant.URL_GET_OAUTH2_ACCESS_TOKEN, appId, secret, code); + //调用微信接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response, WxOauth2AccessToken.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2AccessToken.getErrcode()) { + throw new BaseException(wxOauth2AccessToken.getErrcode(), wxOauth2AccessToken.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) { + throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); + } + wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds()); + return wxOauth2AccessToken; + } + + /** + * 通过网页授权accessToken获取用户信息 + * @param accessToken 网页授权接口调用凭证 + * @param openId 用户标识 + * @return SNSUserInfo + */ + private static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) { + WxOauth2UserInfo wxOauth2UserInfo; + //拼接访问路径 + String url = String.format(WxConstant.URL_GET_OAUTH2_USER_INFO, accessToken, openId); + //调用微信接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2UserInfo.getErrcode()) { + throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { + throw new BaseException(WxCodeError.OPENID_ERROR); + } + return wxOauth2UserInfo; + } + + /** + * 根据openid查询用户信息 + * @param openid + * @return + * @throws BaseException + */ + public static WxOauth2UserInfo getUserInfo(String openid,String appId, String secret) throws BaseException, IOException { + WxOauth2UserInfo wxOauth2UserInfo; + + String url = String.format(WxConstant.USER_INFO, WxCommonUtil.getAccessToken(appId,secret),openid); + String response = HttpRequest.get(url).execute().body(); + Console.log("请求路径:{}, 返回结果:{}", url, response); +// pageResponse(response); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2UserInfo.getErrcode()) { + throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { + throw new BaseException(WxCodeError.OPENID_ERROR); + } + return wxOauth2UserInfo; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialQrCodeUtil.java b/util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialQrCodeUtil.java similarity index 100% rename from wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialQrCodeUtil.java rename to util_wechat/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialQrCodeUtil.java diff --git a/wechatutil/src/main/resources/application-common.yml b/util_wechat/src/main/resources/application-common.yml similarity index 100% rename from wechatutil/src/main/resources/application-common.yml rename to util_wechat/src/main/resources/application-common.yml diff --git a/wechatutil/src/main/resources/application-dev.yml b/util_wechat/src/main/resources/application-dev.yml similarity index 100% rename from wechatutil/src/main/resources/application-dev.yml rename to util_wechat/src/main/resources/application-dev.yml diff --git a/wechatutil/src/main/resources/application-prod.yml b/util_wechat/src/main/resources/application-prod.yml similarity index 95% rename from wechatutil/src/main/resources/application-prod.yml rename to util_wechat/src/main/resources/application-prod.yml index 6e4e23d..190d744 100644 --- a/wechatutil/src/main/resources/application-prod.yml +++ b/util_wechat/src/main/resources/application-prod.yml @@ -1,50 +1,50 @@ -server: - port: 7130 - servlet: - context-path: -spring: - snowflake: - datacenterId: 1 - workerId: 1 - application: - name: wechatutil - datasource: - type: com.alibaba.druid.pool.DruidDataSource - rabbitmq: - host: 127.0.0.1 - password: 111111 - port: 5672 - username: admin - redis: - database: 0 - host: 127.0.0.1 - jedis: - pool: - max-active: 200 - max-idle: 10 - max-wait: -1ms - min-idle: 0 -# password: '' - password: 'areowqr!@43ef' - port: 6379 - timeout: 1000ms -swagger: - enable: false -eureka: - instance: - # www.tall.wiki -# ip-address: 140.143.228.3 -# ip-address: 81.70.54.64 - ip-address: 121.36.3.207 - -gatewayUrl: https://www.tall.wiki/gateway/ -notGatewayUrl: https://www.tall.wiki/ -smsCode: 1 -wx: - prefixUrl: https://www.tall.wiki/wxconfigurer-api/ -file: - path: /home/cloud/tall/uploads/ - domain: https://www.tall.wiki/gateway/wechatutil/ - imgDomain: https://www.tall.wiki/gateway/wechatutil/uploads - queryPowerAddress: /power/query - +server: + port: 7130 + servlet: + context-path: +spring: + snowflake: + datacenterId: 1 + workerId: 1 + application: + name: wechatutil + datasource: + type: com.alibaba.druid.pool.DruidDataSource + rabbitmq: + host: 127.0.0.1 + password: 111111 + port: 5672 + username: admin + redis: + database: 0 + host: 127.0.0.1 + jedis: + pool: + max-active: 200 + max-idle: 10 + max-wait: -1ms + min-idle: 0 +# password: '' + password: 'areowqr!@43ef' + port: 6379 + timeout: 1000ms +swagger: + enable: false +eureka: + instance: + # www.tall.wiki +# ip-address: 140.143.228.3 +# ip-address: 81.70.54.64 + ip-address: 121.36.3.207 + +gatewayUrl: https://www.tall.wiki/gateway/ +notGatewayUrl: https://www.tall.wiki/ +smsCode: 1 +wx: + prefixUrl: https://www.tall.wiki/wxconfigurer-api/ +file: + path: /home/cloud/tall/uploads/ + domain: https://www.tall.wiki/gateway/wechatutil/ + imgDomain: https://www.tall.wiki/gateway/wechatutil/uploads + queryPowerAddress: /power/query + diff --git a/wechatutil/src/main/resources/application-test.yml b/util_wechat/src/main/resources/application-test.yml similarity index 95% rename from wechatutil/src/main/resources/application-test.yml rename to util_wechat/src/main/resources/application-test.yml index c26d239..50116a7 100644 --- a/wechatutil/src/main/resources/application-test.yml +++ b/util_wechat/src/main/resources/application-test.yml @@ -1,50 +1,50 @@ -server: - port: 7130 - servlet: - context-path: -spring: - snowflake: - datacenterId: 1 - workerId: 1 - application: - name: wechatutil - datasource: - type: com.alibaba.druid.pool.DruidDataSource - rabbitmq: - host: 49.233.89.188 - password: 111111 - port: 5672 - username: admin - redis: - database: 0 - host: 127.0.0.1 - jedis: - pool: - max-active: 200 - max-idle: 10 - max-wait: -1ms - min-idle: 0 - password: '' - port: 6379 - timeout: 1000ms -swagger: - enable: false -eureka: - instance: - ip-address: 192.168.0.99 -# ip-address: 49.233.89.188 -#gatewayUrl: http://192.168.0.99/gateway/ -#notGatewayUrl: http://192.168.0.99/ -gatewayUrl: https://test.tall.wiki/gateway/ -notGatewayUrl: https://test.tall.wiki/ -smsCode: 0 -wx: - prefixUrl: https://www.tall.wiki/wxconfigurer-api/ -file: - path: /home/cloud/tall/uploads/ - domain: https://test.tall.wiki/gateway/wechatutil - imgDomain: https://test.tall.wiki/gateway/wechatutil/uploads - queryPowerAddress: /power/query -#file: -# domain: http://192.168.0.99/gateway/tall/v1.0/ +server: + port: 7130 + servlet: + context-path: +spring: + snowflake: + datacenterId: 1 + workerId: 1 + application: + name: wechatutil + datasource: + type: com.alibaba.druid.pool.DruidDataSource + rabbitmq: + host: 49.233.89.188 + password: 111111 + port: 5672 + username: admin + redis: + database: 0 + host: 127.0.0.1 + jedis: + pool: + max-active: 200 + max-idle: 10 + max-wait: -1ms + min-idle: 0 + password: '' + port: 6379 + timeout: 1000ms +swagger: + enable: false +eureka: + instance: + ip-address: 192.168.0.99 +# ip-address: 49.233.89.188 +#gatewayUrl: http://192.168.0.99/gateway/ +#notGatewayUrl: http://192.168.0.99/ +gatewayUrl: https://test.tall.wiki/gateway/ +notGatewayUrl: https://test.tall.wiki/ +smsCode: 0 +wx: + prefixUrl: https://www.tall.wiki/wxconfigurer-api/ +file: + path: /home/cloud/tall/uploads/ + domain: https://test.tall.wiki/gateway/wechatutil + imgDomain: https://test.tall.wiki/gateway/wechatutil/uploads + queryPowerAddress: /power/query +#file: +# domain: http://192.168.0.99/gateway/tall/v1.0/ # imgDomain: http://192.168.0.99/gateway/tall/v1.0/uploads \ No newline at end of file diff --git a/wechatutil/src/main/resources/application.yml b/util_wechat/src/main/resources/application.yml similarity index 100% rename from wechatutil/src/main/resources/application.yml rename to util_wechat/src/main/resources/application.yml diff --git a/wechatutil/src/main/resources/business.yml b/util_wechat/src/main/resources/business.yml similarity index 100% rename from wechatutil/src/main/resources/business.yml rename to util_wechat/src/main/resources/business.yml diff --git a/wechatutil/src/main/resources/druid-dev.yml b/util_wechat/src/main/resources/druid-dev.yml similarity index 100% rename from wechatutil/src/main/resources/druid-dev.yml rename to util_wechat/src/main/resources/druid-dev.yml diff --git a/wechatutil/src/main/resources/druid-prod.yml b/util_wechat/src/main/resources/druid-prod.yml similarity index 97% rename from wechatutil/src/main/resources/druid-prod.yml rename to util_wechat/src/main/resources/druid-prod.yml index 2441b0b..92be190 100644 --- a/wechatutil/src/main/resources/druid-prod.yml +++ b/util_wechat/src/main/resources/druid-prod.yml @@ -1,34 +1,34 @@ -spring: - datasource: - druid: - connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 - driverClassName: com.mysql.cj.jdbc.Driver - dynamicUrl: jdbc:mysql://127.0.0.1:3306/${schema} - filterExclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' - filterName: druidFilter - filterProfileEnable: true - filterUrlPattern: /* - filters: stat,wall - initialSize: 5 - maxActive: 20 - maxPoolPreparedStatementPerConnectionSize: 20 - maxWait: 60000 - minEvictableIdleTimeMillis: 300000 - minIdle: 5 -# password: 7cdefb88e0b8c8a401b66a83ee0cf80387461268074d1c3dcb146ab485318633 - password: - poolPreparedStatements: true - servletLogSlowSql: true - servletLoginPassword: 111111 - servletLoginUsername: druid - servletName: druidServlet - servletResetEnable: true - servletUrlMapping: /druid/* - testOnBorrow: false - testOnReturn: false - testWhileIdle: true - timeBetweenEvictionRunsMillis: 60000 - url: jdbc:mysql://127.0.0.1/tall3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true - username: root - validationQuery: SELECT 1 FROM DUAL +spring: + datasource: + druid: + connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 + driverClassName: com.mysql.cj.jdbc.Driver + dynamicUrl: jdbc:mysql://127.0.0.1:3306/${schema} + filterExclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' + filterName: druidFilter + filterProfileEnable: true + filterUrlPattern: /* + filters: stat,wall + initialSize: 5 + maxActive: 20 + maxPoolPreparedStatementPerConnectionSize: 20 + maxWait: 60000 + minEvictableIdleTimeMillis: 300000 + minIdle: 5 +# password: 7cdefb88e0b8c8a401b66a83ee0cf80387461268074d1c3dcb146ab485318633 + password: + poolPreparedStatements: true + servletLogSlowSql: true + servletLoginPassword: 111111 + servletLoginUsername: druid + servletName: druidServlet + servletResetEnable: true + servletUrlMapping: /druid/* + testOnBorrow: false + testOnReturn: false + testWhileIdle: true + timeBetweenEvictionRunsMillis: 60000 + url: jdbc:mysql://127.0.0.1/tall3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true + username: root + validationQuery: SELECT 1 FROM DUAL env: CCSENS_HEALTH \ No newline at end of file diff --git a/wechatutil/src/main/resources/druid-test.yml b/util_wechat/src/main/resources/druid-test.yml similarity index 97% rename from wechatutil/src/main/resources/druid-test.yml rename to util_wechat/src/main/resources/druid-test.yml index f3bbd3c..70f6bdd 100644 --- a/wechatutil/src/main/resources/druid-test.yml +++ b/util_wechat/src/main/resources/druid-test.yml @@ -1,35 +1,35 @@ -spring: - datasource: - druid: - connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 - driverClassName: com.mysql.cj.jdbc.Driver - dynamicUrl: jdbc:mysql://localhost:3306/${schema} - filterExclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' - filterName: druidFilter - filterProfileEnable: true - filterUrlPattern: /* - filters: stat,wall - initialSize: 5 - maxActive: 20 - maxPoolPreparedStatementPerConnectionSize: 20 - maxWait: 60000 - minEvictableIdleTimeMillis: 300000 - minIdle: 5 -# password: - password: 68073a279b399baa1fa12cf39bfbb65bfc1480ffee7b659ccc81cf19be8c4473 - poolPreparedStatements: true - servletLogSlowSql: true - servletLoginPassword: 111111 - servletLoginUsername: druid - servletName: druidServlet - servletResetEnable: true - servletUrlMapping: /druid/* - testOnBorrow: false - testOnReturn: false - testWhileIdle: true - timeBetweenEvictionRunsMillis: 60000 -# url: jdbc:mysql://127.0.0.1/tall?useUnicode=true&characterEncoding=UTF-8 - url: jdbc:mysql://test.tall.wiki/tall3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true - username: root - validationQuery: SELECT 1 FROM DUAL +spring: + datasource: + druid: + connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 + driverClassName: com.mysql.cj.jdbc.Driver + dynamicUrl: jdbc:mysql://localhost:3306/${schema} + filterExclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' + filterName: druidFilter + filterProfileEnable: true + filterUrlPattern: /* + filters: stat,wall + initialSize: 5 + maxActive: 20 + maxPoolPreparedStatementPerConnectionSize: 20 + maxWait: 60000 + minEvictableIdleTimeMillis: 300000 + minIdle: 5 +# password: + password: 68073a279b399baa1fa12cf39bfbb65bfc1480ffee7b659ccc81cf19be8c4473 + poolPreparedStatements: true + servletLogSlowSql: true + servletLoginPassword: 111111 + servletLoginUsername: druid + servletName: druidServlet + servletResetEnable: true + servletUrlMapping: /druid/* + testOnBorrow: false + testOnReturn: false + testWhileIdle: true + timeBetweenEvictionRunsMillis: 60000 +# url: jdbc:mysql://127.0.0.1/tall?useUnicode=true&characterEncoding=UTF-8 + url: jdbc:mysql://test.tall.wiki/tall3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true + username: root + validationQuery: SELECT 1 FROM DUAL env: CCSENS_TALL \ No newline at end of file diff --git a/wechatutil/src/main/resources/logback-spring.xml b/util_wechat/src/main/resources/logback-spring.xml similarity index 100% rename from wechatutil/src/main/resources/logback-spring.xml rename to util_wechat/src/main/resources/logback-spring.xml diff --git a/wechatutil/src/main/resources/mybatis/mybatis-config.xml b/util_wechat/src/main/resources/mybatis/mybatis-config.xml similarity index 100% rename from wechatutil/src/main/resources/mybatis/mybatis-config.xml rename to util_wechat/src/main/resources/mybatis/mybatis-config.xml diff --git a/wechatutil/src/test/java/com/ccsens/wechatutil/WechatutilApplicationTests.java b/util_wechat/src/test/java/com/ccsens/wechatutil/WechatutilApplicationTests.java similarity index 100% rename from wechatutil/src/test/java/com/ccsens/wechatutil/WechatutilApplicationTests.java rename to util_wechat/src/test/java/com/ccsens/wechatutil/WechatutilApplicationTests.java