This commit is contained in:
lu7213 committed 2026-09-27 19:18:44 -04:00
1 parent 0df6716cc3
commit 009955d560
25 files changed
+417 -63

No files matched your search

@@ -0,0 +1,27 @@
package com.ruoyi.system.service;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;
/** 支付 API 签名:按键排序拼接非空参数后追加 secret,MD5 小写。 */
public final class PaymentSignatureService {
private PaymentSignatureService() { }
public static String sign(Map<String, ?> values, String secret) {
TreeMap<String, Object> sorted = new TreeMap<String, Object>(values);
StringBuilder text = new StringBuilder();
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
if (entry.getValue() != null && !"".equals(String.valueOf(entry.getValue())) && !"signature".equals(entry.getKey())) {
if (text.length() > 0) text.append('&');
text.append(entry.getKey()).append('=').append(entry.getValue());
}
}
text.append(secret);
try {
byte[] digest = MessageDigest.getInstance("MD5").digest(text.toString().getBytes("UTF-8"));
StringBuilder result = new StringBuilder();
for (byte b : digest) result.append(String.format("%02x", b & 0xff));
return result.toString();
} catch (Exception ex) { throw new IllegalStateException("MD5 unavailable", ex); }
}
}
@@ -0,0 +1,39 @@
package com.ruoyi.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.IUsdtOrdersService;
import com.ruoyi.system.service.IAppApiKeysService;
import com.ruoyi.system.service.PaymentSignatureService;
import com.ruoyi.system.domain.AppApiKeysPlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
/** 回调只在对方响应正文严格为 ok 时确认,失败保留未确认状态并重试。 */
@Component
public class PaymentCallbackWorker {
@Autowired private IUsdtOrdersService orders;
@Autowired private IAppApiKeysService keys;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
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;
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));
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, key.getApiSecret()));
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(), new HttpEntity<String>(body, headers), String.class);
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
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) { }
}
}
}
@@ -0,0 +1,28 @@
package com.ruoyi.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.IUsdtOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/** 支付订单生命周期任务:先处理过期订单,链上入账由独立扫描器补充。 */
@Component
public class PaymentOrderMonitor {
@Autowired private IUsdtOrdersService orders;
@Scheduled(fixedDelay = 30000L)
public void expireOrders() {
LambdaQueryWrapper<UsdtOrdersPlus> query = new LambdaQueryWrapper<UsdtOrdersPlus>()
.eq(UsdtOrdersPlus::getStatus, 1)
.isNotNull(UsdtOrdersPlus::getCreatedAt)
.lt(UsdtOrdersPlus::getCreatedAt, new Date(System.currentTimeMillis() - 30 * 60 * 1000L));
for (UsdtOrdersPlus order : orders.list(query)) {
order.setStatus(3L);
order.setUpdatedAt(new Date());
orders.updateById(order);
}
}
}
@@ -109,7 +109,9 @@ public class TronNileServiceImpl implements ITronService {
// 获取转账账户的TRX余额
BigInteger trc20Value = token.balanceOf(fromAddress);
// 获取想要转账的数额
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
// USDT uses six decimal places but is not TRX; convert the business amount directly.
BigInteger sunAmountValue = amount == null ? BigInteger.ZERO
: new BigDecimal(amount).movePointRight(6).toBigIntegerExact();
// 进行比较
if (trc20Value.compareTo(sunAmountValue) >= 0) {
// 设置最大矿工费用
@@ -145,7 +147,7 @@ public class TronNileServiceImpl implements ITronService {
String hashTx = api.broadcastTransaction(signTransaction);
return hashTx;
} catch (Exception e) {
e.printStackTrace();
log.error("TRX transfer failed", e);
}
return "";
}
@@ -182,11 +184,9 @@ public class TronNileServiceImpl implements ITronService {
.setAddress(ByteString.copyFrom(address))
.build();
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
long bandwidth =
(res.getFreeNetLimit() - res.getFreeNetUsed()) +
(res.getNetLimit() - res.getNetUsed());
long energy =
res.getEnergyLimit() - res.getEnergyUsed();
long bandwidth = Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())
+ Math.max(0L, res.getNetLimit() - res.getNetUsed());
long energy = Math.max(0L, res.getEnergyLimit() - res.getEnergyUsed());
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
@@ -513,7 +513,7 @@ public class TronNileServiceImpl implements ITronService {
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
return new BigDecimal(allowanceInToken);
} catch (Exception e) {
e.printStackTrace();
log.error("TRON operation failed", e);
}
return new BigDecimal(0);
}
@@ -0,0 +1,45 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.UsdtOrdersPlus;
import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.IUsdtOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
/** 轮询已确认 TRC20 转账,按地址、六位金额和唯一交易哈希入账。 */
@Component
public class TronPaymentScanner {
@Autowired private IUsdtOrdersService orders;
@Autowired private ITronService tron;
private final RestTemplate http = new RestTemplate();
@Scheduled(fixedDelay = 30000L)
public void scan() {
for (UsdtOrdersPlus order : orders.list(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getStatus, 1))) {
if (order.getToken() == null || order.getActualAmount() == null) continue;
try {
String url = tron.tronscanApiUrl() + "/v1/accounts/" + order.getToken() + "/transactions/trc20?limit=200&only_confirmed=true&contract_address=" + tron.contractAddress();
JSONObject root = JSON.parseObject(http.getForObject(url, String.class)); JSONArray data = root == null ? null : root.getJSONArray("data");
if (data == null) continue;
for (int i = 0; i < data.size(); i++) {
JSONObject tx = data.getJSONObject(i);
if (!order.getToken().equals(tx.getString("to"))) continue;
BigDecimal value = new BigDecimal(tx.getString("value")).movePointLeft(6).setScale(6, RoundingMode.DOWN);
if (value.compareTo(order.getActualAmount().setScale(6, RoundingMode.DOWN)) != 0) continue;
String hash = tx.getString("transaction_id"); if (hash == null || hash.trim().isEmpty()) continue;
if (orders.count(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getBlockTransactionId, hash)) > 0) continue;
order.setBlockTransactionId(hash); order.setStatus(2L); order.setUpdatedAt(new Date()); orders.updateById(order); break;
}
} catch (Exception ignored) { }
}
}
}
@@ -156,7 +156,8 @@ public class TronProServiceImpl implements ITronService {
// 获取转账账户的TRX余额
BigInteger trc20Value = token.balanceOf(fromAddress);
// 获取想要转账的数额
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
BigInteger sunAmountValue = amount == null ? BigInteger.ZERO
: new BigDecimal(amount).movePointRight(6).toBigIntegerExact();
// 进行比较
if (trc20Value.compareTo(sunAmountValue) >= 0) {
// 设置最大矿工费用
@@ -192,7 +193,7 @@ public class TronProServiceImpl implements ITronService {
String hashTx = api.broadcastTransaction(signTransaction);
return hashTx;
} catch (Exception e) {
e.printStackTrace();
log.error("TRX transfer failed", e);
}
return "";
}
@@ -229,11 +230,9 @@ public class TronProServiceImpl implements ITronService {
.setAddress(ByteString.copyFrom(address))
.build();
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
long bandwidth =
(res.getFreeNetLimit() - res.getFreeNetUsed()) +
(res.getNetLimit() - res.getNetUsed());
long energy =
res.getEnergyLimit() - res.getEnergyUsed();
long bandwidth = Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())
+ Math.max(0L, res.getNetLimit() - res.getNetUsed());
long energy = Math.max(0L, res.getEnergyLimit() - res.getEnergyUsed());
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
@@ -591,7 +590,7 @@ public class TronProServiceImpl implements ITronService {
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
return new BigDecimal(allowanceInToken);
} catch (Exception e) {
e.printStackTrace();
log.error("TRON operation failed", e);
}
return new BigDecimal(0);
}
@@ -192,7 +192,8 @@ public class TronShastaServiceImpl implements ITronService {
// 获取转账账户的TRX余额
BigInteger trc20Value = token.balanceOf(fromAddress);
// 获取想要转账的数额
BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger();
BigInteger sunAmountValue = amount == null ? BigInteger.ZERO
: new BigDecimal(amount).movePointRight(6).toBigIntegerExact();
// 进行比较
if (trc20Value.compareTo(sunAmountValue) >= 0) {
// 设置最大矿工费用
@@ -228,7 +229,7 @@ public class TronShastaServiceImpl implements ITronService {
String hashTx = api.broadcastTransaction(signTransaction);
return hashTx;
} catch (Exception e) {
e.printStackTrace();
log.error("TRX transfer failed", e);
}
return "";
}
@@ -265,11 +266,9 @@ public class TronShastaServiceImpl implements ITronService {
.setAddress(ByteString.copyFrom(address))
.build();
GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account);
long bandwidth =
(res.getFreeNetLimit() - res.getFreeNetUsed()) +
(res.getNetLimit() - res.getNetUsed());
long energy =
res.getEnergyLimit() - res.getEnergyUsed();
long bandwidth = Math.max(0L, res.getFreeNetLimit() - res.getFreeNetUsed())
+ Math.max(0L, res.getNetLimit() - res.getNetUsed());
long energy = Math.max(0L, res.getEnergyLimit() - res.getEnergyUsed());
EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo();
energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth));
energyAndBandwidthVo.setEnergy(new BigDecimal(energy));
@@ -544,7 +543,7 @@ public class TronShastaServiceImpl implements ITronService {
double allowanceInToken = allowance.doubleValue() / 1_000_000.0;
return new BigDecimal(allowanceInToken);
} catch (Exception e) {
e.printStackTrace();
log.error("TRON operation failed", e);
}
return new BigDecimal(0);
}
@@ -0,0 +1,53 @@
package com.ruoyi.system.service.impl;
import com.ruoyi.system.domain.UsdtAggregationTask;
import com.ruoyi.system.domain.UsdtAggregationTaskItem;
import com.ruoyi.system.domain.UsdtAggregationTaskPlus;
import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus;
import com.ruoyi.system.domain.WalletAddressPlus;
import com.ruoyi.system.service.ITronService;
import com.ruoyi.system.service.IUsdtAggregationTaskItemService;
import com.ruoyi.system.service.IUsdtAggregationTaskService;
import com.ruoyi.system.service.IWalletAddressService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/** 后台逐地址执行归集任务;每个明细独立失败并继续后续地址。 */
@Component
@EnableScheduling
public class UsdtAggregationExecutor {
@Autowired private IUsdtAggregationTaskService taskService;
@Autowired private IUsdtAggregationTaskItemService itemService;
@Autowired private IWalletAddressService walletService;
@Autowired private ITronService tronService;
@Scheduled(fixedDelay = 30000L)
public void executePending() {
List<UsdtAggregationTaskPlus> tasks = taskService.getListByStatusAndLtExeTime(1, new java.util.Date(System.currentTimeMillis() + 1));
for (UsdtAggregationTaskPlus task : tasks) executeTask(task);
}
private void executeTask(UsdtAggregationTaskPlus task) {
List<UsdtAggregationTaskItemPlus> items = itemService.getListByStatusAndParentId(0, task.getId());
boolean failed = false;
for (UsdtAggregationTaskItemPlus item : items) {
WalletAddressPlus wallet = walletService.getByTokenAndAppId(item.getTokenAddress(), item.getAppId());
if (wallet == null || wallet.getTokenKey() == null) { fail(item, "来源钱包不存在或未配置私钥"); failed = true; continue; }
String tx = null;
Exception last = null;
for (int attempt = 0; attempt < 4 && tx == null; attempt++) {
org.tron.trident.core.ApiWrapper api = null;
try { api = tronService.buildApiWrapper(wallet.getTokenKey()); tx = tronService.usdtTrans(api, wallet.getToken(), item.getDistTokenAddress(), item.getOpeAmount().toPlainString()); }
catch (Exception ex) { last = ex; }
finally { if (api != null) api.close(); }
}
if (tx == null || tx.trim().isEmpty()) { fail(item, "重试耗尽:" + (last == null ? "交易失败" : last.getMessage())); failed = true; }
else { item.setStatus(1L); item.setRemark("交易哈希:" + tx); itemService.updateById(item); }
}
task.setStatus(failed ? 3 : 2); taskService.updateById(task);
}
private void fail(UsdtAggregationTaskItemPlus item, String reason) { item.setStatus(2L); item.setRemark(reason); itemService.updateById(item); }
}
@@ -157,7 +157,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
@Override
public WalletAddressPlus getByTokenAndAppId(String token,Long appId, SFunction<WalletAddressPlus, ?>... columns) {
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
if(null != columns || columns.length > 0){
if(columns != null && columns.length > 0){
lambdaQueryWrapper.select(columns);
}
lambdaQueryWrapper.eq(WalletAddressPlus::getToken, token).eq(WalletAddressPlus::getAppId, appId);
@@ -167,7 +167,7 @@ public class WalletAddressServiceImpl extends ServiceImpl<WalletAddressMapper, W
@Override
public List<WalletAddressPlus> getListByAppId(Long appId, SFunction<WalletAddressPlus, ?>... columns) {
LambdaQueryWrapper<WalletAddressPlus> lambdaQueryWrapper = new LambdaQueryWrapper<WalletAddressPlus>();
if(null != columns || columns.length > 0){
if(columns != null && columns.length > 0){
lambdaQueryWrapper.select(columns);
}
lambdaQueryWrapper.eq(WalletAddressPlus::getAppId, appId);