国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

支付系統設計實現(1)——支付與退款

zhigoo / 2481人閱讀

摘要:支付流程以上是微信支付的流程用戶進入選擇商品進行購買,在內部結算時生成用戶本系統訂單待支付狀態,此時返回訂單信息與支付方式列表用戶確認金額無誤,并選擇支付方式。

支付流程

以上是微信app支付的流程:

用戶進入app選擇商品進行購買,在app內部結算時生成用戶本系統訂單(待支付狀態),此時返回訂單信息與支付方式列表

用戶確認金額無誤,并選擇支付方式。此時app將訂單id與支付方式傳給服務器,服務器根據訂單金額與支付方式在外部支付系統下單(預支付訂單),并給app返回可以喚起響應支付工具的‘支付數據’

app獲取到‘支付數據’調用響應支付sdk,此時用戶會看見微信支付或支付寶支付的頁面,此時用戶需要確認支付金額并輸入正確的密碼

sdk會檢查用戶的密碼信息是否正確并返回支付結果,此時app收到sdk同步通知的支付結果,并提交到服務器,服務器會記錄該筆支付的狀態,切記不能使用app上傳回來的支付結果作為最終的支付結果,不能信任前端數據

外部支付系統在處理完成該筆支付后會回調服務器設置的回調接口,通知服務器該筆支付的最終支付狀態
收到通知時需要注意:

同樣的通知可能會多次發送給商戶系統。商戶系統必須能夠正確處理重復的通知。

后臺通知交互時,如果微信收到商戶的應答不符合規范或超時,微信會判定本次通知失敗,重新發送通知,直到成功為止,但微信不保證通知最終一定能成功。

在訂單狀態不明或者沒有收到微信支付結果通知的情況下,建議商戶主動調用微信支付【查詢訂單API】確認訂單狀態。

商戶系統對于支付結果通知的內容一定要做簽名驗證,并校驗返回的訂單金額是否與商戶側的訂單金額一致,防止數據泄漏導致出現“假通知”,造成資金損失。

當收到通知進行處理時,首先檢查對應業務數據的狀態,判斷該通知是否已經處理過,如果沒有處理過再進行處理,如果處理過直接返回結果成功。在對業務數據進行狀態檢查和處理之前,要采用數據鎖進行并發控制,以避免函數重入造成的數據混亂。

線上問題

以上流程時微信與支付寶給出的官方流程,并且也是最標準的流程。但是當外部支付系統并沒有微信與支付寶那么優秀的時候,我們的系統就不能按照該流程正常運行下去,下面我說說在使用‘建行支付’時遇到的問題

服務器收不到支付結果的回調

即使主動查詢支付狀態‘建行支付’依然返回未支付的狀態

以上兩個問題會引發更復雜的問題

由于沒有支付回調,訂單狀態就不會發送改變用戶就會再次支付,造成重復支付的現象

系統沒有預料到會出現重復支付也就沒有相應的策略去彌補

由于系統并不知道支付已經成功,用戶在取消訂單的時候就不會收到退款

根據這些線上出現的問題,我們決定進行重構,并深層次的處理整個支付流程!

設計思路

1.確認支付方式

1.微信App支付
2.支付寶App支付
3.建行支付App支付

2.如何確保支付成功

1.外部支付系統(支付寶)成功后回調通知
2.本系統主動查詢外部支付系統訂單狀態

3.如何避免用戶重復支付

1.本系統在發起支付的時候檢查‘訂單號’是否有已經成功的支付記錄
2.本系統在發起支付的時候檢查‘訂單號’是否有已經提交的支付記錄,如果有需要同步查詢外部支付系統該訂單的支付狀態

4.如果用戶出現重復支付系統如何處理

1.系統需要定時檢查是否有同一個‘訂單號’出現多條成功支付的記錄,如果有需要保留一筆支付,其余的進行退款處理    

5.數據出現異常怎么辦(例如:用戶說支付完成,但是訂單依然是待支付的狀態)

1.所有的支付流程都需要進行數據記錄,形成支付流水,這樣可以直觀的看到用戶支付的路徑,也方便外部支付系統查詢
具體邏輯

‘支付’是一次支付的記錄,可能包含多個訂單的支付金額,因為用戶在購買商品生成訂單的時候會根據商家拆單

‘支付與訂單的隱射’表明該支付中所有的訂單信息,每個‘映射’都記錄了訂單的金額與支付狀態,并且重復支付也是發生在該‘映射’上的,因為一個訂單智能有一次最終成功支付的記錄,最終哪一個映射是有效的由‘是否當前使用’決定,任何時候一個訂單只有一個映射有效

‘支付’可能有多條退款記錄,退款的總金額不能超過支付金額,并且每一筆退款都需要一個唯一的退款交易號來保證不會重復退款,退款交易號由具體業務系統生成(比如退貨,取消訂單,重復支付)

所有的退款必須成功

系統需要主動查詢支付狀態是‘發起支付’,‘app同步通知成功’記錄在外部支付系統的支付狀態,如果在外部支付系統支付成功,這里需要重新設置支付狀態為‘已完成’

支付的外部交易號與退款的退款交易號都是唯一的

為了保證系統的正常工作我們還需要一些定時器來作為最后的防線

接口實現

1. 支付業務邏輯

public interface IPaymentApplicationService {

/**
 * 創建支付,待支付狀態
 * @param orders 訂單JSONArray
 * @param paymentAmount 支付金額
 * @param paymentChannel 支付渠道
 * @param paymentType 支付方式
 * @param accountId 賬戶
 * @param serviceId 服務
 * @param platformId 平臺
 * @param hockParams 回傳參數
 * @return
 */
PaymentResultDTO createPayment(List orders, BigDecimal paymentAmount, PaymentChannelEnum paymentChannel, PaymentTypeEnum paymentType, String accountId, String serviceId, String platformId,String hockParams) throws InvalidOperationException;

/**
 * app、小程序、H5收到回調
 * @param paymentId 支付id
 * @param isSuccess 是否支付成功
 */
void synchronizedCallback(String paymentId,boolean isSuccess) throws InvalidOperationException, PaymentQueryException, PaymentNotExistException;

/**
 * app、小程序、H5收到回調
 * @param orderIds 本次支付的所有訂單id
 * @param isSuccess 是否成功
 */
void synchronizedCallback(Collection orderIds,boolean isSuccess);

/**
 * 服務器端收到回調
 * @param paymentId 支付id
 * @param isSuccess 是否支付成功
 * @param tradeNo 交易號
 */
void asyncCallback(String paymentId,boolean isSuccess,String tradeNo) throws InvalidOperationException;


/**
 * 服務器端收到回調
 * @param outTradeNo 外部交易號
 * @param isSuccess 是否支付成功
 * @param tradeNo 交易號
 */
void asyncCallbackForOutTradeNo(String outTradeNo,boolean isSuccess,String tradeNo);

}

2.退款業務邏輯

public interface IRefundApplicationService {

/**
 * 發起退款
 * @param paymentId 支付id
 * @param sysRefundTradeNo 系統內部退款單號
 * @param refundAmount 退款金額
 * @param refundType 退款類型
 * @param reason 退款理由
 * @return 退款id
 */
void createRefund(String paymentId,String sysRefundTradeNo, BigDecimal refundAmount, RefundTypeEnum refundType, String reason) throws Exception;

/**
 * 針對訂單發起退款
 * @param orderId 訂單id
 * @param sysRefundTradeNo 系統內部退款單號
 * @param refundAmount 退款金額
 * @param refundType 退款類型
 * @param reason 退款理由
 * @return 退款id
 */
void createRefundByOrder(String orderId,String sysRefundTradeNo, BigDecimal refundAmount, RefundTypeEnum refundType, String reason) throws Exception;

/**
 * 退款
 * @param refund 退款實體
 */
void refund(RefundDO refund) throws InvalidOperationException;

}

附件代碼

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class PaymentApplicationServiceImpl implements IPaymentApplicationService {

private final PaymentConfigJpaRepository paymentConfigJpaRepository;
private final PaymentJpaRepository paymentJpaRepository;
private final PaymentOrderJpaRepository paymentOrderJpaRepository;
private final PaymentFlowJpaRepository paymentFlowJpaRepository;
private final OrderRepository orderJpaRepository;
private final PayUtilRepository payUtilRepository;

@Autowired
public PaymentApplicationServiceImpl(PaymentConfigJpaRepository paymentConfigJpaRepository, PaymentJpaRepository paymentJpaRepository, PaymentOrderJpaRepository paymentOrderJpaRepository, PaymentFlowJpaRepository paymentFlowJpaRepository, OrderRepository orderJpaRepository, PayUtilRepository payUtilRepository) {
    this.paymentConfigJpaRepository = paymentConfigJpaRepository;
    this.paymentJpaRepository = paymentJpaRepository;
    this.paymentOrderJpaRepository = paymentOrderJpaRepository;
    this.paymentFlowJpaRepository = paymentFlowJpaRepository;
    this.orderJpaRepository = orderJpaRepository;
    this.payUtilRepository = payUtilRepository;
}

@Override
public PaymentResultDTO createPayment(List orders, BigDecimal paymentAmount, PaymentChannelEnum paymentChannel, PaymentTypeEnum paymentType, String accountId, String serviceId, String platformId, String hockParams,String wechatOpenId) throws Exception {
    Optional paymentConfigOptional = paymentConfigJpaRepository.findByPaymentChannelAndPaymentType(paymentChannel.getValue(),paymentType.getValue());
    if(!paymentConfigOptional.isPresent()){
        throw new InvalidOperationException("支付方式不存在");
    }
    PaymentConfigDO paymentConfig = paymentConfigOptional.get();
    //成功支付的訂單不能再次支付
    List orderIds = orders.stream().map(PaymentOrderDTO::getOrderId).collect(Collectors.toList());
    List oldPaymentOrders = paymentOrderJpaRepository.findByOrderIdIn(orderIds);
    for (PaymentOrderDO po : oldPaymentOrders) {
        if(po.getPaymentStatus().equals(PaymentStatusEnum.ASYNC_CALLBACK_SUCCEED.getValue())){
            throw new InvalidOperationException("訂單:" + po.getOrderId() + "已成功支付");
        }else if(po.getPaymentStatus().equals(PaymentStatusEnum.SYNCHRONIZE_CALLBACK_SUCCEED.getValue()) ||
                po.getPaymentStatus().equals(PaymentStatusEnum.LAUNCH_PAY.getValue())){
            //可能是重復支付
            po.fundRepeatPay();
            paymentOrderJpaRepository.save(po);
            //主動查詢支付是否成功
            PaymentQueryResult paymentQueryResult;
            paymentQueryResult = getPaymentResult(paymentConfig,po.getOutTradeNo());
            if(paymentQueryResult != null && paymentQueryResult.getTradeStatus().equals(PaymentQueryResult.TradeStatus.SUCCESS)){
                asyncCallback(po.getPaymentId(),true,paymentQueryResult.getTradeNo());
            }
        }
    }
    PaymentDO payment = new PaymentDO(paymentAmount,paymentChannel,paymentType,paymentConfig.getMerchantId(),accountId,serviceId,platformId);
    paymentJpaRepository.save(payment);
    PaymentFlowDO paymentFlow = new PaymentFlowDO(payment.getId(),payment.getOutTradeNo(), PaymentFlowEnum.REQUEST_SIGNATURE, JSONArray.toJSONString(orders));
    paymentFlowJpaRepository.save(paymentFlow);
    List paymentOrders = new ArrayList<>();
    for (PaymentOrderDTO order : orders) {
        String orderId = order.getOrderId();
        if (StringUtils.isBlank(orderId)) {
            throw new InvalidOperationException("orderId必傳");
        }
        PaymentOrderDO paymentOrder = new PaymentOrderDO(payment.getId(), orderId, payment.getOutTradeNo(), order.getOrderAmount(), JSONObject.toJSONString(order));
        paymentOrders.add(paymentOrder);
    }
    paymentOrderJpaRepository.saveAll(paymentOrders);
    String sign = lunchPay(payment,paymentOrders,hockParams,wechatOpenId);
    return new PaymentResultDTO(payment.getId(),sign,hockParams,orderIds);
}

private String lunchPay(PaymentDO payment,List paymentOrders,String hockParams,String wechatOpenId) throws Exception {
    Optional paymentConfigOptional = paymentConfigJpaRepository.findByPaymentChannelAndPaymentType(payment.getPaymentChannel(),payment.getPaymentType());
    if(!paymentConfigOptional.isPresent()){
        throw new InvalidOperationException("支付配置不存在");
    }
    PaymentConfigDO paymentConfig = paymentConfigOptional.get();
    //計算簽名字符串
    String signString;
    PaymentChannelEnum paymentChannel = PaymentChannelEnum.getEnumByVal(paymentConfig.getPaymentChannel());
    switch (paymentChannel){
        case ALIPAY:
            AliPayUtil aliPayUtil = payUtilRepository.getAliPay(payment);
            signString = aliPayUtil.getSignStr(paymentConfig.getOrderNamePrefix() + ":" + payment.getId(),payment.getOutTradeNo(),payment.getPaymentAmount(),hockParams);
            break;
        case WECHATPAY:
            WechatPayUtil wechatPayUtil = payUtilRepository.getWechatPay(payment);
            if(StringUtils.isNotBlank(wechatOpenId)) {
                signString = wechatPayUtil.getJsApiSignStr(paymentConfig.getOrderNamePrefix() + ":" + payment.getId(), payment.getOutTradeNo(), payment.getPaymentAmount(), wechatOpenId, hockParams);
            }else {
                signString = wechatPayUtil.getSignStr(paymentConfig.getOrderNamePrefix() + ":" + payment.getId(), payment.getOutTradeNo(), payment.getPaymentAmount(), hockParams);
            }
            break;
        default:
            throw new InvalidOperationException("支付方式異常");
    }
    payment.lunchPay(signString);
    for (PaymentOrderDO po : paymentOrders) {
        po.lunchPay(signString);
    }
    PaymentFlowDO paymentFlow = new PaymentFlowDO(payment.getId(),payment.getOutTradeNo(), PaymentFlowEnum.RECEIVE_SIGNATURE,signString);

    paymentJpaRepository.save(payment);
    paymentOrderJpaRepository.saveAll(paymentOrders);
    paymentFlowJpaRepository.save(paymentFlow);

    return signString;
}

@Override
public void synchronizedCallback(String paymentId, boolean isSuccess) throws InvalidOperationException {
    Optional paymentOptional = paymentJpaRepository.findById(paymentId);
    if(!paymentOptional.isPresent()){
        throw new InvalidOperationException("支付不存在");
    }
    PaymentDO payment = paymentOptional.get();
    payment.synchronizedCallback(isSuccess);
    List paymentOrders = paymentOrderJpaRepository.findByPaymentId(paymentId);
    for (PaymentOrderDO po : paymentOrders) {
        po.synchronizedCallback(isSuccess);
    }
    PaymentFlowDO paymentFlow = new PaymentFlowDO(payment.getId(),payment.getOutTradeNo(), PaymentFlowEnum.SYNCHRONIZE_CALLBACK,isSuccess + "");
    //主動查詢訂單在第三方支付的狀態,確保就算沒有收到異步回調,支付狀態依然正確
    Optional paymentConfigOptional = paymentConfigJpaRepository.findByPaymentChannelAndPaymentType(payment.getPaymentChannel(),payment.getPaymentType());
    if(!paymentConfigOptional.isPresent()){
        throw new InvalidOperationException("支付方式不存在");
    }
    PaymentConfigDO paymentConfig = paymentConfigOptional.get();
    PaymentQueryResult paymentQueryResult = getPaymentResult(paymentConfig,payment.getOutTradeNo());

    if(paymentQueryResult != null && paymentQueryResult.getTradeStatus().equals(PaymentQueryResult.TradeStatus.SUCCESS)){
        asyncCallback(paymentId,true,paymentQueryResult.getTradeNo());
    }
    paymentJpaRepository.save(payment);
    paymentOrderJpaRepository.saveAll(paymentOrders);
    paymentFlowJpaRepository.save(paymentFlow);
}

@Override
public void synchronizedCallback(Collection orderIds, boolean isSuccess) {
    List paymentOrders = paymentOrderJpaRepository.findByOrderIdInAndPaymentStatus(orderIds,PaymentStatusEnum.LAUNCH_PAY.getValue());
    Set paymentIds = paymentOrders.stream().map(PaymentOrderDO::getPaymentId).collect(Collectors.toSet());
    for (String pId : paymentIds) {
        try {
            synchronizedCallback(pId,true);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("支付同步通知異常:" + pId + ":" + e.getMessage());
        }
    }
}

@Override
public void asyncCallback(String paymentId, boolean isSuccess, String tradeNo) throws InvalidOperationException {
    Optional paymentOptional = paymentJpaRepository.findById(paymentId);
    if(!paymentOptional.isPresent()){
        throw new InvalidOperationException("支付不存在");
    }
    PaymentDO payment = paymentOptional.get();
    if(payment.getPaymentStatus().equals(PaymentStatusEnum.ASYNC_CALLBACK_SUCCEED.getValue())){
        return;
    }
    List paymentOrders = paymentOrderJpaRepository.findByPaymentId(paymentId);
    List orderIds = paymentOrders.stream().map(PaymentOrderDO::getOrderId).collect(Collectors.toList());
    //這些訂單的其他支付:設置為重復
    List oldOtherPaymentOrders = paymentOrderJpaRepository.
            findByOrderIdIn(orderIds).stream().
            filter(po -> !po.getPaymentId().equalsIgnoreCase(paymentId)).
            collect(Collectors.toList());
    if(!CollectionUtils.isEmpty(oldOtherPaymentOrders)){
        for (PaymentOrderDO opo : oldOtherPaymentOrders) {
            if(opo.getPaymentStatus().equals(PaymentStatusEnum.ASYNC_CALLBACK_SUCCEED.getValue()) ||
                    opo.getPaymentStatus().equals(PaymentStatusEnum.SYNCHRONIZE_CALLBACK_SUCCEED.getValue()) ||
                    opo.getPaymentStatus().equals(PaymentStatusEnum.LAUNCH_PAY.getValue())) {
                opo.fundRepeatPay();
            }
        }
        paymentOrderJpaRepository.saveAll(oldOtherPaymentOrders);
    }
    payment.asyncCallback(isSuccess,tradeNo);
    for (PaymentOrderDO po : paymentOrders) {
        po.asyncCallback(isSuccess);
        if(isSuccess){
            //todo 需要考慮通知業務系統
            Optional orderOptional = orderJpaRepository.findById(po.getOrderId());
            if(orderOptional.isPresent()) {
                OrderDO order = orderOptional.get();
                order.paymentSucceed();
                orderJpaRepository.save(order);
            }
        }
    }
    PaymentFlowDO paymentFlow = new PaymentFlowDO(payment.getId(),payment.getOutTradeNo(), PaymentFlowEnum.ASYNC_CALLBACK,isSuccess + "");
    paymentJpaRepository.save(payment);
    paymentFlowJpaRepository.save(paymentFlow);
}

@Override
public void asyncCallbackForOutTradeNo(String outTradeNo, boolean isSuccess, String tradeNo) {
    Optional paymentOptional = paymentJpaRepository.findByOutTradeNo(outTradeNo);
    if(paymentOptional.isPresent()){
        PaymentDO payment = paymentOptional.get();
        try{
            asyncCallback(payment.getId(),true,tradeNo);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("支付異步通知異常:" + payment.getId() + ":" + e.getMessage());
        }
    }
}

private PaymentQueryResult getPaymentResult(PaymentConfigDO paymentConfig,String outTradeNo) {
    Optional paymentOptional = paymentJpaRepository.findByOutTradeNo(outTradeNo);
    if(!paymentOptional.isPresent()){
        return null;
    }
    PaymentDO payment = paymentOptional.get();
    PaymentQueryResult paymentQueryResult;
    PaymentChannelEnum paymentChannel = PaymentChannelEnum.getEnumByVal(paymentConfig.getPaymentChannel());
    try{
        switch (paymentChannel){
            case ALIPAY:
                AliPayUtil aliPayUtil = payUtilRepository.getAliPay(payment);
                paymentQueryResult = aliPayUtil.paymentQuery(outTradeNo);
                break;
            case WECHATPAY:
                WechatPayUtil wechatPayUtil = payUtilRepository.getWechatPay(payment);
                paymentQueryResult = wechatPayUtil.paymentQuery(outTradeNo);
                break;
            default:
                throw new InvalidOperationException("支付方式異常");
        }
        return paymentQueryResult;
    }catch (Exception e){
        log.error(e.getMessage());
        return null;
    }
}

}

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class RefundApplicationServiceImpl implements IRefundApplicationService {

private final RefundJpaRepository refundJpaRepository;
private final RefundFlowJpaRepository refundFlowJpaRepository;
private final PaymentJpaRepository paymentJpaRepository;
private final PaymentOrderJpaRepository paymentOrderJpaRepository;

private final WechatPayUtil wechatPayUtil;
private final AliPayUtil aliPayUtil;
private final CcbPayUtil ccbPayUtil;

@Autowired
public RefundApplicationServiceImpl(RefundJpaRepository refundJpaRepository, RefundFlowJpaRepository refundFlowJpaRepository, PaymentJpaRepository paymentJpaRepository, PaymentOrderJpaRepository paymentOrderJpaRepository, WechatPayUtil wechatPayUtil, AliPayUtil aliPayUtil, CcbPayUtil ccbPayUtil) {
    this.refundJpaRepository = refundJpaRepository;
    this.refundFlowJpaRepository = refundFlowJpaRepository;
    this.paymentJpaRepository = paymentJpaRepository;
    this.paymentOrderJpaRepository = paymentOrderJpaRepository;
    this.wechatPayUtil = wechatPayUtil;
    this.aliPayUtil = aliPayUtil;
    this.ccbPayUtil = ccbPayUtil;
}

@Override
public void createRefund(String paymentId,String sysRefundTradeNo, BigDecimal refundAmount, RefundTypeEnum refundType, String reason) throws Exception {
    Optional paymentOptional = paymentJpaRepository.findById(paymentId);
    if(!paymentOptional.isPresent()){
        throw new InvalidOperationException("支付不存在,不可退款");
    }
    PaymentDO payment = paymentOptional.get();
    //檢查支付是否完成,未完成就不可退款
    PaymentChannelEnum paymentChannel = PaymentChannelEnum.getEnumByVal(payment.getPaymentChannel());
    PaymentQueryResult paymentQueryResult = getPaymentResult(paymentChannel,payment.getOutTradeNo());
    log.info("pay query : {}",paymentQueryResult);
    if(paymentQueryResult == null ||
        paymentQueryResult.getTradeStatus().equals(PaymentQueryResult.TradeStatus.FAILED) ||
        paymentQueryResult.getTradeStatus().equals(PaymentQueryResult.TradeStatus.CLOSED) ||
        paymentQueryResult.getTradeStatus().equals(PaymentQueryResult.TradeStatus.PAYING)){
        throw new InvalidOperationException("支付狀態異常,不可退款");
    }

    List refundStatus = Arrays.asList(RefundStatusEnum.START.getValue(),RefundStatusEnum.SUCCESS.getValue(),RefundStatusEnum.FAIL.getValue());
    List oldRefunds = refundJpaRepository.findByPaymentIdAndRefundStatusIn(paymentId,refundStatus);
    BigDecimal oldRefundsAmount = oldRefunds.stream().map(RefundDO::getRefundAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
    if(oldRefundsAmount.add(refundAmount).compareTo(payment.getPaymentAmount()) > 0){
        throw new InvalidOperationException("退款總金額不可超過支付金額");
    }
    RefundDO refund;
    Optional refundOptional = refundJpaRepository.findBySysRefundTradeNo(sysRefundTradeNo);
    if(refundOptional.isPresent()){
        RefundDO oldRefund = refundOptional.get();
        if(oldRefund.getRefundStatus().equals(RefundStatusEnum.SUCCESS.getValue())){
            throw new InvalidOperationException("退款已完成");
        }else if(oldRefund.getRefundStatus().equals(RefundStatusEnum.START.getValue())){
            throw new InvalidOperationException("退款處理中");
        }
    }else {
        refund = new RefundDO(paymentId,payment.getOutTradeNo(),sysRefundTradeNo,refundAmount, refundType,reason,payment.getPaymentChannel(), payment.getPaymentType(),payment.getPaymentAmount());
        refundJpaRepository.save(refund);
    }
}

@Override
public void createRefundByOrder(String orderId, String sysRefundTradeNo, BigDecimal refundAmount, RefundTypeEnum refundType, String reason) throws Exception {
    Optional paymentOrderOptional = paymentOrderJpaRepository.findByOrderIdAndIsCurrent(orderId,true);
    if(paymentOrderOptional.isPresent()){
        PaymentOrderDO paymentOrder = paymentOrderOptional.get();
        createRefund(paymentOrder.getPaymentId(),sysRefundTradeNo,refundAmount,refundType,reason);
        paymentOrderJpaRepository.save(paymentOrder);
    }
}

@Override
public void refund(RefundDO refund) throws InvalidOperationException {
    PaymentChannelEnum paymentChannel = PaymentChannelEnum.getEnumByVal(refund.getPaymentChannel());
    RefundTypeEnum refundType = RefundTypeEnum.getEnumByVal(refund.getRefundType());
    String respData;
    try {
        switch (paymentChannel){
            case ALIPAY:
                respData = aliPayUtil.orderPayRefund(refund.getOutTradeNo(),refund.getOutRefundTradeNo(),refund.getPaymentAmount(),refund.getRefundAmount(),refundType);
                break;
            case WECHATPAY:
                respData = wechatPayUtil.orderPayRefund(refund.getOutTradeNo(),refund.getOutRefundTradeNo(),refund.getPaymentAmount(),refund.getRefundAmount(),refundType);
                break;
            case CCBPAY:
                respData = ccbPayUtil.orderPayRefund(refund.getOutTradeNo(),refund.getOutRefundTradeNo(),refund.getPaymentAmount(),refund.getRefundAmount(),refundType);
                break;
            default:
                throw new InvalidOperationException("支付方式異常");
        }
        refundSuccess(refund,respData);
    }catch (Exception e){
        refundFail(refund,e.getMessage());
    }
}

private void refundSuccess(RefundDO refund,String respData) throws InvalidOperationException {
    refund.asyncCallback(true);
    refundJpaRepository.save(refund);
    RefundFlowDO refundSyncFlow = new RefundFlowDO(refund.getId(), RefundFlowEnum.SYNCHRONIZE_CALLBACK_SUCCESS,respData);
    refundFlowJpaRepository.save(refundSyncFlow);
}
private void refundFail(RefundDO refund,String errorMessage) throws InvalidOperationException{
    refund.asyncCallback(false);
    refundJpaRepository.save(refund);
    RefundFlowDO refundSyncFlow = new RefundFlowDO(refund.getId(), RefundFlowEnum.SYNCHRONIZE_CALLBACK_FAIL,errorMessage);
    refundFlowJpaRepository.save(refundSyncFlow);
}

private PaymentQueryResult getPaymentResult(PaymentChannelEnum paymentChannel,String outTradeNo) {
    try {
        switch (paymentChannel){
            case ALIPAY:
                return aliPayUtil.paymentQuery(outTradeNo);
            case WECHATPAY:
                return wechatPayUtil.paymentQuery(outTradeNo);
            case CCBPAY:
                return ccbPayUtil.paymentQuery(outTradeNo);
            default:
                return null;
        }
    }catch (Exception e){
        log.error(e.getMessage());
        return null;
    }
}

}

@Component
@Slf4j
@DisallowConcurrentExecution
public class CheckPaymentCloseSchedule extends QuartzJobBean {

@Autowired
private PaymentJpaRepository paymentJpaRepository;
@Autowired
private IPaymentQueryService paymentQueryService;

@Override
public void executeInternal(JobExecutionContext context) throws JobExecutionException {
    log.info("檢查關閉支付定時器啟動");
    List payments = paymentJpaRepository.findByPaymentStatus(PaymentStatusEnum.LAUNCH_PAY.getValue());
    LocalDateTime now = LocalDateTime.now();
    List closePayments = new ArrayList<>();
    for (PaymentDO p : payments) {
        long minutes = 10L;
        if(!now.minusMinutes(minutes).isBefore(p.getLaunchPayTime())){
            //超過十分鐘沒有支付,就進行關閉
            try {
                PaymentQueryResult result = paymentQueryService.getPaymentResult(p.getId());
                if(result == null){
                    p.close();
                    closePayments.add(p);
                    if(closePayments.size() > 100){
                        paymentJpaRepository.saveAll(closePayments);
                        closePayments.clear();
                        p = null;
                    }
                }
            } catch (Exception e) {
                log.error("關閉支付異常:" + p.getId() + ":" + e.getMessage());
            }
        }
    }
    paymentJpaRepository.saveAll(closePayments);
}

}

@Component
@Slf4j
@DisallowConcurrentExecution
public class CheckPaymentRepeatSchedule extends QuartzJobBean {

@Autowired
private PaymentOrderJpaRepository paymentOrderJpaRepository;
@Autowired
private IRefundApplicationService refundApplicationService;

@Override
public void executeInternal(JobExecutionContext context)throws JobExecutionException {
    log.info("檢查重復支付定時器啟動");
    //找到尚未處理的重復支付記錄
    List paymentOrders = paymentOrderJpaRepository.findByPaymentStatusAndIsCurrentAndRepeatPayProcess(PaymentStatusEnum.ASYNC_CALLBACK_SUCCEED.getValue(),false,false);
    paymentOrders.forEach(po -> {
        try {
            refundApplicationService.createRefund(po.getPaymentId(), ObjectId.get().toString(),po.getPaymentAmount(), RefundTypeEnum.REPEAT_PAY,RefundTypeEnum.REPEAT_PAY.getDescription());
            po.refundRepeatPay();
            paymentOrderJpaRepository.save(po);
        } catch (Exception e) {
            log.error("支付訂單:" + po.getId() + ":重復支付退款異常:" + e.getMessage());
        }
    });
}

}

@Component
@Slf4j
@DisallowConcurrentExecution
public class CheckPaymentSuccessSchedule extends QuartzJobBean {

@Autowired
private PaymentJpaRepository paymentJpaRepository;
@Autowired
private PaymentFlowJpaRepository paymentFlowJpaRepository;
@Autowired
private IPaymentApplicationService paymentApplicationService;
@Autowired
private IPaymentQueryService paymentQuery;

@Override
public void executeInternal(JobExecutionContext context) throws JobExecutionException {
    log.info("檢查支付成功定時器啟動");
    List payments = paymentJpaRepository.findByPaymentStatusIn(Arrays.asList(PaymentStatusEnum.LAUNCH_PAY.getValue(),PaymentStatusEnum.SYNCHRONIZE_CALLBACK_SUCCEED.getValue()));
    for (PaymentDO p : payments) {
        PaymentQueryResult result = paymentQuery.getPaymentResult(p.getId());
        PaymentFlowDO paymentFlow;
        if(result != null) {
            paymentFlow = new PaymentFlowDO(p.getId(), p.getOutTradeNo(), PaymentFlowEnum.RECEIVE_PAYMENT_DETAIL, JSONObject.toJSONString(result));
        }else {
            if(p.getPaymentStatus().equals(PaymentStatusEnum.SYNCHRONIZE_CALLBACK_SUCCEED.getValue())) {
                String error = "支付:" + p.getId() + "app同步通知成功,但是第三方支付查詢:未支付!";
                log.error(error);
                p.close();
                paymentJpaRepository.save(p);
                paymentFlow = new PaymentFlowDO(p.getId(), p.getOutTradeNo(), PaymentFlowEnum.RECEIVE_PAYMENT_DETAIL, error);
            }else {
                paymentFlow = new PaymentFlowDO(p.getId(), p.getOutTradeNo(), PaymentFlowEnum.RECEIVE_PAYMENT_DETAIL, "未支付");
            }
        }
        paymentFlowJpaRepository.save(paymentFlow);
        if(result != null){
            if(result.getTradeStatus().equals(PaymentQueryResult.TradeStatus.PAYING) ||
               result.getTradeStatus().equals(PaymentQueryResult.TradeStatus.SUCCESS)){
                //第三方支付成功,直接修改支付狀態
                try {
                    paymentApplicationService.asyncCallback(p.getId(),true,result.getTradeNo());
                    PaymentFlowDO successPaymentFlow = new PaymentFlowDO(p.getId(),p.getOutTradeNo(), PaymentFlowEnum.ASYNC_CALLBACK_SUCCESS, JSONObject.toJSONString(result));
                    paymentFlowJpaRepository.save(successPaymentFlow);
                } catch (InvalidOperationException e) {
                    log.error("支付:" + p.getId() + "第三方交易成功,本地修改異常:" + e.getMessage());
                }
            }else if(result.getTradeStatus().equals(PaymentQueryResult.TradeStatus.FAILED)){
                try {
                    paymentApplicationService.asyncCallback(p.getId(),false,"");
                    PaymentFlowDO failPaymentFlow = new PaymentFlowDO(p.getId(),p.getOutTradeNo(), PaymentFlowEnum.ASYNC_CALLBACK_FAILED, JSONObject.toJSONString(result));
                    paymentFlowJpaRepository.save(failPaymentFlow);
                } catch (InvalidOperationException e) {
                    log.error("支付:" + p.getId() + "第三方交易失敗,本地修改異常:" + e.getMessage());
                }
            }
        }
    }
}

}

@Component
@Slf4j
@DisallowConcurrentExecution
public class CheckRefundSuccessSchedule extends QuartzJobBean {

@Autowired
private RefundJpaRepository refundJpaRepository;
@Autowired
private IRefundApplicationService refundApplicationService;

@Override
public void executeInternal(JobExecutionContext context) {
    log.info("檢查退款成功定時器啟動");
    List refunds = refundJpaRepository.findByRefundStatusIn(Arrays.asList(RefundStatusEnum.FAIL.getValue(),RefundStatusEnum.START.getValue()));
    for (RefundDO r : refunds) {
        try {
            refundApplicationService.refund(r);
        } catch (InvalidOperationException e) {
            log.error("退款失敗:" + r.getId() + ":" + e.getMessage());
        }
    }
}

}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/74326.html

相關文章

  • 資損防控體系介紹

    摘要:建立后臺觸發熔斷操作入口,人工錄入熔斷配置或資損防控檢測出異常新增并生效熔斷配置,應急情況生效熔斷,日常支付鏈路不會過熔斷判斷。確認無誤或故障處理完成后,觸發解熔斷操作,業務繼續處理或駁回。 1. 資損盲區 隨著有贊支付體量的增大,資產部門承擔的資金管理,風險把控的責任也越大。我們一方面要小步快跑,快速支撐業務,又要穩住底盤,守好底線。支付業務底線就是守護用戶的每一分錢,不能有資金損失...

    shixinzhang 評論0 收藏0
  • 馬蜂窩火車票系統服務化改造初探

    摘要:為了幫助用戶更好地完成消費決策閉環,馬蜂窩上線了大交通業務。現在,用戶在馬蜂窩也可以完成購買機票火車票等操作。第二階段架構轉變及服務化初探從年開始,整個大交通業務開始從架構向服務化演變。 交通方式是用戶旅行前要考慮的核心要素之一。為了幫助用戶更好地完成消費決策閉環,馬蜂窩上線了大交通業務。現在,用戶在馬蜂窩也可以完成購買機票、火車票等操作。 與大多數業務系統相同,我們一樣經歷著從無到有...

    Raaabbit 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<