Jelajahi Sumber

退款相关接口调试

skyline 2 tahun lalu
induk
melakukan
1ab5fa75b4

+ 2 - 7
admin/src/main/java/com/kym/admin/controller/FinanceController.java

@@ -25,12 +25,7 @@ public class FinanceController {
         this.refundLogService = refundLogService;
     }
 
-    /**
-     * 退款申请列表
-     *
-     * @param params
-     * @return
-     */
+    @SysLog("退款申请列表")
     @GetMapping("/listRefundLog")
     R<?> listRefundLog(@ModelAttribute CommonQueryParam params) {
         return R.success(refundLogService.listRefundLog(params));
@@ -44,7 +39,7 @@ public class FinanceController {
     }
 
     @SysLog("开具发票")
-    @GetMapping("handleInvoice")
+    @GetMapping("/handleInvoice")
     R<?> handleInvoice() {
         return R.success(wxPayService.baseInformation());
     }

+ 2 - 22
miniapp/src/main/java/com/kym/miniapp/controller/PaymentController.java

@@ -1,22 +1,15 @@
 package com.kym.miniapp.controller;
 
-import cn.hutool.core.util.XmlUtil;
 import com.alibaba.fastjson2.JSONObject;
 import com.kym.common.R;
 import com.kym.common.annotation.ApiLog;
 import com.kym.service.wechat.WxPayService;
 import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
 import lombok.SneakyThrows;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.*;
 
-import java.util.HashMap;
-import java.util.Map;
-
 
 /**
  * @author skyline
@@ -27,7 +20,6 @@ import java.util.Map;
 @RequestMapping("/payment")
 public class PaymentController {
     private final WxPayService wxPayService;
-    private Logger logger = LoggerFactory.getLogger(PaymentController.class);
 
     public PaymentController(WxPayService wxPayService) {
         this.wxPayService = wxPayService;
@@ -58,19 +50,7 @@ public class PaymentController {
 
     @ApiLog(value = "微信退款回调", ignoreParams = true)
     @PostMapping("/refundNotify")
-    String refundNotify(HttpServletRequest request, HttpServletResponse response) {
-        response.setContentType("text/xml");
-        Map<String, String> result = new HashMap<>();
-        try {
-            wxPayService.wxRefundNotify(request);
-            result.put("return_code", "SUCCESS");
-            result.put("return_msg", "OK");
-        } catch (Exception e) {
-            result.put("return_code", "FAIL");
-            result.put("return_msg", e.getMessage());
-        }
-        String resp = XmlUtil.mapToXmlStr(result);
-        logger.info("wxRefund notify result>>>:{}", resp);
-        return resp;
+    ResponseEntity<Object> refundNotify(HttpServletRequest request) {
+        return wxPayService.wxRefundNotify(request);
     }
 }

+ 1 - 1
service/src/main/java/com/kym/service/wechat/WxPayService.java

@@ -25,7 +25,7 @@ public interface WxPayService {
     Refund queryByOutRefundNo(String outRefundNo);
 
     @SneakyThrows
-    void wxRefundNotify(HttpServletRequest request);
+    ResponseEntity<Object> wxRefundNotify(HttpServletRequest request);
 
     PrepayWithRequestPaymentResponse wxPay(JSONObject rechargeAmount);
 

+ 29 - 25
service/src/main/java/com/kym/service/wechat/impl/WxPayServiceImpl.java

@@ -376,7 +376,7 @@ public class WxPayServiceImpl implements WxPayService {
         }
 
         // 将余额转移至冻结余额
-        accountService.lambdaUpdate().setSql(" frozen_amount = (frozen_amount + balance ,balance = 0").eq(Account::getUserId, userId).update();
+        accountService.lambdaUpdate().setSql(" frozen_amount = (frozen_amount + balance) ,balance = 0").eq(Account::getUserId, userId).update();
 
         // 余减去优惠金额作为退款金额
         AtomicInteger refundAmount = new AtomicInteger(account.getBalance() - account.getDiscountAmount());
@@ -393,10 +393,10 @@ public class WxPayServiceImpl implements WxPayService {
         // 最后一次的充值金额可以覆盖退款金额
         if (!CommUtil.isEmptyOrNull(payLogs) && payLogs.get(0).getTotal() >= refundAmount.get()) {
             // 退款日志
-            new RefundLog().setUserId(payLogs.get(0).getUserId()).setOutTradeNo(payLogs.get(0).getOutTradeNo())
+            var refundLog = new RefundLog().setUserId(payLogs.get(0).getUserId()).setOutTradeNo(payLogs.get(0).getOutTradeNo())
                     .setTotal(payLogs.get(0).getTotal()).setRefund(payLogs.get(0).getTotal() - account.getDiscountAmount())
                     .setDiscountAmount(account.getDiscountAmount()).setOutRefundNo(OrderUtils.getOrderNo());
-
+            refundLogService.save(refundLog);
         } else if (!CommUtil.isEmptyOrNull(payLogs) && payLogs.get(0).getTotal() < refundAmount.get()) {
             // 最后一次的充值金额不能覆盖退款金额,拆分成多笔退款
             int amount = 0;
@@ -433,7 +433,7 @@ public class WxPayServiceImpl implements WxPayService {
                 if (index < size) {
                     discountAmount = account.getDiscountAmount() * (refundLog.getRefund() / refundAmount.get());
                 } else {
-                    // 签名存在精度误差,最后一个元素用总数详见最精确
+                    // 前面存在精度误差,最后一个元素用总数详见最精确
                     discountAmount = account.getDiscountAmount() - refundLogList.stream().mapToInt(RefundLog::getDiscountAmount).sum();
                 }
                 refundLog.setDiscountAmount(discountAmount);
@@ -443,7 +443,7 @@ public class WxPayServiceImpl implements WxPayService {
             refundLogService.saveBatch(refundLogList);
         } else {
             // 退款异常
-            LOGGER.error("退款异常:userId:{},余额:{},payLogs:{}", userId, refundAmount.get(), payLogs);
+            LOGGER.error("退款异常:userId:{},余额:{},payLogs:{}", userId, refundAmount.get(), payLogs);
             throw new BusinessException("退款异常");
         }
     }
@@ -513,10 +513,11 @@ public class WxPayServiceImpl implements WxPayService {
      * 微信退款结果通知
      *
      * @param request
+     * @return
      */
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public void wxRefundNotify(HttpServletRequest request) {
+    public ResponseEntity<Object> wxRefundNotify(HttpServletRequest request) {
         var notifyRes = handleWxNotify(request);
 
         try {
@@ -528,22 +529,22 @@ public class WxPayServiceImpl implements WxPayService {
             var refundLog = refundLogService.lambdaQuery().eq(RefundLog::getOutRefundNo, refundNotification.getOutRefundNo()).one();
             // 防止重复处理消息
             if (RefundLog.STATUS_退款成功.equals(refundLog.getStatus())) {
-                return;
+                return ResponseEntity.status(HttpStatus.OK).build();
             }
 
             DateTime dt = DateUtil.parse(refundNotification.getSuccessTime());
             LocalDateTime successTime = LocalDateTimeUtil.of(dt);
 
-            refundLog
-                    .setRefundId(refundNotification.getRefundId())
-                    .setTransactionId(refundNotification.getTransactionId())
-                    .setUserReceivedAccount(refundNotification.getUserReceivedAccount())
-                    .setSuccessTime(successTime)
-                    .setStatus(refundNotification.getRefundStatus().name())
-                    .setTotal(refundNotification.getAmount().getTotal().intValue())
-                    .setRefund(refundNotification.getAmount().getRefund().intValue());
-            refundLog.setCreateTime(LocalDateTimeUtil.of(DateUtil.parse(refundNotification.getCreateTime())));
-            refundLogService.updateById(refundLog);
+            refundLogService.lambdaUpdate()
+                    .set(RefundLog::getRefundId, refundNotification.getRefundId())
+                    .set(RefundLog::getTransactionId, refundNotification.getTransactionId())
+                    .set(RefundLog::getUserReceivedAccount, refundNotification.getUserReceivedAccount())
+                    .set(RefundLog::getSuccessTime, successTime)
+                    .set(RefundLog::getStatus, refundNotification.getRefundStatus().name())
+                    .set(RefundLog::getTotal, refundNotification.getAmount().getTotal().intValue())
+                    .set(RefundLog::getRefund, refundNotification.getAmount().getRefund().intValue())
+                    .set(RefundLog::getCreateTime, LocalDateTimeUtil.of(DateUtil.parse(refundNotification.getCreateTime())))
+                    .eq(RefundLog::getId, refundLog.getId()).update();
 
             if (RefundLog.STATUS_退款成功.equals(refundNotification.getRefundStatus().name())) {
                 // 冻结金额扣减此次(退款金额+优惠金额),优惠金额字段减去申请退款时的优惠金额
@@ -553,22 +554,25 @@ public class WxPayServiceImpl implements WxPayService {
 
                 // 更新资金流水
                 var walletDetail = walletDetailService.getWalletDetailByOrderNo(refundNotification.getOutRefundNo(), WalletDetail.TYPE_提现);
-                walletDetail.setStatus(WalletDetail.STATUS_已确认)  //已确认
-                        .setCurrency(refundNotification.getAmount().getCurrency())
-                        .setAmount(refundNotification.getAmount().getRefund().intValue())
-                        .setTransactionTime(successTime);
-                walletDetailService.updateById(walletDetail);
-
+                walletDetailService.lambdaUpdate()
+                        .set(WalletDetail::getStatus, WalletDetail.STATUS_已确认)
+                        .set(WalletDetail::getTransactionId, refundNotification.getTransactionId())
+                        .set(WalletDetail::getTransactionTime, successTime)
+                        .set(WalletDetail::getCurrency, refundNotification.getAmount().getCurrency())
+                        .set(WalletDetail::getAmount, refundNotification.getAmount().getRefund().intValue())
+                        .set(WalletDetail::getTransactionTime, successTime)
+                        .eq(WalletDetail::getId, walletDetail.getId()).update();
                 LOGGER.info("微信退款回调{}:业务处理结束", notifyRes[2]);
+                return ResponseEntity.status(HttpStatus.OK).build();
             } else {
                 // 退款失败
                 LOGGER.error("微信退款失败,用户id:{},退款状态:{} \n 退款结果通知详情:{}", refundLog.getUserId(), refundNotification.getRefundStatus().name(), refundNotification);
-                throw new BusinessException("处理异常");
+                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("code", HttpStatus.INTERNAL_SERVER_ERROR, "message", "退款处理异常"));
             }
         } catch (ValidationException e) {
             // 签名验证失败,返回 401 UNAUTHORIZED 状态码
             LOGGER.error("微信退款通知验签失败", e);
-            throw new BusinessException("验签失败");
+            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("code", HttpStatus.UNAUTHORIZED, "message", "验签失败"));
         }
     }