apps_balance_ledger.payout_order_id 已补充实体、Mapper、查询条件、流水写入及前端展示。
实现代付创建、余额冻结、后台/Telegram 审核、配置密码广播、链上确认。 链上成功后原子更新冻结余额,并幂等写入 PAYOUT_SUCCESS、PAYOUT_FEE 流水。 支持执行失败重新输入密码重试,并防止并发重复广播。 查询成功订单返回 RSA 签名 redirect_url,异步通知主动 POST,支持多实例防重复领取。 新增管理员代付页面,支持分页查询、审核、广播、失败重试和详情查看。 SysUsdtDemoController 已包含代付创建、查询、回调及跳转验签示例。 新增 [usdt_payout_order.sql](D:/myprojects/usdt/myEpusdt/sql/usdt_payout_order.sql) 和 [usdt_payout_menu.sql](D:/myprojects/usdt/myEpusdt/sql/usdt_payout_menu.sql)。
This commit is contained in:
1 parent
9c879c1312
commit
d81820c74f
17 files changed
+348
-11
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
package com.ruoyi.task;
|
||||||
|
import com.ruoyi.system.service.PayoutProcessingService;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
/** 定时确认已广播代付交易,链上成功后执行最终结算。 */
|
||||||
|
@Component public class PayoutConfirmationTask {private final PayoutProcessingService service;public PayoutConfirmationTask(PayoutProcessingService service){this.service=service;}@Scheduled(fixedDelay=30000L)public void confirm(){service.confirmPending();}}
|
||||||
@@ -49,6 +49,10 @@ public class SysUsdtDemoController {
|
|||||||
"http://192.168.3.103:2020/api/v1/order/create-transaction";
|
"http://192.168.3.103:2020/api/v1/order/create-transaction";
|
||||||
private static final String DEFAULT_QUERY_API_URL =
|
private static final String DEFAULT_QUERY_API_URL =
|
||||||
"http://192.168.3.103:2020/api/v1/order/query";
|
"http://192.168.3.103:2020/api/v1/order/query";
|
||||||
|
private static final String DEFAULT_PAYOUT_API_URL =
|
||||||
|
"http://192.168.3.103:2020/api/v1/payout/create";
|
||||||
|
private static final String DEFAULT_PAYOUT_QUERY_API_URL =
|
||||||
|
"http://192.168.3.103:2020/api/v1/payout/query";
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
|
|
||||||
public SysUsdtDemoController() {
|
public SysUsdtDemoController() {
|
||||||
@@ -156,6 +160,37 @@ public class SysUsdtDemoController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** RSA-AES-HMAC代付创建客户端示例,不依赖浏览器上下文。 */
|
||||||
|
@PostMapping("/payout")
|
||||||
|
public AjaxResult payout(@RequestParam String orderId,@RequestParam String currency,
|
||||||
|
@RequestParam String amount,@RequestParam String toAddress,
|
||||||
|
@RequestParam String notifyUrl,@RequestParam(required=false) String redirectUrl) {
|
||||||
|
Map<String,Object> p=new HashMap<String,Object>();p.put("order_id",orderId);p.put("currency",currency);
|
||||||
|
p.put("amount",amount);p.put("to_address",toAddress);p.put("notify_url",notifyUrl);p.put("redirect_url",redirectUrl);
|
||||||
|
try{return AjaxResult.success(sendEncryptedRequest(optionalEnv("PAYOUT_API_URL",DEFAULT_PAYOUT_API_URL),p,"创建代付订单失败"));}
|
||||||
|
catch(Exception e){throw e instanceof CustomException?(CustomException)e:new CustomException("创建代付订单失败");}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 代付查询示例;完成后响应中的redirect_url由商户前端自行跳转。 */
|
||||||
|
@PostMapping("/payout-status")
|
||||||
|
public AjaxResult payoutStatus(@RequestParam String orderId) {
|
||||||
|
Map<String,Object> p=new HashMap<String,Object>();p.put("order_id",orderId);
|
||||||
|
try{return AjaxResult.success(sendEncryptedRequest(optionalEnv("PAYOUT_QUERY_API_URL",DEFAULT_PAYOUT_QUERY_API_URL),p,"查询代付订单失败"));}
|
||||||
|
catch(Exception e){throw e instanceof CustomException?(CustomException)e:new CustomException("查询代付订单失败");}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/payout-notify") @ResponseBody
|
||||||
|
public ResponseEntity<String> payoutNotify(@RequestHeader(value="X-Payment-Api-Key",required=false)String apiKey,
|
||||||
|
@RequestHeader(value="X-Payment-Rsa-Signature",required=false)String signature,@RequestBody(required=false)String body){
|
||||||
|
try{JSONObject p=JSON.parseObject(body);if(p==null||!"3".equals(p.getString("status"))||!verifyCallback(p,apiKey,signature))return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("invalid signature");return ResponseEntity.ok("ok");}
|
||||||
|
catch(Exception e){return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("invalid signature");}}
|
||||||
|
|
||||||
|
@GetMapping("/payout-redirect") @ResponseBody
|
||||||
|
public ResponseEntity<String> payoutRedirect(@RequestParam Map<String,String> parameters){
|
||||||
|
String signature=parameters.remove("signature");parameters.remove("api_key");
|
||||||
|
if(!"3".equals(parameters.get("status"))||!verifyCallback(parameters,null,signature))return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("invalid signature");
|
||||||
|
return ResponseEntity.ok("payout redirect SUCCESS");}
|
||||||
|
|
||||||
private Object sendEncryptedRequest(String apiUrl, Map<String, Object> params,
|
private Object sendEncryptedRequest(String apiUrl, Map<String, Object> params,
|
||||||
String failureMessage) throws Exception {
|
String failureMessage) throws Exception {
|
||||||
String apiKey = requiredEnvWithAlias("PAYMENT_API_KEY", "PAYMENT_API_KEK");
|
String apiKey = requiredEnvWithAlias("PAYMENT_API_KEY", "PAYMENT_API_KEK");
|
||||||
|
|||||||
@@ -140,6 +140,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
.antMatchers("/system/config/setVerifyStatus").permitAll()
|
.antMatchers("/system/config/setVerifyStatus").permitAll()
|
||||||
.antMatchers("/api/v1/wallet/**").permitAll()
|
.antMatchers("/api/v1/wallet/**").permitAll()
|
||||||
.antMatchers("/api/v1/order/**").permitAll()
|
.antMatchers("/api/v1/order/**").permitAll()
|
||||||
|
.antMatchers("/api/v1/payout/**").permitAll()
|
||||||
.antMatchers("/api/telegram/webhook").permitAll()
|
.antMatchers("/api/telegram/webhook").permitAll()
|
||||||
.antMatchers("/system/demoUsdt/**").permitAll()
|
.antMatchers("/system/demoUsdt/**").permitAll()
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
|
|||||||
@@ -6,15 +6,16 @@ import com.ruoyi.system.domain.dto.EncryptedRequest;
|
|||||||
import com.ruoyi.system.domain.vo.DecryptResult;
|
import com.ruoyi.system.domain.vo.DecryptResult;
|
||||||
import com.ruoyi.system.service.ApiSecurityService;
|
import com.ruoyi.system.service.ApiSecurityService;
|
||||||
import com.ruoyi.system.service.PayoutOrderService;
|
import com.ruoyi.system.service.PayoutOrderService;
|
||||||
|
import com.ruoyi.system.service.PayoutCallbackService;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
/** 代付开放接口,不依赖浏览器会话或请求上下文。 */
|
/** 代付开放接口,不依赖浏览器会话或请求上下文。 */
|
||||||
@RestController @RequestMapping("/api/v1/payout")
|
@RestController @RequestMapping("/api/v1/payout")
|
||||||
public class PayoutOpenApiController {
|
public class PayoutOpenApiController {
|
||||||
@Autowired private ApiSecurityService security; @Autowired private PayoutOrderService service;
|
@Autowired private ApiSecurityService security; @Autowired private PayoutOrderService service; @Autowired private PayoutCallbackService callbacks;
|
||||||
@PostMapping("/create") public AjaxResult create(@RequestBody EncryptedRequest request){return AjaxResult.success(view(service.create(security.decryptAndVerify(request)),null));}
|
@PostMapping("/create") public AjaxResult create(@RequestBody EncryptedRequest request){return AjaxResult.success(view(service.create(security.decryptAndVerify(request)),null));}
|
||||||
@PostMapping("/query") public AjaxResult query(@RequestBody EncryptedRequest request){DecryptResult d=security.decryptAndVerify(request);String orderId=parseOrderId(d.getPlainData());UsdtPayoutOrder o=service.find(d.getAppId(),orderId);return o==null?AjaxResult.error("代付订单不存在"):AjaxResult.success(view(o,null));}
|
@PostMapping("/query") public AjaxResult query(@RequestBody EncryptedRequest request){DecryptResult d=security.decryptAndVerify(request);String orderId=parseOrderId(d.getPlainData());UsdtPayoutOrder o=service.find(d.getAppId(),orderId);return o==null?AjaxResult.error("代付订单不存在"):AjaxResult.success(view(o,callbacks.signedRedirect(o,request.getApiKey())));}
|
||||||
private java.util.Map<String,Object> view(UsdtPayoutOrder o,String redirect){java.util.Map<String,Object> m=new java.util.LinkedHashMap<>();m.put("order_id",o.getOrderId());m.put("trade_id",o.getTradeId());m.put("currency",o.getCurrency());m.put("amount",o.getAmount());m.put("fee_currency",o.getFeeCurrency());m.put("fee_amount",o.getFeeAmount());m.put("to_address",o.getToAddress());m.put("status",o.getStatus());m.put("transaction_id",o.getBlockTransactionId());if(redirect!=null)m.put("redirect_url",redirect);return m;}
|
private java.util.Map<String,Object> view(UsdtPayoutOrder o,String redirect){java.util.Map<String,Object> m=new java.util.LinkedHashMap<>();m.put("order_id",o.getOrderId());m.put("trade_id",o.getTradeId());m.put("currency",o.getCurrency());m.put("amount",o.getAmount());m.put("fee_currency",o.getFeeCurrency());m.put("fee_amount",o.getFeeAmount());m.put("to_address",o.getToAddress());m.put("status",o.getStatus());m.put("transaction_id",o.getBlockTransactionId());if(redirect!=null)m.put("redirect_url",redirect);return m;}
|
||||||
private String parseOrderId(String s){if(s==null||!s.startsWith("order_id=")||!s.endsWith("&"))throw new com.ruoyi.common.exception.CustomException("业务参数格式错误");return s.substring(9,s.length()-1);}
|
private String parseOrderId(String s){if(s==null||!s.startsWith("order_id=")||!s.endsWith("&"))throw new com.ruoyi.common.exception.CustomException("业务参数格式错误");return s.substring(9,s.length()-1);}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.ruoyi.system.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.ruoyi.common.core.controller.BaseController;
|
||||||
|
import com.ruoyi.common.core.domain.AjaxResult;
|
||||||
|
import com.ruoyi.common.core.page.TableDataInfo;
|
||||||
|
import com.ruoyi.system.domain.UsdtPayoutOrder;
|
||||||
|
import com.ruoyi.system.domain.dto.PayoutExecuteRequest;
|
||||||
|
import com.ruoyi.system.mapper.UsdtPayoutOrderMapper;
|
||||||
|
import com.ruoyi.system.service.PayoutProcessingService;
|
||||||
|
import com.ruoyi.system.service.TelegramAuditService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 管理后台代付审核与执行接口。 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/system/payout")
|
||||||
|
public class PayoutOrderController extends BaseController {
|
||||||
|
@Autowired
|
||||||
|
private UsdtPayoutOrderMapper mapper;
|
||||||
|
@Autowired
|
||||||
|
private PayoutProcessingService processingService;
|
||||||
|
@Autowired
|
||||||
|
private TelegramAuditService telegramAuditService;
|
||||||
|
|
||||||
|
@PreAuthorize("@ss.hasPermi('system:payout:list')")
|
||||||
|
@GetMapping("/list")
|
||||||
|
public TableDataInfo list(UsdtPayoutOrder query) {
|
||||||
|
LambdaQueryWrapper<UsdtPayoutOrder> wrapper = new LambdaQueryWrapper<UsdtPayoutOrder>()
|
||||||
|
.isNull(UsdtPayoutOrder::getDeletedAt)
|
||||||
|
.orderByDesc(UsdtPayoutOrder::getId);
|
||||||
|
if (query.getAppId() != null) {
|
||||||
|
wrapper.eq(UsdtPayoutOrder::getAppId, query.getAppId());
|
||||||
|
}
|
||||||
|
if (query.getStatus() != null) {
|
||||||
|
wrapper.eq(UsdtPayoutOrder::getStatus, query.getStatus());
|
||||||
|
}
|
||||||
|
startPage();
|
||||||
|
List<UsdtPayoutOrder> rows = mapper.selectList(wrapper);
|
||||||
|
return getDataTable(rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("@ss.hasPermi('system:payout:review')")
|
||||||
|
@PostMapping("/{id}/review")
|
||||||
|
public AjaxResult review(@PathVariable Long id, @RequestParam boolean approved,
|
||||||
|
@RequestParam(required = false) String remark) {
|
||||||
|
telegramAuditService.reviewPayoutFromBackoffice(id, approved, remark);
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreAuthorize("@ss.hasPermi('system:payout:execute')")
|
||||||
|
@PostMapping("/{id}/execute")
|
||||||
|
public AjaxResult execute(@PathVariable Long id, @RequestBody PayoutExecuteRequest request) {
|
||||||
|
try {
|
||||||
|
return AjaxResult.success(processingService.execute(id, request.getConfigurationPassword()));
|
||||||
|
} finally {
|
||||||
|
request.setConfigurationPassword(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,6 +85,10 @@ public class AppsBalanceLedger extends BaseEntity
|
|||||||
@Excel(name = "orders.id")
|
@Excel(name = "orders.id")
|
||||||
private Long orderId;
|
private Long orderId;
|
||||||
|
|
||||||
|
/** 代付订单ID */
|
||||||
|
@Excel(name = "代付订单ID")
|
||||||
|
private Long payoutOrderId;
|
||||||
|
|
||||||
/** 商户订单号 */
|
/** 商户订单号 */
|
||||||
@Excel(name = "商户订单号")
|
@Excel(name = "商户订单号")
|
||||||
private String merchantOrderId;
|
private String merchantOrderId;
|
||||||
@@ -267,6 +271,8 @@ public class AppsBalanceLedger extends BaseEntity
|
|||||||
{
|
{
|
||||||
return orderId;
|
return orderId;
|
||||||
}
|
}
|
||||||
|
public void setPayoutOrderId(Long payoutOrderId) { this.payoutOrderId = payoutOrderId; }
|
||||||
|
public Long getPayoutOrderId() { return payoutOrderId; }
|
||||||
public void setMerchantOrderId(String merchantOrderId)
|
public void setMerchantOrderId(String merchantOrderId)
|
||||||
{
|
{
|
||||||
this.merchantOrderId = merchantOrderId;
|
this.merchantOrderId = merchantOrderId;
|
||||||
@@ -351,6 +357,7 @@ public class AppsBalanceLedger extends BaseEntity
|
|||||||
.append("frozenBefore", getFrozenBefore())
|
.append("frozenBefore", getFrozenBefore())
|
||||||
.append("frozenAfter", getFrozenAfter())
|
.append("frozenAfter", getFrozenAfter())
|
||||||
.append("orderId", getOrderId())
|
.append("orderId", getOrderId())
|
||||||
|
.append("payoutOrderId", getPayoutOrderId())
|
||||||
.append("merchantOrderId", getMerchantOrderId())
|
.append("merchantOrderId", getMerchantOrderId())
|
||||||
.append("aggregationTaskId", getAggregationTaskId())
|
.append("aggregationTaskId", getAggregationTaskId())
|
||||||
.append("walletLedgerId", getWalletLedgerId())
|
.append("walletLedgerId", getWalletLedgerId())
|
||||||
|
|||||||
@@ -71,6 +71,9 @@ public class AppsBalanceLedgerPlus implements Serializable
|
|||||||
/** orders.id */
|
/** orders.id */
|
||||||
@Excel(name = "orders.id")
|
@Excel(name = "orders.id")
|
||||||
private Long orderId;
|
private Long orderId;
|
||||||
|
/** 代付订单ID */
|
||||||
|
@Excel(name = "代付订单ID")
|
||||||
|
private Long payoutOrderId;
|
||||||
/** 商户订单号 */
|
/** 商户订单号 */
|
||||||
@Excel(name = "商户订单号")
|
@Excel(name = "商户订单号")
|
||||||
private String merchantOrderId;
|
private String merchantOrderId;
|
||||||
@@ -249,6 +252,8 @@ public class AppsBalanceLedgerPlus implements Serializable
|
|||||||
{
|
{
|
||||||
return orderId;
|
return orderId;
|
||||||
}
|
}
|
||||||
|
public void setPayoutOrderId(Long payoutOrderId) { this.payoutOrderId = payoutOrderId; }
|
||||||
|
public Long getPayoutOrderId() { return payoutOrderId; }
|
||||||
public void setMerchantOrderId(String merchantOrderId)
|
public void setMerchantOrderId(String merchantOrderId)
|
||||||
{
|
{
|
||||||
this.merchantOrderId = merchantOrderId;
|
this.merchantOrderId = merchantOrderId;
|
||||||
@@ -342,6 +347,7 @@ public class AppsBalanceLedgerPlus implements Serializable
|
|||||||
.append("frozenBefore", getFrozenBefore())
|
.append("frozenBefore", getFrozenBefore())
|
||||||
.append("frozenAfter", getFrozenAfter())
|
.append("frozenAfter", getFrozenAfter())
|
||||||
.append("orderId", getOrderId())
|
.append("orderId", getOrderId())
|
||||||
|
.append("payoutOrderId", getPayoutOrderId())
|
||||||
.append("merchantOrderId", getMerchantOrderId())
|
.append("merchantOrderId", getMerchantOrderId())
|
||||||
.append("aggregationTaskId", getAggregationTaskId())
|
.append("aggregationTaskId", getAggregationTaskId())
|
||||||
.append("walletLedgerId", getWalletLedgerId())
|
.append("walletLedgerId", getWalletLedgerId())
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.ruoyi.system.domain.dto;
|
||||||
|
|
||||||
|
/** 管理员执行代付时提交的配置密码。 */
|
||||||
|
public class PayoutExecuteRequest {
|
||||||
|
private String configurationPassword;
|
||||||
|
public String getConfigurationPassword(){return configurationPassword;}
|
||||||
|
public void setConfigurationPassword(String value){configurationPassword=value;}
|
||||||
|
}
|
||||||
@@ -4,8 +4,31 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
|||||||
import com.ruoyi.system.domain.UsdtPayoutOrder;
|
import com.ruoyi.system.domain.UsdtPayoutOrder;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.annotations.Update;
|
||||||
|
|
||||||
public interface UsdtPayoutOrderMapper extends BaseMapper<UsdtPayoutOrder> {
|
public interface UsdtPayoutOrderMapper extends BaseMapper<UsdtPayoutOrder> {
|
||||||
@Select("select * from usdt_payout_order where id=#{id} and deleted_at is null for update")
|
@Select("select * from usdt_payout_order where id=#{id} and deleted_at is null for update")
|
||||||
UsdtPayoutOrder selectByIdForUpdate(@Param("id") Long id);
|
UsdtPayoutOrder selectByIdForUpdate(@Param("id") Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 原子领取待广播订单。允许失败订单在重新输入配置密码后重试,防止并发请求重复广播。
|
||||||
|
*/
|
||||||
|
@Update("update usdt_payout_order set status=#{processingStatus}, updated_at=now() "
|
||||||
|
+ "where id=#{id} and status in (#{pendingStatus}, #{failedStatus}) and deleted_at is null")
|
||||||
|
int claimForExecution(@Param("id") Long id,
|
||||||
|
@Param("pendingStatus") Integer pendingStatus,
|
||||||
|
@Param("failedStatus") Integer failedStatus,
|
||||||
|
@Param("processingStatus") Integer processingStatus);
|
||||||
|
|
||||||
|
/** 多实例定时任务通过当前重试次数领取一次通知机会。 */
|
||||||
|
@Update("update usdt_payout_order set callback_num=callback_num+1, updated_at=now() "
|
||||||
|
+ "where id=#{id} and status=#{completedStatus} and callback_confirm=0 "
|
||||||
|
+ "and callback_num=#{callbackNum} and deleted_at is null")
|
||||||
|
int claimCallback(@Param("id") Long id,
|
||||||
|
@Param("completedStatus") Integer completedStatus,
|
||||||
|
@Param("callbackNum") Integer callbackNum);
|
||||||
|
|
||||||
|
@Update("update usdt_payout_order set callback_confirm=1, updated_at=now() "
|
||||||
|
+ "where id=#{id} and callback_confirm=0 and deleted_at is null")
|
||||||
|
int confirmCallback(@Param("id") Long id);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package com.ruoyi.system.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.ruoyi.common.exception.CustomException;
|
||||||
|
import com.ruoyi.system.domain.*;
|
||||||
|
import com.ruoyi.system.mapper.UsdtPayoutOrderMapper;
|
||||||
|
import com.ruoyi.system.security.RsaKeyUtil;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.security.PrivateKey;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** 代付完成后的RSA签名同步地址和平台主动异步通知。 */
|
||||||
|
@Service
|
||||||
|
public class PayoutCallbackService {
|
||||||
|
@Autowired private IAppsService apps; @Autowired private IAppApiKeysService keys;
|
||||||
|
@Autowired private AppPrivateKeyCipher cipher; @Autowired private UsdtPayoutOrderMapper mapper;
|
||||||
|
private final RestTemplate http;
|
||||||
|
public PayoutCallbackService(){SimpleClientHttpRequestFactory f=new SimpleClientHttpRequestFactory();f.setConnectTimeout(60000);f.setReadTimeout(60000);http=new RestTemplate(f);}
|
||||||
|
public String signedRedirect(UsdtPayoutOrder o,String apiKey){if(o==null||!Integer.valueOf(PayoutOrderService.COMPLETED).equals(o.getStatus())||blank(o.getRedirectUrl()))return null;return append(o.getRedirectUrl(),values(o),apiKey,sign(o));}
|
||||||
|
@Scheduled(fixedDelay=10000L) public void notifyCompleted(){List<UsdtPayoutOrder> list=mapper.selectList(new LambdaQueryWrapper<UsdtPayoutOrder>().eq(UsdtPayoutOrder::getStatus,PayoutOrderService.COMPLETED).eq(UsdtPayoutOrder::getCallbackConfirm,0).lt(UsdtPayoutOrder::getCallbackNum,10).isNull(UsdtPayoutOrder::getDeletedAt).last("limit 50"));for(UsdtPayoutOrder o:list){int callbackNum=o.getCallbackNum()==null?0:o.getCallbackNum();if(mapper.claimCallback(o.getId(),PayoutOrderService.COMPLETED,callbackNum)!=1)continue;try{AppApiKeysPlus k=activeKey(o.getAppId());Map<String,Object> body=values(o);HttpHeaders h=new HttpHeaders();h.setContentType(MediaType.APPLICATION_JSON);h.set("X-Payment-Api-Key",k.getApiKey());h.set("X-Payment-Rsa-Signature",sign(o));ResponseEntity<String> r=http.postForEntity(o.getNotifyUrl(),new HttpEntity<Map<String,Object>>(body,h),String.class);if(r.getStatusCode().is2xxSuccessful()&&"ok".equalsIgnoreCase(r.getBody()==null?"":r.getBody().trim()))mapper.confirmCallback(o.getId());}catch(Exception ignored){}}}
|
||||||
|
private Map<String,Object> values(UsdtPayoutOrder o){Map<String,Object> m=new TreeMap<>();m.put("order_id",o.getOrderId());m.put("trade_id",o.getTradeId());m.put("status",o.getStatus());m.put("transaction_id",o.getBlockTransactionId());m.put("currency",o.getCurrency());m.put("amount",o.getAmount());m.put("fee_currency",o.getFeeCurrency());m.put("fee_amount",o.getFeeAmount());m.put("to_address",o.getToAddress());return m;}
|
||||||
|
private String sign(UsdtPayoutOrder o){try{AppsPlus a=apps.getById(o.getAppId());if(a==null||blank(a.getPrivateKey()))throw new CustomException("应用RSA私钥不存在");PrivateKey p=RsaKeyUtil.loadPrivateKey(cipher.decrypt(a.getPrivateKey()));return PaymentSignatureService.signRsa(values(o),p);}catch(Exception e){throw new CustomException("代付回调签名失败");}}
|
||||||
|
private AppApiKeysPlus activeKey(Long appId){AppApiKeysPlus k=keys.getOne(new LambdaQueryWrapper<AppApiKeysPlus>().eq(AppApiKeysPlus::getAppId,appId).eq(AppApiKeysPlus::getStatus,1).isNull(AppApiKeysPlus::getDeletedAt).and(w->w.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt,new Date())).last("limit 1"));if(k==null)throw new CustomException("应用API Key不存在");return k;}
|
||||||
|
private String append(String base,Map<String,Object> values,String apiKey,String signature){try{int fragmentIndex=base.indexOf('#');String fragment=fragmentIndex>=0?base.substring(fragmentIndex):"";String target=fragmentIndex>=0?base.substring(0,fragmentIndex):base;StringBuilder b=new StringBuilder(target);b.append(target.contains("?")?'&':'?');for(Map.Entry<String,Object> e:values.entrySet())b.append(URLEncoder.encode(e.getKey(),"UTF-8")).append('=').append(URLEncoder.encode(String.valueOf(e.getValue()),"UTF-8")).append('&');b.append("api_key=").append(URLEncoder.encode(apiKey,"UTF-8")).append("&signature=").append(URLEncoder.encode(signature,"UTF-8"));return b.append(fragment).toString();}catch(Exception e){throw new CustomException("代付跳转地址生成失败");}}
|
||||||
|
private boolean blank(String s){return s==null||s.trim().isEmpty();}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import com.ruoyi.system.mapper.UsdtConfigMapper;
|
|||||||
import com.ruoyi.system.mapper.UsdtPayoutOrderMapper;
|
import com.ruoyi.system.mapper.UsdtPayoutOrderMapper;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.RoundingMode;
|
import java.math.RoundingMode;
|
||||||
@@ -28,6 +29,7 @@ public class PayoutOrderService {
|
|||||||
@Autowired private AppsMapper appsMapper;
|
@Autowired private AppsMapper appsMapper;
|
||||||
@Autowired private UsdtConfigMapper configMapper;
|
@Autowired private UsdtConfigMapper configMapper;
|
||||||
@Autowired private UsdtPayoutOrderMapper payoutMapper;
|
@Autowired private UsdtPayoutOrderMapper payoutMapper;
|
||||||
|
@Autowired private ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
@Transactional(rollbackFor=Exception.class)
|
@Transactional(rollbackFor=Exception.class)
|
||||||
public UsdtPayoutOrder create(DecryptResult request) {
|
public UsdtPayoutOrder create(DecryptResult request) {
|
||||||
@@ -48,12 +50,12 @@ public class PayoutOrderService {
|
|||||||
if("USDT".equals(currency)){if(ub.compareTo(amount)<0)throw new CustomException("USDT可用余额不足");if(tb.compareTo(fee)<0)throw new CustomException("TRX手续费余额不足");ub=ub.subtract(amount);uf=uf.add(amount);tb=tb.subtract(fee);tf=tf.add(fee);}
|
if("USDT".equals(currency)){if(ub.compareTo(amount)<0)throw new CustomException("USDT可用余额不足");if(tb.compareTo(fee)<0)throw new CustomException("TRX手续费余额不足");ub=ub.subtract(amount);uf=uf.add(amount);tb=tb.subtract(fee);tf=tf.add(fee);}
|
||||||
else {BigDecimal total=amount.add(fee);if(tb.compareTo(total)<0)throw new CustomException("TRX可用余额不足");tb=tb.subtract(total);tf=tf.add(total);}
|
else {BigDecimal total=amount.add(fee);if(tb.compareTo(total)<0)throw new CustomException("TRX可用余额不足");tb=tb.subtract(total);tf=tf.add(total);}
|
||||||
Date now=new Date();if(appsMapper.updatePayoutBalances(app.getId(),ub,tb,uf,tf,now)!=1)throw new CustomException("冻结余额失败");
|
Date now=new Date();if(appsMapper.updatePayoutBalances(app.getId(),ub,tb,uf,tf,now)!=1)throw new CustomException("冻结余额失败");
|
||||||
UsdtPayoutOrder o=new UsdtPayoutOrder();o.setTradeId(UUID.randomUUID().toString().replace("-",""));o.setOrderId(orderId);o.setAppId(app.getId());o.setUserId(app.getUserId());o.setCurrency(currency);o.setAmount(amount);o.setFeeCurrency("TRX");o.setFeeAmount(fee);o.setToAddress(address);o.setStatus(PENDING_AUDIT);o.setNotifyUrl(notifyUrl);o.setRedirectUrl(redirectUrl);o.setCallbackNum(0);o.setCallbackConfirm(0);o.setExecuteCount(0);o.setCreatedAt(now);o.setUpdatedAt(now);payoutMapper.insert(o);return o;
|
UsdtPayoutOrder o=new UsdtPayoutOrder();o.setTradeId(UUID.randomUUID().toString().replace("-",""));o.setOrderId(orderId);o.setAppId(app.getId());o.setUserId(app.getUserId());o.setCurrency(currency);o.setAmount(amount);o.setFeeCurrency("TRX");o.setFeeAmount(fee);o.setToAddress(address);o.setStatus(PENDING_AUDIT);o.setNotifyUrl(notifyUrl);o.setRedirectUrl(redirectUrl);o.setCallbackNum(0);o.setCallbackConfirm(0);o.setExecuteCount(0);o.setCreatedAt(now);o.setUpdatedAt(now);payoutMapper.insert(o);eventPublisher.publishEvent(new TelegramPayoutAuditEvent(o.getId(),o.getOrderId(),o.getCurrency(),o.getAmount().toPlainString(),o.getToAddress(),o.getFeeAmount().toPlainString()));return o;
|
||||||
}
|
}
|
||||||
public UsdtPayoutOrder find(Long appId,String orderId){return payoutMapper.selectOne(new LambdaQueryWrapper<UsdtPayoutOrder>().eq(UsdtPayoutOrder::getAppId,appId).eq(UsdtPayoutOrder::getOrderId,orderId).isNull(UsdtPayoutOrder::getDeletedAt).last("limit 1"));}
|
public UsdtPayoutOrder find(Long appId,String orderId){return payoutMapper.selectOne(new LambdaQueryWrapper<UsdtPayoutOrder>().eq(UsdtPayoutOrder::getAppId,appId).eq(UsdtPayoutOrder::getOrderId,orderId).isNull(UsdtPayoutOrder::getDeletedAt).last("limit 1"));}
|
||||||
@Transactional(rollbackFor=Exception.class)
|
@Transactional(rollbackFor=Exception.class)
|
||||||
public void review(Long id,boolean approved,String channel,String reviewer,String remark){UsdtPayoutOrder probe=payoutMapper.selectById(id);if(probe==null)throw new CustomException("代付订单不存在");Apps app=appsMapper.selectAppsByIdForUpdate(probe.getAppId());UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(PENDING_AUDIT).equals(o.getStatus()))throw new CustomException("订单状态不允许审核");Date now=new Date();o.setAuditType(channel);o.setAuditorId(reviewer);o.setAuditRemark(remark);o.setAuditedAt(now);o.setUpdatedAt(now);if(approved)o.setStatus(PENDING_EXECUTE);else{unfreeze(app,o);o.setStatus(REJECTED);}payoutMapper.updateById(o);}
|
public void review(Long id,boolean approved,String channel,String reviewer,String remark){UsdtPayoutOrder probe=payoutMapper.selectById(id);if(probe==null)throw new CustomException("代付订单不存在");Apps app=appsMapper.selectAppsByIdForUpdate(probe.getAppId());UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(PENDING_AUDIT).equals(o.getStatus()))throw new CustomException("订单状态不允许审核");Date now=new Date();o.setAuditType(channel);o.setAuditorId(reviewer);o.setAuditRemark(remark);o.setAuditedAt(now);o.setUpdatedAt(now);if(approved)o.setStatus(PENDING_EXECUTE);else{unfreeze(app,o);o.setStatus(REJECTED);}payoutMapper.updateById(o);}
|
||||||
private void unfreeze(Apps a,UsdtPayoutOrder o){BigDecimal ub=z(a.getUsdtBalance()),tb=z(a.getTrxBalance()),uf=z(a.getUsdtFrozenBalance()),tf=z(a.getTrxFrozenBalance());if("USDT".equals(o.getCurrency())){ub=ub.add(o.getAmount());uf=uf.subtract(o.getAmount());}else{tb=tb.add(o.getAmount());tf=tf.subtract(o.getAmount());}tb=tb.add(o.getFeeAmount());tf=tf.subtract(o.getFeeAmount());appsMapper.updatePayoutBalances(a.getId(),ub,tb,uf,tf,new Date());}
|
private void unfreeze(Apps a,UsdtPayoutOrder o){BigDecimal ub=z(a.getUsdtBalance()),tb=z(a.getTrxBalance()),uf=z(a.getUsdtFrozenBalance()),tf=z(a.getTrxFrozenBalance());if("USDT".equals(o.getCurrency())){ub=ub.add(o.getAmount());uf=uf.subtract(o.getAmount());}else{tb=tb.add(o.getAmount());tf=tf.subtract(o.getAmount());}tb=tb.add(o.getFeeAmount());tf=tf.subtract(o.getFeeAmount());if(uf.signum()<0||tf.signum()<0)throw new CustomException("代付冻结余额异常");if(appsMapper.updatePayoutBalances(a.getId(),ub,tb,uf,tf,new Date())!=1)throw new CustomException("代付解冻余额失败");}
|
||||||
private BigDecimal z(BigDecimal v){return v==null?BigDecimal.ZERO:v;} private String trim(String v){return v==null||v.trim().isEmpty()?null:v.trim();}
|
private BigDecimal z(BigDecimal v){return v==null?BigDecimal.ZERO:v;} private String trim(String v){return v==null||v.trim().isEmpty()?null:v.trim();}
|
||||||
private BigDecimal amount(String v){try{BigDecimal n=new BigDecimal(v).setScale(6,RoundingMode.UNNECESSARY);if(n.signum()<=0)throw new Exception();return n;}catch(Exception e){throw new CustomException("amount必须大于0且最多6位小数");}}
|
private BigDecimal amount(String v){try{BigDecimal n=new BigDecimal(v).setScale(6,RoundingMode.UNNECESSARY);if(n.signum()<=0)throw new Exception();return n;}catch(Exception e){throw new CustomException("amount必须大于0且最多6位小数");}}
|
||||||
private String required(Map<String,String> p,String n){String v=trim(p.get(n));if(v==null)throw new CustomException(n+"不能为空");return v;}
|
private String required(Map<String,String> p,String n){String v=trim(p.get(n));if(v==null)throw new CustomException(n+"不能为空");return v;}
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.ruoyi.system.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.ruoyi.common.exception.CustomException;
|
||||||
|
import com.ruoyi.system.domain.*;
|
||||||
|
import com.ruoyi.system.mapper.*;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
|
import org.tron.trident.core.ApiWrapper;
|
||||||
|
import org.tron.trident.proto.Response;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/** 代付广播、链上确认和最终账务结算。 */
|
||||||
|
@Service
|
||||||
|
public class PayoutProcessingService {
|
||||||
|
/** 仅用于广播期间的并发占位,避免同一订单重复提交链上交易。 */
|
||||||
|
public static final int EXECUTING = 6;
|
||||||
|
@Autowired private UsdtPayoutOrderMapper payoutMapper; @Autowired private UsdtConfigMapper configMapper;
|
||||||
|
@Autowired private AppsMapper appsMapper; @Autowired private AppsBalanceLedgerMapper ledgerMapper;
|
||||||
|
@Autowired private WalletSigningService signingService; @Autowired private TronServiceProvider tronProvider;
|
||||||
|
@Autowired private TransactionTemplate transactionTemplate;
|
||||||
|
|
||||||
|
/** 配置密码仅用于本次内存解锁,广播成功后订单进入待链上确认状态。 */
|
||||||
|
public String execute(Long id, String password) {
|
||||||
|
if (payoutMapper.claimForExecution(id, PayoutOrderService.PENDING_EXECUTE,
|
||||||
|
PayoutOrderService.EXECUTE_FAILED, EXECUTING) != 1) {
|
||||||
|
throw new CustomException("仅待执行或执行失败的订单可以广播,请勿重复操作");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
UsdtPayoutOrder order = payoutMapper.selectById(id);
|
||||||
|
UsdtConfigPlus config = config();
|
||||||
|
WalletAddressPlus mainWallet = new WalletAddressPlus();
|
||||||
|
mainWallet.setToken(config.getTokenAddress());
|
||||||
|
mainWallet.setTokenIndex("0");
|
||||||
|
String hash = signingService.execute(mainWallet, password, (tron, api, wallet) ->
|
||||||
|
"USDT".equals(order.getCurrency())
|
||||||
|
? tron.usdtTransWithBroadcastRetry(api, wallet.getToken(),
|
||||||
|
order.getToAddress(), order.getAmount(), 3)
|
||||||
|
: tron.trxTrans(api, wallet.getToken(), order.getToAddress(), order.getAmount()));
|
||||||
|
transactionTemplate.execute(status -> { markBroadcasted(id, hash); return null; });
|
||||||
|
return hash;
|
||||||
|
} catch (Exception exception) {
|
||||||
|
transactionTemplate.execute(status -> { markFailed(id, safe(exception)); return null; });
|
||||||
|
throw exception instanceof CustomException
|
||||||
|
? (CustomException) exception : new CustomException("代付广播失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor=Exception.class)
|
||||||
|
public void markBroadcasted(Long id,String hash){UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(EXECUTING).equals(o.getStatus()))throw new CustomException("代付订单状态已变化");o.setStatus(PayoutOrderService.BROADCASTED);o.setBlockTransactionId(hash);o.setExecuteCount(n(o.getExecuteCount())+1);o.setExecutedAt(new Date());o.setExecuteError(null);o.setUpdatedAt(new Date());payoutMapper.updateById(o);}
|
||||||
|
@Transactional(rollbackFor=Exception.class)
|
||||||
|
public void markFailed(Long id,String error){UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(EXECUTING).equals(o.getStatus()))return;o.setStatus(PayoutOrderService.EXECUTE_FAILED);o.setExecuteCount(n(o.getExecuteCount())+1);o.setExecuteError(error);o.setUpdatedAt(new Date());payoutMapper.updateById(o);}
|
||||||
|
|
||||||
|
/** 查询已广播交易,只有链上SUCCESS后才完成账务结算。 */
|
||||||
|
public void confirmPending(){List<UsdtPayoutOrder> list=payoutMapper.selectList(new LambdaQueryWrapper<UsdtPayoutOrder>().eq(UsdtPayoutOrder::getStatus,PayoutOrderService.BROADCASTED).isNotNull(UsdtPayoutOrder::getBlockTransactionId).isNull(UsdtPayoutOrder::getDeletedAt).last("limit 50"));if(list.isEmpty())return;ITronService tron=tronProvider.getCurrentService();ApiWrapper api=tron.buildApiWrapper();for(UsdtPayoutOrder o:list){try{Response.TransactionInfo info=api.getTransactionInfoById(o.getBlockTransactionId());if(info!=null&&!info.getId().isEmpty()){if(info.getResultValue()==0)settle(o.getId());else markChainFailed(o.getId(),"链上交易执行失败,resultValue="+info.getResultValue());}}catch(Exception ignored){}}}
|
||||||
|
|
||||||
|
public void markChainFailed(Long id,String error){transactionTemplate.execute(status->{UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o!=null&&Integer.valueOf(PayoutOrderService.BROADCASTED).equals(o.getStatus())){o.setStatus(PayoutOrderService.EXECUTE_FAILED);o.setExecuteError(error);o.setUpdatedAt(new Date());payoutMapper.updateById(o);}return null;});}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor=Exception.class)
|
||||||
|
public void settle(Long id){transactionTemplate.execute(status->{settleInternal(id);return null;});}
|
||||||
|
private void settleInternal(Long id){UsdtPayoutOrder probe=payoutMapper.selectById(id);if(probe==null)return;Apps app=appsMapper.selectAppsByIdForUpdate(probe.getAppId());UsdtPayoutOrder o=payoutMapper.selectByIdForUpdate(id);if(o==null||!Integer.valueOf(PayoutOrderService.BROADCASTED).equals(o.getStatus()))return;Date now=new Date();BigDecimal ub=z(app.getUsdtBalance()),tb=z(app.getTrxBalance()),uf=z(app.getUsdtFrozenBalance()),tf=z(app.getTrxFrozenBalance());BigDecimal principalFrozenBefore="USDT".equals(o.getCurrency())?uf:tf;BigDecimal principalFrozenAfter=principalFrozenBefore.subtract(o.getAmount());if("USDT".equals(o.getCurrency()))uf=principalFrozenAfter;else tf=principalFrozenAfter;BigDecimal feeFrozenBefore=tf;BigDecimal feeFrozenAfter=feeFrozenBefore.subtract(o.getFeeAmount());tf=feeFrozenAfter;if(uf.signum()<0||tf.signum()<0)throw new CustomException("代付冻结余额异常");if(appsMapper.updatePayoutBalances(app.getId(),ub,tb,uf,tf,now)!=1)throw new CustomException("代付结算余额更新失败");post(o,"PAYOUT_SUCCESS",o.getCurrency(),o.getAmount(),"PAYOUT_PRINCIPAL:"+o.getId(),"USDT".equals(o.getCurrency())?ub:tb,principalFrozenBefore,principalFrozenAfter,now);if(o.getFeeAmount().signum()>0)post(o,"PAYOUT_FEE","TRX",o.getFeeAmount(),"PAYOUT_FEE:"+o.getId(),tb,feeFrozenBefore,feeFrozenAfter,now);o.setStatus(PayoutOrderService.COMPLETED);o.setConfirmedAt(now);o.setUpdatedAt(now);payoutMapper.updateById(o);}
|
||||||
|
private void post(UsdtPayoutOrder o,String type,String currency,BigDecimal amount,String key,BigDecimal available,BigDecimal frozenBefore,BigDecimal frozenAfter,Date now){AppsBalanceLedger l=new AppsBalanceLedger();l.setTradeNo("PL"+UUID.randomUUID().toString().replace("-","").substring(0,24));l.setIdempotencyKey(key);l.setAppId(o.getAppId());l.setUserId(o.getUserId());l.setCurrency(currency);l.setBalanceType(2);l.setBusinessType(type);l.setDirection(2);l.setAmount(amount);l.setBalanceBefore(frozenBefore);l.setBalanceAfter(frozenAfter);l.setAvailableBefore(available);l.setAvailableAfter(available);l.setFrozenBefore(frozenBefore);l.setFrozenAfter(frozenAfter);l.setPayoutOrderId(o.getId());l.setMerchantOrderId(o.getOrderId());l.setTransactionId(o.getBlockTransactionId());l.setRemark("应用代付链上确认");l.setCreatedAt(now);ledgerMapper.insertSystemLedgerIgnoreDuplicate(l);}
|
||||||
|
private UsdtConfigPlus config(){UsdtConfigPlus c=configMapper.selectOne(new LambdaQueryWrapper<UsdtConfigPlus>().orderByAsc(UsdtConfigPlus::getId).last("limit 1"));if(c==null||c.getTokenAddress()==null)throw new CustomException("主钱包配置不存在");return c;}
|
||||||
|
private int n(Integer v){return v==null?0:v;}private BigDecimal z(BigDecimal v){return v==null?BigDecimal.ZERO:v;}private String safe(Exception e){String s=e.getMessage();return s==null?e.getClass().getSimpleName():s.substring(0,Math.min(1000,s.length()));}
|
||||||
|
}
|
||||||
@@ -40,10 +40,12 @@ import java.util.UUID;
|
|||||||
public class TelegramAuditService {
|
public class TelegramAuditService {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(TelegramAuditService.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(TelegramAuditService.class);
|
||||||
private static final String BUSINESS_TYPE = "USDT_AGGREGATION";
|
private static final String BUSINESS_TYPE = "USDT_AGGREGATION";
|
||||||
|
private static final String PAYOUT_BUSINESS_TYPE = "USDT_PAYOUT";
|
||||||
private static final int MAX_PUSH_RETRIES = 8;
|
private static final int MAX_PUSH_RETRIES = 8;
|
||||||
|
|
||||||
private final TelegramAuditMapper mapper;
|
private final TelegramAuditMapper mapper;
|
||||||
private final UsdtAggregationWorkflowService workflow;
|
private final UsdtAggregationWorkflowService workflow;
|
||||||
|
private final PayoutOrderService payoutOrderService;
|
||||||
private final RestTemplate restTemplate;
|
private final RestTemplate restTemplate;
|
||||||
private final TransactionTemplate transactionTemplate;
|
private final TransactionTemplate transactionTemplate;
|
||||||
|
|
||||||
@@ -55,9 +57,11 @@ public class TelegramAuditService {
|
|||||||
@Value("${telegram.allowed-user-ids:}") private String allowedUserIds;
|
@Value("${telegram.allowed-user-ids:}") private String allowedUserIds;
|
||||||
|
|
||||||
public TelegramAuditService(TelegramAuditMapper mapper, UsdtAggregationWorkflowService workflow,
|
public TelegramAuditService(TelegramAuditMapper mapper, UsdtAggregationWorkflowService workflow,
|
||||||
|
PayoutOrderService payoutOrderService,
|
||||||
PlatformTransactionManager transactionManager) {
|
PlatformTransactionManager transactionManager) {
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
this.workflow = workflow;
|
this.workflow = workflow;
|
||||||
|
this.payoutOrderService = payoutOrderService;
|
||||||
this.transactionTemplate = new TransactionTemplate(transactionManager);
|
this.transactionTemplate = new TransactionTemplate(transactionManager);
|
||||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||||
requestFactory.setConnectTimeout(60000);
|
requestFactory.setConnectTimeout(60000);
|
||||||
@@ -202,6 +206,25 @@ public class TelegramAuditService {
|
|||||||
mapper.insertPushTask(record.getAuditNo(), now, now);
|
mapper.insertPushTask(record.getAuditNo(), now, now);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 代付事务提交后创建审核记录,Telegram不可直接执行资金操作。 */
|
||||||
|
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||||
|
public void onPayoutCreated(TelegramPayoutAuditEvent event) {
|
||||||
|
if (!enabled) return;
|
||||||
|
transactionTemplate.execute(status -> { createPayoutAuditRecord(event); return null; });
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createPayoutAuditRecord(TelegramPayoutAuditEvent event) {
|
||||||
|
if (mapper.selectByBusiness(PAYOUT_BUSINESS_TYPE, String.valueOf(event.getId())) != null) return;
|
||||||
|
Date now = new Date(); TelegramAuditRecord record = new TelegramAuditRecord();
|
||||||
|
record.setAuditNo("PO-" + event.getId() + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||||
|
record.setBusinessType(PAYOUT_BUSINESS_TYPE); record.setBusinessId(String.valueOf(event.getId()));
|
||||||
|
record.setTitle("应用代付审核"); record.setAuditStatus("PENDING");
|
||||||
|
JSONObject payload = new JSONObject(); payload.put("orderId", event.getOrderId()); payload.put("currency", event.getCurrency());
|
||||||
|
payload.put("amount", event.getAmount()); payload.put("address", event.getAddress()); payload.put("fee", event.getFee());
|
||||||
|
record.setPayload(payload.toJSONString()); record.setCreatedAt(now); record.setUpdatedAt(now);
|
||||||
|
mapper.insertRecord(record); mapper.insertPushTask(record.getAuditNo(), now, now);
|
||||||
|
}
|
||||||
|
|
||||||
/** update_id先占位防重;归集审核与Telegram最终状态在同一事务内提交。 */
|
/** update_id先占位防重;归集审核与Telegram最终状态在同一事务内提交。 */
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public void handleUpdate(JSONObject update) {
|
public void handleUpdate(JSONObject update) {
|
||||||
@@ -242,7 +265,12 @@ public class TelegramAuditService {
|
|||||||
|
|
||||||
boolean approved = "A".equals(parts[2]);
|
boolean approved = "A".equals(parts[2]);
|
||||||
String newStatus = approved ? "APPROVED" : "REJECTED";
|
String newStatus = approved ? "APPROVED" : "REJECTED";
|
||||||
|
if (PAYOUT_BUSINESS_TYPE.equals(record.getBusinessType())) {
|
||||||
|
payoutOrderService.review(Long.valueOf(record.getBusinessId()), approved,
|
||||||
|
"TELEGRAM", userId, "Telegram审核");
|
||||||
|
} else {
|
||||||
workflow.approve(Long.valueOf(record.getBusinessId()), approved);
|
workflow.approve(Long.valueOf(record.getBusinessId()), approved);
|
||||||
|
}
|
||||||
Date now = new Date();
|
Date now = new Date();
|
||||||
if (mapper.approve(auditNo, newStatus, userId, username, now, now) != 1) {
|
if (mapper.approve(auditNo, newStatus, userId, username, now, now) != 1) {
|
||||||
throw new CustomException("审核状态已被其他操作修改,请刷新后重试");
|
throw new CustomException("审核状态已被其他操作修改,请刷新后重试");
|
||||||
@@ -276,6 +304,18 @@ public class TelegramAuditService {
|
|||||||
afterCommit(null, record, approved ? "审核通过" : "审核拒绝");
|
afterCommit(null, record, approved ? "审核通过" : "审核拒绝");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 后台审核代付并同步Telegram审核单状态。 */
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void reviewPayoutFromBackoffice(Long payoutId, boolean approved, String remark) {
|
||||||
|
payoutOrderService.review(payoutId, approved, "BACKOFFICE", SecurityUtils.getUsername(), remark);
|
||||||
|
TelegramAuditRecord record = mapper.selectByBusiness(PAYOUT_BUSINESS_TYPE, String.valueOf(payoutId));
|
||||||
|
if (record == null || !"PENDING".equals(record.getAuditStatus())) return;
|
||||||
|
String status = approved ? "APPROVED" : "REJECTED"; Date now = new Date();
|
||||||
|
mapper.approve(record.getAuditNo(), status, "SYSTEM", SecurityUtils.getUsername(), now, now);
|
||||||
|
record.setAuditStatus(status); record.setReviewerTelegramId("SYSTEM"); record.setReviewerName(SecurityUtils.getUsername()); record.setReviewedAt(now);
|
||||||
|
afterCommit(null, record, approved ? "审核通过" : "审核拒绝");
|
||||||
|
}
|
||||||
|
|
||||||
private String[] parseCallbackData(String data) {
|
private String[] parseCallbackData(String data) {
|
||||||
String[] parts = StringUtils.isBlank(data) ? new String[0] : data.split(":");
|
String[] parts = StringUtils.isBlank(data) ? new String[0] : data.split(":");
|
||||||
if (parts.length != 3 || !"ta".equals(parts[0])
|
if (parts.length != 3 || !"ta".equals(parts[0])
|
||||||
@@ -331,7 +371,11 @@ public class TelegramAuditService {
|
|||||||
|
|
||||||
private Long sendAuditMessage(TelegramAuditRecord record) {
|
private Long sendAuditMessage(TelegramAuditRecord record) {
|
||||||
JSONObject payload = JSONObject.parseObject(record.getPayload());
|
JSONObject payload = JSONObject.parseObject(record.getPayload());
|
||||||
String text = "归集审核\n审核单:" + record.getAuditNo()
|
String text = PAYOUT_BUSINESS_TYPE.equals(record.getBusinessType())
|
||||||
|
? "代付审核\n审核单:" + record.getAuditNo() + "\n商户订单:" + payload.getString("orderId")
|
||||||
|
+ "\n金额:" + payload.getString("amount") + " " + payload.getString("currency")
|
||||||
|
+ "\n手续费:" + payload.getString("fee") + " TRX\n收款地址:" + payload.getString("address")
|
||||||
|
: "归集审核\n审核单:" + record.getAuditNo()
|
||||||
+ "\n任务:" + payload.getString("taskName")
|
+ "\n任务:" + payload.getString("taskName")
|
||||||
+ "\n子账号:" + payload.getIntValue("itemCount")
|
+ "\n子账号:" + payload.getIntValue("itemCount")
|
||||||
+ "\n金额:" + payload.getString("amount") + " USDT"
|
+ "\n金额:" + payload.getString("amount") + " USDT"
|
||||||
@@ -364,9 +408,15 @@ public class TelegramAuditService {
|
|||||||
Map<String, Object> body = new HashMap<>();
|
Map<String, Object> body = new HashMap<>();
|
||||||
body.put("chat_id", record.getTelegramChatId());
|
body.put("chat_id", record.getTelegramChatId());
|
||||||
body.put("message_id", record.getTelegramMessageId());
|
body.put("message_id", record.getTelegramMessageId());
|
||||||
body.put("text", "归集审核 - " + result + "\n审核单:" + record.getAuditNo()
|
String text = PAYOUT_BUSINESS_TYPE.equals(record.getBusinessType())
|
||||||
|
? "代付审核 - " + result + "\n审核单:" + record.getAuditNo()
|
||||||
|
+ "\n商户订单:" + payload.getString("orderId")
|
||||||
|
+ "\n金额:" + payload.getString("amount") + " " + payload.getString("currency")
|
||||||
|
+ "\n收款地址:" + payload.getString("address") + "\n审核人:" + reviewer
|
||||||
|
: "归集审核 - " + result + "\n审核单:" + record.getAuditNo()
|
||||||
+ "\n任务:" + payload.getString("taskName")
|
+ "\n任务:" + payload.getString("taskName")
|
||||||
+ "\n目标:" + payload.getString("destination") + "\n审核人:" + reviewer);
|
+ "\n目标:" + payload.getString("destination") + "\n审核人:" + reviewer;
|
||||||
|
body.put("text", text);
|
||||||
invokeTelegramApi("editMessageText", body);
|
invokeTelegramApi("editMessageText", body);
|
||||||
} catch (Exception exception) {
|
} catch (Exception exception) {
|
||||||
LOGGER.warn("Telegram审核结果消息更新失败,auditNo={}", record.getAuditNo());
|
LOGGER.warn("Telegram审核结果消息更新失败,auditNo={}", record.getAuditNo());
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package com.ruoyi.system.service;
|
||||||
|
/** 代付订单创建后的Telegram审核事件。 */
|
||||||
|
public class TelegramPayoutAuditEvent {private final Long id;private final String orderId,currency,amount,address,fee;public TelegramPayoutAuditEvent(Long id,String orderId,String currency,String amount,String address,String fee){this.id=id;this.orderId=orderId;this.currency=currency;this.amount=amount;this.address=address;this.fee=fee;}public Long getId(){return id;}public String getOrderId(){return orderId;}public String getCurrency(){return currency;}public String getAmount(){return amount;}public String getAddress(){return address;}public String getFee(){return fee;}}
|
||||||
@@ -22,6 +22,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
<result property="frozenBefore" column="frozen_before" />
|
<result property="frozenBefore" column="frozen_before" />
|
||||||
<result property="frozenAfter" column="frozen_after" />
|
<result property="frozenAfter" column="frozen_after" />
|
||||||
<result property="orderId" column="order_id" />
|
<result property="orderId" column="order_id" />
|
||||||
|
<result property="payoutOrderId" column="payout_order_id" />
|
||||||
<result property="merchantOrderId" column="merchant_order_id" />
|
<result property="merchantOrderId" column="merchant_order_id" />
|
||||||
<result property="aggregationTaskId" column="aggregation_task_id" />
|
<result property="aggregationTaskId" column="aggregation_task_id" />
|
||||||
<result property="walletLedgerId" column="wallet_ledger_id" />
|
<result property="walletLedgerId" column="wallet_ledger_id" />
|
||||||
@@ -33,7 +34,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
</resultMap>
|
</resultMap>
|
||||||
|
|
||||||
<sql id="selectAppsBalanceLedgerVo">
|
<sql id="selectAppsBalanceLedgerVo">
|
||||||
select id, trade_no, idempotency_key, app_id, user_id, currency, balance_type, business_type, direction, amount, balance_before, balance_after, available_before, available_after, frozen_before, frozen_after, order_id, merchant_order_id, aggregation_task_id, wallet_ledger_id, transaction_id, operator_id, request_id, remark, created_at from apps_balance_ledger
|
select id, trade_no, idempotency_key, app_id, user_id, currency, balance_type, business_type, direction, amount, balance_before, balance_after, available_before, available_after, frozen_before, frozen_after, order_id, payout_order_id, merchant_order_id, aggregation_task_id, wallet_ledger_id, transaction_id, operator_id, request_id, remark, created_at from apps_balance_ledger
|
||||||
</sql>
|
</sql>
|
||||||
|
|
||||||
<select id="selectAppsBalanceLedgerList" parameterType="AppsBalanceLedger" resultMap="AppsBalanceLedgerResult">
|
<select id="selectAppsBalanceLedgerList" parameterType="AppsBalanceLedger" resultMap="AppsBalanceLedgerResult">
|
||||||
@@ -55,6 +56,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
<if test="frozenBefore != null "> and frozen_before = #{frozenBefore}</if>
|
<if test="frozenBefore != null "> and frozen_before = #{frozenBefore}</if>
|
||||||
<if test="frozenAfter != null "> and frozen_after = #{frozenAfter}</if>
|
<if test="frozenAfter != null "> and frozen_after = #{frozenAfter}</if>
|
||||||
<if test="orderId != null "> and order_id = #{orderId}</if>
|
<if test="orderId != null "> and order_id = #{orderId}</if>
|
||||||
|
<if test="payoutOrderId != null "> and payout_order_id = #{payoutOrderId}</if>
|
||||||
<if test="merchantOrderId != null and merchantOrderId != ''"> and merchant_order_id = #{merchantOrderId}</if>
|
<if test="merchantOrderId != null and merchantOrderId != ''"> and merchant_order_id = #{merchantOrderId}</if>
|
||||||
<if test="aggregationTaskId != null "> and aggregation_task_id = #{aggregationTaskId}</if>
|
<if test="aggregationTaskId != null "> and aggregation_task_id = #{aggregationTaskId}</if>
|
||||||
<if test="walletLedgerId != null "> and wallet_ledger_id = #{walletLedgerId}</if>
|
<if test="walletLedgerId != null "> and wallet_ledger_id = #{walletLedgerId}</if>
|
||||||
@@ -92,6 +94,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
<if test="frozenBefore != null">frozen_before,</if>
|
<if test="frozenBefore != null">frozen_before,</if>
|
||||||
<if test="frozenAfter != null">frozen_after,</if>
|
<if test="frozenAfter != null">frozen_after,</if>
|
||||||
<if test="orderId != null">order_id,</if>
|
<if test="orderId != null">order_id,</if>
|
||||||
|
<if test="payoutOrderId != null">payout_order_id,</if>
|
||||||
<if test="merchantOrderId != null">merchant_order_id,</if>
|
<if test="merchantOrderId != null">merchant_order_id,</if>
|
||||||
<if test="aggregationTaskId != null">aggregation_task_id,</if>
|
<if test="aggregationTaskId != null">aggregation_task_id,</if>
|
||||||
<if test="walletLedgerId != null">wallet_ledger_id,</if>
|
<if test="walletLedgerId != null">wallet_ledger_id,</if>
|
||||||
@@ -118,6 +121,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
<if test="frozenBefore != null">#{frozenBefore},</if>
|
<if test="frozenBefore != null">#{frozenBefore},</if>
|
||||||
<if test="frozenAfter != null">#{frozenAfter},</if>
|
<if test="frozenAfter != null">#{frozenAfter},</if>
|
||||||
<if test="orderId != null">#{orderId},</if>
|
<if test="orderId != null">#{orderId},</if>
|
||||||
|
<if test="payoutOrderId != null">#{payoutOrderId},</if>
|
||||||
<if test="merchantOrderId != null">#{merchantOrderId},</if>
|
<if test="merchantOrderId != null">#{merchantOrderId},</if>
|
||||||
<if test="aggregationTaskId != null">#{aggregationTaskId},</if>
|
<if test="aggregationTaskId != null">#{aggregationTaskId},</if>
|
||||||
<if test="walletLedgerId != null">#{walletLedgerId},</if>
|
<if test="walletLedgerId != null">#{walletLedgerId},</if>
|
||||||
@@ -134,12 +138,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
(trade_no, idempotency_key, app_id, user_id, currency, balance_type,
|
(trade_no, idempotency_key, app_id, user_id, currency, balance_type,
|
||||||
business_type, direction, amount, balance_before, balance_after,
|
business_type, direction, amount, balance_before, balance_after,
|
||||||
available_before, available_after, frozen_before, frozen_after,
|
available_before, available_after, frozen_before, frozen_after,
|
||||||
order_id, merchant_order_id, transaction_id, remark, created_at)
|
order_id, payout_order_id, merchant_order_id, transaction_id, remark, created_at)
|
||||||
values
|
values
|
||||||
(#{tradeNo}, #{idempotencyKey}, #{appId}, #{userId}, #{currency}, #{balanceType},
|
(#{tradeNo}, #{idempotencyKey}, #{appId}, #{userId}, #{currency}, #{balanceType},
|
||||||
#{businessType}, #{direction}, #{amount}, #{balanceBefore}, #{balanceAfter},
|
#{businessType}, #{direction}, #{amount}, #{balanceBefore}, #{balanceAfter},
|
||||||
#{availableBefore}, #{availableAfter}, #{frozenBefore}, #{frozenAfter},
|
#{availableBefore}, #{availableAfter}, #{frozenBefore}, #{frozenAfter},
|
||||||
#{orderId}, #{merchantOrderId}, #{transactionId}, #{remark}, #{createdAt})
|
#{orderId}, #{payoutOrderId}, #{merchantOrderId}, #{transactionId}, #{remark}, #{createdAt})
|
||||||
on duplicate key update id = id
|
on duplicate key update id = id
|
||||||
</insert>
|
</insert>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- 代付订单后台菜单和权限。父菜单名称请按实际部署环境调整。
|
||||||
|
SET @parent_id = (SELECT menu_id FROM sys_menu WHERE menu_name = 'USDT管理' AND menu_type = 'M' LIMIT 1);
|
||||||
|
INSERT INTO sys_menu
|
||||||
|
(menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type,
|
||||||
|
visible, status, perms, icon, create_by, create_time)
|
||||||
|
SELECT '代付订单', @parent_id, 8, 'payout', 'system/payout/index', 1, 0, 'C',
|
||||||
|
'0', '0', 'system:payout:list', 'money', 'admin', NOW()
|
||||||
|
WHERE @parent_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE perms = 'system:payout:list');
|
||||||
|
|
||||||
|
SET @payout_menu_id = (SELECT menu_id FROM sys_menu WHERE perms = 'system:payout:list' LIMIT 1);
|
||||||
|
INSERT INTO sys_menu
|
||||||
|
(menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type,
|
||||||
|
visible, status, perms, icon, create_by, create_time)
|
||||||
|
SELECT '代付审核', @payout_menu_id, 1, '#', '', 1, 0, 'F',
|
||||||
|
'0', '0', 'system:payout:review', '#', 'admin', NOW()
|
||||||
|
WHERE @payout_menu_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE perms = 'system:payout:review');
|
||||||
|
|
||||||
|
INSERT INTO sys_menu
|
||||||
|
(menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type,
|
||||||
|
visible, status, perms, icon, create_by, create_time)
|
||||||
|
SELECT '代付执行', @payout_menu_id, 2, '#', '', 1, 0, 'F',
|
||||||
|
'0', '0', 'system:payout:execute', '#', 'admin', NOW()
|
||||||
|
WHERE @payout_menu_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE perms = 'system:payout:execute');
|
||||||
@@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS `usdt_payout_order` (
|
|||||||
`fee_currency` VARCHAR(8) NOT NULL DEFAULT 'TRX' COMMENT '手续费币种,固定TRX',
|
`fee_currency` VARCHAR(8) NOT NULL DEFAULT 'TRX' COMMENT '手续费币种,固定TRX',
|
||||||
`fee_amount` DECIMAL(30,6) NOT NULL DEFAULT 0 COMMENT '代付手续费',
|
`fee_amount` DECIMAL(30,6) NOT NULL DEFAULT 0 COMMENT '代付手续费',
|
||||||
`to_address` VARCHAR(64) NOT NULL COMMENT '收款TRON地址',
|
`to_address` VARCHAR(64) NOT NULL COMMENT '收款TRON地址',
|
||||||
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '0待审核 1待执行 2广播中 3已完成 4已拒绝 5执行失败',
|
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '0待审核 1待执行 2已广播待确认 3已完成 4已拒绝 5执行失败 6广播处理中',
|
||||||
`audit_type` VARCHAR(16) DEFAULT NULL COMMENT '审核渠道:BACKOFFICE、TELEGRAM',
|
`audit_type` VARCHAR(16) DEFAULT NULL COMMENT '审核渠道:BACKOFFICE、TELEGRAM',
|
||||||
`auditor_id` VARCHAR(64) DEFAULT NULL COMMENT '审核人标识',
|
`auditor_id` VARCHAR(64) DEFAULT NULL COMMENT '审核人标识',
|
||||||
`audit_remark` VARCHAR(255) DEFAULT NULL COMMENT '审核备注',
|
`audit_remark` VARCHAR(255) DEFAULT NULL COMMENT '审核备注',
|
||||||
|
|||||||
Reference in new issue
Block a user