diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/refund/PayRefundMapper.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/refund/PayRefundMapper.java index 34af794..7f3461b 100755 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/refund/PayRefundMapper.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/refund/PayRefundMapper.java @@ -6,10 +6,15 @@ import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.pay.controller.admin.refund.vo.PayRefundExportReqVO; import cn.iocoder.yudao.module.pay.controller.admin.refund.vo.PayRefundPageReqVO; import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO; +import cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Options; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import java.time.LocalDateTime; import java.util.List; @Mapper @@ -42,12 +47,60 @@ public interface PayRefundMapper extends BaseMapperX { return selectOne(PayRefundDO::getNo, no); } + /** + * 获得退款单,不使用 MyBatis 一级缓存,用于查询退款单的最新状态 + * + * 原因是:createRefund 不加入事务(NOT_SUPPORTED),但 Spring 事务同步仍然生效,同一次调用复用同一个 SqlSession, + * 重复查询会命中一级缓存,查询不到其它事务(例如说,退款回调)已提交的更新 + * + * @param id 退款单编号 + * @return 退款单 + */ + @Select("SELECT * FROM pay_refund WHERE id = #{id} AND deleted = 0") + @Options(flushCache = Options.FlushCachePolicy.TRUE) + PayRefundDO selectLatestById(@Param("id") Long id); + default int updateByIdAndStatus(Long id, Integer status, PayRefundDO update) { return update(update, new LambdaQueryWrapper() .eq(PayRefundDO::getId, id).eq(PayRefundDO::getStatus, status)); } /** + * 更新退款单,并校验状态、更新时间 + * + * 用于更新退款结果:退款单的更新时间变化,说明已被并发更新、或者已是其它退款尝试(例如说,退款失败后重新发起),则不更新 + * + * @param id 退款单编号 + * @param status 原状态 + * @param updateTime 原更新时间 + * @param update 更新对象 + * @return 更新数量 + */ + default int updateByIdAndStatusAndUpdateTime(Long id, Integer status, LocalDateTime updateTime, PayRefundDO update) { + return update(update, new LambdaQueryWrapper() + .eq(PayRefundDO::getId, id).eq(PayRefundDO::getStatus, status) + .eq(PayRefundDO::getUpdateTime, updateTime)); + } + + /** + * 刷新结果未知的退款单的更新时间,用于重新发起退款前的占位 + * + * 条件:待退款、渠道未受理(没有渠道退款单号)、并且更新时间早于 maxUpdateTime(超过重新发起的间隔)。 + * 不会清空渠道结果:如果已被退款回调写入渠道退款单号、或者更新为最终状态,则更新失败 + * + * @param id 退款单编号 + * @param maxUpdateTime 最大更新时间 + * @return 更新数量 + */ + default int updateUpdateTimeByIdAndWaiting(Long id, LocalDateTime maxUpdateTime) { + return update(null, new LambdaUpdateWrapper() + .set(PayRefundDO::getUpdateTime, LocalDateTime.now()) + .eq(PayRefundDO::getId, id).eq(PayRefundDO::getStatus, PayRefundStatusEnum.WAITING.getStatus()) + .and(w -> w.isNull(PayRefundDO::getChannelRefundNo).or().eq(PayRefundDO::getChannelRefundNo, "")) + .lt(PayRefundDO::getUpdateTime, maxUpdateTime)); + } + + /** * 更新退款单,并清空上一次退款的渠道结果 * * 用于退款失败后重新发起退款,避免新的退款结果残留上一次的失败原因、渠道退款单号等 diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/wallet/PayWalletTransactionMapper.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/wallet/PayWalletTransactionMapper.java index 212a90c..4a9f569 100644 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/wallet/PayWalletTransactionMapper.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/wallet/PayWalletTransactionMapper.java @@ -60,6 +60,11 @@ public interface PayWalletTransactionMapper extends BaseMapperX { PayRefundDO payRefund = refundService.getRefundByNo(outRefundNo); // 支付退款单不存在, 返回退款失败状态 if (payRefund == null) { - return PayRefundRespDTO.failureOf(String.valueOf(REFUND_NOT_FOUND), REFUND_NOT_FOUND.getMsg(), + return PayRefundRespDTO.failureOf(String.valueOf(REFUND_NOT_FOUND.getCode()), REFUND_NOT_FOUND.getMsg(), outRefundNo, ""); } + // 退款成功:以已提交的钱包退款流水为准,不依赖退款单的状态 + // 例如说:钱包已退款入账,但更新退款单失败,退款单仍是 WAITING。关联 https://github.com/YunaiV/ruoyi-vue-pro/issues/1290 + PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransaction( + String.valueOf(payRefund.getId()), PayWalletBizTypeEnum.PAYMENT_REFUND); + if (walletTransaction != null) { + return PayRefundRespDTO.successOf(walletTransaction.getNo(), walletTransaction.getCreateTime(), + outRefundNo, walletTransaction); + } // 退款失败 if (PayRefundStatusEnum.isFailure(payRefund.getStatus())) { return PayRefundRespDTO.failureOf(payRefund.getChannelErrorCode(), payRefund.getChannelErrorMsg(), outRefundNo, ""); } - // 退款成功 + // 退款成功,但钱包流水不存在,为无效状态 if (PayRefundStatusEnum.isSuccess(payRefund.getStatus())) { - PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransaction( - String.valueOf(payRefund.getId()), PayWalletBizTypeEnum.PAYMENT_REFUND); - Assert.notNull(walletTransaction, "支付退款单 {} 钱包流水不能为空", outRefundNo); - return PayRefundRespDTO.successOf(walletTransaction.getNo(), walletTransaction.getCreateTime(), - outRefundNo, walletTransaction); + log.error("[doGetRefund] 支付退款单 {} 的钱包流水不存在", outRefundNo); + throw new IllegalStateException(String.format("支付退款单[%s] 钱包流水不能为空", outRefundNo)); } - // 其它状态为无效状态 - log.error("[doGetRefund] 支付退款单 {} 的状态不正确", outRefundNo); - throw new IllegalStateException(String.format("支付退款单[%s] 状态不正确", outRefundNo)); + // 待退款,但钱包流水不存在:可能未退款、或者退款事务尚未提交,返回结果未知(没有渠道退款单号),不能作为退款失败 + return PayRefundRespDTO.waitingOf(null, outRefundNo, ""); } @Override diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClient.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClient.java index acc042c..dd5c25c 100644 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClient.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClient.java @@ -297,6 +297,14 @@ public abstract class AbstractWxPayClient extends AbstractPayClient record.getOutRefundNo().equals(outRefundNo)); - if (refund == null) { - return PayRefundRespDTO.failureOf(outRefundNo, response); + if (refund == null) { // 查询不到退款单,返回结果未知 + return PayRefundRespDTO.waitingOf(null, outRefundNo, response); } switch (refund.getRefundStatus()) { case "SUCCESS": diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundService.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundService.java index 38b6e15..b6a69d5 100755 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundService.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundService.java @@ -33,6 +33,16 @@ public interface PayRefundService { PayRefundDO getRefundByNo(String no); /** + * 获得退款订单,并锁定(FOR UPDATE) + * + * 注意:需要在事务中调用,锁持有到事务提交 + * + * @param id 编号 + * @return 退款订单 + */ + PayRefundDO getRefundForUpdate(Long id); + + /** * 获得指定应用的退款数量 * * @param appId 应用编号 diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceImpl.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceImpl.java index 4ece8f2..f351eb9 100755 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceImpl.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceImpl.java @@ -37,6 +37,8 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; +import java.time.Duration; +import java.time.LocalDateTime; import java.util.List; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; @@ -58,6 +60,15 @@ public class PayRefundServiceImpl implements PayRefundService { */ private static final long CREATE_LOCK_TIMEOUT_MILLIS = 120 * DateUtils.SECOND_MILLIS; + /** + * 结果未知(WAITING)的退款单,距离上一次发起退款的最小间隔,超过后才允许重新发起 + * + * 注意:只用于避免频繁、并发地重新发起,不作为退款失败的依据。重新发起依赖渠道对原退款单号、原退款金额的幂等 + * + * @see #1290 + */ + private static final Duration RETRY_WAITING_INTERVAL = Duration.ofMinutes(10); + @Resource private PayProperties payProperties; @@ -88,6 +99,11 @@ public class PayRefundServiceImpl implements PayRefundService { } @Override + public PayRefundDO getRefundForUpdate(Long id) { + return refundMapper.selectOneForUpdate(PayRefundDO::getId, id); + } + + @Override public Long getRefundCountByAppId(Long appId) { return refundMapper.selectCountByAppId(appId); } @@ -118,66 +134,179 @@ public class PayRefundServiceImpl implements PayRefundService { log.error("[createRefund][渠道编号({}) 找不到对应的支付客户端]", channel.getId()); throw exception(CHANNEL_NOT_FOUND); } - // 2. 加锁,创建退款单、或者重新发起退款失败的退款单 + // 2. 情况一:存在结果未知(WAITING)的退款单,先查询渠道退款单,必要时使用原退款单号重新发起 + // 关联 https://github.com/YunaiV/ruoyi-vue-pro/issues/1290、https://github.com/YunaiV/ruoyi-vue-pro/pull/1301 + PayRefundDO refund = refundMapper.selectByAppIdAndMerchantRefundId(app.getId(), reqDTO.getMerchantRefundId()); + if (refund != null && PayRefundStatusEnum.WAITING.getStatus().equals(refund.getStatus())) { + return retryWaitingRefund(reqDTO, order, channel, client, refund); + } + + // 3. 情况二:加锁,创建退款单、或者重新发起退款失败的退款单 // 原因是:同一支付订单串行创建退款单,避免 select 后 insert 时,并发请求重复创建退款单,导致重复退款 // 注意:createRefund 不加入调用方的事务,退款单立即提交,所以释放锁后,其它请求可以查询到该退款单 - PayRefundDO refund = refundLockRedisDAO.lock(order.getId(), CREATE_LOCK_TIMEOUT_MILLIS, + refund = refundLockRedisDAO.lock(order.getId(), CREATE_LOCK_TIMEOUT_MILLIS, () -> createOrRetryRefund(reqDTO, app, order)); + // 4. 调用三方渠道发起退款,并通知退款结果 + invokeRefund(channel, client, order, refund, reqDTO.getReason(), false); + return refund.getId(); + } + + /** + * 重新发起结果未知(WAITING)的退款单 + * + * 例如说:发起退款发生异常,并且查询渠道退款单没有明确结果,退款单保留 WAITING。此时,商户使用相同的商户退款编号再次发起: + * 1. 先查询渠道退款单:退款成功,则同步退款结果;渠道已受理(有渠道退款单号),则继续等待退款回调、或者退款轮询 + * 2. 结果仍未知,并且超过重新发起的间隔,则原子刷新 update_time 占位后,使用原退款单号、原退款金额重新发起 + * + * 注意:结果未知时,不会将退款单更新为退款失败,避免误判后业务错误处理(例如说,钱包充值退款失败时解冻余额) + * + * @param reqDTO 退款申请信息 + * @param order 支付订单 + * @param channel 支付渠道 + * @param client 支付客户端 + * @param refund 结果未知的退款单 + * @return 退款单编号 + * @see #1290 + */ + private Long retryWaitingRefund(PayRefundCreateReqDTO reqDTO, PayOrderDO order, PayChannelDO channel, + PayClient client, PayRefundDO refund) { + // 1.1 校验参数是否一致 + validateRefundConsistent(refund, reqDTO, order); + // 1.2 渠道已受理退款,继续等待退款回调、或者退款轮询,不重新发起 + if (StrUtil.isNotEmpty(refund.getChannelRefundNo())) { + throw exception(REFUND_HAS_REFUNDING); + } + + // 2. 查询渠道退款单:退款成功、或者渠道已受理,以查询结果为准,不重新发起 + // 注意:查询到的退款失败、或者查询不到,不作为最终结果。原因是:不能证明原退款请求失败,所以不通知退款失败,交给下面重新发起 + PayRefundRespDTO queryRespDTO = null; + try { + queryRespDTO = client.getRefund(refund.getOrderNo(), refund.getNo()); + } catch (Throwable e) { + log.warn("[retryWaitingRefund][退款编号({}) 查询渠道退款单发生异常]", refund.getId(), e); + } + if (isRefundAccepted(queryRespDTO)) { + getSelf().notifyRefund(channel, queryRespDTO); + if (PayRefundStatusEnum.isSuccess(queryRespDTO.getStatus())) { + return refund.getId(); + } + throw exception(REFUND_HAS_REFUNDING); + } - // 3.1 调用三方渠道发起退款 + // 3. 原子刷新 update_time 占位:仍是 WAITING、渠道未受理,并且超过重新发起的间隔,保证只有一个请求重新发起 + // 注意:createRefund 不加入调用方的事务,占位立即提交,即使调用方的事务回滚,也不会被撤销,避免短时间内重复发起 + int updateCount = refundMapper.updateUpdateTimeByIdAndWaiting(refund.getId(), + LocalDateTime.now().minus(RETRY_WAITING_INTERVAL)); + if (updateCount == 0) { // 未超过重新发起的间隔、或者已被并发更新(例如说,退款回调、其它请求重新发起) + return validateRetryWaitingRefundConcurrent(refund.getId()); + } + // 4.1 占位后,重新查询退款单,作为本次退款尝试的快照 + // 注意:占位不代表退款结果,占位后仍可能被退款回调更新(例如说,退款成功、写入渠道退款单号),此时以最新状态为准,不再重新发起 + PayRefundDO latestRefund = refundMapper.selectLatestById(refund.getId()); + if (latestRefund == null || !PayRefundStatusEnum.WAITING.getStatus().equals(latestRefund.getStatus()) + || StrUtil.isNotEmpty(latestRefund.getChannelRefundNo())) { + return validateRetryWaitingRefundConcurrent(refund.getId()); + } + // 4.2 使用原退款单号、原退款金额、原退款原因重新发起,保证与原退款请求一致,依赖渠道幂等,避免重复退款 + invokeRefund(channel, client, order, latestRefund, latestRefund.getReason(), true); + return refund.getId(); + } + + /** + * 重新发起结果未知的退款单时,退款单已被并发更新、或者未超过重新发起的间隔,以最新的退款单为准 + * + * @param id 退款单编号 + * @return 退款成功时,返回退款单编号;否则,抛出退款处理中的异常 + */ + private Long validateRetryWaitingRefundConcurrent(Long id) { + PayRefundDO latestRefund = refundMapper.selectLatestById(id); + if (latestRefund != null && PayRefundStatusEnum.isSuccess(latestRefund.getStatus())) { + return id; + } + throw exception(REFUND_HAS_REFUNDING); + } + + /** + * 调用三方渠道发起退款,并通知退款结果 + * + * @param channel 支付渠道 + * @param client 支付客户端 + * @param order 支付订单 + * @param refund 退款单;需要是发起前查询的最新退款单,它的 updateTime 用于避免旧的退款结果,更新新的退款尝试 + * @param reason 退款原因 + * @param retryWaiting 是否为重新发起结果未知的退款单 + */ + private void invokeRefund(PayChannelDO channel, PayClient client, PayOrderDO order, PayRefundDO refund, + String reason, boolean retryWaiting) { + // 1.1 调用三方渠道发起退款 PayRefundRespDTO refundRespDTO = null; + PayRefundUnifiedReqDTO unifiedReqDTO = new PayRefundUnifiedReqDTO() + .setPayPrice(order.getPrice()) + .setRefundPrice(refund.getRefundPrice()) + .setOutTradeNo(order.getNo()) + .setOutRefundNo(refund.getNo()) + .setNotifyUrl(genChannelRefundNotifyUrl(channel)) + .setReason(reason); try { - PayRefundUnifiedReqDTO unifiedReqDTO = new PayRefundUnifiedReqDTO() - .setPayPrice(order.getPrice()) - .setRefundPrice(reqDTO.getPrice()) - .setOutTradeNo(order.getNo()) - .setOutRefundNo(refund.getNo()) - .setNotifyUrl(genChannelRefundNotifyUrl(channel)) - .setReason(reqDTO.getReason()); refundRespDTO = client.unifiedRefund(unifiedReqDTO); } catch (Throwable e) { // 注意:这里仅打印异常,不进行抛出。 // 原因是:虽然调用支付渠道进行退款发生异常(网络请求超时),实际退款成功。 // 所以下面会查询一次渠道退款单,查询不到明确结果时,后续通过退款回调、或者退款轮询补偿可以拿到 - log.error("[createRefund][退款编号({}) requestDTO({}) 发生异常]", refund.getId(), reqDTO, e); + log.error("[invokeRefund][退款编号({}) unifiedReqDTO({}) 发生异常]", refund.getId(), unifiedReqDTO, e); } - // 3.2 发起退款没有返回结果、或者返回失败时,查询一次渠道退款单,避免误判 + // 1.2 发起退款没有返回结果、返回失败、或者返回结果未知(例如说,支付宝 fund_change 不为 Y)时,查询一次渠道退款单,避免误判 // 关联知识星球帖子:https://t.zsxq.com/JRLye、https://t.zsxq.com/gDETH - if (refundRespDTO == null || PayRefundStatusEnum.isFailure(refundRespDTO.getStatus())) { + if (refundRespDTO == null || PayRefundStatusEnum.isFailure(refundRespDTO.getStatus()) + || isRefundUnknown(refundRespDTO)) { refundRespDTO = getRefundAfterUnifiedRefund(client, refund, refundRespDTO); } - // 4. 通知退款结果 - if (refundRespDTO != null) { - if (PayRefundStatusEnum.isFailure(refundRespDTO.getStatus())) { - // 4.1 情况一:退款失败 - PayRefundDO latestRefund = null; - try { - getSelf().notifyRefund(channel, refundRespDTO); - } catch (ServiceException ex) { - // 由于退款回调、退款轮询可能同时更新退款单,导致存在并发更新问题,此时以最新的退款状态为准 - latestRefund = validateRefundNotifyConcurrent(refund.getId(), ex); - log.warn("[createRefund][refund({}) channel({}) 退款结果({}) 通知时发生并发更新,最新状态为({})]", - refund.getId(), channel.getId(), refundRespDTO, latestRefund.getStatus(), ex); - } - // 如有渠道错误码,则抛出业务异常,提示用户 - // 特殊:如果已被并发更新为成功,则以最新状态为准,避免旧的失败结果误报 + // 2. 通知退款结果 + if (refundRespDTO == null) { + return; + } + if (PayRefundStatusEnum.isFailure(refundRespDTO.getStatus())) { + // 2.1 情况一:退款失败 + // 特殊:重新发起结果未知的退款单时,本次返回失败(例如说,渠道对重复请求的报错),不能证明原退款请求失败, + // 所以不更新为退款失败、不通知业务,保留 WAITING 交给退款回调、退款轮询、或者人工核对后再次发起 + if (retryWaiting) { + log.warn("[invokeRefund][退款编号({}) 重新发起结果未知的退款单,返回失败({}),保留 WAITING]", + refund.getId(), refundRespDTO); + // 特殊:如果已被并发更新为成功(例如说,退款回调),则以最新状态为准,避免误报 + PayRefundDO latestRefund = refundMapper.selectLatestById(refund.getId()); if (StrUtil.isNotEmpty(refundRespDTO.getChannelErrorCode()) - && (latestRefund == null || PayRefundStatusEnum.isFailure(latestRefund.getStatus()))) { + && (latestRefund == null || !PayRefundStatusEnum.isSuccess(latestRefund.getStatus()))) { throw exception(REFUND_SUBMIT_CHANNEL_ERROR, refundRespDTO.getChannelErrorCode(), refundRespDTO.getChannelErrorMsg()); } - } else { - // 4.2 情况二:退款成功、或者退款中 - // 注意:这里仅打印异常,不进行抛出。原因是:渠道可能已经退款成功,抛出会导致调用方回滚,后续通过退款回调、或者退款轮询补偿 - try { - getSelf().notifyRefund(channel, refundRespDTO); - } catch (Throwable e) { - log.error("[createRefund][退款编号({}) 退款结果({}) 通知时发生异常]", refund.getId(), refundRespDTO, e); - } + return; + } + PayRefundDO latestRefund = null; + try { + getSelf().notifyRefund(channel, refundRespDTO, refund.getUpdateTime()); + } catch (ServiceException ex) { + // 由于退款回调、退款轮询可能同时更新退款单,导致存在并发更新问题,此时以最新的退款状态为准 + latestRefund = validateRefundNotifyConcurrent(refund.getId(), ex); + log.warn("[invokeRefund][refund({}) channel({}) 退款结果({}) 通知时发生并发更新,最新状态为({})]", + refund.getId(), channel.getId(), refundRespDTO, latestRefund.getStatus(), ex); + } + // 如有渠道错误码,则抛出业务异常,提示用户 + // 特殊:如果已被并发更新为成功,则以最新状态为准,避免旧的失败结果误报 + if (StrUtil.isNotEmpty(refundRespDTO.getChannelErrorCode()) + && (latestRefund == null || PayRefundStatusEnum.isFailure(latestRefund.getStatus()))) { + throw exception(REFUND_SUBMIT_CHANNEL_ERROR, refundRespDTO.getChannelErrorCode(), + refundRespDTO.getChannelErrorMsg()); + } + } else { + // 2.2 情况二:退款成功、或者退款中 + // 注意:这里仅打印异常,不进行抛出。原因是:渠道可能已经退款成功,抛出会导致调用方回滚,后续通过退款回调、或者退款轮询补偿 + try { + getSelf().notifyRefund(channel, refundRespDTO); + } catch (Throwable e) { + log.error("[invokeRefund][退款编号({}) 退款结果({}) 通知时发生异常]", refund.getId(), refundRespDTO, e); } } - return refund.getId(); } /** @@ -186,7 +315,7 @@ public class PayRefundServiceImpl implements PayRefundService { * @param reqDTO 退款申请信息 * @param app 支付应用 * @param order 支付订单 - * @return 退款单 + * @return 退款单;重新查询的最新退款单,作为本次退款尝试的快照 */ private PayRefundDO createOrRetryRefund(PayRefundCreateReqDTO reqDTO, PayAppDO app, PayOrderDO order) { // 1. 校验退款单是否可以发起:不存在,或者之前退款失败 @@ -209,22 +338,26 @@ public class PayRefundServiceImpl implements PayRefundService { } else { // 2.2 情况二:存在退款失败的退款单,则复用原退款单(包括原退款单号)重新发起,并清空上一次退款的渠道结果 // 原因是:微信、支付宝等渠道要求退款失败后重新提交时,使用原商户退款单号,避免上一次实际受理时重复退款。未校验一致的请求字段,以本次请求为准 + PayRefundDO updateObj = new PayRefundDO().setStatus(PayRefundStatusEnum.WAITING.getStatus()) + .setReason(reqDTO.getReason()).setUserIp(reqDTO.getUserIp()) + .setNotifyUrl(app.getRefundNotifyUrl()); + // 注意:update_time 需要大于退款失败时的 update_time(至少 1 秒,兼容 datetime 秒级精度),用于区分新旧退款尝试, + // 避免旧的查询结果(例如说,退款轮询查询到的退款失败),更新新的退款尝试,详见 notifyRefund 方法的 waitingUpdateTime 参数 + updateObj.setUpdateTime(DateUtils.max(LocalDateTime.now(), refund.getUpdateTime().plusSeconds(1))); int updateCount = refundMapper.updateByIdAndStatusAndClearChannelResult(refund.getId(), refund.getStatus(), - new PayRefundDO().setStatus(PayRefundStatusEnum.WAITING.getStatus()) - .setReason(reqDTO.getReason()).setUserIp(reqDTO.getUserIp()) - .setNotifyUrl(app.getRefundNotifyUrl())); + updateObj); if (updateCount == 0) { // 校验状态,避免并发重新发起退款 throw exception(REFUND_HAS_REFUNDING); } } - return refund; + return refundMapper.selectById(refund.getId()); } /** - * 发起退款没有返回结果、或者返回失败时,查询一次渠道退款单,确认退款结果 + * 发起退款没有返回结果、返回失败、或者返回结果未知时,查询一次渠道退款单,确认退款结果 * * 注意:只有查询到渠道已受理退款,才以查询结果为准;查询到的退款失败,不作为最终结果。 - * 原因是:一次查询可能存在渠道退款单尚未生成、或者结果尚未同步的情况,例如说微信、钱包查询不存在的退款单时返回失败 + * 原因是:一次查询可能存在渠道退款单尚未生成、或者结果尚未同步的情况,例如说微信查询不存在的退款单 * * @param client 支付客户端 * @param refund 退款单 @@ -239,18 +372,40 @@ public class PayRefundServiceImpl implements PayRefundService { log.warn("[getRefundAfterUnifiedRefund][退款编号({}) 查询渠道退款单发生异常]", refund.getId(), e); } // 情况一:查询到退款成功、或者已有渠道退款单号的退款中,说明渠道实际已受理退款,以查询结果为准 - if (queryRespDTO != null && (PayRefundStatusEnum.isSuccess(queryRespDTO.getStatus()) - || (PayRefundStatusEnum.WAITING.getStatus().equals(queryRespDTO.getStatus()) - && StrUtil.isNotEmpty(queryRespDTO.getChannelRefundNo())))) { + if (isRefundAccepted(queryRespDTO)) { return queryRespDTO; } // 情况二:其它情况,以发起退款的结果为准 // ① 发起退款发生异常:返回 null,保留 WAITING 交给退款回调、或者退款轮询补偿 - // ② 发起退款明确返回失败:以渠道明确返回的失败为准。原因是:支付宝查询不存在的退款单时返回 WAITING、钱包查询 WAITING 退款单时抛出异常,退款轮询无法补偿 + // ② 发起退款返回结果未知:保留 WAITING 交给退款回调、退款轮询、或者商户使用原退款单号重新发起 + // ③ 发起退款明确返回失败:以渠道明确返回的失败为准。原因是:查询不存在的退款单时(例如说,微信、支付宝)返回结果未知,退款轮询无法补偿 return unifiedRespDTO; } /** + * 是否渠道已受理退款:退款成功、或者已有渠道退款单号的退款中 + * + * @param respDTO 退款结果 + * @return 是否已受理 + */ + private static boolean isRefundAccepted(PayRefundRespDTO respDTO) { + return respDTO != null && (PayRefundStatusEnum.isSuccess(respDTO.getStatus()) + || (PayRefundStatusEnum.WAITING.getStatus().equals(respDTO.getStatus()) + && StrUtil.isNotEmpty(respDTO.getChannelRefundNo()))); + } + + /** + * 是否退款结果未知:退款中,但没有渠道退款单号,例如说,支付宝 fund_change 不为 Y、或者查询不到退款单 + * + * @param respDTO 退款结果 + * @return 是否未知 + */ + private static boolean isRefundUnknown(PayRefundRespDTO respDTO) { + return PayRefundStatusEnum.WAITING.getStatus().equals(respDTO.getStatus()) + && StrUtil.isEmpty(respDTO.getChannelRefundNo()); + } + + /** * 校验退款结果通知时的并发更新 * * 只有状态竞争导致的通知失败,并且退款单已被并发更新为成功或失败时,才返回最新的退款单; @@ -266,7 +421,7 @@ public class PayRefundServiceImpl implements PayRefundService { throw ex; } // 2. 校验最新状态为成功或失败 - PayRefundDO latestRefund = refundMapper.selectById(id); + PayRefundDO latestRefund = refundMapper.selectLatestById(id); if (latestRefund == null || !(PayRefundStatusEnum.isSuccess(latestRefund.getStatus()) || PayRefundStatusEnum.isFailure(latestRefund.getStatus()))) { throw ex; @@ -320,13 +475,24 @@ public class PayRefundServiceImpl implements PayRefundService { throw exception(REFUND_EXISTS); } // 校验参数是否一致 + validateRefundConsistent(refund, reqDTO, order); + return refund; + } + + /** + * 校验再次发起退款时,原退款单与本次请求的支付订单、退款金额是否一致 + * + * @param refund 原退款单 + * @param reqDTO 退款申请信息 + * @param order 支付订单 + */ + private void validateRefundConsistent(PayRefundDO refund, PayRefundCreateReqDTO reqDTO, PayOrderDO order) { if (ObjectUtil.notEqual(refund.getOrderId(), order.getId())) { throw exception(REFUND_CREATE_FAIL_ORDER_NOT_MATCH); } if (ObjectUtil.notEqual(refund.getRefundPrice(), reqDTO.getPrice())) { throw exception(REFUND_CREATE_FAIL_PRICE_NOT_MATCH); } - return refund; } /** @@ -356,6 +522,21 @@ public class PayRefundServiceImpl implements PayRefundService { // 注意,如果是方法内调用该方法,需要通过 getSelf().notifyRefund(channel, notify) 调用,否则事务不生效 @Transactional(rollbackFor = Exception.class) public void notifyRefund(PayChannelDO channel, PayRefundRespDTO notify) { + notifyRefund(channel, notify, null); + } + + /** + * 通知并更新订单的退款结果 + * + * @param channel 支付渠道 + * @param notify 通知 + * @param waitingUpdateTime 查询(发起)退款前,待退款的退款单的更新时间;非空时,只有退款单的更新时间未变化,才更新为退款失败。 + * 原因是:退款失败后,可以使用原退款单号重新发起(新的退款尝试),旧的退款失败结果不能关闭新的退款尝试。 + * 退款成功不需要校验:同一退款单号的退款成功,与哪次退款尝试无关 + */ + // 注意,如果是方法内调用该方法,需要通过 getSelf().notifyRefund(channel, notify, waitingUpdateTime) 调用,否则事务不生效 + @Transactional(rollbackFor = Exception.class) + public void notifyRefund(PayChannelDO channel, PayRefundRespDTO notify, LocalDateTime waitingUpdateTime) { // 情况一:退款成功 if (PayRefundStatusEnum.isSuccess(notify.getStatus())) { notifyRefundSuccess(channel, notify); @@ -363,7 +544,7 @@ public class PayRefundServiceImpl implements PayRefundService { } // 情况二:退款失败 if (PayRefundStatusEnum.isFailure(notify.getStatus())) { - notifyRefundFailure(channel, notify); + notifyRefundFailure(channel, notify, waitingUpdateTime); return; } // 情况三:退款中 @@ -390,9 +571,13 @@ public class PayRefundServiceImpl implements PayRefundService { return; } // 1.2 更新 PayRefundDO:仍是待退款,补充渠道已受理的退款单号 - int updateCounts = refundMapper.updateByIdAndStatus(refund.getId(), refund.getStatus(), new PayRefundDO() - .setChannelRefundNo(notify.getChannelRefundNo()).setChannelNotifyData(toJsonString(notify))); - if (updateCounts == 0) { // 已被并发更新为最终状态,以最新状态为准 + // 注意:update_time 作为退款尝试的令牌,不能回退,并且校验读后未被并发更新,详见 notifyRefundFailure 方法 + PayRefundDO updateRefundObj = new PayRefundDO() + .setChannelRefundNo(notify.getChannelRefundNo()).setChannelNotifyData(toJsonString(notify)); + updateRefundObj.setUpdateTime(DateUtils.max(LocalDateTime.now(), refund.getUpdateTime())); + int updateCounts = refundMapper.updateByIdAndStatusAndUpdateTime(refund.getId(), refund.getStatus(), + refund.getUpdateTime(), updateRefundObj); + if (updateCounts == 0) { // 已被并发更新(例如说,最终状态、占位重新发起),以最新状态为准 log.info("[notifyRefundWaiting][退款订单({}) 已被并发更新,无需更新渠道退款单号]", refund.getId()); return; } @@ -433,7 +618,7 @@ public class PayRefundServiceImpl implements PayRefundService { refund.getId()); } - private void notifyRefundFailure(PayChannelDO channel, PayRefundRespDTO notify) { + private void notifyRefundFailure(PayChannelDO channel, PayRefundRespDTO notify, LocalDateTime waitingUpdateTime) { // 1.1 查询 PayRefundDO PayRefundDO refund = refundMapper.selectByAppIdAndNo( channel.getAppId(), notify.getOutRefundNo()); @@ -448,13 +633,20 @@ public class PayRefundServiceImpl implements PayRefundService { throw exception(REFUND_STATUS_IS_NOT_WAITING); } // 1.2 更新 PayRefundDO + // 校验状态,必须是等待状态;并且校验更新时间:如果传入查询(发起)退款前的更新时间,需要是同一次退款尝试,避免关闭重新发起的新退款尝试; + // 否则,需要是上面查询到的更新时间,避免读后更新期间,退款单被并发更新(例如说,占位重新发起) + // 注意:update_time 作为退款尝试的令牌,不能回退(重新发起时 update_time 可能大于当前时间),否则同一秒内再次失败、重新发起时, + // 新的退款尝试会复用旧的令牌,导致旧的退款失败结果关闭新的退款尝试。关联 https://github.com/YunaiV/ruoyi-vue-pro/issues/1290 + LocalDateTime expectedUpdateTime = waitingUpdateTime != null ? waitingUpdateTime : refund.getUpdateTime(); PayRefundDO updateRefundObj = new PayRefundDO() .setChannelRefundNo(notify.getChannelRefundNo()) .setStatus(PayRefundStatusEnum.FAILURE.getStatus()) .setChannelNotifyData(toJsonString(notify)) .setChannelErrorCode(notify.getChannelErrorCode()).setChannelErrorMsg(notify.getChannelErrorMsg()); - int updateCounts = refundMapper.updateByIdAndStatus(refund.getId(), refund.getStatus(), updateRefundObj); - if (updateCounts == 0) { // 校验状态,必须是等待状态 + updateRefundObj.setUpdateTime(DateUtils.max(LocalDateTime.now(), expectedUpdateTime)); + int updateCounts = refundMapper.updateByIdAndStatusAndUpdateTime(refund.getId(), refund.getStatus(), + expectedUpdateTime, updateRefundObj); + if (updateCounts == 0) { throw exception(REFUND_STATUS_IS_NOT_WAITING); } log.info("[notifyRefundFailure][退款订单({}) 更新为退款失败]", refund.getId()); @@ -495,7 +687,10 @@ public class PayRefundServiceImpl implements PayRefundService { } PayRefundRespDTO respDTO = payClient.getRefund(refund.getOrderNo(), refund.getNo()); // 1.2 回调退款结果 - notifyRefund(refund.getChannelId(), respDTO); + // 注意:传入查询前的 updateTime,避免查询期间退款单已失败、并使用原退款单号重新发起时,旧的退款失败结果关闭新的退款尝试 + PayChannelDO channel = channelService.validPayChannel(refund.getChannelId()); + TenantUtils.execute(channel.getTenantId(), + () -> getSelf().notifyRefund(channel, respDTO, refund.getUpdateTime())); // 2. 如果同步到,则返回 true return PayRefundStatusEnum.isSuccess(respDTO.getStatus()) diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletService.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletService.java index 6efdc92..5a40c33 100644 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletService.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletService.java @@ -50,6 +50,8 @@ public interface PayWalletService { /** * 钱包订单支付退款 * + * 幂等:同一退款单已退款到钱包时,返回原退款流水,不会重复增加余额 + * * @param outRefundNo 外部退款号 * @param refundPrice 退款金额 * @param reason 退款原因 diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java index 81cfd6c..f2a0e02 100644 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java @@ -1,6 +1,7 @@ package cn.iocoder.yudao.module.pay.service.wallet; import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.ObjectUtil; import cn.hutool.extra.spring.SpringUtil; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.date.DateUtils; @@ -20,6 +21,7 @@ import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -121,41 +123,49 @@ public class PayWalletServiceImpl implements PayWalletService { } @Override - @Transactional(rollbackFor = Exception.class) + // 注意:新建事务时,使用读已提交(READ_COMMITTED),避免下面当前读(FOR UPDATE)不存在的退款流水时,MySQL 可重复读下加间隙锁, + // 导致不同退款单并发退款到钱包时死锁;加入调用方的已有事务时,沿用调用方的隔离级别,仍由当前读、退款单行锁保证只退款一次 + // 关联 https://github.com/YunaiV/ruoyi-vue-pro/issues/1290 + @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED) public PayWalletTransactionDO orderRefund(String outRefundNo, Integer refundPrice, String reason) { // 1.1 判断退款单是否存在 PayRefundDO payRefund = refundService.getRefundByNo(outRefundNo); if (payRefund == null) { throw exception(REFUND_NOT_FOUND); } - // 1.2 校验是否可以退款 - Long walletId = validateWalletCanRefund(payRefund.getId(), payRefund.getChannelOrderNo()); - PayWalletDO wallet = walletMapper.selectById(walletId); - Assert.notNull(wallet, "钱包 {} 不存在", walletId); - - // 2. 增加余额 - return addWalletBalance(walletId, String.valueOf(payRefund.getId()), PAYMENT_REFUND, refundPrice); - } - - /** - * 校验是否能退款 - * - * @param refundId 支付退款单 id - * @param walletPayNo 钱包支付 no - */ - private Long validateWalletCanRefund(Long refundId, String walletPayNo) { - // 1. 校验钱包支付交易存在 - PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransactionByNo(walletPayNo); - if (walletTransaction == null) { - throw exception(WALLET_TRANSACTION_NOT_FOUND); + // 1.2 锁定退款单(FOR UPDATE),锁持有到事务提交,保证同一退款单串行退款到钱包 + // 原因是:同一退款单可能使用原退款单号重新发起(例如说,结果未知后重新发起),新旧调用可能重叠,需要保证只退款到钱包一次 + // 关联 https://github.com/YunaiV/ruoyi-vue-pro/issues/1290 + Long refundId = payRefund.getId(); + payRefund = refundService.getRefundForUpdate(refundId); + if (payRefund == null) { + throw exception(REFUND_NOT_FOUND); } - // 2. 校验退款是否存在 - PayWalletTransactionDO refundTransaction = walletTransactionService.getWalletTransaction( + // 1.3 已存在退款流水,说明已退款到钱包,直接返回原流水,避免重复退款 + // 注意:使用当前读(FOR UPDATE)查询退款流水,不能使用快照读。原因是:调用方可能存在事务,MySQL 可重复读下, + // 快照读可能读不到其它事务(例如说,等待退款单锁期间)已提交的退款流水,导致重复退款 + PayWalletTransactionDO refundTransaction = walletTransactionService.getWalletTransactionForUpdate( String.valueOf(refundId), PAYMENT_REFUND); if (refundTransaction != null) { - throw exception(WALLET_REFUND_EXIST); + if (ObjectUtil.notEqual(refundTransaction.getPrice(), refundPrice)) { + log.error("[orderRefund][退款单({}) 已存在退款流水({}),但退款金额({})不一致]", + refundId, refundTransaction.getId(), refundPrice); + throw exception(WALLET_REFUND_EXIST); + } + return refundTransaction; } - return walletTransaction.getWalletId(); + // 1.4 校验钱包支付交易存在 + PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransactionByNo( + payRefund.getChannelOrderNo()); + if (walletTransaction == null) { + throw exception(WALLET_TRANSACTION_NOT_FOUND); + } + Long walletId = walletTransaction.getWalletId(); + PayWalletDO wallet = walletMapper.selectById(walletId); + Assert.notNull(wallet, "钱包 {} 不存在", walletId); + + // 2. 增加余额 + return addWalletBalance(walletId, String.valueOf(refundId), PAYMENT_REFUND, refundPrice); } @Override diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionService.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionService.java index af9c6a8..0bde3b5 100644 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionService.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionService.java @@ -61,6 +61,18 @@ public interface PayWalletTransactionService { PayWalletTransactionDO getWalletTransaction(String bizId, PayWalletBizTypeEnum type); /** + * 获取钱包流水,并锁定(FOR UPDATE) + * + * 当前读:可以查询到其它事务已提交的钱包流水,不受 MySQL 可重复读下一致性视图的影响。 + * 注意:需要在事务中调用,锁持有到事务提交 + * + * @param bizId 业务编号 + * @param type 业务类型 + * @return 钱包流水 + */ + PayWalletTransactionDO getWalletTransactionForUpdate(String bizId, PayWalletBizTypeEnum type); + + /** * 获得钱包流水统计 * * @param userId 用户编号 diff --git a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionServiceImpl.java b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionServiceImpl.java index 4c01cd8..d02cf04 100644 --- a/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionServiceImpl.java +++ b/yudao-module-pay/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletTransactionServiceImpl.java @@ -85,6 +85,11 @@ public class PayWalletTransactionServiceImpl implements PayWalletTransactionServ } @Override + public PayWalletTransactionDO getWalletTransactionForUpdate(String bizId, PayWalletBizTypeEnum type) { + return payWalletTransactionMapper.selectByBizForUpdate(bizId, type.getType()); + } + + @Override public AppPayWalletTransactionSummaryRespVO getWalletTransactionSummary(Long userId, Integer userType, LocalDateTime[] createTime) { PayWalletDO wallet = payWalletService.getOrCreateWallet(userId, userType); return new AppPayWalletTransactionSummaryRespVO() diff --git a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/alipay/AbstractAlipayClientTest.java b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/alipay/AbstractAlipayClientTest.java index cb723c9..baedc04 100644 --- a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/alipay/AbstractAlipayClientTest.java +++ b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/alipay/AbstractAlipayClientTest.java @@ -15,7 +15,9 @@ import com.alipay.api.AlipayApiException; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.DefaultSigner; import com.alipay.api.domain.AlipayTradeRefundModel; +import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest; import com.alipay.api.request.AlipayTradeRefundRequest; +import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse; import com.alipay.api.response.AlipayTradeRefundResponse; import lombok.Setter; import org.junit.jupiter.api.BeforeEach; @@ -30,6 +32,7 @@ import java.util.Date; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.pay.framework.pay.core.client.impl.alipay.AlipayPayClientConfig.MODE_PUBLIC_KEY; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.when; @@ -86,6 +89,7 @@ public abstract class AbstractAlipayClientTest extends BaseMockitoUnitTest { AlipayTradeRefundResponse response = randomPojo(AlipayTradeRefundResponse.class, o -> { o.setSubCode(""); o.setGmtRefundPay(refundTime); + o.setFundChange("Y"); }); when(defaultAlipayClient.execute(argThat((ArgumentMatcher) request -> { assertInstanceOf(AlipayTradeRefundModel.class, request.getBizModel()); @@ -194,6 +198,128 @@ public abstract class AbstractAlipayClientTest extends BaseMockitoUnitTest { } @Test + @DisplayName("支付宝 Client 统一退款:fund_change 为 N,结果未知") + public void testUnifiedRefund_fundChangeN() throws AlipayApiException { + testUnifiedRefund_fundChangeNotY("N"); + } + + @Test + @DisplayName("支付宝 Client 统一退款:没有返回 fund_change,结果未知") + public void testUnifiedRefund_fundChangeNull() throws AlipayApiException { + testUnifiedRefund_fundChangeNotY(null); + } + + private void testUnifiedRefund_fundChangeNotY(String fundChange) throws AlipayApiException { + // mock 方法:code=10000(没有 sub_code),只代表退款请求成功 + AlipayTradeRefundResponse response = new AlipayTradeRefundResponse(); + response.setCode("10000"); + response.setFundChange(fundChange); + when(defaultAlipayClient.execute(any(AlipayTradeRefundRequest.class))).thenReturn(response); + // 准备请求参数 + String outRefundNo = randomString(); + PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> { + o.setOutRefundNo(outRefundNo); + o.setNotifyUrl(randomURL()); + o.setPayPrice(100); + o.setRefundPrice(10); + }); + + // 调用 + PayRefundRespDTO resp = client.unifiedRefund(refundReqDTO); + // 断言:返回结果未知(没有渠道退款单号),需要查询退款确认 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertEquals(outRefundNo, resp.getOutRefundNo()); + assertNull(resp.getChannelRefundNo()); + assertNull(resp.getSuccessTime()); + } + + @Test + @DisplayName("支付宝 Client 统一退款:系统错误,结果未知") + public void testUnifiedRefund_systemError() throws AlipayApiException { + // mock 方法 + AlipayTradeRefundResponse response = new AlipayTradeRefundResponse(); + response.setSubCode("ACQ.SYSTEM_ERROR"); + when(defaultAlipayClient.execute(any(AlipayTradeRefundRequest.class))).thenReturn(response); + // 准备请求参数 + PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> { + o.setNotifyUrl(randomURL()); + o.setPayPrice(100); + o.setRefundPrice(10); + }); + + // 调用 + PayRefundRespDTO resp = client.unifiedRefund(refundReqDTO); + // 断言 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertNull(resp.getChannelRefundNo()); + } + + @Test + @DisplayName("支付宝 Client 查询退款:退款成功") + public void testGetRefund_success() throws AlipayApiException { + // mock 方法 + Date refundTime = randomDate(); + AlipayTradeFastpayRefundQueryResponse response = new AlipayTradeFastpayRefundQueryResponse(); + response.setCode("10000"); + response.setRefundStatus("REFUND_SUCCESS"); + response.setGmtRefundPay(refundTime); + when(defaultAlipayClient.execute(any(AlipayTradeFastpayRefundQueryRequest.class))).thenReturn(response); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), resp.getStatus()); + assertEquals("R001", resp.getOutRefundNo()); + assertEquals(LocalDateTimeUtil.of(refundTime), resp.getSuccessTime()); + } + + @Test + @DisplayName("支付宝 Client 查询退款:没有退款数据(refund_status),结果未知") + public void testGetRefund_noRefundStatus() throws AlipayApiException { + // mock 方法:code=10000,但没有返回 refund_status + AlipayTradeFastpayRefundQueryResponse response = new AlipayTradeFastpayRefundQueryResponse(); + response.setCode("10000"); + when(defaultAlipayClient.execute(any(AlipayTradeFastpayRefundQueryRequest.class))).thenReturn(response); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言:不能作为退款失败 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertEquals("R001", resp.getOutRefundNo()); + assertNull(resp.getChannelRefundNo()); + } + + @Test + @DisplayName("支付宝 Client 查询退款:系统错误,结果未知") + public void testGetRefund_systemError() throws AlipayApiException { + // mock 方法 + AlipayTradeFastpayRefundQueryResponse response = new AlipayTradeFastpayRefundQueryResponse(); + response.setSubCode("ACQ.SYSTEM_ERROR"); + when(defaultAlipayClient.execute(any(AlipayTradeFastpayRefundQueryRequest.class))).thenReturn(response); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertNull(resp.getChannelRefundNo()); + } + + @Test + @DisplayName("支付宝 Client 查询退款:交易不存在,结果未知") + public void testGetRefund_tradeNotExist() throws AlipayApiException { + // mock 方法:交易维度的错误,不是退款单明确失败的状态 + AlipayTradeFastpayRefundQueryResponse response = new AlipayTradeFastpayRefundQueryResponse(); + response.setSubCode("ACQ.TRADE_NOT_EXIST"); + when(defaultAlipayClient.execute(any(AlipayTradeFastpayRefundQueryRequest.class))).thenReturn(response); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言:不能作为退款失败 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertNull(resp.getChannelRefundNo()); + } + + @Test @DisplayName("支付宝 Client 统一下单:参数校验不通过") public void testUnifiedOrder_paramInvalidate() { // 准备请求参数 diff --git a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/wallet/WalletPayClientTest.java b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/wallet/WalletPayClientTest.java new file mode 100644 index 0000000..df02957 --- /dev/null +++ b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/wallet/WalletPayClientTest.java @@ -0,0 +1,133 @@ +package cn.iocoder.yudao.module.pay.framework.pay.core.client.impl.wallet; + +import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; +import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO; +import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO; +import cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum; +import cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum; +import cn.iocoder.yudao.module.pay.framework.pay.core.client.dto.refund.PayRefundRespDTO; +import cn.iocoder.yudao.module.pay.framework.pay.core.client.exception.PayClientException; +import cn.iocoder.yudao.module.pay.framework.pay.core.client.impl.NonePayClientConfig; +import cn.iocoder.yudao.module.pay.service.refund.PayRefundService; +import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService; +import cn.iocoder.yudao.module.pay.service.wallet.PayWalletTransactionService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.springframework.test.util.ReflectionTestUtils; + +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.REFUND_NOT_FOUND; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * {@link WalletPayClient} 的单元测试类 + * + * @author 芋道源码 + */ +public class WalletPayClientTest extends BaseMockitoUnitTest { + + private WalletPayClient client; + + @Mock + private PayWalletService walletService; + @Mock + private PayWalletTransactionService walletTransactionService; + @Mock + private PayRefundService refundService; + + @BeforeEach + public void setUp() { + client = new WalletPayClient(1L, new NonePayClientConfig()); + ReflectionTestUtils.setField(client, "wallService", walletService); + ReflectionTestUtils.setField(client, "walletTransactionService", walletTransactionService); + ReflectionTestUtils.setField(client, "refundService", refundService); + } + + @Test // 已退款到钱包,但退款单仍是 WAITING(例如说:退款入账后,更新退款单失败):以钱包退款流水为准,返回退款成功 + public void testGetRefund_waitingWithTransaction() { + // mock 方法 + PayRefundDO refund = mockRefund(PayRefundStatusEnum.WAITING.getStatus()); + PayWalletTransactionDO transaction = mockRefundTransaction(refund); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), resp.getStatus()); + assertEquals(transaction.getNo(), resp.getChannelRefundNo()); + assertEquals("R001", resp.getOutRefundNo()); + } + + @Test // 已退款到钱包,但退款单是退款失败:以钱包退款流水为准,返回退款成功 + public void testGetRefund_failureWithTransaction() { + // mock 方法 + PayRefundDO refund = mockRefund(PayRefundStatusEnum.FAILURE.getStatus()); + mockRefundTransaction(refund); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), resp.getStatus()); + } + + @Test // 退款单是 WAITING,钱包退款流水不存在:可能未退款、或者退款事务尚未提交,返回结果未知,不作为退款失败 + public void testGetRefund_waitingWithoutTransaction() { + // mock 方法 + mockRefund(PayRefundStatusEnum.WAITING.getStatus()); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertNull(resp.getChannelRefundNo()); + assertEquals("R001", resp.getOutRefundNo()); + } + + @Test // 退款单是退款失败,钱包退款流水不存在:返回退款失败 + public void testGetRefund_failureWithoutTransaction() { + // mock 方法 + PayRefundDO refund = mockRefund(PayRefundStatusEnum.FAILURE.getStatus()); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), resp.getStatus()); + assertEquals(refund.getChannelErrorCode(), resp.getChannelErrorCode()); + assertEquals(refund.getChannelErrorMsg(), resp.getChannelErrorMsg()); + } + + @Test // 退款单是退款成功,但钱包退款流水不存在:无效状态,抛出异常 + public void testGetRefund_successWithoutTransaction() { + // mock 方法 + mockRefund(PayRefundStatusEnum.SUCCESS.getStatus()); + + // 调用,并断言异常 + assertThrows(PayClientException.class, () -> client.getRefund("P001", "R001")); + } + + @Test // 退款单不存在:返回退款失败,错误码为数字编码 + public void testGetRefund_refundNotFound() { + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), resp.getStatus()); + assertEquals(String.valueOf(REFUND_NOT_FOUND.getCode()), resp.getChannelErrorCode()); + assertEquals(REFUND_NOT_FOUND.getMsg(), resp.getChannelErrorMsg()); + } + + private PayRefundDO mockRefund(Integer status) { + PayRefundDO refund = randomPojo(PayRefundDO.class, o -> o.setId(100L).setNo("R001").setStatus(status)); + when(refundService.getRefundByNo(eq("R001"))).thenReturn(refund); + return refund; + } + + private PayWalletTransactionDO mockRefundTransaction(PayRefundDO refund) { + PayWalletTransactionDO transaction = randomPojo(PayWalletTransactionDO.class); + when(walletTransactionService.getWalletTransaction(eq(String.valueOf(refund.getId())), + eq(PayWalletBizTypeEnum.PAYMENT_REFUND))).thenReturn(transaction); + return transaction; + } + +} diff --git a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClientTest.java b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClientTest.java index 172ae94..ea27cb2 100644 --- a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClientTest.java +++ b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/framework/pay/core/client/impl/weixin/AbstractWxPayClientTest.java @@ -1,10 +1,16 @@ package cn.iocoder.yudao.module.pay.framework.pay.core.client.impl.weixin; import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; +import cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum; import cn.iocoder.yudao.module.pay.enums.transfer.PayTransferStatusEnum; +import cn.iocoder.yudao.module.pay.framework.pay.core.client.dto.refund.PayRefundRespDTO; +import cn.iocoder.yudao.module.pay.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO; import cn.iocoder.yudao.module.pay.framework.pay.core.client.dto.transfer.PayTransferRespDTO; import cn.iocoder.yudao.module.pay.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO; import cn.iocoder.yudao.module.pay.framework.pay.core.client.exception.PayClientException; +import com.github.binarywang.wxpay.bean.request.WxPayRefundQueryV3Request; +import com.github.binarywang.wxpay.bean.request.WxPayRefundV3Request; +import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryV3Result; import com.github.binarywang.wxpay.bean.transfer.TransferBillsGetResult; import com.github.binarywang.wxpay.exception.WxPayException; import com.github.binarywang.wxpay.service.TransferService; @@ -18,8 +24,10 @@ import java.util.Map; import static cn.iocoder.yudao.module.pay.framework.pay.core.client.impl.weixin.WxPayClientConfig.API_VERSION_V3; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -32,6 +40,7 @@ import static org.mockito.Mockito.when; public class AbstractWxPayClientTest extends BaseMockitoUnitTest { private WxLitePayClient client; + private WxPayService wxPayService; private TransferService transferService; @BeforeEach @@ -40,9 +49,9 @@ public class AbstractWxPayClientTest extends BaseMockitoUnitTest { config.setApiVersion(API_VERSION_V3); config.setAppId("wx-app-id"); client = new WxLitePayClient(1L, config); - WxPayService wxPayService = mock(WxPayService.class); + wxPayService = mock(WxPayService.class); transferService = mock(TransferService.class); - when(wxPayService.getTransferService()).thenReturn(transferService); + lenient().when(wxPayService.getTransferService()).thenReturn(transferService); // 退款相关的测试不使用 ReflectionTestUtils.setField(client, "client", wxPayService); } @@ -83,6 +92,102 @@ public class AbstractWxPayClientTest extends BaseMockitoUnitTest { verify(transferService).transferBills(any()); } + @Test // 发起微信退款发生 IO 异常:退款可能已受理,抛出异常,不误判为退款失败 + public void testUnifiedRefund_ioException() throws Exception { + // mock 方法 + when(wxPayService.refundV3(any(WxPayRefundV3Request.class))).thenThrow(new WxPayException("timeout", + new IOException("read timeout"))); + + // 调用,并断言异常 + assertThrows(PayClientException.class, () -> client.unifiedRefund(buildRefundUnifiedReqDTO())); + } + + @Test // 发起微信退款返回系统错误:退款可能已受理,返回结果未知,不误判为退款失败 + public void testUnifiedRefund_systemError() throws Exception { + // mock 方法 + when(wxPayService.refundV3(any(WxPayRefundV3Request.class))).thenThrow(WxPayException.newBuilder() + .errCode("SYSTEM_ERROR").errCodeDes("系统错误").build()); + + // 调用 + PayRefundRespDTO resp = client.unifiedRefund(buildRefundUnifiedReqDTO()); + // 断言 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertNull(resp.getChannelRefundNo()); + assertEquals("R001", resp.getOutRefundNo()); + } + + @Test // 发起微信退款返回业务错误(例如说:余额不足):明确的退款失败 + public void testUnifiedRefund_businessError() throws Exception { + // mock 方法 + when(wxPayService.refundV3(any(WxPayRefundV3Request.class))).thenThrow(WxPayException.newBuilder() + .errCode("NOT_ENOUGH").errCodeDes("余额不足").build()); + + // 调用 + PayRefundRespDTO resp = client.unifiedRefund(buildRefundUnifiedReqDTO()); + // 断言 + assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), resp.getStatus()); + assertEquals("NOT_ENOUGH", resp.getChannelErrorCode()); + assertEquals("余额不足", resp.getChannelErrorMsg()); + } + + @Test // 查询微信退款单不存在(例如说:退款请求未受理、或者尚未生成退款单):返回结果未知,不作为退款失败 + public void testGetRefund_notExists() throws Exception { + // mock 方法 + when(wxPayService.refundQueryV3(any(WxPayRefundQueryV3Request.class))).thenThrow(WxPayException.newBuilder() + .errCode("RESOURCE_NOT_EXISTS").errCodeDes("退款单不存在").build()); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertNull(resp.getChannelRefundNo()); + assertEquals("R001", resp.getOutRefundNo()); + } + + @Test // 查询微信退款单处理中:渠道已受理,返回渠道退款单号 + public void testGetRefund_processing() throws Exception { + // mock 方法 + WxPayRefundQueryV3Result result = new WxPayRefundQueryV3Result(); + result.setStatus("PROCESSING"); + result.setRefundId("WX_REFUND_001"); + when(wxPayService.refundQueryV3(any(WxPayRefundQueryV3Request.class))).thenReturn(result); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), resp.getStatus()); + assertEquals("WX_REFUND_001", resp.getChannelRefundNo()); + } + + @Test // 查询微信退款单已关闭:明确的退款失败 + public void testGetRefund_closed() throws Exception { + // mock 方法 + WxPayRefundQueryV3Result result = new WxPayRefundQueryV3Result(); + result.setStatus("CLOSED"); + when(wxPayService.refundQueryV3(any(WxPayRefundQueryV3Request.class))).thenReturn(result); + + // 调用 + PayRefundRespDTO resp = client.getRefund("P001", "R001"); + // 断言 + assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), resp.getStatus()); + } + + @Test // 查询微信退款单发生其它错误(例如说:系统错误):抛出异常,不作为退款失败 + public void testGetRefund_systemError() throws Exception { + // mock 方法 + when(wxPayService.refundQueryV3(any(WxPayRefundQueryV3Request.class))).thenThrow(WxPayException.newBuilder() + .errCode("SYSTEM_ERROR").errCodeDes("系统错误").build()); + + // 调用,并断言异常 + assertThrows(PayClientException.class, () -> client.getRefund("P001", "R001")); + } + + private static PayRefundUnifiedReqDTO buildRefundUnifiedReqDTO() { + return new PayRefundUnifiedReqDTO().setOutTradeNo("P001").setOutRefundNo("R001") + .setReason("测试退款").setPayPrice(100).setRefundPrice(10) + .setNotifyUrl("http://127.0.0.1/refund"); + } + private static PayTransferUnifiedReqDTO buildTransferUnifiedReqDTO() { return new PayTransferUnifiedReqDTO().setUserIp("127.0.0.1").setOutTransferNo("T001") .setPrice(100).setSubject("佣金提现").setUserAccount("openid") diff --git a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceTest.java b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceTest.java index d6cd9a7..c87c085 100755 --- a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceTest.java +++ b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/refund/PayRefundServiceTest.java @@ -29,18 +29,29 @@ import cn.iocoder.yudao.module.pay.service.order.PayOrderService; import jakarta.annotation.Resource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InOrder; import org.mockito.MockedStatic; import org.springframework.context.annotation.Import; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.util.AopTestUtils; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; @@ -597,6 +608,60 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { verify(client, times(1)).unifiedRefund(any()); } + @Test // 并发使用相同的商户退款编号发起退款,锁外都查询不到退款单;前者退款成功后,后者加锁,在锁内重新查询到退款单,只能创建一个退款单 + // 注意:锁内需要重新查询数据库,不能复用锁外查询的结果(例如说,MyBatis 一级缓存) + public void testCreateRefund_concurrentCreateAfterSuccess() throws Exception { + // mock 方法(client 退款成功) + PayClient client = mockPayClient(); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenAnswer(invocation -> PayRefundRespDTO.successOf( + "CHANNEL_R001", LocalDateTime.now(), ((PayRefundUnifiedReqDTO) invocation.getArgument(0)).getOutRefundNo(), "success")); + // mock 方法(mapper):两个请求锁外都查询不到退款单后,第一个请求继续;第二个请求等待第一个请求完成后,再继续 + CountDownLatch bothMissing = new CountDownLatch(2); + CountDownLatch firstFinished = new CountDownLatch(1); + AtomicReference secondThread = new AtomicReference<>(); + ThreadLocal outerQueried = ThreadLocal.withInitial(() -> false); + PayRefundMapper refundMapperSpy = mock(PayRefundMapper.class, delegatesTo(refundMapper)); + doAnswer(invocation -> { + PayRefundDO refund = refundMapper.selectByAppIdAndMerchantRefundId(invocation.getArgument(0), + invocation.getArgument(1)); + if (!outerQueried.get()) { // 锁外的查询 + outerQueried.set(true); + assertNull(refund); + bothMissing.countDown(); + assertTrue(bothMissing.await(10, TimeUnit.SECONDS)); + if (Thread.currentThread() == secondThread.get()) { + assertTrue(firstFinished.await(10, TimeUnit.SECONDS)); + } + } + return refund; + }).when(refundMapperSpy).selectByAppIdAndMerchantRefundId(any(), any()); + Object target = AopTestUtils.getTargetObject(refundService); + ReflectionTestUtils.setField(target, "refundMapper", refundMapperSpy); + ExecutorService executor = Executors.newFixedThreadPool(2); + Long refundId; + Throwable exception; + try { + // 调用:两个请求并发发起退款 + Future future01 = executor.submit(() -> refundService.createRefund(buildRefundCreateReqDTO())); + Future future02 = executor.submit(() -> { + secondThread.set(Thread.currentThread()); + return refundService.createRefund(buildRefundCreateReqDTO()); + }); + refundId = future01.get(10, TimeUnit.SECONDS); + firstFinished.countDown(); + exception = assertThrows(ExecutionException.class, () -> future02.get(10, TimeUnit.SECONDS)).getCause(); + } finally { + firstFinished.countDown(); + executor.shutdownNow(); + ReflectionTestUtils.setField(target, "refundMapper", refundMapper); + } + // 断言:第二个请求提示退款单已存在,只创建一个退款单,只发起一次退款 + assertEquals(REFUND_EXISTS.getCode(), ((ServiceException) exception).getCode()); + assertEquals(1, refundMapper.selectList().size()); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refundMapper.selectById(refundId).getStatus()); + verify(client, times(1)).unifiedRefund(any()); + } + @Test // 调用 unifiedRefund 接口返回失败,但查询确认渠道退款成功 public void testCreateRefund_invokeFailure_querySuccess() { // mock 方法(client) @@ -647,6 +712,28 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { verify(notifyService, never()).createPayNotifyTask(any(), any()); } + @Test // 调用 unifiedRefund 接口返回存在渠道错误,但退款回调已在其它事务中并发更新为成功:需要查询到最新状态,不能命中 MyBatis 一级缓存 + public void testCreateRefund_channelErrorWhenConcurrentSuccessNotify() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayChannelDO channel = channelService.validPayChannel(10L); + mockUnifiedRefundFailure(client); + when(client.getRefund(any(), any())).thenAnswer(invocation -> { + // 模拟:退款回调在其它事务中,并发更新为退款成功 + refundService.notifyRefund(channel, PayRefundRespDTO.successOf("CHANNEL_R001", LocalDateTime.now(), + invocation.getArgument(1), "success")); + return PayRefundRespDTO.failureOf("REFUND_NOT_EXISTS", "退款单不存在", invocation.getArgument(1), "failure"); + }); + + // 调用:以最新的退款成功为准,不向调用方误报失败 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言 + PayRefundDO refund = refundMapper.selectById(refundId); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + verify(notifyService, times(1)).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refundId)); + } + @Test // 调用 unifiedRefund 接口返回存在渠道错误,通知时发生状态竞争,但退款单仍是待退款 public void testCreateRefund_channelErrorWhenConcurrentWaiting() { PayRefundServiceImpl payRefundServiceImpl = mock(PayRefundServiceImpl.class); @@ -654,7 +741,7 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { springUtilMockedStatic.when(() -> SpringUtil.getBean(eq(PayRefundServiceImpl.class))) .thenReturn(payRefundServiceImpl); doThrow(exception(REFUND_STATUS_IS_NOT_WAITING)) - .when(payRefundServiceImpl).notifyRefund(any(PayChannelDO.class), any()); + .when(payRefundServiceImpl).notifyRefund(any(PayChannelDO.class), any(), any()); // mock 方法(client) PayClient client = mockPayClient(); mockUnifiedRefundFailure(client); @@ -755,6 +842,8 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { assertNull(refund.getChannelErrorMsg()); assertNull(refund.getChannelNotifyData()); verify(client).getRefund(eq(failureRefund.getOrderNo()), eq(failureRefund.getNo())); + // 断言:update_time 大于退款失败时的 update_time,用于区分新旧退款尝试 + assertTrue(refund.getUpdateTime().isAfter(failureRefund.getUpdateTime())); } @Test // 退款失败后再次发起,但退款单已被并发重新发起 @@ -842,6 +931,345 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { verify(client, never()).unifiedRefund(any()); } + @Test // 调用 unifiedRefund 接口返回结果未知(例如说:支付宝 fund_change 不为 Y),查询确认渠道退款成功 + public void testCreateRefund_invokeUnknown_querySuccess() { + // mock 方法(client) + PayClient client = mockPayClient(); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenAnswer(invocation -> PayRefundRespDTO.waitingOf( + null, ((PayRefundUnifiedReqDTO) invocation.getArgument(0)).getOutRefundNo(), "unknown")); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.successOf(null, + LocalDateTime.now(), invocation.getArgument(1), "success")); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言:按查询结果更新为退款成功 + PayRefundDO refund = refundMapper.selectById(refundId); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refund.getStatus()); + verify(client).getRefund(eq(refund.getOrderNo()), eq(refund.getNo())); + verify(notifyService).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refundId)); + } + + @Test // 调用 unifiedRefund 接口返回结果未知(例如说:支付宝 fund_change 不为 Y),查询也没有退款数据:保留 WAITING,不通知 + public void testCreateRefund_invokeUnknown_queryUnknown() { + // mock 方法(client) + PayClient client = mockPayClient(); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenAnswer(invocation -> PayRefundRespDTO.waitingOf( + null, ((PayRefundUnifiedReqDTO) invocation.getArgument(0)).getOutRefundNo(), "unknown")); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.waitingOf( + null, invocation.getArgument(1), "unknown")); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言 + PayRefundDO refund = refundMapper.selectById(refundId); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertNull(refund.getChannelRefundNo()); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + } + + @Test // 结果未知(WAITING)的退款单,使用相同的商户退款编号再次发起:查询不到结果,使用原退款单号、原退款金额重新发起 + public void testCreateRefund_retryWaiting_success() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.waitingOf( + null, invocation.getArgument(1), "unknown")); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenAnswer(invocation -> PayRefundRespDTO.successOf( + "CHANNEL_R001", LocalDateTime.now(), ((PayRefundUnifiedReqDTO) invocation.getArgument(0)).getOutRefundNo(), "success")); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO().setReason("再次退款")); + // 断言:复用原退款单,退款成功 + assertEquals(unknownRefund.getId(), refundId); + assertEquals(1, refundMapper.selectList().size()); + PayRefundDO refund = refundMapper.selectById(refundId); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + assertEquals("原退款原因", refund.getReason()); + // 断言:先查询渠道退款单,再使用原退款单号、原退款金额、原退款原因重新发起 + InOrder inOrder = inOrder(client); + inOrder.verify(client).getRefund(eq(unknownRefund.getOrderNo()), eq(unknownRefund.getNo())); + inOrder.verify(client).unifiedRefund(argThat(unifiedReqDTO -> unknownRefund.getNo().equals(unifiedReqDTO.getOutRefundNo()) + && Integer.valueOf(9).equals(unifiedReqDTO.getRefundPrice()) && "原退款原因".equals(unifiedReqDTO.getReason()))); + verify(notifyService).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refundId)); + } + + @Test // 结果未知的退款单再次发起,查询到渠道退款成功:同步退款结果,不重新发起 + public void testCreateRefund_retryWaiting_querySuccess() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.successOf("CHANNEL_R001", + LocalDateTime.now(), invocation.getArgument(1), "success")); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言 + assertEquals(unknownRefund.getId(), refundId); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refundMapper.selectById(refundId).getStatus()); + verify(client, never()).unifiedRefund(any()); + verify(notifyService).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refundId)); + } + + @Test // 结果未知的退款单再次发起,查询到渠道已受理(退款中):保存渠道退款单号,继续等待,不重新发起 + public void testCreateRefund_retryWaiting_queryProcessing() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.waitingOf( + "CHANNEL_R001", invocation.getArgument(1), "processing")); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_HAS_REFUNDING); + // 断言 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + verify(client, never()).unifiedRefund(any()); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + } + + @Test // 结果未知的退款单再次发起,查询到退款失败:不能证明原退款请求失败,不更新为退款失败,使用原退款单号重新发起; + // 渠道明确的退款失败,仍由退款轮询(或者退款回调)收敛为退款失败 + public void testCreateRefund_retryWaiting_queryFailure() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.failureOf( + "CLOSED", "退款关闭", invocation.getArgument(1), "failure")); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenThrow(new RuntimeException("模拟网络超时")); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言:保留 WAITING,使用原退款单号重新发起,不通知退款失败 + assertEquals(unknownRefund.getId(), refundId); + PayRefundDO refund = refundMapper.selectById(refundId); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertNull(refund.getChannelErrorCode()); + verify(client).unifiedRefund(argThat(unifiedReqDTO -> unknownRefund.getNo().equals(unifiedReqDTO.getOutRefundNo()))); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + + // 调用:退款轮询,查询到退款失败(同一次退款尝试) + assertEquals(1, refundService.syncRefund()); + // 断言:更新为退款失败 + assertRefundFailure("CLOSED"); + } + + @Test // 结果未知的退款单再次发起,但已有渠道退款单号(渠道已受理):不查询、不重新发起 + public void testCreateRefund_retryWaiting_hasChannelRefundNo() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + refundMapper.updateById(new PayRefundDO().setId(unknownRefund.getId()).setChannelRefundNo("CHANNEL_R001")); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_HAS_REFUNDING); + // 断言 + verify(client, never()).getRefund(any(), any()); + verify(client, never()).unifiedRefund(any()); + } + + @Test // 结果未知的退款单再次发起,未超过重新发起的间隔:不重新发起,也不刷新 update_time + public void testCreateRefund_retryWaiting_withinInterval() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusMinutes(1).withNano(0)); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_HAS_REFUNDING); + // 断言 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertEquals(unknownRefund.getUpdateTime(), refund.getUpdateTime()); + verify(client).getRefund(eq(unknownRefund.getOrderNo()), eq(unknownRefund.getNo())); + verify(client, never()).unifiedRefund(any()); + } + + @Test // 结果未知的退款单再次发起,但支付订单不一致 + public void testCreateRefund_retryWaiting_orderNotMatch() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + refundMapper.updateById(new PayRefundDO().setId(unknownRefund.getId()).setOrderId(-1L)); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_CREATE_FAIL_ORDER_NOT_MATCH); + // 断言 + verify(client, never()).getRefund(any(), any()); + verify(client, never()).unifiedRefund(any()); + } + + @Test // 结果未知的退款单再次发起,但退款金额不一致 + public void testCreateRefund_retryWaiting_priceNotMatch() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + refundMapper.updateById(new PayRefundDO().setId(unknownRefund.getId()).setRefundPrice(5)); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_CREATE_FAIL_PRICE_NOT_MATCH); + // 断言 + verify(client, never()).getRefund(any(), any()); + verify(client, never()).unifiedRefund(any()); + } + + @Test // 结果未知的退款单重新发起,结果仍未知:保留 WAITING、不通知;占位独立提交,调用方事务回滚不撤销,间隔内不会再次发起 + public void testCreateRefund_retryWaiting_unknownWhenOuterTransactionRollback() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenThrow(new RuntimeException("模拟网络超时")); + when(client.getRefund(any(), any())).thenThrow(new RuntimeException("模拟查询超时")); + + // 调用:调用方事务中再次发起,随后调用方事务回滚 + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.executeWithoutResult(status -> { + refundService.createRefund(buildRefundCreateReqDTO()); + status.setRollbackOnly(); + }); + // 断言:保留 WAITING,不更新为退款失败、不通知 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertNull(refund.getChannelErrorCode()); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + // 断言:已刷新 update_time 占位,不受调用方事务回滚影响;使用原退款单号重新发起 + assertTrue(refund.getUpdateTime().isAfter(LocalDateTime.now().minusMinutes(1))); + verify(client).unifiedRefund(argThat(unifiedReqDTO -> unknownRefund.getNo().equals(unifiedReqDTO.getOutRefundNo()))); + + // 调用:间隔内再次发起,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_HAS_REFUNDING); + // 断言:不会再次向渠道发起退款 + verify(client, times(1)).unifiedRefund(any()); + } + + @Test // 结果未知的退款单重新发起,渠道返回失败:不能证明原退款请求失败,保留 WAITING、不通知,提示渠道错误 + public void testCreateRefund_retryWaiting_resendFailure() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + mockUnifiedRefundFailure(client); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_SUBMIT_CHANNEL_ERROR, "BALANCE_NOT_ENOUGH", "余额不足"); + // 断言 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertNull(refund.getChannelErrorCode()); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + } + + @Test // 结果未知的退款单重新发起,渠道返回失败,但退款回调已并发更新为退款成功:以最新状态为准,不提示渠道错误 + public void testCreateRefund_retryWaiting_resendFailureWhenConcurrentSuccess() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + PayChannelDO channel = channelService.validPayChannel(10L); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenAnswer(invocation -> { + // 模拟:原退款请求的退款回调,并发更新为退款成功 + refundService.notifyRefund(channel, PayRefundRespDTO.successOf("CHANNEL_R001", LocalDateTime.now(), + unknownRefund.getNo(), "success")); + return PayRefundRespDTO.failureOf("INVALID_REQUEST", "退款单号重复", + ((PayRefundUnifiedReqDTO) invocation.getArgument(0)).getOutRefundNo(), "failure"); + }); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言 + assertEquals(unknownRefund.getId(), refundId); + PayRefundDO refund = refundMapper.selectById(refundId); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + verify(notifyService, times(1)).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refundId)); + } + + @Test // 结果未知的退款单再次发起,查询后、占位前,退款回调写入渠道退款单号:占位失败,不重新发起,保留渠道退款单号 + public void testCreateRefund_retryWaiting_concurrentCallbackWaiting() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> { + // 模拟:退款回调并发写入渠道退款单号。保持原 update_time,只验证渠道退款单号的占位条件 + PayRefundDO updateObj = new PayRefundDO().setId(unknownRefund.getId()).setChannelRefundNo("CHANNEL_R001"); + updateObj.setUpdateTime(unknownRefund.getUpdateTime()); + refundMapper.updateById(updateObj); + return PayRefundRespDTO.waitingOf(null, invocation.getArgument(1), "unknown"); + }); + + // 调用,并断言异常 + assertServiceException(() -> refundService.createRefund(buildRefundCreateReqDTO()), + REFUND_HAS_REFUNDING); + // 断言:不清空渠道退款单号,不刷新 update_time + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + assertEquals(unknownRefund.getUpdateTime(), refund.getUpdateTime()); + verify(client, never()).unifiedRefund(any()); + } + + @Test // 结果未知的退款单再次发起,查询后、占位前,退款回调更新为退款成功:占位失败,以最新的退款成功为准 + public void testCreateRefund_retryWaiting_concurrentCallbackSuccess() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + PayChannelDO channel = channelService.validPayChannel(10L); + when(client.getRefund(any(), any())).thenAnswer(invocation -> { + // 模拟:退款回调并发更新为退款成功 + refundService.notifyRefund(channel, PayRefundRespDTO.successOf("CHANNEL_R001", LocalDateTime.now(), + unknownRefund.getNo(), "success")); + return PayRefundRespDTO.waitingOf(null, invocation.getArgument(1), "unknown"); + }); + + // 调用 + Long refundId = refundService.createRefund(buildRefundCreateReqDTO()); + // 断言 + assertEquals(unknownRefund.getId(), refundId); + assertEquals(PayRefundStatusEnum.SUCCESS.getStatus(), refundMapper.selectById(refundId).getStatus()); + verify(client, never()).unifiedRefund(any()); + } + + @Test // 结果未知的退款单,并发再次发起:只有一个请求占位成功、重新发起,避免重复发起 + public void testCreateRefund_retryWaiting_concurrentRetry() throws Exception { + // mock 方法(client):两个请求都查询完成后,再继续占位,放大并发窗口 + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + CountDownLatch queryLatch = new CountDownLatch(2); + when(client.getRefund(any(), any())).thenAnswer(invocation -> { + queryLatch.countDown(); + queryLatch.await(5, TimeUnit.SECONDS); + return PayRefundRespDTO.waitingOf(null, invocation.getArgument(1), "unknown"); + }); + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenAnswer(invocation -> PayRefundRespDTO.waitingOf( + "CHANNEL_R001", ((PayRefundUnifiedReqDTO) invocation.getArgument(0)).getOutRefundNo(), "processing")); + + // 调用:两个请求并发再次发起 + List> futures = Arrays.asList( + CompletableFuture.supplyAsync(() -> refundService.createRefund(buildRefundCreateReqDTO())), + CompletableFuture.supplyAsync(() -> refundService.createRefund(buildRefundCreateReqDTO()))); + List exceptions = new ArrayList<>(); + for (CompletableFuture future : futures) { + try { + future.get(); + } catch (Exception ex) { + exceptions.add(ex.getCause()); + } + } + // 断言:只有一个请求重新发起,另一个请求提示退款处理中 + assertEquals(1, exceptions.size()); + assertEquals(REFUND_HAS_REFUNDING.getCode(), ((ServiceException) exceptions.get(0)).getCode()); + verify(client, times(2)).getRefund(any(), any()); + verify(client, times(1)).unifiedRefund(any()); + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + } + @Test public void testCreateRefund_invokeSuccess() { PayRefundServiceImpl payRefundServiceImpl = mock(PayRefundServiceImpl.class); @@ -1157,6 +1585,160 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { assertEquals(count, 0); } + @Test // 退款轮询:查询到退款失败,并且查询期间退款单未变化(同一次退款尝试),更新为退款失败 + public void testSyncRefund_failureWhenSameAttempt() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> PayRefundRespDTO.failureOf( + "CLOSED", "退款关闭", invocation.getArgument(1), "failure")); + + // 调用 + int count = refundService.syncRefund(); + // 断言 + assertEquals(1, count); + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), refund.getStatus()); + assertEquals("CLOSED", refund.getChannelErrorCode()); + verify(notifyService).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refund.getId())); + } + + @Test // 退款轮询:查询期间,退款单已被重新发起(新的退款尝试),旧的查询结果(退款失败)不能关闭新的退款尝试 + public void testSyncRefund_failureWhenRetried() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + when(client.getRefund(any(), any())).thenAnswer(invocation -> { + // 模拟:查询期间,商户再次发起,占位后使用原退款单号重新发起 + assertEquals(1, refundMapper.updateUpdateTimeByIdAndWaiting(unknownRefund.getId(), LocalDateTime.now())); + return PayRefundRespDTO.failureOf("CLOSED", "退款关闭", invocation.getArgument(1), "failure"); + }); + + // 调用 + int count = refundService.syncRefund(); + // 断言:保留 WAITING,不通知 + assertEquals(0, count); + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertNull(refund.getChannelErrorCode()); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + } + + @Test // 退款轮询:查询期间,同一秒内退款失败、再次重新发起,旧的查询结果(退款失败)不能关闭新的退款尝试 + public void testSyncRefund_failureWhenRetriedInSameSecond() { + // mock 方法(client) + PayClient client = mockPayClient(); + PayChannelDO channel = channelService.validPayChannel(10L); + // 准备参数:已存在退款失败的退款单 + LocalDateTime now = LocalDateTime.now().withNano(0); + PayRefundDO failureRefund = insertFailureRefund(9); + PayRefundDO updateObj = new PayRefundDO().setId(failureRefund.getId()).setChannelId(10L); + updateObj.setUpdateTime(now); + refundMapper.updateById(updateObj); + // mock 方法(client 发起退款发生异常;轮询查询期间,第一次重新发起的退款失败回调到达,并且商户在同一秒内第二次重新发起) + when(client.unifiedRefund(any(PayRefundUnifiedReqDTO.class))).thenThrow(new RuntimeException("模拟网络超时")); + AtomicBoolean polling = new AtomicBoolean(false); + when(client.getRefund(any(), any())).thenAnswer(invocation -> { + if (!polling.compareAndSet(true, false)) { + return PayRefundRespDTO.waitingOf(null, invocation.getArgument(1), "unknown"); + } + refundService.notifyRefund(channel, PayRefundRespDTO.failureOf("CLOSED", "第一次重新发起失败", + invocation.getArgument(1), "failure")); + assertEquals(failureRefund.getId(), refundService.createRefund(buildRefundCreateReqDTO())); + return PayRefundRespDTO.failureOf("CLOSED", "第一次重新发起失败", invocation.getArgument(1), "failure"); + }); + + // 固定当前时间,模拟同一秒内发生 + try (MockedStatic clock = mockStatic(LocalDateTime.class, CALLS_REAL_METHODS)) { + clock.when(LocalDateTime::now).thenReturn(now); + // 调用:第一次重新发起,结果未知 + assertEquals(failureRefund.getId(), refundService.createRefund(buildRefundCreateReqDTO())); + LocalDateTime firstUpdateTime = refundMapper.selectById(failureRefund.getId()).getUpdateTime(); + // 调用:退款轮询 + polling.set(true); + int count = refundService.syncRefund(); + + // 断言:第二次重新发起的退款单,保留 WAITING,并且 update_time 大于第一次重新发起时的 update_time + assertFalse(polling.get()); + assertEquals(0, count); + PayRefundDO refund = refundMapper.selectById(failureRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertNull(refund.getChannelErrorCode()); + assertTrue(refund.getUpdateTime().isAfter(firstUpdateTime)); + // 断言:只通知第一次重新发起的退款失败 + verify(notifyService).createPayNotifyTask(eq(PayNotifyTypeEnum.REFUND.getType()), eq(refund.getId())); + } + } + + @Test // 退款回调:读取退款单后、更新前,退款单已被重新发起占位,不能关闭新的退款尝试 + public void testNotifyRefundFailure_concurrentRetry() { + // mock 方法(client) + mockPayClient(); + PayChannelDO channel = channelService.validPayChannel(10L); + PayRefundDO unknownRefund = insertUnknownRefund(LocalDateTime.now().minusHours(1).withNano(0)); + // mock 方法(mapper):读取退款单后,其它请求(独立事务)占位重新发起 + PayRefundMapper refundMapperSpy = mock(PayRefundMapper.class, delegatesTo(refundMapper)); + TransactionTemplate otherTransaction = new TransactionTemplate(transactionManager); + otherTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + doAnswer(invocation -> { + PayRefundDO refund = refundMapper.selectByAppIdAndNo(invocation.getArgument(0), invocation.getArgument(1)); + Integer updateCount = otherTransaction.execute(status -> + refundMapper.updateUpdateTimeByIdAndWaiting(unknownRefund.getId(), LocalDateTime.now())); + assertEquals(1, updateCount); + return refund; + }).when(refundMapperSpy).selectByAppIdAndNo(any(), any()); + Object target = AopTestUtils.getTargetObject(refundService); + ReflectionTestUtils.setField(target, "refundMapper", refundMapperSpy); + try { + // 调用,并断言异常:渠道会重试退款回调 + assertServiceException(() -> refundService.notifyRefund(channel, PayRefundRespDTO.failureOf("CLOSED", + "退款关闭", unknownRefund.getNo(), "failure")), REFUND_STATUS_IS_NOT_WAITING); + } finally { + ReflectionTestUtils.setField(target, "refundMapper", refundMapper); + } + // 断言:保留占位后的 WAITING,不通知 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertTrue(refund.getUpdateTime().isAfter(unknownRefund.getUpdateTime())); + assertNull(refund.getChannelErrorCode()); + verify(notifyService, never()).createPayNotifyTask(any(), any()); + } + + @Test // 退款回调:退款失败时,update_time 作为退款尝试的令牌,不能回退(重新发起时 update_time 可能大于当前时间) + public void testNotifyRefundFailure_notRollbackUpdateTime() { + // mock 方法(client) + mockPayClient(); + PayChannelDO channel = channelService.validPayChannel(10L); + LocalDateTime updateTime = LocalDateTime.now().plusHours(1).withNano(0); + PayRefundDO unknownRefund = insertUnknownRefund(updateTime); + + // 调用 + refundService.notifyRefund(channel, PayRefundRespDTO.failureOf("CLOSED", "退款关闭", + unknownRefund.getNo(), "failure")); + // 断言 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), refund.getStatus()); + assertEquals(updateTime, refund.getUpdateTime()); + } + + @Test // 退款回调:渠道已受理(退款中)时,update_time 作为退款尝试的令牌,不能回退 + public void testNotifyRefundWaiting_notRollbackUpdateTime() { + // mock 方法(client) + mockPayClient(); + PayChannelDO channel = channelService.validPayChannel(10L); + LocalDateTime updateTime = LocalDateTime.now().plusHours(1).withNano(0); + PayRefundDO unknownRefund = insertUnknownRefund(updateTime); + + // 调用 + refundService.notifyRefund(channel, PayRefundRespDTO.waitingOf("CHANNEL_R001", + unknownRefund.getNo(), "processing")); + // 断言 + PayRefundDO refund = refundMapper.selectById(unknownRefund.getId()); + assertEquals(PayRefundStatusEnum.WAITING.getStatus(), refund.getStatus()); + assertEquals("CHANNEL_R001", refund.getChannelRefundNo()); + assertEquals(updateTime, refund.getUpdateTime()); + } + private PayClient mockPayClient() { // mock 方法(app) PayAppDO app = randomPojo(PayAppDO.class, o -> o.setId(1L)); @@ -1205,6 +1787,21 @@ public class PayRefundServiceTest extends BaseDbAndRedisUnitTest { return refund; } + /** + * 插入结果未知(WAITING,并且没有渠道退款单号)的退款单,关联 {@link #mockPayClient()} 的支付订单 + */ + private PayRefundDO insertUnknownRefund(LocalDateTime updateTime) { + PayOrderDO order = orderService.getOrder(1L, "100"); + PayRefundDO refund = randomPojo(PayRefundDO.class, o -> o.setAppId(1L).setMerchantRefundId("200") + .setOrderId(order.getId()).setOrderNo(order.getNo()).setChannelId(10L) + .setRefundPrice(9).setReason("原退款原因") + .setStatus(PayRefundStatusEnum.WAITING.getStatus()).setChannelRefundNo(null).setSuccessTime(null) + .setChannelErrorCode(null).setChannelErrorMsg(null)); + refund.setUpdateTime(updateTime); + refundMapper.insert(refund); + return refund; + } + private void assertRefundFailure(String channelErrorCode) { PayRefundDO refund = refundMapper.selectByAppIdAndMerchantRefundId(1L, "200"); assertEquals(PayRefundStatusEnum.FAILURE.getStatus(), refund.getStatus()); diff --git a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceTest.java b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceTest.java index a53d5f2..0c60e2f 100644 --- a/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceTest.java +++ b/yudao-module-pay/src/test/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceTest.java @@ -1,24 +1,48 @@ package cn.iocoder.yudao.module.pay.service.wallet; import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest; +import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO; import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO; import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO; +import cn.iocoder.yudao.module.pay.dal.mysql.refund.PayRefundMapper; import cn.iocoder.yudao.module.pay.dal.mysql.wallet.PayWalletMapper; +import cn.iocoder.yudao.module.pay.dal.mysql.wallet.PayWalletTransactionMapper; import cn.iocoder.yudao.module.pay.dal.redis.wallet.PayWalletLockRedisDAO; +import cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum; import cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum; import cn.iocoder.yudao.module.pay.service.order.PayOrderService; import cn.iocoder.yudao.module.pay.service.refund.PayRefundService; +import cn.iocoder.yudao.module.pay.service.wallet.bo.WalletTransactionCreateReqBO; import jakarta.annotation.Resource; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import javax.sql.DataSource; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString; +import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.REFUND_NOT_FOUND; +import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.WALLET_REFUND_EXIST; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; /** * {@link PayWalletServiceImpl} 的单元测试类 @@ -33,9 +57,15 @@ public class PayWalletServiceTest extends BaseDbAndRedisUnitTest { @Resource private PayWalletMapper walletMapper; + @Resource + private PayWalletTransactionMapper walletTransactionMapper; + @Resource + private PayRefundMapper refundMapper; @Resource private PlatformTransactionManager transactionManager; + @Resource + private DataSource dataSource; @MockitoBean private PayWalletTransactionService walletTransactionService; @@ -82,4 +112,260 @@ public class PayWalletServiceTest extends BaseDbAndRedisUnitTest { assertEquals(100, dbWallet.getBalance()); } + @Test + public void testOrderRefund_success() { + // mock 数据 + PayRefundDO refund = insertWalletRefund(); + // mock 方法 + mockRefundAndWalletTransaction(); + + // 调用 + PayWalletTransactionDO transaction = walletService.orderRefund(refund.getNo(), 30, "测试退款"); + // 断言 + assertEquals(30, transaction.getPrice()); + assertEquals(String.valueOf(refund.getId()), transaction.getBizId()); + assertEquals(PayWalletBizTypeEnum.PAYMENT_REFUND.getType(), transaction.getBizType()); + assertEquals(130, walletMapper.selectById(transaction.getWalletId()).getBalance()); + } + + @Test // 已退款到钱包(例如说:退款入账后,更新退款单失败,退款单仍是 WAITING),使用原退款单号重新发起:返回原退款流水,不重复增加余额 + public void testOrderRefund_refundExists() { + // mock 数据 + PayRefundDO refund = insertWalletRefund(); + PayWalletTransactionDO refundTransaction = insertRefundTransaction(refund, 30); + // mock 方法 + mockRefundAndWalletTransaction(); + + // 调用 + PayWalletTransactionDO transaction = walletService.orderRefund(refund.getNo(), 30, "测试退款"); + // 断言 + assertEquals(refundTransaction.getId(), transaction.getId()); + assertEquals(100, walletMapper.selectById(refundTransaction.getWalletId()).getBalance()); + verify(walletTransactionService, never()).createWalletTransaction(any()); + } + + @Test // 已退款到钱包,但退款金额不一致 + public void testOrderRefund_refundExistsAndPriceNotMatch() { + // mock 数据 + PayRefundDO refund = insertWalletRefund(); + PayWalletTransactionDO refundTransaction = insertRefundTransaction(refund, 30); + // mock 方法 + mockRefundAndWalletTransaction(); + + // 调用,并断言异常 + assertServiceException(() -> walletService.orderRefund(refund.getNo(), 20, "测试退款"), + WALLET_REFUND_EXIST); + // 断言 + assertEquals(100, walletMapper.selectById(refundTransaction.getWalletId()).getBalance()); + verify(walletTransactionService, never()).createWalletTransaction(any()); + } + + @Test + public void testOrderRefund_refundNotFound() { + // mock 方法 + mockRefundAndWalletTransaction(); + + // 调用,并断言异常 + assertServiceException(() -> walletService.orderRefund("R404", 30, "测试退款"), + REFUND_NOT_FOUND); + } + + @Test // 调用方存在事务,退款到钱包后调用方事务回滚:退款流水、余额一起回滚,再次发起时只增加一次余额 + public void testOrderRefund_outerTransactionRollback() { + // mock 数据 + PayRefundDO refund = insertWalletRefund(); + Long walletId = walletTransactionMapper.selectByNo("W001").getWalletId(); + // mock 方法 + mockRefundAndWalletTransaction(); + + // 调用:调用方事务中退款到钱包,随后调用方事务回滚 + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.executeWithoutResult(status -> { + walletService.orderRefund(refund.getNo(), 30, "测试退款"); + status.setRollbackOnly(); + }); + // 断言:退款流水、余额一起回滚 + assertNull(walletTransactionMapper.selectByBiz(String.valueOf(refund.getId()), + PayWalletBizTypeEnum.PAYMENT_REFUND.getType())); + assertEquals(100, walletMapper.selectById(walletId).getBalance()); + + // 调用:再次退款到钱包 + PayWalletTransactionDO transaction = walletService.orderRefund(refund.getNo(), 30, "测试退款"); + // 断言:只记录一条退款流水,只增加一次余额 + assertEquals(transaction.getId(), walletTransactionMapper.selectByBiz(String.valueOf(refund.getId()), + PayWalletBizTypeEnum.PAYMENT_REFUND.getType()).getId()); + assertEquals(130, walletMapper.selectById(walletId).getBalance()); + } + + @Test // 并发使用同一退款单退款到钱包(例如说:结果未知的退款单重新发起,与原退款请求重叠),并且调用方存在事务: + // 后者在退款单的行锁上等待,前者提交后,当前读到已提交的退款流水,返回原流水,只增加一次余额 + public void testOrderRefund_concurrent() throws Exception { + // mock 数据 + PayRefundDO refund = insertWalletRefund(); + // mock 方法 + mockRefundAndWalletTransaction(); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + CountDownLatch firstWritten = new CountDownLatch(1); + CountDownLatch firstCommit = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + // 调用:第一个请求在调用方事务中退款到钱包,写入退款流水后,暂不提交 + Future future01 = executor.submit(() -> transactionTemplate.execute(status -> { + PayWalletTransactionDO transaction = walletService.orderRefund(refund.getNo(), 30, "测试退款"); + firstWritten.countDown(); + awaitLatch(firstCommit); + return transaction; + })); + assertTrue(firstWritten.await(10, TimeUnit.SECONDS)); + // 调用:第二个请求在调用方事务中,先查询退款流水(不存在),再退款到钱包,在退款单的行锁上等待 + Future future02 = executor.submit(() -> transactionTemplate.execute(status -> { + assertNull(walletTransactionMapper.selectByBiz(String.valueOf(refund.getId()), + PayWalletBizTypeEnum.PAYMENT_REFUND.getType())); + return walletService.orderRefund(refund.getNo(), 30, "测试退款"); + })); + // 断言:第二个请求确实在等待锁,然后提交第一个请求 + assertTrue(waitLockWaiting()); + firstCommit.countDown(); + PayWalletTransactionDO transaction01 = future01.get(10, TimeUnit.SECONDS); + PayWalletTransactionDO transaction02 = future02.get(10, TimeUnit.SECONDS); + + // 断言:返回同一条退款流水,只记录一条退款流水,只增加一次余额 + assertEquals(transaction01.getId(), transaction02.getId()); + verify(walletTransactionService, times(1)).createWalletTransaction(any()); + assertEquals(1L, walletTransactionMapper.selectCount(PayWalletTransactionDO::getBizType, + PayWalletBizTypeEnum.PAYMENT_REFUND.getType())); + assertEquals(130, walletMapper.selectById(transaction01.getWalletId()).getBalance()); + } finally { + firstCommit.countDown(); + executor.shutdownNow(); + } + } + + @Test // 新建事务时,使用读已提交,避免当前读不存在的退款流水时加间隙锁;加入调用方的已有事务时,沿用调用方的隔离级别 + // 注意:H2 无法模拟 MySQL 可重复读下的间隙锁,这里只校验事务的隔离级别,间隙锁死锁需要 MySQL 实库验证 + public void testOrderRefund_isolation() { + // mock 数据 + PayRefundDO refund = insertWalletRefund(); + // mock 方法:锁定退款单时,记录当前事务声明、实际连接的隔离级别 + mockRefundAndWalletTransaction(); + List declaredIsolationLevels = new ArrayList<>(); + List connectionIsolationLevels = new ArrayList<>(); + when(refundService.getRefundForUpdate(any())).thenAnswer(invocation -> { + declaredIsolationLevels.add(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + connectionIsolationLevels.add(DataSourceUtils.getConnection(dataSource).getTransactionIsolation()); + return refundMapper.selectOneForUpdate(PayRefundDO::getId, invocation.getArgument(0)); + }); + + // 调用:不存在调用方事务,新建事务退款到钱包 + PayWalletTransactionDO transaction = walletService.orderRefund(refund.getNo(), 30, "测试退款"); + // 调用:调用方事务(可重复读)中,再次退款到钱包 + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + PayWalletTransactionDO transaction02 = transactionTemplate.execute(status -> + walletService.orderRefund(refund.getNo(), 30, "测试退款")); + + // 断言:新建事务使用读已提交;加入调用方事务时,不覆盖调用方的可重复读 + assertEquals(Arrays.asList(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ), + declaredIsolationLevels); + assertEquals(Arrays.asList(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ), + connectionIsolationLevels); + // 断言:返回同一条退款流水,只增加一次余额 + assertNotNull(transaction02); + assertEquals(transaction.getId(), transaction02.getId()); + verify(walletTransactionService, times(1)).createWalletTransaction(any()); + assertEquals(130, walletMapper.selectById(transaction.getWalletId()).getBalance()); + } + + /** + * 插入钱包、钱包支付流水、退款单:钱包余额为 100 + */ + private PayRefundDO insertWalletRefund() { + PayWalletDO wallet = new PayWalletDO().setUserId(1L).setUserType(2) + .setBalance(100).setFreezePrice(0).setTotalExpense(30).setTotalRecharge(130); + walletMapper.insert(wallet); + PayWalletTransactionDO payTransaction = randomPojo(PayWalletTransactionDO.class, o -> { + o.setNo("W001"); + o.setWalletId(wallet.getId()); + o.setBizType(PayWalletBizTypeEnum.PAYMENT.getType()); + o.setPrice(-30); + }); + walletTransactionMapper.insert(payTransaction); + PayRefundDO refund = randomPojo(PayRefundDO.class, o -> o.setNo("R001").setChannelOrderNo("W001") + .setRefundPrice(30).setStatus(PayRefundStatusEnum.WAITING.getStatus())); + refundMapper.insert(refund); + return refund; + } + + /** + * 插入已退款到钱包的退款流水(未增加余额,只用于校验不会重复退款) + */ + private PayWalletTransactionDO insertRefundTransaction(PayRefundDO refund, Integer price) { + PayWalletTransactionDO payTransaction = walletTransactionMapper.selectByNo("W001"); + PayWalletTransactionDO refundTransaction = randomPojo(PayWalletTransactionDO.class, o -> { + o.setWalletId(payTransaction.getWalletId()); + o.setBizType(PayWalletBizTypeEnum.PAYMENT_REFUND.getType()); + o.setBizId(String.valueOf(refund.getId())); + o.setPrice(price); + }); + walletTransactionMapper.insert(refundTransaction); + return refundTransaction; + } + + /** + * mock 退款单、钱包流水的方法:使用数据库的真实查询,校验锁定退款单、查询退款流水的顺序 + */ + private void mockRefundAndWalletTransaction() { + when(refundService.getRefundByNo(any())).thenAnswer(invocation -> + refundMapper.selectByNo(invocation.getArgument(0))); + when(refundService.getRefundForUpdate(any())).thenAnswer(invocation -> + refundMapper.selectOneForUpdate(PayRefundDO::getId, invocation.getArgument(0))); + when(walletTransactionService.getWalletTransactionByNo(any())).thenAnswer(invocation -> + walletTransactionMapper.selectByNo(invocation.getArgument(0))); + when(walletTransactionService.getWalletTransactionForUpdate(any(), any())).thenAnswer(invocation -> + walletTransactionMapper.selectByBizForUpdate(invocation.getArgument(0), + ((PayWalletBizTypeEnum) invocation.getArgument(1)).getType())); + when(walletTransactionService.createWalletTransaction(any())).thenAnswer(invocation -> + createWalletTransaction(invocation.getArgument(0))); + } + + /** + * 等待存在锁等待的数据库会话,基于 H2 的 INFORMATION_SCHEMA.SESSIONS 表的 BLOCKER_ID 字段 + * + * @return 是否存在 + */ + private boolean waitLockWaiting() throws InterruptedException { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + for (int i = 0; i < 500; i++) { + Integer count = jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SESSIONS WHERE BLOCKER_ID IS NOT NULL", Integer.class); + if (count != null && count > 0) { + return true; + } + Thread.sleep(10); + } + return false; + } + + private static void awaitLatch(CountDownLatch latch) { + try { + assertTrue(latch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + private PayWalletTransactionDO createWalletTransaction(WalletTransactionCreateReqBO bo) { + PayWalletTransactionDO transaction = new PayWalletTransactionDO(); + transaction.setNo(randomString()); + transaction.setWalletId(bo.getWalletId()); + transaction.setBizType(bo.getBizType()); + transaction.setBizId(bo.getBizId()); + transaction.setTitle(bo.getTitle()); + transaction.setPrice(bo.getPrice()); + transaction.setBalance(bo.getBalance()); + walletTransactionMapper.insert(transaction); + return transaction; + } + } diff --git a/yudao-module-pay/src/test/resources/sql/clean.sql b/yudao-module-pay/src/test/resources/sql/clean.sql index 41b4d2d..5c7d94f 100644 --- a/yudao-module-pay/src/test/resources/sql/clean.sql +++ b/yudao-module-pay/src/test/resources/sql/clean.sql @@ -5,5 +5,6 @@ DELETE FROM pay_order_extension; DELETE FROM pay_refund; DELETE FROM pay_transfer; DELETE FROM pay_wallet; +DELETE FROM pay_wallet_transaction; DELETE FROM pay_notify_task; DELETE FROM pay_notify_log; diff --git a/yudao-module-pay/src/test/resources/sql/create_tables.sql b/yudao-module-pay/src/test/resources/sql/create_tables.sql index 833e61c..e5a59d8 100644 --- a/yudao-module-pay/src/test/resources/sql/create_tables.sql +++ b/yudao-module-pay/src/test/resources/sql/create_tables.sql @@ -196,3 +196,20 @@ CREATE TABLE IF NOT EXISTS `pay_wallet` ( `deleted` bit(1) NOT NULL DEFAULT FALSE, PRIMARY KEY ("id") ) COMMENT = '会员钱包'; + +CREATE TABLE IF NOT EXISTS `pay_wallet_transaction` ( + "id" number NOT NULL GENERATED BY DEFAULT AS IDENTITY, + `no` varchar(64) NOT NULL, + `wallet_id` bigint(20) NOT NULL, + `biz_type` tinyint(4) NOT NULL, + `biz_id` varchar(64) NOT NULL, + `title` varchar(128) NOT NULL, + `price` int(11) NOT NULL, + `balance` int(11) NOT NULL, + `creator` varchar(64) NULL DEFAULT '', + `create_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP, + `updater` varchar(64) NULL DEFAULT '', + `update_time` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `deleted` bit(1) NOT NULL DEFAULT FALSE, + PRIMARY KEY ("id") +) COMMENT = '会员钱包流水';