cloud-server-activity/src/main/java/com/dsh/activity/controller/BenefitVideoController.java
@@ -69,15 +69,16 @@ @ApiImplicitParam(value = "视频分类id", name = "classificationId", dataType = "int", required = true), @ApiImplicitParam(value = "页码,首页1", name = "pageSize", dataType = "int", required = true), @ApiImplicitParam(value = "页条数", name = "pageNo", dataType = "int", required = true), @ApiImplicitParam(value = "搜索内容", name = "search", dataType = "string", required = false), @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....") }) public ResultUtil<List<BenefitsVideosListVo>> queryBenefitsVideosList(Integer classificationId, Integer pageSize, Integer pageNo){ public ResultUtil<List<BenefitsVideosListVo>> queryBenefitsVideosList(Integer classificationId, String search, Integer pageSize, Integer pageNo){ try { Integer uid = tokenUtil.getUserIdFormRedis(); if(null == uid){ return ResultUtil.tokenErr(); } List<BenefitsVideosListVo> benefitsVideosListVos = bfvService.queryBenefitsVideosList(uid, classificationId, pageSize, pageNo); List<BenefitsVideosListVo> benefitsVideosListVos = bfvService.queryBenefitsVideosList(uid, classificationId, search, pageSize, pageNo); return ResultUtil.success(benefitsVideosListVos); }catch (Exception e){ e.printStackTrace(); cloud-server-activity/src/main/java/com/dsh/activity/controller/UserCouponController.java
@@ -114,6 +114,35 @@ } @ResponseBody @PostMapping("/api/coupon/querySiteCouponList") @ApiOperation(value = "获取场地支付页面可用优惠券列表", tags = {"APP-预约场地", ""}) @ApiImplicitParams({ @ApiImplicitParam(value = "场地id", name = "siteId", dataType = "int", required = true), @ApiImplicitParam(value = "支付金额", name = "price", dataType = "double", required = true), @ApiImplicitParam(value = "经度", name = "lon", dataType = "string", required = true), @ApiImplicitParam(value = "纬度", name = "lat", dataType = "string", required = true), @ApiImplicitParam(name = "Authorization", value = "用户token(Bearer +token)", required = true, dataType = "String", paramType = "header", defaultValue = "Bearer eyJhbGciOiJIUzUxMiJ9.....") }) public ResultUtil<List<CouponListVo>> querySiteCouponList(Integer siteId, Double price, String lon, String lat){ try { Integer uid = tokenUtil.getUserIdFormRedis(); if(null == uid){ return ResultUtil.tokenErr(); } List<CouponListVo> listVos = userCouponService.querySiteCouponList(uid, siteId, price, lon, lat); return ResultUtil.success(listVos); }catch (Exception e){ e.printStackTrace(); return ResultUtil.runErr(); } } /** * 根据id获取用户优惠券数据 * @param id @@ -130,6 +159,22 @@ return null; } } /** * 修改优惠券数据 * @param userCoupon */ @ResponseBody @PostMapping("/userCoupon/updateUserCoupon") public void updateUserCoupon(@RequestBody UserCoupon userCoupon){ try { userCouponService.updateById(userCoupon); }catch (Exception e){ e.printStackTrace(); } } cloud-server-activity/src/main/java/com/dsh/activity/feignclient/course/CourseClient.java
@@ -4,6 +4,8 @@ import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; /** * @author zhibing.pu * @date 2023/7/12 9:57 @@ -18,4 +20,13 @@ */ @PostMapping("/course/queryCourseById") Course queryCourseById(Integer id); /** * 根据名称获取课程数据 * @param name * @return */ @PostMapping("/course/queryCourseByName") List<Course> queryCourseByName(String name); } cloud-server-activity/src/main/java/com/dsh/activity/feignclient/other/SiteClient.java
New file @@ -0,0 +1,22 @@ package com.dsh.activity.feignclient.other; import com.dsh.activity.feignclient.other.model.Site; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; /** * @author zhibing.pu * @Date 2023/7/18 11:38 */ @FeignClient("mb-cloud-other") public interface SiteClient { /** * 根据id获取场地数据 * @param id * @return */ @PostMapping("/site/querySiteById") Site querySiteById(Integer id); } cloud-server-activity/src/main/java/com/dsh/activity/feignclient/other/model/Site.java
New file @@ -0,0 +1,85 @@ package com.dsh.activity.feignclient.other.model; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; /** * @author zhibing.pu * @Date 2023/7/18 11:39 */ @Data public class Site { private Integer id; /** * 门店id */ private Integer storeId; /** * 场地名称 */ private String name; /** * 场地类型id */ private Integer siteTypeId; /** * 城市管理员id */ private Integer cityManagerId; /** * 省 */ private String province; /** * 省编号 */ private String provinceCode; /** * 市名称 */ private String city; /** * 市编号 */ private String cityCode; /** * 预约开始时间 */ private String appointmentStartTime; /** * 预约结束时间 */ private String appointmentEndTime; /** * 现金价格(x/半小时) */ private Double cashPrice; /** * 玩湃币价格(x/半小时) */ private Integer playPaiCoin; /** * 场地责任险有效期 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date insuranceEndTime; /** * 场地责任险图片 */ private String insuranceImg; /** * 消防应急管理方案 */ private String managementPlan; /** * 状态(1=正常,2=冻结,3=删除) */ private Integer state; /** * 添加时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date insertTime; } cloud-server-activity/src/main/java/com/dsh/activity/mapper/BenefitsVideosMapper.java
@@ -28,5 +28,5 @@ * @return */ List<Map<String, Object>> queryBenefitsVideosList(@Param("uid") Integer uid, @Param("classificationId") Integer classificationId, @Param("pageSize") Integer pageSize, @Param("pageNo") Integer pageNo); @Param("ids") List<Integer> ids, @Param("pageSize") Integer pageSize, @Param("pageNo") Integer pageNo); } cloud-server-activity/src/main/java/com/dsh/activity/service/BenefitsVideosService.java
@@ -38,7 +38,7 @@ * @return * @throws Exception */ List<BenefitsVideosListVo> queryBenefitsVideosList(Integer uid, Integer classificationId, Integer pageSize, Integer pageNo) throws Exception; List<BenefitsVideosListVo> queryBenefitsVideosList(Integer uid, Integer classificationId, String search, Integer pageSize, Integer pageNo) throws Exception; /** cloud-server-activity/src/main/java/com/dsh/activity/service/UserCouponService.java
@@ -27,5 +27,17 @@ */ List<CouponListVo> queryAvailableCouponList(Integer uid, Integer coursePackageId, Double price, String lon, String lat) throws Exception; /** * 获取预约场地支付页面可用优惠券列表 * @param siteId * @param price * @return * @throws Exception */ List<CouponListVo> querySiteCouponList(Integer uid, Integer siteId, Double price, String lon, String lat) throws Exception; List<CouponPackageResp> queryCouponPackagesList(Integer uid, CouponPackageReq req); } cloud-server-activity/src/main/java/com/dsh/activity/service/impl/BenefitsVideosServiceImpl.java
@@ -99,9 +99,14 @@ @Override public List<BenefitsVideosListVo> queryBenefitsVideosList(Integer uid, Integer classificationId, Integer pageSize, Integer pageNo) throws Exception { public List<BenefitsVideosListVo> queryBenefitsVideosList(Integer uid, Integer classificationId, String search, Integer pageSize, Integer pageNo) throws Exception { pageSize = (pageSize - 1) * pageNo; List<Map<String, Object>> benefitsVideos = this.baseMapper.queryBenefitsVideosList(uid, classificationId, pageSize, pageNo); List<Integer> ids = null; if(ToolUtil.isNotEmpty(search)){ List<Course> courses = courseClient.queryCourseByName(search); ids = courses.stream().map(Course::getId).collect(Collectors.toList()); } List<Map<String, Object>> benefitsVideos = this.baseMapper.queryBenefitsVideosList(uid, classificationId, ids, pageSize, pageNo); List<BenefitsVideosListVo> lists = new ArrayList<>(); for (Map<String, Object> benefitsVideo : benefitsVideos) { Integer id = Integer.valueOf(benefitsVideo.get("id").toString()); cloud-server-activity/src/main/java/com/dsh/activity/service/impl/UserCouponServiceImpl.java
@@ -12,7 +12,9 @@ import com.dsh.activity.feignclient.account.model.AppUser; import com.dsh.activity.feignclient.course.CoursePackageClient; import com.dsh.activity.feignclient.course.model.CoursePackage; import com.dsh.activity.feignclient.other.SiteClient; import com.dsh.activity.feignclient.other.StoreClient; import com.dsh.activity.feignclient.other.model.Site; import com.dsh.activity.feignclient.other.model.StoreDetailOfCourse; import com.dsh.activity.mapper.CouponMapper; import com.dsh.activity.mapper.CouponStoreMapper; @@ -66,6 +68,13 @@ @Resource private CouponStoreMapper csMapper; @Resource private SiteClient siteClient; /** * 获取购买课程可用优惠券列表 * @param uid @@ -117,6 +126,59 @@ return listVos; } /** * 获取预约场地可用优惠券列表 * @param siteId * @param price * @return * @throws Exception */ @Override public List<CouponListVo> querySiteCouponList(Integer uid, Integer siteId, Double price, String lon, String lat) throws Exception { Site site = siteClient.querySiteById(siteId); Integer storeId = site.getStoreId(); Map<String, String> geocode = gdMapGeocodingUtil.geocode(lon, lat); String provinceCode = geocode.get("provinceCode"); String cityCode = geocode.get("cityCode"); List<Map<String, Object>> userCoupons = this.baseMapper.queryAvailableCouponList(uid, storeId, provinceCode, cityCode); List<CouponListVo> listVos = new ArrayList<>(); for (Map<String, Object> userCoupon : userCoupons) { Integer type = Integer.valueOf(userCoupon.get("type").toString()); CouponListVo couponListVo = new CouponListVo(); couponListVo.setId(Long.valueOf(userCoupon.get("id").toString())); couponListVo.setName(userCoupon.get("name").toString()); couponListVo.setType(type); couponListVo.setEffectiveTime(userCoupon.get("endTime").toString()); String content = userCoupon.get("content").toString(); if (type == 1) {//满减{"num1":1,"num2":1} JSONObject jsonObject = JSON.parseObject(content); Double num1 = jsonObject.getDouble("conditionalAmount"); if(price.compareTo(num1) <= 0){ continue; } couponListVo.setUseCondition("满" + num1 + "元可用"); couponListVo.setFavorable(jsonObject.getDouble("deductionAmount") + "元"); } if (type == 2) {//代金券{"num1":1} JSONObject jsonObject = JSON.parseObject(content); Double num1 = jsonObject.getDouble("deductionAmount"); if(price.compareTo(num1) <= 0){ continue; } couponListVo.setUseCondition(""); couponListVo.setFavorable(num1 + "元"); } if (type == 3) {//体验券{"num1":1} JSONObject jsonObject = JSON.parseObject(content); couponListVo.setUseCondition(""); couponListVo.setFavorable(jsonObject.getString("experienceName")); } listVos.add(couponListVo); } return listVos; } @Override public List<CouponPackageResp> queryCouponPackagesList(Integer uid, CouponPackageReq req) { List<CouponPackageResp> respList = new ArrayList<>(); cloud-server-activity/src/main/resources/mapper/BenefitsVideosMapper.xml
@@ -14,6 +14,12 @@ <if test="null != classificationId"> and benefitsVideoClassificationId = #{classificationId} </if> <if test="null != ids"> and courseId in <foreach collection="ids" item="item" index="index" separator="," open="(" close=")"> #{item} </foreach> </if> order by insertTime desc) union all @@ -27,6 +33,12 @@ <if test="null != classificationId"> and benefitsVideoClassificationId = #{classificationId} </if> <if test="null != ids"> and courseId in <foreach collection="ids" item="item" index="index" separator="," open="(" close=")"> #{item} </foreach> </if> order by insertTime desc) ) as a limit #{pageSize}, #{pageNo} </select> cloud-server-course/src/main/java/com/dsh/course/controller/CourseController.java
@@ -259,4 +259,21 @@ return null; } } /** * 根据名称获取数据 * @param name * @return */ @ResponseBody @PostMapping("/course/queryCourseByName") public List<TCourse> queryCourseByName(@RequestBody String name){ try { return courseService.list(new QueryWrapper<TCourse>().like("name", name).eq("state", 1)); }catch (Exception e){ e.printStackTrace(); return null; } } } cloud-server-course/src/main/java/com/dsh/course/entity/TCourse.java
@@ -25,8 +25,6 @@ @Accessors(chain = true) @TableName("t_course") public class TCourse { /** * 主键 */ cloud-server-other/pom.xml
@@ -96,6 +96,16 @@ <artifactId>geodesy</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>com.alipay.sdk</groupId> <artifactId>alipay-sdk-java</artifactId> <version>4.8.10.ALL</version> </dependency> </dependencies> <build> cloud-server-other/src/main/java/com/dsh/other/controller/SiteController.java
@@ -1,19 +1,27 @@ package com.dsh.other.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.dsh.other.entity.Site; import com.dsh.other.entity.SiteBooking; import com.dsh.other.model.*; import com.dsh.other.service.ISiteBookingService; import com.dsh.other.service.ISiteService; import com.dsh.other.service.ISiteTypeService; import com.dsh.other.util.PayMoneyUtil; import com.dsh.other.util.ResultUtil; import com.dsh.other.util.TokenUtil; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.Date; import java.util.List; import java.util.Map; /** * @author zhibing.pu @@ -28,6 +36,15 @@ @Autowired private ISiteTypeService siteTypeService; @Autowired private TokenUtil tokenUtil; @Autowired private PayMoneyUtil payMoneyUtil; @Autowired private ISiteBookingService siteBookingService; @@ -71,10 +88,12 @@ @ApiOperation(value = "获取场地详情", tags = {"用户—预约场地"}) @ApiImplicitParams({ @ApiImplicitParam(value = "场地id", name = "id", dataType = "int", required = true), @ApiImplicitParam(value = "经度", name = "lon", dataType = "string", required = false), @ApiImplicitParam(value = "纬度", name = "lat", dataType = "string", required = false), }) public ResultUtil<QuerySiteInfoVo> querySiteInfo(Integer id){ public ResultUtil<QuerySiteInfoVo> querySiteInfo(Integer id, String lon, String lat){ try { QuerySiteInfoVo querySiteInfoVo = siteService.querySiteInfo(id); QuerySiteInfoVo querySiteInfoVo = siteService.querySiteInfo(id, lon, lat); return ResultUtil.success(querySiteInfoVo); }catch (Exception e){ e.printStackTrace(); @@ -100,4 +119,104 @@ return ResultUtil.runErr(); } } /** * 根据id获取数据 * @param id * @return */ @ResponseBody @PostMapping("/site/querySiteById") public Site querySiteById(@RequestBody Integer id){ try { return siteService.getById(id); }catch (Exception e){ e.printStackTrace(); return null; } } public ResultUtil reservationSite(ReservationSite reservationSite){ try { Integer uid = tokenUtil.getUserIdFormRedis(); if(null == uid){ return ResultUtil.tokenErr(); } }catch (Exception e){ e.printStackTrace(); return ResultUtil.runErr(); } } /** * 购买课程微信支付回调 * @param request * @param response */ @ResponseBody @PostMapping("/base/site/weChatPaymentSiteCallback") public void weChatPaymentSiteCallback(HttpServletRequest request, HttpServletResponse response){ try { Map<String, String> map = payMoneyUtil.weixinpayCallback(request); if(null != map){ String code = map.get("out_trade_no"); String transaction_id = map.get("transaction_id"); String result = map.get("result"); SiteBooking siteBooking = siteBookingService.getOne(new QueryWrapper<SiteBooking>().eq("orderNo", code).eq("state", 1)); if(siteBooking.getStatus() == 0){ siteBooking.setPayTime(new Date()); siteBooking.setStatus(1); siteBooking.setPayOrderNo(transaction_id); siteBookingService.updateById(siteBooking); } PrintWriter out = response.getWriter(); out.write(result); out.flush(); out.close(); } }catch (Exception e){ e.printStackTrace(); } } /** * 购买课程支付宝回调 * @param request * @param response */ @ResponseBody @PostMapping("/base/site/aliPaymentSiteCallback") public void aliPaymentSiteCallback(HttpServletRequest request, HttpServletResponse response){ try { Map<String, String> map = payMoneyUtil.alipayCallback(request); if(null != map){ String code = map.get("out_trade_no"); String trade_no = map.get("trade_no"); SiteBooking siteBooking = siteBookingService.getOne(new QueryWrapper<SiteBooking>().eq("orderNo", code).eq("state", 1)); if(siteBooking.getStatus() == 0){ siteBooking.setPayTime(new Date()); siteBooking.setStatus(1); siteBooking.setPayOrderNo(trade_no); siteBookingService.updateById(siteBooking); } PrintWriter out = response.getWriter(); out.write("success"); out.flush(); out.close(); } }catch (Exception e){ e.printStackTrace(); } } } cloud-server-other/src/main/java/com/dsh/other/entity/Site.java
@@ -64,12 +64,12 @@ * 预约开始时间 */ @TableField("appointmentStartTime") private Date appointmentStartTime; private String appointmentStartTime; /** * 预约结束时间 */ @TableField("appointmentEndTime") private Date appointmentEndTime; private String appointmentEndTime; /** * 现金价格(x/半小时) */ cloud-server-other/src/main/java/com/dsh/other/entity/SiteBooking.java
@@ -21,6 +21,11 @@ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 业务流水号 */ @TableField("orderNo") private String orderNo; /** * 省 */ @TableField("province") @@ -51,6 +56,11 @@ @TableField("siteId") private Integer siteId; /** * 用户id */ @TableField("appUserId") private Integer appUserId; /** * 预约开始时间 */ @TableField("startTime") @@ -71,10 +81,40 @@ @TableField("phone") private String phone; /** * 支付方式(1=微信,2=支付宝,3=玩湃比,4=手动支付) */ @TableField("payType") private Integer payType; /** * 支付时间 */ @TableField("payTime") private Date payTime; /** * 支付金额 */ @TableField("payMoney") private Double payMoney; /** * 优惠券id */ @TableField("userCouponId") private Long userCouponId; /** * 状态(0=待支付,1=待核销,2=已到店,3=已完成,4=已过期,5=已取消) */ @TableField("status") private Integer status; /** * 第三方支付流水号 */ @TableField("payOrderNo") private String payOrderNo; /** * 手动支付操作用户id */ @TableField("payUserId") private Integer payUserId; /** * 取消用户id */ @@ -96,6 +136,11 @@ @TableField("cancelTime") private Date cancelTime; /** * 第三方取消退款流水号 */ @TableField("refundOrderNo") private String refundOrderNo; /** * 状态(1=正常,2=冻结,3=删除) */ @TableField("state") cloud-server-other/src/main/java/com/dsh/other/entity/SiteLock.java
New file @@ -0,0 +1,38 @@ package com.dsh.other.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; /** * @author zhibing.pu * @Date 2023/7/18 14:41 */ @Data @TableName("t_site_lock") public class SiteLock { /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 场地id */ @TableField("siteId") private Integer siteId; /** * 锁定开始时间 */ @TableField("startTime") private Date startTime; /** * 锁定结束时间 */ @TableField("endTime") private Date endTime; } cloud-server-other/src/main/java/com/dsh/other/feignclient/account/AppUserClient.java
New file @@ -0,0 +1,29 @@ package com.dsh.other.feignclient.account; import com.dsh.other.feignclient.account.model.AppUser; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; /** * @author zhibing.pu * @date 2023/6/29 14:09 */ @FeignClient("mb-cloud-account") public interface AppUserClient { /** * 根据用户id获取用户信息 * @param appUserId * @return */ @PostMapping("/base/appUser/queryAppUser") AppUser queryAppUser(Integer appUserId); /** * 修改用户信息 * @param appUser */ @PostMapping("/base/appUser/updateAppUser") void updateAppUser(AppUser appUser); } cloud-server-other/src/main/java/com/dsh/other/feignclient/account/model/AppUser.java
New file @@ -0,0 +1,114 @@ package com.dsh.other.feignclient.account.model; import lombok.Data; import java.util.Date; /** * @author zhibing.pu * @date 2023/6/29 14:09 */ @Data public class AppUser { private Integer id; /** * 编号 */ private String code; /** * 姓名 */ private String name; /** * 电话 */ private String phone; /** * 密码 */ private String password; /** * 生日 */ private Date birthday; /** * 性别(1=男,2=女) */ private Integer gender; /** * 身高 */ private Double height; /** * 体重 */ private Double weight; /** * bmi健康值 */ private Double bmi; /** * 身份证号 */ private String idCard; /** * 微信openid */ private String openid; /** * 省 */ private String province; /** * 省编号 */ private String provinceCode; /** * 市 */ private String city; /** * 市编号 */ private String cityCode; /** * 是否是年度会员(0=否,1=是) */ private Integer isVip; /** * 会员有效期 */ private Date vipEndTime; /** * 会员等级id */ private Integer viplevelId; /** * 推荐用户id */ private Integer referralUserId; /** * 销售员id */ private Integer salesmanUserId; /** * 状态(1=正常,2=冻结,3=删除) */ private Integer state; /** * 剩余积分 */ private Integer integral; /** * 玩湃币 */ private Integer playPaiCoins; /** * 用户头像 */ private String headImg; /** * 添加时间 */ private Date insertTime; } cloud-server-other/src/main/java/com/dsh/other/feignclient/activity/CouponClient.java
New file @@ -0,0 +1,22 @@ package com.dsh.other.feignclient.activity; import com.dsh.other.feignclient.activity.model.Coupon; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; /** * @author zhibing.pu * @date 2023/7/5 21:06 */ @FeignClient("mb-cloud-activity") public interface CouponClient { /** * 根据id获取优惠券 * @param id * @return */ @PostMapping("/coupon/queryCouponById") Coupon queryCouponById(Integer id); } cloud-server-other/src/main/java/com/dsh/other/feignclient/activity/UserCouponClient.java
New file @@ -0,0 +1,29 @@ package com.dsh.other.feignclient.activity; import com.dsh.other.feignclient.activity.model.UserCoupon; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; /** * @author zhibing.pu * @date 2023/7/5 20:54 */ @FeignClient("mb-cloud-activity") public interface UserCouponClient { /** * 根据id获取用户优惠券数据 * @param id * @return */ @PostMapping("/userCoupon/queryUserCouponById") UserCoupon queryUserCouponById(Long id); /** * 修改优惠券数据 * @param userCoupon */ @PostMapping("/userCoupon/updateUserCoupon") void updateUserCoupon(UserCoupon userCoupon); } cloud-server-other/src/main/java/com/dsh/other/feignclient/activity/model/Coupon.java
New file @@ -0,0 +1,115 @@ package com.dsh.other.feignclient.activity.model; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author zhibing.pu * @date 2023/7/5 21:06 */ @Data public class Coupon { private Integer id; /** * 优惠券名称 */ private String name; /** * 优惠券类型(1=满减券,2=代金券,3=体验券) */ private Integer type; /** * 优惠券规则JSON */ private String content; /** * 优惠券说明 */ private String illustrate; /** * 发放方式(1=积分购买,2=注册赠送,3=自动发券) */ private Integer distributionMethod; /** * 兑换方式(1=积分,2=积分+现金) */ private Integer redemptionMethod; /** * 所需现金 */ private BigDecimal cash; /** * 所属积分 */ private BigDecimal integral; /** * 用户人群(1=全部用户,2=年度会员,3=已有学员用户) */ private Integer userPopulation; /** * 发放数量 */ private Integer quantityIssued; /** * 限领数量 */ private Integer pickUpQuantity; /** * 开始时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date startTime; /** * 结束时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date endTime; /** * 使用范围(1=全国,2=指定城市,3=指定门店) */ private Integer useScope; /** * 省 */ private String province; /** * 省编号 */ private String provinceCode; /** * 市 */ private String city; /** * 市编号 */ private String cityCode; /** * 审核状态(1=待审核,2=已通过,3=已拒绝) */ private Integer auditStatus; /** * 审核人id */ private Integer auditUserId; /** * 审核备注 */ private String auditRemark; /** * 状态(1=未开始,2=已开始,3=已结束,4=已取消) */ private Integer status; /** * 状态(1=正常,2=冻结,3=删除) */ private Integer state; /** * 添加时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date insertTime; } cloud-server-other/src/main/java/com/dsh/other/feignclient/activity/model/UserCoupon.java
New file @@ -0,0 +1,41 @@ package com.dsh.other.feignclient.activity.model; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; /** * @author zhibing.pu * @date 2023/7/5 20:55 */ @Data public class UserCoupon { private Long id; /** * 优惠券id */ private Integer couponId; /** * 用户id */ private Integer userId; /** * 状态(1=待核销,2=已核销) */ private Integer status; /** * 核销人员id */ private Integer verificationUserId; /** * 核销时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date verificationTime; /** * 领取时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date insertTime; } cloud-server-other/src/main/java/com/dsh/other/mapper/SiteLockMapper.java
New file @@ -0,0 +1,11 @@ package com.dsh.other.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.dsh.other.entity.SiteLock; /** * @author zhibing.pu * @Date 2023/7/18 14:43 */ public interface SiteLockMapper extends BaseMapper<SiteLock> { } cloud-server-other/src/main/java/com/dsh/other/model/QuerySiteInfoVo.java
@@ -19,6 +19,8 @@ private String siteTypeName; @ApiModelProperty("门店名称") private String storeName; @ApiModelProperty("门店照片") private String storeCoverDrawing; @ApiModelProperty("门店地址") private String storeAddress; @ApiModelProperty("门店经度") @@ -27,6 +29,8 @@ private String storeLat; @ApiModelProperty("门店电话") private String storePhone; @ApiModelProperty("距离") private Double distance; @ApiModelProperty("现金价格(x/半小时)") private Double cashPrice; @ApiModelProperty("玩湃币价格(x/半小时)") cloud-server-other/src/main/java/com/dsh/other/model/QuerySiteList.java
@@ -21,6 +21,8 @@ private String cityCode; @ApiModelProperty(value = "所在门店id", required = false, dataType = "int") private Integer storeId; @ApiModelProperty(value = "搜索内容", required = false, dataType = "String") private String search; @ApiModelProperty(value = "页码,首页1", required = true, dataType = "int") private Integer pageNum; @ApiModelProperty(value = "页条数", required = true, dataType = "int") cloud-server-other/src/main/java/com/dsh/other/model/ReservationSite.java
New file @@ -0,0 +1,26 @@ package com.dsh.other.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author zhibing.pu * @Date 2023/7/18 14:33 */ @Data @ApiModel public class ReservationSite { @ApiModelProperty(value = "场地id", dataType = "String", required = true) private Integer id; @ApiModelProperty(value = "预约时间段,分号分隔(2023-07-15 12:00-12:30)", dataType = "String", required = true) private String times; @ApiModelProperty(value = "优惠券id", dataType = "long", required = false) private Long couponId; @ApiModelProperty(value = "预约人姓名", dataType = "String", required = true) private String booker; @ApiModelProperty(value = "预约人电话", dataType = "String", required = true) private String phone; @ApiModelProperty(value = "支付方式(1=微信,2=支付宝,3=玩湃比)", dataType = "int", required = true) private Integer payType; } cloud-server-other/src/main/java/com/dsh/other/service/ISiteLockService.java
New file @@ -0,0 +1,11 @@ package com.dsh.other.service; import com.baomidou.mybatisplus.extension.service.IService; import com.dsh.other.entity.SiteLock; /** * @author zhibing.pu * @Date 2023/7/18 14:44 */ public interface ISiteLockService extends IService<SiteLock> { } cloud-server-other/src/main/java/com/dsh/other/service/ISiteService.java
@@ -2,10 +2,8 @@ import com.baomidou.mybatisplus.extension.service.IService; import com.dsh.other.entity.Site; import com.dsh.other.model.QuerySiteInfoVo; import com.dsh.other.model.QuerySiteList; import com.dsh.other.model.QuerySiteListVo; import com.dsh.other.model.QuerySiteTimes; import com.dsh.other.model.*; import com.dsh.other.util.ResultUtil; import java.util.List; @@ -31,7 +29,7 @@ * @return * @throws Exception */ QuerySiteInfoVo querySiteInfo(Integer id) throws Exception; QuerySiteInfoVo querySiteInfo(Integer id, String lon, String lat) throws Exception; /** @@ -42,4 +40,13 @@ * @throws Exception */ List<QuerySiteTimes> querySiteTimes(Integer id, String day) throws Exception; /** * 预约场地 * @param reservationSite * @return * @throws Exception */ ResultUtil reservationSite(Integer uid, ReservationSite reservationSite) throws Exception; } cloud-server-other/src/main/java/com/dsh/other/service/impl/SiteLockServiceImpl.java
New file @@ -0,0 +1,15 @@ package com.dsh.other.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.dsh.other.entity.SiteLock; import com.dsh.other.mapper.SiteLockMapper; import com.dsh.other.service.ISiteLockService; import org.springframework.stereotype.Service; /** * @author zhibing.pu * @Date 2023/7/18 14:45 */ @Service public class SiteLockServiceImpl extends ServiceImpl<SiteLockMapper, SiteLock> implements ISiteLockService { } cloud-server-other/src/main/java/com/dsh/other/service/impl/SiteServiceImpl.java
@@ -1,26 +1,27 @@ package com.dsh.other.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.dsh.other.entity.Site; import com.dsh.other.entity.SiteBooking; import com.dsh.other.entity.SiteType; import com.dsh.other.entity.Store; import com.dsh.other.entity.*; import com.dsh.other.feignclient.account.AppUserClient; import com.dsh.other.feignclient.account.model.AppUser; import com.dsh.other.feignclient.activity.CouponClient; import com.dsh.other.feignclient.activity.UserCouponClient; import com.dsh.other.feignclient.activity.model.Coupon; import com.dsh.other.feignclient.activity.model.UserCoupon; import com.dsh.other.mapper.SiteMapper; import com.dsh.other.model.QuerySiteInfoVo; import com.dsh.other.model.QuerySiteList; import com.dsh.other.model.QuerySiteListVo; import com.dsh.other.model.QuerySiteTimes; import com.dsh.other.service.ISiteBookingService; import com.dsh.other.service.ISiteService; import com.dsh.other.service.ISiteTypeService; import com.dsh.other.service.StoreService; import com.dsh.other.util.GeodesyUtil; import com.dsh.other.util.ToolUtil; import com.dsh.other.model.*; import com.dsh.other.service.*; import com.dsh.other.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.*; @@ -39,6 +40,21 @@ @Autowired private ISiteBookingService siteBookingService; @Autowired private ISiteLockService siteLockService; @Resource private AppUserClient appUserClient; @Resource private UserCouponClient userCouponClient; @Resource private CouponClient couponClient; @Autowired private PayMoneyUtil payMoneyUtil; @@ -73,7 +89,7 @@ * @throws Exception */ @Override public QuerySiteInfoVo querySiteInfo(Integer id) throws Exception { public QuerySiteInfoVo querySiteInfo(Integer id, String lon, String lat) throws Exception { Site site = this.getById(id); SiteType siteType = siteTypeService.getById(site.getSiteTypeId()); Store store = storeService.getById(site.getStoreId()); @@ -82,10 +98,17 @@ querySiteInfoVo.setName(site.getName()); querySiteInfoVo.setSiteTypeName(siteType.getName()); querySiteInfoVo.setStoreName(store.getName()); querySiteInfoVo.setStoreCoverDrawing(store.getCoverDrawing()); querySiteInfoVo.setStoreAddress(store.getAddress()); querySiteInfoVo.setStoreLon(store.getLon()); querySiteInfoVo.setStoreLat(store.getLat()); querySiteInfoVo.setStorePhone(store.getPhone()); querySiteInfoVo.setDistance(0D); if(ToolUtil.isNotEmpty(lon) && ToolUtil.isNotEmpty(lat)){ Map<String, Double> distance = GeodesyUtil.getDistance(lon + "," + lat, store.getLon() + "," + store.getLat()); double wgs84 = new BigDecimal(distance.get("WGS84")).divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); querySiteInfoVo.setDistance(wgs84); } querySiteInfoVo.setCashPrice(site.getCashPrice()); querySiteInfoVo.setPlayPaiCoin(site.getPlayPaiCoin()); return querySiteInfoVo; @@ -130,6 +153,11 @@ if(null != siteBooking){ querySiteTimes.setSelectable(0); } int count = siteLockService.count(new QueryWrapper<SiteLock>().eq("siteId", id).last(" and DATE_FORMAT(startTime, '%Y-%m-%d %H:%i') <= '" + day + " " + start + "' and DATE_FORMAT(endTime, '%Y-%m-%d %H:%i') >= '" + day + " " + end + "'")); if(count > 0){ querySiteTimes.setSelectable(0); } list.add(querySiteTimes); if(e_hour == hour && minute == e_minute){ @@ -138,4 +166,275 @@ } return list; } /** * 预约场地 * @param reservationSite * @return * @throws Exception */ @Override public ResultUtil reservationSite(Integer uid, ReservationSite reservationSite) throws Exception { Site site = this.getById(reservationSite.getId()); AppUser appUser = appUserClient.queryAppUser(uid); String[] split = reservationSite.getTimes().split(";"); if(reservationSite.getPayType() == 3){ Integer playPaiCoin = site.getPlayPaiCoin() * split.length; if(appUser.getPlayPaiCoins().compareTo(playPaiCoin) < 0){ return ResultUtil.error("玩湃币不足"); } } for (String s : split) { String day = s.split(" ")[0]; String time = s.split(" ")[1]; List<QuerySiteTimes> querySiteTimes = querySiteTimes(reservationSite.getId(), day); for (QuerySiteTimes querySiteTime : querySiteTimes) { if(querySiteTime.getTime().equals(time) && querySiteTime.getSelectable() == 0){ return ResultUtil.error("【" + s + "】时间段已被使用"); } } } String s_time = split[0]; String e_time = split[split.length - 1]; s_time = s_time.substring(s_time.lastIndexOf("-")); String[] s1 = e_time.split(" "); e_time = s1[0] + " " + s1[1].split("-")[1]; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); Double payMoney = 0D; if(reservationSite.getPayType() == 3){ payMoney = new BigDecimal(site.getCashPrice()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); }else{ payMoney = new BigDecimal(site.getCashPrice()).multiply(new BigDecimal(split.length)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); } //校验优惠券 Long couponId = reservationSite.getCouponId(); if(null != couponId && reservationSite.getPayType() != 3){ UserCoupon userCoupon = userCouponClient.queryUserCouponById(couponId); if(userCoupon.getStatus() == 2){ return ResultUtil.error("优惠券已被核销"); } Coupon coupon = couponClient.queryCouponById(userCoupon.getCouponId()); long time = coupon.getEndTime().getTime(); if(System.currentTimeMillis() >= time){ return ResultUtil.error("优惠券已过期"); } if(coupon.getType() == 1){//满减 JSONObject jsonObject = JSON.parseObject(coupon.getContent()); Double num1 = jsonObject.getDouble("num1"); Double num2 = jsonObject.getDouble("num2"); if(payMoney.compareTo(num1) <= 0){ return ResultUtil.error("该优惠券无法使用"); } payMoney = new BigDecimal(payMoney).subtract(new BigDecimal(num2)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); } if(coupon.getType() == 2){//代金券 JSONObject jsonObject = JSON.parseObject(coupon.getContent()); Double num1 = jsonObject.getDouble("num1"); if(payMoney.compareTo(num1) <= 0){ return ResultUtil.error("该优惠券无法使用"); } payMoney = new BigDecimal(payMoney).subtract(new BigDecimal(num1)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); } userCoupon.setStatus(2); userCouponClient.updateUserCoupon(userCoupon); } SiteBooking siteBooking = new SiteBooking(); siteBooking.setOrderNo(sdf.format(new Date()) + UUIDUtil.getNumberRandom(3)); siteBooking.setProvince(site.getProvince()); siteBooking.setProvinceCode(site.getProvinceCode()); siteBooking.setCity(site.getCity()); siteBooking.setCityCode(site.getCityCode()); siteBooking.setStoreId(site.getStoreId()); siteBooking.setSiteId(reservationSite.getId()); siteBooking.setAppUserId(uid); siteBooking.setStartTime(sdf1.parse(s_time)); siteBooking.setEndTime(sdf1.parse(e_time)); siteBooking.setBooker(reservationSite.getBooker()); siteBooking.setPhone(reservationSite.getPhone()); siteBooking.setPayType(reservationSite.getPayType()); siteBooking.setPayMoney(payMoney); siteBooking.setUserCouponId(reservationSite.getCouponId()); siteBooking.setStatus(0); siteBooking.setState(1); siteBooking.setInsertTime(new Date()); siteBookingService.save(siteBooking); if(reservationSite.getPayType() == 1){//微信支付 return weChatPaymentSite(uid, payMoney, siteBooking); } if(reservationSite.getPayType() == 2){//支付宝支付 return aliPaymentSite(payMoney, siteBooking); } if(reservationSite.getPayType() == 3){//玩湃币支付 return playPaiCoinPaymentSite(appUser, payMoney, siteBooking); } return ResultUtil.success(); } /** * 课程微信支付 * @param uid * @param paymentPrice * @return * @throws Exception */ public ResultUtil weChatPaymentSite(Integer uid, Double paymentPrice, SiteBooking siteBooking) throws Exception{ String code = siteBooking.getOrderNo(); Integer id = siteBooking.getId(); ResultUtil weixinpay = payMoneyUtil.weixinpay("预约场地", "", code, paymentPrice.toString(), "/base/site/weChatPaymentSiteCallback", "APP", ""); if(weixinpay.getCode() == 200){ new Thread(new Runnable() { @Override public void run() { try { int num = 1; int wait = 0; while (num <= 10){ int min = 5000; wait += (min * num); Thread.sleep(wait); SiteBooking siteBooking = siteBookingService.getById(id); if(siteBooking.getStatus() != 0){ break; } ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(siteBooking.getOrderNo(), ""); if(resultUtil.getCode() == 200 && siteBooking.getStatus() == 0){ /** * SUCCESS—支付成功, * REFUND—转入退款, * NOTPAY—未支付, * CLOSED—已关闭, * REVOKED—已撤销(刷卡支付), * USERPAYING--用户支付中, * PAYERROR--支付失败(其他原因,如银行返回失败) */ Map<String, String> data1 = resultUtil.getData(); String s = data1.get("trade_state"); String transaction_id = data1.get("transaction_id"); if("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10){ siteBooking.setState(3); siteBookingService.updateById(siteBooking); if(null != siteBooking.getUserCouponId()){ UserCoupon userCoupon = userCouponClient.queryUserCouponById(siteBooking.getUserCouponId()); userCoupon.setStatus(1); userCouponClient.updateUserCoupon(userCoupon); } break; } if("SUCCESS".equals(s)){ siteBooking.setPayTime(new Date()); siteBooking.setStatus(1); siteBooking.setPayOrderNo(transaction_id); siteBookingService.updateById(siteBooking); break; } if("USERPAYING".equals(s)){ num++; } } } }catch (Exception e){ e.printStackTrace(); } } }).start(); } return weixinpay; } /** * 课程支付宝支付 * @param paymentPrice * @return * @throws Exception */ public ResultUtil aliPaymentSite(Double paymentPrice, SiteBooking siteBooking) throws Exception{ String code = siteBooking.getOrderNo(); Integer id = siteBooking.getId(); ResultUtil alipay = payMoneyUtil.alipay("预约场地", "预约场地", "", code, paymentPrice.toString(), "/base/site/aliPaymentSiteCallback"); if(alipay.getCode() == 200){ new Thread(new Runnable() { @Override public void run() { try { int num = 1; int wait = 0; while (num <= 10){ int min = 5000; wait += (min * num); Thread.sleep(wait); SiteBooking siteBooking = siteBookingService.getById(id); if(siteBooking.getStatus() != 0){ break; } ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryALIOrder(code); if(resultUtil.getCode() == 200 && siteBooking.getStatus() == 0){ /** * WAIT_BUYER_PAY(交易创建,等待买家付款)、 * TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、 * TRADE_SUCCESS(交易支付成功)、 * TRADE_FINISHED(交易结束,不可退款) */ Map<String, String> data1 = resultUtil.getData(); String s = data1.get("tradeStatus"); String tradeNo = data1.get("tradeNo"); if("TRADE_CLOSED".equals(s) || "TRADE_FINISHED".equals(s) || num == 10){ siteBooking.setState(3); siteBookingService.updateById(siteBooking); if(null != siteBooking.getUserCouponId()){ UserCoupon userCoupon = userCouponClient.queryUserCouponById(siteBooking.getUserCouponId()); userCoupon.setStatus(1); userCouponClient.updateUserCoupon(userCoupon); } break; } if("TRADE_SUCCESS".equals(s)){ siteBooking.setPayTime(new Date()); siteBooking.setStatus(1); siteBooking.setPayOrderNo(tradeNo); siteBookingService.updateById(siteBooking); break; } if("WAIT_BUYER_PAY".equals(s)){ num++; } } } }catch (Exception e){ e.printStackTrace(); } } }).start(); } return alipay; } /** * 玩湃币支付课程 * @param appUser * @param paymentPrice * @return * @throws Exception */ public ResultUtil playPaiCoinPaymentSite(AppUser appUser, Double paymentPrice, SiteBooking siteBooking) throws Exception{ Integer playPaiCoins = appUser.getPlayPaiCoins(); appUser.setPlayPaiCoins(playPaiCoins - paymentPrice.intValue()); appUserClient.updateAppUser(appUser); siteBooking.setPayTime(new Date()); siteBooking.setStatus(1); siteBookingService.updateById(siteBooking); return ResultUtil.success(); } } cloud-server-other/src/main/java/com/dsh/other/util/HttpClientUtil.java
@@ -39,7 +39,7 @@ private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); private PoolingHttpClientConnectionManager connectionManager; private static PoolingHttpClientConnectionManager connectionManager; public HttpClientUtil(){ @@ -53,14 +53,14 @@ /** * 创建一个httpClient对象 */ private CloseableHttpClient getHttpCline(){ private static CloseableHttpClient getHttpCline(){ return HttpClients.custom() .setConnectionManager(connectionManager) .disableAutomaticRetries() .build(); } private RequestConfig getRequestConfig(){ private static RequestConfig getRequestConfig(){ RequestConfig.Builder builder = RequestConfig.custom(); builder.setSocketTimeout(60000)//3.1设置客户端等待服务端返回数据的超时时间 .setConnectTimeout(30000)//3.2设置客户端发起TCP连接请求的超时时间 @@ -169,7 +169,7 @@ * @param header 自定义请求头 * @return */ public HttpResult pushHttpRequsetXml(String url, String xml, Map<String, String> header) throws Exception{ public static HttpResult pushHttpRequsetXml(String url, String xml, Map<String, String> header) throws Exception{ HttpPost httpPost = new HttpPost(url); httpPost.setConfig(getRequestConfig()); for(String key : header.keySet()){ @@ -181,7 +181,7 @@ int statusCode = httpResponse.getStatusLine().getStatusCode(); String content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); HttpResult httpResult = HttpResult.getHttpResult(statusCode, content); this.close(httpResponse); close(httpResponse); return httpResult; } @@ -198,14 +198,14 @@ * @return * @throws Exception */ public String pushHttpsRequsetXml(String url, String xml, Map<String, String> header, String certPassword, String certPath, String certType) throws Exception{ public static String pushHttpsRequsetXml(String url, String xml, Map<String, String> header, String certPassword, String certPath, String certType) throws Exception{ HttpPost httpPost = new HttpPost(url); for(String key : header.keySet()){ httpPost.setHeader(key, header.get(key)); } httpPost.setHeader("Content-Type", "application/xml"); httpPost.setEntity(new StringEntity(xml, "UTF-8")); CloseableHttpClient httpCline = this.initCert(certPassword, certPath, certType); CloseableHttpClient httpCline = initCert(certPassword, certPath, certType); CloseableHttpResponse httpResponse = httpCline.execute(httpPost); String content = null; if(httpResponse.getStatusLine().getStatusCode() == 200){ @@ -213,7 +213,7 @@ }else{ content = "返回状态码:" + httpResponse.getStatusLine() + "。" + EntityUtils.toString(httpResponse.getEntity()); } this.close(httpResponse); close(httpResponse); httpCline.close(); return content; } @@ -226,7 +226,7 @@ * @param certType 证书类型 * @throws Exception */ private CloseableHttpClient initCert(String key, String certPath, String certType) throws Exception { private static CloseableHttpClient initCert(String key, String certPath, String certType) throws Exception { KeyStore keyStore = KeyStore.getInstance(certType); InputStream inputStream = new FileInputStream(new File(certPath)); try { @@ -246,7 +246,7 @@ /** * 关闭资源 */ private void close(CloseableHttpResponse httpResponse){ private static void close(CloseableHttpResponse httpResponse){ try { if(null != httpResponse){ EntityUtils.consume(httpResponse.getEntity());//此处高能,通过源码分析,由EntityUtils是否回收HttpEntity cloud-server-other/src/main/java/com/dsh/other/util/MD5AndKL.java
New file @@ -0,0 +1,112 @@ package com.dsh.other.util; import java.security.MessageDigest; public class MD5AndKL { /** * MD5加码。32位 * * @param inStr * @return */ public static String MD5(String inStr) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new RuntimeException(e.toString()); } byte[] md5Bytes = md5.digest(inStr.getBytes()); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } /** * 可逆的加密算法 * * @param inStr * @return */ public static String KL(String inStr) { char[] a = inStr.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String s = new String(a); return s; } /** * 加密后解密 * * @param inStr * @return */ public static String JM(String inStr) { char[] a = inStr.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String k = new String(a); return k; } private static String byteArrayToHexString(byte b[]) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) resultSb.append(byteToHexString(b[i])); return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n += 256; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } public static String MD5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)){ resultString = byteArrayToHexString(md.digest(resultString.getBytes())); }else{ resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname))); } } catch (Exception exception) { exception.printStackTrace(); } return resultString; } private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static void main(String args[]) { System.out.println("MD5后再加密:" + KL(MD5("123456"))); System.out.println(MD5("123456")); // System.out.println("加密:" + KL(MD5("123456"))); // s = KL(s); // System.out.println("解密:" + KL("81dc9bdb52d04dc20036dbd8313ed055")); // System.out.println("解密:" + JM(KL(s))); // System.out.println("解密为MD5后的:" + KL(KL(MD5(s)))); // System.out.println(JM("5d62957bb57d3e49dcf48a0df064be4c")); // System.out.println(MD5AndKL.KL(MD5AndKL.MD5("admin"+"87654321"))); } } cloud-server-other/src/main/java/com/dsh/other/util/PayMoneyUtil.java
New file @@ -0,0 +1,1149 @@ package com.dsh.other.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.CertAlipayRequest; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayTradeAppPayModel; import com.alipay.api.request.*; import com.alipay.api.response.*; import org.apache.commons.collections.map.HashedMap; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.math.BigDecimal; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Security; import java.util.*; /** * 第三方支付工具类 */ @Component public class PayMoneyUtil { private String aliAppid = "2021004105665036";//支付宝appid private String appPrivateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCi5i9nW/hGLJ3A06cZxTQdviFC7THpdSihoTYGLr9q006hu0V26ecBMY/o4w5bvIX0Ok/yofmZsVcCJpAPvbXL/uqVrIjnRRxXiaeBFThlxoBUTdunvbUSDYfzlEhJr5NvUKI6H6lz2niXlQGx4qy8Hau4ccWit9kM8jwUvsBVQoFgJA+xrjMvooA7YLopQtpOD+UJr5thApTSf1xrnr1W12yolTLEH15JmNV372cqXrYUuqnY0QsaPtxeqJUGAOcGdVLllQ7easEznP8DFBvDdHATcmp2SHNQDUEWN6MCVPbMgY06NQVqAXxqjTAYSVh+6TRu6bofPmpYC3TZB003AgMBAAECggEBAJAcR2+PA3NBYUYHeFrqBRMS8uX8ZR19kjZ7IgoSLTFaQsP9opRylPSPXhrPVBKAE5leRQAHn4MCSlESwHvMfxo7KFjFTFAc6dffZZpipYQUOc9bGampwJh58/3e/pyBgVMG6J23CPf/HJQtNFSkjd/V9+ayb/9l2dUEL3bC0fAZ/dbx8HsxdLw8wn3fLlWLj68hOMqa2deCZe3JdSVsPbeWqkh56FFsMLug0Nd+Ar4TgRl9/jnhXF0JWiD0LmPUYLhboY7EfUBzN4w1iYbDi1P+3zvoOYsiVKAXox9GMhQ2VzOO2UcSTuizSza2e98mGpabl/GpKmCz+RDFjtkX6eECgYEA2MyCij65eO3aGIm3FUe93DULRBYTfX8qJQSJq2WOWA3mmQlEW6L3O2B5/lG2h+8WmN6iLEs9eHpgycGYp7vAqgrANEn16ACVcuyx0scFtrZfZ+kmHMzFfiUWxJjVYk/6YngsGVBLdw6ueM42C8TTP67X9tU5TdVGoGWuqEj4W98CgYEAwFqwprXOch5Pqk/RPbb49r0Ou03K/UbciWnWWKzUhFFNS8MdlQPoDvQZbMwHLeWsa2VhaKITK3x5biLQb3U+0GLOn6lTvEyrEUH+ucREyLgVYTRAvwBPtnvlrzpyxPk2HnslQjju8WrvvLLBMKWUjlTrTOzhaHT21gz3pHMiOakCgYEAhLmfaXdBITGshb054sNLDtdCkGpbgEcrzAHdLps769iGxkYQHXHFngpQZUwtTUcoNGqIKknd1jZFrv7gsD+XkgKG7PwimehRlkwmCX5ilxtLiVgJRzRt6+5U5AMVD90a0tHzXYP0z2yjj73fBJF5KtGl0a10KZxaYrQdm1UhB00CgYBZZgzx/k9rtHC8LAqIj1CYhHejT92G53c6Gkl3vyOqN4sgKhfGmSEySfrDGPRBPZxr8ZtbIPCd5mUdberH0osWGMYFaJI1UsCy7aQwvGpniz7MhZeN7dweaOjwDs8mgtjHQ96mL4XGCDhR0BZ/wIURvZ/6iaGdhbbu9unlsWj3uQKBgQCmZYdsbbZkd3ev6f8rwyvMz+DrCQyYpY44cegBYuJgrZiQnL2fJioeN7ixX0UM48SfwsZEIrzshP/LGAwnc2MdjxKUl4jLN8SEe0NAjXOnz9Zaw740+aOmLpXcLWdP4uM2gIhWsvW1tEkQZCXmm7c9s/RsU8Pmzv+YL3+fSijOzA==";//支付宝开发者应用私钥 private String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAouYvZ1v4RiydwNOnGcU0Hb4hQu0x6XUooaE2Bi6/atNOobtFdunnATGP6OMOW7yF9DpP8qH5mbFXAiaQD721y/7qlayI50UcV4mngRU4ZcaAVE3bp721Eg2H85RISa+Tb1CiOh+pc9p4l5UBseKsvB2ruHHForfZDPI8FL7AVUKBYCQPsa4zL6KAO2C6KULaTg/lCa+bYQKU0n9ca569VtdsqJUyxB9eSZjVd+9nKl62FLqp2NELGj7cXqiVBgDnBnVS5ZUO3mrBM5z/AxQbw3RwE3JqdkhzUA1BFjejAlT2zIGNOjUFagF8ao0wGElYfuk0bum6Hz5qWAt02QdNNwIDAQAB";//支付宝应用公钥 private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmu8n/4yTHWbn7VOrNc9OsLtDL1bEQ8gC1dHkj8Wy5z0mkaOsjJRIG/28ze12M0V8jdCKuuDr5Z1OPKiqf+XO3ypguEh+mYUVMBM/cZodDFQfTY1TKLWjvQCuaqlA+QUTCK6f7T7stsgyQ1o9Jj0rXZDz6PM4QHSTzjrLIBaeqM5WIBvH+fy/X+QG5Utd+/UT0kc0JyvuKhZ65yVUd/C9VcwJJAPliRsAQNrqYterwAJ9zvw9tF11wj9W0XgJ8Ccu4x3gR1vrlLRJJo/OA97RmxPQ+5hSacWQZCUd1dwiBq+YCrKVHGTj14izRHXrLc0yBlRXo7tBOIqcy3IsvKVthQIDAQAB";//支付宝支付公钥 private String appid = "";//微信appid private String appletsAppid = "";//微信小程序appid private String mchId = "";//微信商户号 private String key = "";//微信商户号 private String callbackPath = "";//支付回调网关地址 private String app_cert_path = "C:/cert/alipay/user/app_cert_path.crt";//应用公钥证书路径 private String alipay_cert_path = "C:/cert/alipay/user/alipay_cert_path.crt";//支付宝公钥证书文件路径 private String alipay_root_cert_path = "C:/cert/alipay/user/alipay_root_cert_path.crt";//支付宝CA根证书文件路径 private String certPath = "C:\\cert\\1523106371_20211206_cert\\apiclient_cert.p12";//微信证书 /** * 支付宝支付 */ public ResultUtil alipay(String body, String subject, String passbackParams, String outTradeNo, String amount, String notifyUrl){ // //构造client // CertAlipayRequest certAlipayRequest = new CertAlipayRequest (); // //设置网关地址 // certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); // //设置应用Id // certAlipayRequest.setAppId(aliAppid); // //设置应用私钥 // certAlipayRequest.setPrivateKey(appPrivateKey); // //设置请求格式,固定值json // certAlipayRequest.setFormat("json"); // //设置字符集 // certAlipayRequest.setCharset("UTF-8"); // //设置签名类型 // certAlipayRequest.setSignType("RSA2"); // //设置应用公钥证书路径 // certAlipayRequest.setCertPath(app_cert_path); // //设置支付宝公钥证书路径 // certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path); // //设置支付宝根证书路径 // certAlipayRequest.setRootCertPath(alipay_root_cert_path); // //构造client // AlipayClient alipayClient = null; // try { // alipayClient = new DefaultAlipayClient(certAlipayRequest); // } catch (AlipayApiException e) { // e.printStackTrace(); // } // //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay // AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest (); // //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 // AlipayTradeAppPayModel model = new AlipayTradeAppPayModel (); // model.setBody(body); // model.setSubject (subject); // model.setOutTradeNo (outTradeNo); // model.setTimeoutExpress ("30m" ); // model.setTotalAmount (amount); // model.setProductCode ( "QUICK_MSECURITY_PAY" ); // model.setPassbackParams(passbackParams);//自定义参数 // request.setBizModel ( model ); // request.setNotifyUrl (callbackPath + notifyUrl); // try { // //这里和普通的接口调用不同,使用的是sdkExecute // AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request); // Map<String, String> map = new HashMap<>(); // map.put("orderString", response.getBody()); // System.out.println(map);//就是orderString 可以直接给客户端请求,无需再做处理。 // return ResultUtil.success(map); // } catch (AlipayApiException e ) { // e.printStackTrace(); // } //实例化客户端 AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey, "json", "UTF-8", alipay_public_key, "RSA2"); //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.setBody(body);//对一笔交易的具体描述信息。如果是多种商品,请将商品描述字符串累加传给body。 model.setSubject(subject);//商品的标题/交易标题/订单标题/订单关键字等。 model.setOutTradeNo(outTradeNo);//商户网站唯一订单号 model.setTimeoutExpress("30m"); model.setTotalAmount(amount);//付款金额 model.setProductCode("QUICK_MSECURITY_PAY"); model.setPassbackParams(passbackParams);//自定义参数 request.setBizModel(model); request.setNotifyUrl(callbackPath + notifyUrl); try { //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request); Map<String, String> map = new HashMap<>(); map.put("orderString", response.getBody()); System.out.println(map);//就是orderString 可以直接给客户端请求,无需再做处理。 return ResultUtil.success(map); } catch (AlipayApiException e) { e.printStackTrace(); } return null; } /** * 支付宝扫码支付下单 * @param body * @param subject * @param outTradeNo * @param amount * @param notifyUrl * @return */ public ResultUtil aliScanCodePay(String body, String subject, String outTradeNo, String amount, String notifyUrl){ AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey, "json", "UTF-8", alipay_public_key, "RSA2"); //获得初始化的AlipayClient AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类 request.setBizContent("{" + " \"out_trade_no\":\"" + outTradeNo + "\"," +//商户订单号 " \"total_amount\":\"" + 1 + "\"," + " \"subject\":\"" + subject + "\"," + " \"notify_url\":\"" + callbackPath + notifyUrl + "\"," + " \"body\":\"" + body + "\"," + " \"store_id\":\"NJ_001\"," + " \"timeout_express\":\"90m\"}");//订单允许的最晚付款时间 AlipayTradePrecreateResponse response = null; try { response = alipayClient.execute(request); } catch (AlipayApiException e) { e.printStackTrace(); } JSONObject alipay_trade_precreate_response = JSON.parseObject(response.getBody()).getJSONObject("alipay_trade_precreate_response"); System.err.print(alipay_trade_precreate_response.getString("qr_code")); return ResultUtil.success(alipay_trade_precreate_response.getString("qr_code")); } /** * 支付成功后的回调处理逻辑 * @param request */ public Map<String, String> alipayCallback(HttpServletRequest request){ //获取支付宝POST过来反馈信息 Map<String,String> params = new HashMap<String,String>(); Map requestParams = request.getParameterMap(); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + "_"; } //乱码解决,这段代码在出现乱码时使用。 //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); params.put(name, valueStr); } //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。 //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type) // try { // boolean flag = AlipaySignature.rsaCheckV1(params, alipay_public_key, "UTF-8","RSA2"); // if(flag){ // Map<String, String> map = new HashMap<>(); // String out_trade_no = params.get("out_trade_no"); // String subject = params.get("subject"); // String total_amount = params.get("total_amount"); // String trade_no = params.get("trade_no"); // String passback_params = params.get("passback_params"); // map.put("out_trade_no", out_trade_no);//商家订单号 // map.put("subject", subject); // map.put("total_amount", total_amount); // map.put("trade_no", trade_no);//支付宝交易号 // map.put("passback_params", passback_params);//回传参数 // return map; // }else{ // System.err.println("验签失败"); // } // // } catch (AlipayApiException e) { // e.printStackTrace(); // } // return null; Map<String, String> map = new HashMap<>(); String out_trade_no = params.get("out_trade_no"); String subject = params.get("subject"); String total_amount = params.get("total_amount"); String trade_no = params.get("trade_no"); String passback_params = params.get("passback_params"); map.put("out_trade_no", out_trade_no);//商家订单号 map.put("subject", subject); map.put("total_amount", total_amount); map.put("trade_no", trade_no);//支付宝交易号 map.put("passback_params", passback_params);//回传参数 return map; } /** * 支付宝查询订单支付状态 * @param out_trade_no * @return * @throws Exception */ public ResultUtil queryALIOrder(String out_trade_no) throws Exception{ AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",aliAppid, appPrivateKey,"json","UTF-8", alipay_public_key,"RSA2"); AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); request.setBizContent("{" + "\"out_trade_no\":" + out_trade_no + " }"); AlipayTradeQueryResponse response = alipayClient.execute(request); if(response.isSuccess()){ String tradeStatus = response.getTradeStatus();//交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款) return ResultUtil.success(tradeStatus); } else { return ResultUtil.error(response.getMsg()); } } /** * 微信统一下单 * @param body 商品描述 * @param attach 附加数据 * @param out_trade_no 商户订单号 * @param total_fee 标价金额 * @param notify_url 通知地址 * @param tradeType 交易类型 * @return */ public ResultUtil weixinpay(String body, String attach, String out_trade_no, String total_fee, String notify_url, String tradeType, String openId) throws Exception{ int i = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue(); String hostAddress = null; try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } String nonce_str = UUIDUtil.getRandomCode(16); Map<String, Object> map = new HashMap<>(); map.put("appid", "APP".equals(tradeType) ? appid : appletsAppid); map.put("mch_id", mchId); map.put("nonce_str", nonce_str); map.put("body", body); map.put("attach", attach);//存储订单id map.put("out_trade_no", out_trade_no);//存储的订单code map.put("total_fee", i); map.put("spbill_create_ip", hostAddress); map.put("notify_url", callbackPath + notify_url); map.put("trade_type", tradeType); if("JSAPI".equals(tradeType)){ map.put("openid", openId); } String s = this.weixinSignature(map); map.put("sign", s); String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); Set<String> strings = map.keySet(); String[] keys = {}; keys = strings.toArray(keys); Arrays.sort(keys); xmlString.append("<xml>"); for(int l = 0; l < keys.length; l++){ xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">"); } xmlString.append("</xml>"); Map<String, String> map1 = null; String body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData(); //将结果xml解析成map body1 = body1.replaceAll("<!\\[CDATA\\[",""); body1 = body1.replaceAll("]]>", ""); try { map1 = this.xmlToMap(body1, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } String return_code = map1.get("return_code"); if("SUCCESS".equals(return_code)){ String result_code = map1.get("result_code"); if("SUCCESS".equals(result_code)){ String type = map1.get("trade_type"); String prepay_id = map1.get("prepay_id"); switch (type){ case "JSAPI": //重新进行签名后返回给前端 Map<String, Object> map2 = new HashMap<>(); map2.put("appId", map1.get("appid")); map2.put("nonceStr", map1.get("nonce_str")); map2.put("package", "prepay_id=" + prepay_id); map2.put("signType", "MD5"); map2.put("timeStamp", new Date().getTime() + ""); String s2 = this.weixinSignature(map2); map2.put("prepay_id", prepay_id); map2.put("mch_id", map1.get("mch_id")); map2.put("trade_type", map1.get("trade_type")); map2.put("sign", s2); return ResultUtil.success(map2); case "NATIVE": String code_url = map1.get("code_url"); return ResultUtil.success(code_url); case "APP": //重新进行签名后返回给前端 Map<String, Object> map3 = new HashMap<>(); map3.put("appid", appid); map3.put("noncestr", nonce_str); map3.put("package", "Sign=WXPay"); map3.put("partnerid", mchId); map3.put("prepayid", prepay_id); map3.put("timestamp", new Date().getTime() / 1000); String s1 = this.weixinSignature(map3); map3.put("sign", s1); System.err.println(map3); return ResultUtil.success(map3); } return null; }else{ System.err.println(map1.get("err_code_des")); return ResultUtil.error(map1.get("err_code_des")); } }else{ System.err.println(map1.get("return_msg") + appid + "----" + mchId); return ResultUtil.error(map1.get("return_msg"), new JSONObject()); } } /** * 微信支付成功后的回调处理 * @param request */ public Map<String, String> weixinpayCallback(HttpServletRequest request){ try { String param = this.getParam(request); param = param.replaceAll("<!\\[CDATA\\[",""); param = param.replaceAll("]]>", ""); Map<String, String> map = this.xmlToMap(param, "UTF-8"); String return_code = map.get("return_code"); if("SUCCESS".equals(return_code)){ String result_code = map.get("result_code"); if("SUCCESS".equals(result_code)){ Map<String, String> map1 = new HashedMap(); map1.put("nonce_str", map.get("nonce_str")); map1.put("out_trade_no", map.get("out_trade_no"));//存储的订单code map1.put("attach", map.get("attach"));//存储订单id map1.put("total_fee", map.get("total_fee")); map1.put("transaction_id", map.get("transaction_id"));//微信支付订单号 String result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"; map1.put("result", result); return map1; }else{ System.err.println(map.get("err_code_des")); } }else{ System.err.println(map.get("return_msg")); } } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return null; } /** * 微信扫码收款 * @param body 商品描述 * @param attach 附加数据 * @param nonce_str 随机字符串 * @param out_trade_no 商户订单号 * @param total_fee 订单金额 * @param auth_code 授权码 扫码支付授权码,设备读取用户微信中的条码或者二维码信息(注:用户付款码条形码规则:18位纯数字,以10、11、12、13、14、15开头) * @return */ public ResultUtil wxScanQRCodePay(String body, String attach, String nonce_str, String out_trade_no, String total_fee, String auth_code){ int i = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue(); String hostAddress = null; try { InetAddress address = InetAddress.getLocalHost(); hostAddress = address.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } String randomCode = null; try { randomCode = UUIDUtil.getRandomCode(10); } catch (Exception e) { e.printStackTrace(); } Map<String, Object> map = new HashMap<>(); map.put("appid", appid); map.put("mch_id", mchId); map.put("nonce_str", nonce_str);//存储的支付人员id,员工扫描二维码支付的时候存储的是收款员工id map.put("body", body); map.put("attach", attach);//存储的费用月份数据,员工扫描二维码支付的时候存储的是收费项id map.put("out_trade_no", randomCode + "_" + out_trade_no);//存储的房间id map.put("total_fee", i); map.put("spbill_create_ip", hostAddress); map.put("auth_code", auth_code); String s = this.weixinSignature(map); map.put("sign", s); String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); Set<String> strings = map.keySet(); String[] keys = {}; keys = strings.toArray(keys); Arrays.sort(keys); xmlString.append("<xml>"); for(int l = 0; l < keys.length; l++){ xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">"); } xmlString.append("</xml>"); Map<String, String> map1 = null; String body1 = null; try { body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData(); } catch (Exception e) { e.printStackTrace(); } //将结果xml解析成map body1 = body1.replaceAll("<!\\[CDATA\\[",""); body1 = body1.replaceAll("]]>", ""); try { map1 = this.xmlToMap(body1, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } String return_code = map1.get("return_code"); if("SUCCESS".equals(return_code)){ String result_code = map1.get("result_code"); if("SUCCESS".equals(result_code)){ String type = map1.get("trade_type"); switch (type){ case "JSAPI": break; case "NATIVE": String code_url = map1.get("code_url"); return ResultUtil.success(code_url); case "APP": String prepay_id = map1.get("prepay_id"); //重新进行签名后返回给前端 Map<String, Object> map2 = new HashMap<>(); map2.put("appid", appid); map2.put("noncestr", nonce_str); map2.put("package", "Sign=WXPay"); map2.put("partnerid", mchId); map2.put("prepayid", prepay_id); map2.put("timestamp", new Date().getTime() + ""); String s1 = this.weixinSignature(map2); map2.put("pac", "Sign=WXPay"); map2.put("sign", s1); // System.err.println(map2); return ResultUtil.success(map2); } return null; }else{ // System.err.println(map1.get("err_code_des")); return ResultUtil.error(map1.get("err_code_des")); } }else{ // System.err.println(map1.get("return_msg") + appid + "----" + mchId); return ResultUtil.error(map1.get("return_msg"), new JSONObject()); } } /** * 支付宝扫码收款 * @param data * @return */ public Object aliScanQRCodePay(String data){ return null; } /** * 微信退款申请 * @param transaction_id 微信订单号。微信生成的订单号,在支付通知中有返回 * @param out_refund_no 商户退款单号。商户系统内部的退款单号,商户系统内部唯一,只能是数字、大小写字母_-|*@ ,同一退款单号多次请求只退一笔。 * @param total_fee 订单金额。订单总金额,单位为分,只能为整数 * @param refund_fee 退款金额。退款总金额,订单总金额,单位为分,只能为整数 * @param notify_url 退款结果通知url。异步接收微信支付退款结果通知的回调地址,通知URL必须为外网可访问的url,不允许带参数 如果参数中传了notify_url,则商户平台上配置的回调地址将不会生效。 * @return */ public Map<String, String> wxRefund(String transaction_id, String out_refund_no, String total_fee, String refund_fee, String notify_url){ int tf = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue(); int rf = new BigDecimal(refund_fee).multiply(new BigDecimal("100")).intValue(); String nonce_str = UUIDUtil.getRandomCode(); Map<String, Object> map = new HashMap<>(); map.put("appid", appid); map.put("mch_id", mchId); map.put("nonce_str", nonce_str); map.put("transaction_id", transaction_id); map.put("out_refund_no", out_refund_no); map.put("total_fee", tf); map.put("refund_fee", rf); map.put("notify_url", callbackPath + notify_url); String s = this.weixinSignature(map, key); map.put("sign", s); String url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); Set<String> strings = map.keySet(); String[] keys = {}; keys = strings.toArray(keys); Arrays.sort(keys); xmlString.append("<xml>"); for(int l = 0; l < keys.length; l++){ xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">"); } xmlString.append("</xml>"); Map<String, String> map1 = null; String body1 = null; try { body1 = HttpClientUtil.pushHttpsRequsetXml(url, xmlString.toString(), new HashMap<>(), mchId, certPath, "PKCS12"); } catch (Exception e) { e.printStackTrace(); } System.err.println(body1); //将结果xml解析成map body1 = body1.replaceAll("<!\\[CDATA\\[",""); body1 = body1.replaceAll("]]>", ""); try { map1 = this.xmlToMap(body1, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } String return_code = map1.get("return_code"); Map<String, String> map2 = new HashMap<>(); if("SUCCESS".equals(return_code)){ String result_code = map1.get("result_code"); if("SUCCESS".equals(result_code)){ map2.put("return_code", result_code); map2.put("refund_id", String.valueOf(map1.get("refund_id")));//微信退款订单号 map2.put("refund_fee", String.valueOf(map1.get("refund_fee")));//退款金额 return map2; }else{ map2.put("return_code", result_code); map2.put("return_msg", map1.get("err_code_des")); return map2; } }else{ map2.put("return_code", return_code); map2.put("return_msg", map1.get("return_msg")); return map2; } } /** * 微信退款成功后的回调处理 * @param request * @return */ public Map<String, String> wxRefundCallback(HttpServletRequest request){ try { String param = this.getParam(request); param = param.replaceAll("<!\\[CDATA\\[",""); param = param.replaceAll("]]>", ""); Map<String, String> map = this.xmlToMap(param, "UTF-8"); String return_code = map.get("return_code"); if("SUCCESS".equals(return_code)){ String req_info = map.get("req_info");//加密信息请用商户秘钥进行解密 String s = this.wxDecrypt(req_info); s = s.replaceAll("<!\\[CDATA\\[",""); s = s.replaceAll("]]>", ""); map = this.xmlToMap(s, "UTF-8"); Map<String, String> map1 = new HashMap<>(); map1.put("refund_id", map.get("refund_id")); map1.put("out_refund_no", map.get("out_refund_no")); String result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"; map1.put("result", result); return map1; }else{ // System.err.println(map.get("return_msg")); } } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return null; } /** * 支付宝退款 * @param trade_no 支付宝交易号 * @param refund_amount 退款金额 * @return * @throws AlipayApiException */ public Map<String, String> aliRefund(String trade_no, String refund_amount) throws AlipayApiException { AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, appPrivateKey,"json","UTF-8", alipay_public_key,"RSA2"); AlipayTradeRefundRequest request = new AlipayTradeRefundRequest(); JSONObject jsonObject = new JSONObject(); jsonObject.put("trade_no", trade_no); jsonObject.put("refund_amount", refund_amount); request.setBizContent(jsonObject.toJSONString()); AlipayTradeRefundResponse response = alipayClient.execute(request); Map<String, String> map = new HashMap<>(); if(response.isSuccess()){ System.out.println("调用成功"); String outTradeNo = response.getOutTradeNo(); map.put("code", response.getCode());//10000 map.put("trade_no", response.getTradeNo());//支付宝交易号 map.put("out_trade_no", outTradeNo);//商户订单号 } else { System.out.println("调用失败"); map.put("code", response.getCode()); map.put("msg", response.getSubMsg()); } return map; } /** * 查询微信支付订单 * @return * @throws Exception */ public ResultUtil<Map<String, String>> queryWXOrder(String out_trade_no, String transaction_id) throws Exception{ String url = "https://api.mch.weixin.qq.com/pay/orderquery"; String nonce_str = UUIDUtil.getRandomCode(16); Map<String, Object> map = new HashMap<>(); map.put("appid", appid); map.put("mch_id", mchId); map.put("out_trade_no", out_trade_no);//商户订单号 map.put("transaction_id", transaction_id);//微信订单号 map.put("nonce_str", nonce_str);//随机字符串 String s = this.weixinSignature(map); map.put("sign", s); //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); Set<String> strings = map.keySet(); String[] keys = {}; keys = strings.toArray(keys); Arrays.sort(keys); xmlString.append("<xml>"); for(int l = 0; l < keys.length; l++){ xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">"); } xmlString.append("</xml>"); Map<String, String> map1 = null; String body1 = HttpClientUtil.pushHttpRequsetXml(url, xmlString.toString(), new HashMap<>()).getData(); //将结果xml解析成map body1 = body1.replaceAll("<!\\[CDATA\\[",""); body1 = body1.replaceAll("]]>", ""); try { map1 = this.xmlToMap(body1, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } String return_code = map1.get("return_code"); if("SUCCESS".equals(return_code)){ String result_code = map1.get("result_code"); if("SUCCESS".equals(result_code)){ Map<String, String> map2 = new HashMap<>(); map2.put("trade_type", map1.get("trade_type")); map2.put("trade_state", map1.get("trade_state"));//订单状态SUCCESS—支付成功,REFUND—转入退款,NOTPAY—未支付,CLOSED—已关闭,REVOKED—已撤销(刷卡支付),USERPAYING--用户支付中,PAYERROR--支付失败(其他原因,如银行返回失败) map2.put("transaction_id", map1.get("transaction_id")); return ResultUtil.success(map2); }else{ System.err.println(map1.get("err_code_des")); return ResultUtil.error(map1.get("err_code_des")); } }else{ System.err.println(map1.get("return_msg") + appid + "----" + mchId); return ResultUtil.error(map1.get("return_msg")); } } /** * 微信转账功能(企业付款到零钱) * @param openid 商户appid下,某用户的openid * @param desc 企业付款备注,必填。 * @param total_fee 企业付款金额 * @param partner_trade_no 商户订单号,需保持唯一性 * @return */ public Map<String, String> wxTransfers(String openid, String desc, String total_fee, String partner_trade_no) throws Exception{ int amount = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue(); String nonce_str = UUIDUtil.getRandomCode(); Map<String, Object> map = new HashMap<>(); map.put("mch_appid", appid);//申请商户号的appid或商户号绑定的appid map.put("mchid", mchId);//微信支付分配的商户号 map.put("nonce_str", nonce_str);//随机字符串,不长于32位 map.put("partner_trade_no", partner_trade_no);//商户订单号,需保持唯一性 map.put("openid", openid);//商户appid下,某用户的openid map.put("check_name", "NO_CHECK");//NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓名 map.put("amount", amount);//企业付款金额,单位为分 map.put("desc", desc);//企业付款备注,必填。 String s = this.weixinSignature(map, key); map.put("sign", s); String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); Set<String> strings = map.keySet(); String[] keys = {}; keys = strings.toArray(keys); Arrays.sort(keys); xmlString.append("<xml>"); for(int l = 0; l < keys.length; l++){ xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">"); } xmlString.append("</xml>"); Map<String, String> map1 = null; String body1 = HttpClientUtil.pushHttpsRequsetXml(url, xmlString.toString(), new HashMap<>(), mchId, certPath, "PKCS12"); //将结果xml解析成map body1 = body1.replaceAll("<!\\[CDATA\\[",""); body1 = body1.replaceAll("]]>", ""); try { map1 = this.xmlToMap(body1, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } String return_code = map1.get("return_code"); Map<String, String> map2 = new HashMap<>(); if("SUCCESS".equals(return_code)){ String result_code = map1.get("result_code"); if("SUCCESS".equals(result_code)){ map2.put("return_code", result_code); map2.put("payment_no", String.valueOf(map1.get("payment_no")));//付款订单号 map2.put("payment_time", String.valueOf(map1.get("payment_time")));//付款时间 return map2; }else{ map2.put("return_code", result_code); map2.put("err_code", map1.get("err_code")); map2.put("err_code_des", map1.get("err_code_des")); return map2; } }else{ map2.put("return_code", return_code); map2.put("return_msg", map1.get("return_msg")); return map2; } } /** * 微信转账功能(企业付款到银行卡) * @param desc 备注信息 * @param total_fee 转账金额 * @param partner_trade_no 订单号 * @param enc_bank_no 银行卡号 * @param enc_true_name 收款方用户名 * @param bankName 银行名称 * @return * @throws Exception */ public Map<String, String> wxPayBank(String desc, String total_fee, String partner_trade_no, String enc_bank_no, String enc_true_name, String bankName) throws Exception{ int amount = new BigDecimal(total_fee).multiply(new BigDecimal("100")).intValue(); String nonce_str = UUIDUtil.getRandomCode(); Map<String, Object> map = new HashMap<>(); map.put("mch_id", mchId);//微信支付分配的商户号 map.put("nonce_str", nonce_str);//随机字符串,不长于32位 map.put("partner_trade_no", partner_trade_no);//商户订单号,需保持唯一性 map.put("enc_bank_no", enc_bank_no);//收款方银行卡号(采用标准RSA算法,公钥由微信侧提供) map.put("enc_true_name", enc_true_name);//收款方用户名(采用标准RSA算法,公钥由微信侧提供) map.put("bank_code", findBankCode(bankName));// map.put("amount", amount);//企业付款金额,单位为分 map.put("desc", desc);//企业付款备注,必填。 String s = this.weixinSignature(map, key); map.put("sign", s); String url = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank"; //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); Set<String> strings = map.keySet(); String[] keys = {}; keys = strings.toArray(keys); Arrays.sort(keys); xmlString.append("<xml>"); for(int l = 0; l < keys.length; l++){ xmlString.append("<" + keys[l] + ">" + map.get(keys[l]) + "</" + keys[l] + ">"); } xmlString.append("</xml>"); Map<String, String> map1 = null; String body1 = HttpClientUtil.pushHttpsRequsetXml(url, xmlString.toString(), new HashMap<>(), mchId, certPath, "PKCS12"); //将结果xml解析成map body1 = body1.replaceAll("<!\\[CDATA\\[",""); body1 = body1.replaceAll("]]>", ""); try { map1 = this.xmlToMap(body1, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } String return_code = map1.get("return_code"); Map<String, String> map2 = new HashMap<>(); if("SUCCESS".equals(return_code)){ String result_code = map1.get("result_code"); if("SUCCESS".equals(result_code)){ map2.put("return_code", result_code); map2.put("payment_no", String.valueOf(map1.get("payment_no")));//付款订单号 map2.put("cmms_amt", String.valueOf(map1.get("cmms_amt")));//手续费金额 RMB:分 return map2; }else{ map2.put("return_code", result_code); map2.put("err_code", map1.get("err_code")); map2.put("err_code_des", map1.get("err_code_des")); return map2; } }else{ map2.put("return_code", return_code); map2.put("return_msg", map1.get("return_msg")); return map2; } } /** * 微信转账到银行卡不编号 * @param bankName * @return */ public String findBankCode(String bankName){ String json = "{\"工商银行 \":1002,\"农业银行\":1005,\"建设银行\":1003,\"中国银行\":1026,\"交通银行 \":1020,\"招商银行 \":1001,\"邮储银行\":1066,\"民生银行 \":1006,\"平安银行 \":1010,\"中信银行\":1021,\"浦发银行 \":1004,\"兴业银行 \":1009,\"光大银行 \":1022,\"广发银行\":1027,\"华夏银行\":1025,\"宁波银行\":1056,\"北京银行\":4836,\"上海银行\":1024,\"南京银行\":1054,\"长子县融汇村镇银行\":4755,\"长沙银行\":4216,\"浙江泰隆商业银行\":4051,\"中原银行 \":4753,\"企业银行(中国)\":4761,\"顺德农商银行 \":4036,\"衡水银行\":4752,\"长治银行\":4756,\"大同银行\":4767,\"河南省农村信用社\":4115,\"宁夏黄河农村商业银行\":4150,\"山西省农村信用社\":4156,\"安徽省农村信用社\":4166,\"甘肃省农村信用社\":4157,\"天津农村商业银行\":4153,\"广西壮族自治区农村信用社\":4113,\"陕西省农村信用社\":4108,\"深圳农村商业银行\":4076,\"宁波鄞州农村商业银行\":4052,\"浙江省农村信用社联合社\":4764,\"江苏省农村信用社联合社\":4217,\"江苏紫金农村商业银行股份有限公司 \":4072,\"北京中关村银行股份有限公司 \":4769,\"星展银行( 中国) 有限公司 \":4778,\"枣庄银行股份有限公司 \":4766,\"海口联合农村商业银行股份有限公司 \":4758,\"南洋商业银行( 中国) 有限公司 \":4763}"; JSONObject jsonObject = JSON.parseObject(json); Set<String> strings = jsonObject.keySet(); for(String key : strings){ if(key.indexOf(bankName) >= 0){ return jsonObject.getString(key); } } return ""; } /** * 支付宝转账 * @param out_biz_no 商家侧唯一订单号,由商家自定义。对于不同转账请求,商家需保证该订单号在自身系统唯一。 * @param trans_amount 订单总金额,单位为元,精确到小数点后两位 * @param order_title 转账业务的标题,用于在支付宝用户的账单里显示 * @param identity 参与方的唯一标识(收款方支付宝账号) * @param name 参与方真实姓名,如果非空,将校验收款支付宝账号姓名一致性。 * @param remark 业务备注 * @return * @throws Exception */ public Map<String, Object> aliTransfer(String out_biz_no, Double trans_amount, String order_title, String identity, String name, String remark) throws Exception{ CertAlipayRequest certAlipayRequest = new CertAlipayRequest(); certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); //gateway:支付宝网关(固定)https://openapi.alipay.com/gateway.do certAlipayRequest.setAppId(aliAppid); //APPID 即创建应用后生成,详情见创建应用并获取 APPID certAlipayRequest.setPrivateKey(appPrivateKey); //开发者应用私钥,由开发者自己生成 certAlipayRequest.setFormat("json"); //参数返回格式,只支持 json 格式 certAlipayRequest.setCharset("UTF-8"); //请求和签名使用的字符编码格式,支持 GBK和 UTF-8 certAlipayRequest.setSignType("RSA2"); //商户生成签名字符串所使用的签名算法类型,目前支持 RSA2 和 RSA,推荐商家使用 RSA2。 certAlipayRequest.setCertPath(app_cert_path); //应用公钥证书路径(app_cert_path 文件绝对路径) certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path); //支付宝公钥证书文件路径(alipay_cert_path 文件绝对路径) certAlipayRequest.setRootCertPath(alipay_root_cert_path); //支付宝CA根证书文件路径(alipay_root_cert_path 文件绝对路径) AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest); AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest(); request.setBizContent("{" + "\"out_biz_no\":\"" + out_biz_no + "\"," + "\"trans_amount\":" + trans_amount + "," + "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," + "\"biz_scene\":\"DIRECT_TRANSFER\"," + "\"order_title\":\"" + order_title + "\"," + "\"payee_info\":{" + "\"identity\":\"" + identity + "\"," + "\"identity_type\":\"ALIPAY_USER_ID\"," + "\"name\":\"" + name + "\"," + "}," + "\"remark\":\"" + remark + "\"" + "}"); AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request); Map<String, Object> map = new HashMap<>(); if(response.isSuccess()){ String status = response.getStatus(); if(status.equals("SUCCESS")){//成功 map.put("code", response.getCode()); map.put("order_id", response.getOrderId());//支付宝订单号 map.put("pay_fund_order_id", response.getPayFundOrderId());//支付宝流水号 }else{ map.put("code", response.getCode()); map.put("sub_msg", response.getSubMsg()); } } else { map.put("code", response.getSubCode()); map.put("sub_msg", response.getSubMsg()); } return map; } /** * 获取请求内容 * @param request * @return * @throws IOException */ private String getParam(HttpServletRequest request) throws IOException { // 读取参数 InputStream inputStream; StringBuilder sb = new StringBuilder(); inputStream = request.getInputStream(); String s; BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); while ((s = in.readLine()) != null) { sb.append(s); } in.close(); inputStream.close(); return sb.toString(); } /** * 微信下单的签名算法 * @param map * @return */ private String weixinSignature(Map<String, Object> map){ try { Set<Map.Entry<String, Object>> entries = map.entrySet(); List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(entries); // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序) Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() { public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) { return (o1.getKey()).toString().compareTo(o2.getKey()); } }); // 构造签名键值对的格式 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Object> item : infoIds) { if (item.getKey() != null || item.getKey() != "") { String key = item.getKey(); Object val = item.getValue(); if (!(val == "" || val == null)) { sb.append(key + "=" + val + "&"); } } } sb.append("key=" + key); String sign = MD5AndKL.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); //注:MD5签名方式 return sign; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 微信下单的签名算法 * @param map * @return */ private String weixinSignature(Map<String, Object> map, String key_){ try { Set<Map.Entry<String, Object>> entries = map.entrySet(); List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(entries); // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序) Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() { public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) { return (o1.getKey()).toString().compareTo(o2.getKey()); } }); // 构造签名键值对的格式 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, Object> item : infoIds) { if (item.getKey() != null || item.getKey() != "") { String key = item.getKey(); Object val = item.getValue(); if (!(val == "" || val == null)) { sb.append(key + "=" + val + "&"); } } } sb.append("key=" + key_); String sign = MD5AndKL.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); //注:MD5签名方式 return sign; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 微信退款成功后的解密 * @param req_info * @return */ private String wxDecrypt(String req_info) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { byte[] decode = Base64.getDecoder().decode(req_info); String sign = MD5AndKL.MD5Encode(key, "UTF-8").toLowerCase(); if (Security.getProvider("BC") == null){ Security.addProvider(new BouncyCastleProvider()); } Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); SecretKeySpec secretKeySpec = new SecretKeySpec(sign.getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); return new String(cipher.doFinal(decode)); } public static void main(String[] ages){ // PayMoneyUtil payMoneyUtil = new PayMoneyUtil(); // payMoneyUtil.weixinpay("测试", "123", "12.5", ""); } /** * xml转map * @param xml * @param charset * @return * @throws UnsupportedEncodingException * @throws DocumentException */ public static Map<String, String> xmlToMap(String xml, String charset) throws UnsupportedEncodingException, DocumentException { Map<String, String> respMap = new HashMap<String, String>(); SAXReader reader = new SAXReader(); Document doc = reader.read(new ByteArrayInputStream(xml.getBytes(charset))); Element root = doc.getRootElement(); xmlToMap(root, respMap); return respMap; } public static Map<String, String> xmlToMap(Element tmpElement, Map<String, String> respMap){ if (tmpElement.isTextOnly()) { respMap.put(tmpElement.getName(), tmpElement.getText()); return respMap; } @SuppressWarnings("unchecked") Iterator<Element> eItor = tmpElement.elementIterator(); while (eItor.hasNext()) { Element element = eItor.next(); xmlToMap(element, respMap); } return respMap; } } cloud-server-other/src/main/java/com/dsh/other/util/UUIDUtil.java
New file @@ -0,0 +1,101 @@ package com.dsh.other.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * 定义生成随机码的工具类 */ public class UUIDUtil { private int i = 1; /** * 定义生成原生的UUID随机码 * @return */ public static String getNativeUUID(){ return UUID.randomUUID().toString(); } /** * 生成32位随机码 * @return */ public static String getRandomCode(){ return UUIDUtil.getNativeUUID().replaceAll("-", ""); } /** * 获取给定长度的随机码 * @param num * @return * @throws Exception */ public static String getRandomCode(Integer num) throws Exception{ String str = null; if(0 < num){ if(num % 32 > 0){ Integer s = num / 32; Integer l = num % 32; StringBuffer sb = new StringBuffer(); for(int i = 0; i < s; i++){ sb.append(UUIDUtil.getRandomCode()); } sb.append(UUIDUtil.getRandomCode().substring(0, l)); str = sb.toString(); }else if(num % 32 == 0){ Integer s = num / 32; StringBuffer sb = new StringBuffer(); for(int i = 0; i < s; i++){ sb.append(UUIDUtil.getRandomCode()); } str = sb.toString(); }else{ str = UUIDUtil.getRandomCode().substring(0, num); } }else{ throw new Exception("参数只能大于0"); } return str; } /** * 获取根据当前时间的字符串数据 * @return */ public synchronized static String getTimeStr(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmssS"); return simpleDateFormat.format(new Date()); } /** * @Description: 获取数字随机码 * @Author pzb * @Date 2021/8/11 16:52 * @Param * @Return * @Exception */ public static String getNumberRandom(Integer num){ if(null == num){ num = 32; } StringBuffer sb = new StringBuffer(); for(int i = 0; i < num; i++){ sb.append(Double.valueOf(Math.random() * 10).intValue()); } return sb.toString(); } } cloud-server-other/src/main/java/com/dsh/other/util/httpClinet/HttpClientUtil.java
@@ -196,14 +196,14 @@ * @return * @throws Exception */ public String pushHttpsRequsetXml(String url, String xml, Map<String, String> header, String certPassword, String certPath, String certType) throws Exception{ public static String pushHttpsRequsetXml(String url, String xml, Map<String, String> header, String certPassword, String certPath, String certType) throws Exception{ HttpPost httpPost = new HttpPost(url); for(String key : header.keySet()){ httpPost.setHeader(key, header.get(key)); } httpPost.setHeader("Content-Type", "application/xml"); httpPost.setEntity(new StringEntity(xml, "UTF-8")); CloseableHttpClient httpCline = this.initCert(certPassword, certPath, certType); CloseableHttpClient httpCline = initCert(certPassword, certPath, certType); CloseableHttpResponse httpResponse = httpCline.execute(httpPost); String content = null; if(httpResponse.getStatusLine().getStatusCode() == 200){ @@ -211,7 +211,7 @@ }else{ content = "返回状态码:" + httpResponse.getStatusLine() + "。" + EntityUtils.toString(httpResponse.getEntity()); } this.close(httpResponse); close(httpResponse); httpCline.close(); return content; } @@ -224,7 +224,7 @@ * @param certType 证书类型 * @throws Exception */ private CloseableHttpClient initCert(String key, String certPath, String certType) throws Exception { private static CloseableHttpClient initCert(String key, String certPath, String certType) throws Exception { KeyStore keyStore = KeyStore.getInstance(certType); InputStream inputStream = new FileInputStream(new File(certPath)); try { cloud-server-other/src/main/resources/mapper/SiteLockMapper.xml
New file @@ -0,0 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dsh.other.mapper.SiteLockMapper"> </mapper> cloud-server-other/src/main/resources/mapper/SiteMapper.xml
@@ -30,6 +30,9 @@ <if test="null != item.storeId"> and a.storeId = #{item.storeId} </if> <if test="null != item.search and '' != item.search"> and (a.name like CONCAT('%', #{item.search}, '%') or b.name like CONCAT('%', #{item.search}, '%')) </if> order by a.insertTime desc limit #{item.pageNum}, #{item.pageSize} </select> </mapper>