退款申请接口实现优化

This commit is contained in:
dzl 2025-05-19 09:47:18 +08:00
parent df1e4a4574
commit aa3c09b95e

View File

@ -96,7 +96,7 @@ public class WxPayServiceImpl implements WxPayService {
@Override @Override
public JSONObject prepay(String orderId){ public JSONObject prepay(String orderId) {
JSONObject r = new JSONObject(); JSONObject r = new JSONObject();
// 首先检查订单是否正在付中或者已经支付成功 // 首先检查订单是否正在付中或者已经支付成功
// 关闭了的订单重新发起请求 // 关闭了的订单重新发起请求
@ -109,26 +109,26 @@ public class WxPayServiceImpl implements WxPayService {
return r; return r;
} }
if (String.valueOf(Transaction.TradeStateEnum.NOTPAY.ordinal()).equals(tradeState) if (String.valueOf(Transaction.TradeStateEnum.NOTPAY.ordinal()).equals(tradeState)
||String.valueOf(Transaction.TradeStateEnum.USERPAYING.ordinal()).equals(tradeState)) { || String.valueOf(Transaction.TradeStateEnum.USERPAYING.ordinal()).equals(tradeState)) {
// 检查订单是否关闭 // 检查订单是否关闭
Transaction t = queryOrderByOutTradeNo(ebikePayment.getPaymentId()); Transaction t = queryOrderByOutTradeNo(ebikePayment.getPaymentId());
if (t != null && Transaction.TradeStateEnum.CLOSED.equals(t.getTradeState())) { if (t != null && Transaction.TradeStateEnum.CLOSED.equals(t.getTradeState())) {
// 增加状态检查防止已支付消息未返回重复发起请求 // 增加状态检查防止已支付消息未返回重复发起请求
HandleNotifyResult hr = queryOrderStatusByOrderId(ebikePayment); HandleNotifyResult hr = queryOrderStatusByOrderId(ebikePayment);
if(hr.isSuccess()){ if (hr.isSuccess()) {
r.put("error", "订单已经支付成功"); r.put("error", "订单已经支付成功");
return r; return r;
} }
log.info("订单已经关闭,订单号:{}, 重新发起请求", orderId); log.info("订单已经关闭,订单号:{}, 重新发起请求", orderId);
ebikePayment.setTradeState(String.valueOf(Transaction.TradeStateEnum.CLOSED.ordinal())); ebikePayment.setTradeState(String.valueOf(Transaction.TradeStateEnum.CLOSED.ordinal()));
ebikePayment.setPaymentId(StringUtils.generateSnowflakeId("paymentId")); ebikePayment.setPaymentId(StringUtils.generateSnowflakeId("paymentId"));
}else{ } else {
log.info("订单正在支付中,订单号:{}", orderId); log.info("订单正在支付中,订单号:{}", orderId);
} }
} else if (String.valueOf(Transaction.TradeStateEnum.CLOSED.ordinal()).equals(tradeState)) { } else if (String.valueOf(Transaction.TradeStateEnum.CLOSED.ordinal()).equals(tradeState)) {
log.info("订单已经关闭,订单号:{}, 重新发起请求", orderId); log.info("订单已经关闭,订单号:{}, 重新发起请求", orderId);
ebikePayment.setPaymentId(StringUtils.generateSnowflakeId("paymentId")); ebikePayment.setPaymentId(StringUtils.generateSnowflakeId("paymentId"));
}else { } else {
log.info("订单状态异常,订单号:{}", orderId); log.info("订单状态异常,订单号:{}", orderId);
r.put("error", "订单状态异常: "); r.put("error", "订单状态异常: ");
return r; return r;
@ -138,7 +138,7 @@ public class WxPayServiceImpl implements WxPayService {
JsonResult<?> result = ordersFeignClient.getPaymentDetails(Long.valueOf(orderId)); JsonResult<?> result = ordersFeignClient.getPaymentDetails(Long.valueOf(orderId));
if (result.getCode() != 200) { if (result.getCode() != 200) {
log.error("查询订单 {} 失败, {}", orderId, result.getMessage()); log.error("查询订单 {} 失败, {}", orderId, result.getMessage());
r.put("error", "查询订单失败, "+result.getMessage()); r.put("error", "查询订单失败, " + result.getMessage());
return r; return r;
} }
EbikePaymentDto paymentDto = JSON.parseObject(JSONObject.toJSONString(result.getData()), EbikePaymentDto.class); EbikePaymentDto paymentDto = JSON.parseObject(JSONObject.toJSONString(result.getData()), EbikePaymentDto.class);
@ -149,7 +149,7 @@ public class WxPayServiceImpl implements WxPayService {
/** /**
* JSAPI支付下单 * JSAPI支付下单
* *
* @param paymentDto 支付信息 * @param paymentDto 支付信息
* @param ebikePayment 原始支付记录 * @param ebikePayment 原始支付记录
* @return 下单成功返回wx支付请求参数否则返回null * @return 下单成功返回wx支付请求参数否则返回null
*/ */
@ -161,7 +161,7 @@ public class WxPayServiceImpl implements WxPayService {
String openId = paymentDto.getOpenId(); String openId = paymentDto.getOpenId();
AmountDto amount = paymentDto.getAmount(); AmountDto amount = paymentDto.getAmount();
DetailDto detail = paymentDto.getDetail(); DetailDto detail = paymentDto.getDetail();
String payId = ebikePayment==null?outTradeNo : ebikePayment.getPaymentId(); String payId = ebikePayment == null ? outTradeNo : ebikePayment.getPaymentId();
try { try {
PrepayRequest request = new PrepayRequest(); PrepayRequest request = new PrepayRequest();
request.setAppid(wxPayConfig.getAppId()); request.setAppid(wxPayConfig.getAppId());
@ -185,21 +185,21 @@ public class WxPayServiceImpl implements WxPayService {
goodsDetailReq.setGoodsName(goodsDetail.getItemName()); goodsDetailReq.setGoodsName(goodsDetail.getItemName());
goodsDetailReq.setMerchantGoodsId(goodsDetail.getItemId()); goodsDetailReq.setMerchantGoodsId(goodsDetail.getItemId());
goodsDetailReq.setQuantity(goodsDetail.getQuantity()); goodsDetailReq.setQuantity(goodsDetail.getQuantity());
goodsDetailReq.setUnitPrice(BigDecimal.valueOf(goodsDetail.getUnitPrice()*100.0).intValue()); goodsDetailReq.setUnitPrice(BigDecimal.valueOf(goodsDetail.getUnitPrice() * 100.0).intValue());
return goodsDetailReq; return goodsDetailReq;
}).toList(); }).toList();
if (goodsDetails.isEmpty()){ if (goodsDetails.isEmpty()) {
goodsDetails = new ArrayList<>(); goodsDetails = new ArrayList<>();
GoodsDetail goodsDetail = new GoodsDetail(); GoodsDetail goodsDetail = new GoodsDetail();
String snowId = StringUtils.generateSnowflakeId("goodsId"); String snowId = StringUtils.generateSnowflakeId("goodsId");
goodsDetail.setMerchantGoodsId(snowId); goodsDetail.setMerchantGoodsId(snowId);
goodsDetail.setGoodsName(goodsTag); goodsDetail.setGoodsName(goodsTag);
goodsDetail.setQuantity(1); goodsDetail.setQuantity(1);
goodsDetail.setUnitPrice(BigDecimal.valueOf(amount.getTotal()*100.0).intValue()); goodsDetail.setUnitPrice(BigDecimal.valueOf(amount.getTotal() * 100.0).intValue());
goodsDetails.add(goodsDetail); goodsDetails.add(goodsDetail);
} }
detailReq.setGoodsDetail(goodsDetails); detailReq.setGoodsDetail(goodsDetails);
detailReq.setCostPrice(BigDecimal.valueOf(detail.getCostPrice()*100.0).intValue()); detailReq.setCostPrice(BigDecimal.valueOf(detail.getCostPrice() * 100.0).intValue());
detailReq.setInvoiceId(detail.getInvoiceId()); detailReq.setInvoiceId(detail.getInvoiceId());
request.setDetail(detailReq); request.setDetail(detailReq);
SettleInfo settleInfo = new SettleInfo(); SettleInfo settleInfo = new SettleInfo();
@ -220,7 +220,7 @@ public class WxPayServiceImpl implements WxPayService {
ebikePayment.setCostPrice(amount.getTotal()); ebikePayment.setCostPrice(amount.getTotal());
ebikePayment.setTradeState(String.valueOf(Transaction.TradeStateEnum.NOTPAY.ordinal())); ebikePayment.setTradeState(String.valueOf(Transaction.TradeStateEnum.NOTPAY.ordinal()));
ebikePaymentService.save(ebikePayment); ebikePaymentService.save(ebikePayment);
}else{ } else {
ebikePayment.setPaymentId(payId); ebikePayment.setPaymentId(payId);
ebikePayment.setCreateTime(LocalDateTime.now()); ebikePayment.setCreateTime(LocalDateTime.now());
ebikePayment.setPaymentMethod(PayMethod.wechat.name()); ebikePayment.setPaymentMethod(PayMethod.wechat.name());
@ -239,9 +239,9 @@ public class WxPayServiceImpl implements WxPayService {
log.error("微信支付下单prepay失败订单号{}", outTradeNo); log.error("微信支付下单prepay失败订单号{}", outTradeNo);
r.put("error", "微信支付下单prepay失败"); r.put("error", "微信支付下单prepay失败");
return r; return r;
}catch (Exception e) { } catch (Exception e) {
logError("微信支付下单prepay", e); logError("微信支付下单prepay", e);
r.put("error", "微信支付下单prepay失败: "+e.getMessage()); r.put("error", "微信支付下单prepay失败: " + e.getMessage());
return r; return r;
} }
} }
@ -257,7 +257,7 @@ public class WxPayServiceImpl implements WxPayService {
@Override @Override
public Transaction queryOrderByOrderId(String orderId) { public Transaction queryOrderByOrderId(String orderId) {
EbikePayment ebikePayment = ebikePaymentService.getByOrderId(orderId); EbikePayment ebikePayment = ebikePaymentService.getByOrderId(orderId);
if (ebikePayment==null){ if (ebikePayment == null) {
log.error("{}支付订单不存在", orderId); log.error("{}支付订单不存在", orderId);
return null; return null;
} }
@ -290,8 +290,8 @@ public class WxPayServiceImpl implements WxPayService {
*/ */
private HandleNotifyResult queryOrderStatusByOrderId(EbikePayment ebikePayment) { private HandleNotifyResult queryOrderStatusByOrderId(EbikePayment ebikePayment) {
HandleNotifyResult result = new HandleNotifyResult(); HandleNotifyResult result = new HandleNotifyResult();
Transaction r =queryOrderByOutTradeNo(ebikePayment.getPaymentId()); Transaction r = queryOrderByOutTradeNo(ebikePayment.getPaymentId());
if(r!=null&& Transaction.TradeStateEnum.SUCCESS.equals(r.getTradeState())) { if (r != null && Transaction.TradeStateEnum.SUCCESS.equals(r.getTradeState())) {
result.setMessage(String.format("订单%s支付成功", ebikePayment.getOrderId())); result.setMessage(String.format("订单%s支付成功", ebikePayment.getOrderId()));
result.setSuccess(true); result.setSuccess(true);
// 更新支付状态 // 更新支付状态
@ -320,7 +320,7 @@ public class WxPayServiceImpl implements WxPayService {
.nonce(nonce) .nonce(nonce)
.build(); .build();
// 验签并解析通知 // 验签并解析通知
NotificationParser parser = new NotificationParser((NotificationConfig)certificateConfig); NotificationParser parser = new NotificationParser((NotificationConfig) certificateConfig);
// 解析解密后的通知 // 解析解密后的通知
Transaction transaction = parser.parse(requestParam, Transaction.class); Transaction transaction = parser.parse(requestParam, Transaction.class);
// 更新状态 // 更新状态
@ -329,7 +329,7 @@ public class WxPayServiceImpl implements WxPayService {
result.setSuccess(true); result.setSuccess(true);
result.setMessage("success"); result.setMessage("success");
return result; return result;
}catch (Exception e) { } catch (Exception e) {
result.setMessage(String.format("verify failed, request-id=[%s]", requestId)); result.setMessage(String.format("verify failed, request-id=[%s]", requestId));
logError("支付通知回调handlePayNotify", e); logError("支付通知回调handlePayNotify", e);
return result; return result;
@ -340,12 +340,12 @@ public class WxPayServiceImpl implements WxPayService {
public String refundApply(String outTradeNo, String reason) { public String refundApply(String outTradeNo, String reason) {
// 检查是否重复退款申请 // 检查是否重复退款申请
EbikeRefund ebikeRefund = ebikeRefundService.getByOrderId(outTradeNo); EbikeRefund ebikeRefund = ebikeRefundService.getByOrderId(outTradeNo);
if (ebikeRefund!= null) { if (ebikeRefund != null) {
if(String.valueOf(Status.PROCESSING.ordinal()).equals(ebikeRefund.getStatus())){ if (String.valueOf(Status.PROCESSING.ordinal()).equals(ebikeRefund.getStatus())) {
log.error("订单{}正在退款中", outTradeNo); log.error("订单{}正在退款中", outTradeNo);
return null; return null;
} }
if(String.valueOf(Status.SUCCESS.ordinal()).equals(ebikeRefund.getStatus())) { if (String.valueOf(Status.SUCCESS.ordinal()).equals(ebikeRefund.getStatus())) {
log.error("订单{}已经退款过", outTradeNo); log.error("订单{}已经退款过", outTradeNo);
return null; return null;
} }
@ -374,7 +374,7 @@ public class WxPayServiceImpl implements WxPayService {
@Override @Override
public Boolean refundReview(ReqRefundProcessDto processDto) { public Boolean refundReview(ReqRefundProcessDto processDto) {
EbikeRefund ebikeRefund = ebikeRefundService.getById(processDto.getRefundId()); EbikeRefund ebikeRefund = ebikeRefundService.getById(processDto.getRefundId());
if (ebikeRefund==null){ if (ebikeRefund == null) {
log.error("审核refundReview失败{} 退款申请不存在", processDto.getRefundId()); log.error("审核refundReview失败{} 退款申请不存在", processDto.getRefundId());
return false; return false;
} }
@ -382,8 +382,9 @@ public class WxPayServiceImpl implements WxPayService {
ebikeRefund.setProcessState(processDto.getOperate()); ebikeRefund.setProcessState(processDto.getOperate());
ebikeRefund.setProcessTime(LocalDateTime.now()); ebikeRefund.setProcessTime(LocalDateTime.now());
ebikeRefund.setRemark(processDto.getReason()); ebikeRefund.setRemark(processDto.getReason());
if(String.valueOf(RefundProcessState.processing).equals(processDto.getOperate())){ if (String.valueOf(RefundProcessState.processing).equals(processDto.getOperate())) {
ebikeRefund.setRefund(ebikeRefund.getRefundApply()); ebikeRefund.setRefund(ebikeRefund.getRefundApply());
ebikeRefund.setRefundMethod(processDto.getMethod());
} }
return ebikeRefundService.updateById(ebikeRefund); return ebikeRefundService.updateById(ebikeRefund);
} }
@ -396,7 +397,7 @@ public class WxPayServiceImpl implements WxPayService {
//} //}
// 检查退款记录是否存在 // 检查退款记录是否存在
EbikeRefund ebikeRefund = ebikeRefundService.getById(refundDto.getRefundId()); EbikeRefund ebikeRefund = ebikeRefundService.getById(refundDto.getRefundId());
if (ebikeRefund==null){ if (ebikeRefund == null) {
log.error("退款refund失败{} 退款申请不存在", refundDto.getRefundId()); log.error("退款refund失败{} 退款申请不存在", refundDto.getRefundId());
return false; return false;
} }
@ -428,7 +429,7 @@ public class WxPayServiceImpl implements WxPayService {
ebikeRefund.setTotal(amount.getTotal()); ebikeRefund.setTotal(amount.getTotal());
ebikeRefund.setStatus(String.valueOf(result.getStatus().ordinal())); ebikeRefund.setStatus(String.valueOf(result.getStatus().ordinal()));
ebikeRefund.setCurrency(amount.getCurrency()); ebikeRefund.setCurrency(amount.getCurrency());
if(Status.SUCCESS.equals(result.getStatus())){ if (Status.SUCCESS.equals(result.getStatus())) {
ebikeRefund.setRefund(result.getAmount().getRefund().doubleValue() / 100.0); ebikeRefund.setRefund(result.getAmount().getRefund().doubleValue() / 100.0);
ebikeRefund.setRefundTime(LocalDateTime.now()); ebikeRefund.setRefundTime(LocalDateTime.now());
ebikeRefund.setRemark(refundDto.getRemark()); ebikeRefund.setRemark(refundDto.getRemark());
@ -453,20 +454,20 @@ public class WxPayServiceImpl implements WxPayService {
HandleNotifyResult result = new HandleNotifyResult(); HandleNotifyResult result = new HandleNotifyResult();
// 先查本地数据库如果退款状态不为SUCCESS需要查询微信支付 // 先查本地数据库如果退款状态不为SUCCESS需要查询微信支付
EbikeRefund ebikeRefund = ebikeRefundService.getById(outRefundNo); EbikeRefund ebikeRefund = ebikeRefundService.getById(outRefundNo);
if (ebikeRefund==null){ if (ebikeRefund == null) {
log.error("{}退款订单不存在", outRefundNo); log.error("{}退款订单不存在", outRefundNo);
result.setMessage(String.format("{%s}退款订单不存在", outRefundNo)); result.setMessage(String.format("{%s}退款订单不存在", outRefundNo));
return result; return result;
} }
result.setSuccess(String.valueOf(Status.SUCCESS.ordinal()).equals(ebikeRefund.getStatus())); result.setSuccess(String.valueOf(Status.SUCCESS.ordinal()).equals(ebikeRefund.getStatus()));
if (result.isSuccess()){ if (result.isSuccess()) {
result.setMessage(String.format("退款%s成功", ebikeRefund.getRefundId())); result.setMessage(String.format("退款%s成功", ebikeRefund.getRefundId()));
return result; return result;
} }
QueryByOutRefundNoRequest request = new QueryByOutRefundNoRequest(); QueryByOutRefundNoRequest request = new QueryByOutRefundNoRequest();
request.setOutRefundNo(outRefundNo); request.setOutRefundNo(outRefundNo);
Refund r = wxRefundService.queryByOutRefundNo(request); Refund r = wxRefundService.queryByOutRefundNo(request);
if(r!=null&& r.getStatus().equals(Status.SUCCESS)) { if (r != null && r.getStatus().equals(Status.SUCCESS)) {
result.setMessage(String.format("退款%s成功", ebikeRefund.getRefundId())); result.setMessage(String.format("退款%s成功", ebikeRefund.getRefundId()));
result.setSuccess(true); result.setSuccess(true);
// 更新退款状态 // 更新退款状态
@ -495,7 +496,7 @@ public class WxPayServiceImpl implements WxPayService {
.nonce(nonce) .nonce(nonce)
.build(); .build();
// 验签并解析通知 // 验签并解析通知
NotificationParser parser = new NotificationParser((NotificationConfig)certificateConfig); NotificationParser parser = new NotificationParser((NotificationConfig) certificateConfig);
// 解析解密后的通知 // 解析解密后的通知
Refund refund = parser.parse(requestParam, Refund.class); Refund refund = parser.parse(requestParam, Refund.class);
// 更新状态 // 更新状态
@ -504,7 +505,7 @@ public class WxPayServiceImpl implements WxPayService {
result.setSuccess(true); result.setSuccess(true);
result.setMessage("success"); result.setMessage("success");
return result; return result;
}catch (Exception e) { } catch (Exception e) {
result.setMessage(String.format("verify failed, request-id=[%s]", requestId)); result.setMessage(String.format("verify failed, request-id=[%s]", requestId));
logError("退款通知回调handleRefundNotify", e); logError("退款通知回调handleRefundNotify", e);
return result; return result;
@ -526,22 +527,18 @@ public class WxPayServiceImpl implements WxPayService {
* 打印日志 * 打印日志
* *
* @param desc 描述 * @param desc 描述
* @param e 异常 * @param e 异常
*/ */
private void logError(String desc, Exception e) { private void logError(String desc, Exception e) {
if (e instanceof HttpException httpException) { if (e instanceof HttpException httpException) {
log.error("{} 发送HTTP请求失败, {}", desc, httpException.getHttpRequest()); log.error("{} 发送HTTP请求失败, {}", desc, httpException.getHttpRequest());
} } else if (e instanceof ServiceException serviceException) {
else if (e instanceof ServiceException serviceException) {
log.error("{} 服务返回状态不正常, {}", desc, serviceException.getResponseBody()); log.error("{} 服务返回状态不正常, {}", desc, serviceException.getResponseBody());
} } else if (e instanceof MalformedMessageException malformedMessageException) {
else if (e instanceof MalformedMessageException malformedMessageException) {
log.error("{} 返回体类型不合法或者解析返回体失败, {}", desc, malformedMessageException.getMessage()); log.error("{} 返回体类型不合法或者解析返回体失败, {}", desc, malformedMessageException.getMessage());
} } else if (e instanceof ValidationException validationException) {
else if (e instanceof ValidationException validationException) {
log.error("{} 验签失败,验证签名失败,{}", desc, validationException.getMessage()); log.error("{} 验签失败,验证签名失败,{}", desc, validationException.getMessage());
} } else {
else {
log.error("{} 执行异常, {}", desc, e.getMessage()); log.error("{} 执行异常, {}", desc, e.getMessage());
} }