package com.ghy.web.timer; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.ghy.common.adapay.model.AdapayStatusEnum; import com.ghy.order.service.OrderDetailService; import com.ghy.payment.domain.DrawCashRecord; import com.ghy.payment.mapper.DrawCashRecordMapper; import com.ghy.payment.service.AdapayService; import com.huifu.adapay.core.exception.BaseAdaPayException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.Date; import java.util.List; /** * 定时器 * 主动与Adapay同步支付、撤销支付、提现订单的状态 */ @Slf4j @Component @EnableScheduling public class AdapaySyncTimer { @Resource private AdapayService adapayService; @Resource private OrderDetailService orderDetailService; @Resource private DrawCashRecordMapper drawCashRecordMapper; @Scheduled(fixedRate = 5 * 60 * 1000L) public void syncDrawCash() { List records = drawCashRecordMapper.selectByStatus("pending"); if (CollectionUtils.isEmpty(records)) { log.debug("No pending drawCashRecord."); return; } for (DrawCashRecord record : records) { Long deptId = record.getDept_id(); String orderNo = record.getOrder_no(); if (deptId == null || StringUtils.isBlank(orderNo)) { continue; } try { syncDrawCashRecord(record, deptId, orderNo); } catch (Exception e) { log.error(e.getMessage(), e); } } } @Transactional(rollbackFor = Exception.class) public void syncDrawCashRecord(DrawCashRecord record, Long deptId, String orderNo) throws BaseAdaPayException { JSONObject response = adapayService.queryDrawCash(deptId, orderNo); // 这个status代表API调用状态 不代表提现状态 if (AdapayStatusEnum.succeeded.code.equals(response.getString("status"))) { JSONArray cashList = response.getJSONArray("cash_list"); if (!CollectionUtils.isEmpty(cashList)) { JSONObject cash = cashList.getJSONObject(0); // 这个才是提现状态 String transStat = cash.getString("trans_stat"); switch (transStat) { // 提现成功 case "S": log.info("DrawCashRecord[{}]提现成功", record.getId()); // 更新提现记录表状态 drawCashRecordMapper.updateStatus(record.getId(), "succeeded"); // 更新子订单表状态 orderDetailService.updateDrawCashStatus(record.getId(), 2, new Date()); break; // 提现失败 case "F": log.error("DrawCashRecord[{}]提现失败: {}", record.getId(), response.toJSONString()); // 更新提现记录表状态 drawCashRecordMapper.updateStatus(record.getId(), "failed"); // 更新子订单表状态 orderDetailService.updateDrawCashStatus(record.getId(), -1, null); break; default: break; } } } else { log.error("DrawCash.query请求失败: {}", response.toJSONString()); } } }