fix: verify payment callbacks

This commit is contained in:
lu7213 committed 2026-10-15 04:06:20 -04:00
1 parent 6d868552eb
commit a75869342c
3 files changed
+229 -21

No files matched your search

@@ -12,34 +12,72 @@ import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
/** 回调只在对方响应正文严格为 ok 时确认,失败保留未确认状态并重试。 */
@Component
public class PaymentCallbackWorker {
private static final Logger LOGGER = LoggerFactory.getLogger(PaymentCallbackWorker.class);
@Autowired private IUsdtOrdersService orders;
@Autowired private IAppApiKeysService keys;
@Autowired private AppPrivateKeyCipher privateKeyCipher;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
private final RestTemplate http;
public PaymentCallbackWorker() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(60000);
factory.setReadTimeout(60000);
this.http = new RestTemplate(factory);
}
@Scheduled(fixedDelay = 10000L)
public void dispatch() {
for (UsdtOrdersPlus order : orders.list(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getStatus, 2).eq(UsdtOrdersPlus::getCallbackConfirm, 2).lt(UsdtOrdersPlus::getCallbackNum, 10))) {
try {
if (order.getNotifyUrl() == null || order.getNotifyUrl().trim().isEmpty()) continue;
if (order.getNotifyUrl() == null || order.getNotifyUrl().trim().isEmpty()) {
// 兼容历史无通知地址订单,避免定时任务永久重复扫描。
order.setCallbackConfirm(1L);
continue;
}
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
String body = "{\"order_id\":\"" + order.getOrderId() + "\",\"trade_id\":\"" + order.getTradeId() + "\",\"status\":" + order.getStatus() + ",\"transaction_id\":\"" + (order.getBlockTransactionId() == null ? "" : order.getBlockTransactionId()) + "\"}";
AppApiKeysPlus key = keys.getOne(new LambdaQueryWrapper<AppApiKeysPlus>().eq(AppApiKeysPlus::getAppId, order.getAppId())
.eq(AppApiKeysPlus::getStatus, 1).isNull(AppApiKeysPlus::getDeletedAt)
.and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date()))
.last("limit 1"));
java.util.Map<String, Object> signatureValues = new java.util.HashMap<String, Object>(); signatureValues.put("order_id", order.getOrderId()); signatureValues.put("trade_id", order.getTradeId()); signatureValues.put("status", order.getStatus()); signatureValues.put("transaction_id", order.getBlockTransactionId());
headers.set("X-Payment-Signature", key == null ? "" : PaymentSignatureService.sign(signatureValues, privateKeyCipher.decryptCredentialSecret(key.getApiSecret())));
headers.set("X-Payment-Api-Key", key == null ? "" : key.getApiKey());
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(), new HttpEntity<String>(body, headers), String.class);
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
if (key == null || key.getApiKey() == null || key.getApiSecret() == null) {
throw new IllegalStateException("订单所属应用没有有效回调密钥");
}
Map<String, Object> signatureValues = new HashMap<String, Object>();
signatureValues.put("order_id", order.getOrderId());
signatureValues.put("trade_id", order.getTradeId());
signatureValues.put("status", order.getStatus());
signatureValues.put("transaction_id", order.getBlockTransactionId());
headers.set("X-Payment-Signature", PaymentSignatureService.sign(signatureValues,
privateKeyCipher.decryptCredentialSecret(key.getApiSecret())));
headers.set("X-Payment-Api-Key", key.getApiKey());
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(),
new HttpEntity<String>(JSON.toJSONString(signatureValues), headers), String.class);
if (response.getStatusCode().is2xxSuccessful() && "ok".equalsIgnoreCase(response.getBody() == null ? "" : response.getBody().trim())) order.setCallbackConfirm(1L);
order.setUpdatedAt(new Date()); orders.updateById(order);
} catch (Exception ignored) { }
} catch (Exception exception) {
LOGGER.warn("订单支付回调失败,orderId={},异常类型={}", order.getOrderId(),
exception.getClass().getSimpleName());
} finally {
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
order.setUpdatedAt(new Date());
try {
orders.updateById(order);
} catch (Exception exception) {
// 单条订单状态落库失败不能阻塞同批次其他订单,下一轮仍会重新读取数据库状态。
LOGGER.error("订单支付回调状态更新失败,orderId={},异常类型={}", order.getOrderId(),
exception.getClass().getSimpleName());
}
}
}
}
}