USDT创建订单示例
This commit is contained in:
1 parent
15cc537639
commit
cef85b81ef
2 files changed
+138
-37
No files matched your search
+137
-37
@@ -1,63 +1,163 @@
|
||||
package com.ruoyi.web.controller.system;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.luqj.util.HttpHelper;
|
||||
import com.luqj.util.SignatureUtil;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.system.domain.dto.EncryptedRequest;
|
||||
import com.ruoyi.system.security.RsaKeyUtil;
|
||||
import com.ruoyi.system.security.SecureClient;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestClientResponseException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Arrays;
|
||||
import java.math.BigDecimal;
|
||||
import java.security.PublicKey;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@Slf4j
|
||||
import java.util.UUID;
|
||||
|
||||
/** 公开支付演示入口;加密凭据仅从服务端环境变量读取。 */
|
||||
@RestController
|
||||
@RequestMapping("/system/demoUsdt")
|
||||
public class SysUsdtDemoController {
|
||||
private HttpHelper httpHelper = new HttpHelper();
|
||||
private static final Logger log = LoggerFactory.getLogger(SysUsdtDemoController.class);
|
||||
private static final String DEFAULT_API_URL =
|
||||
"http://192.168.3.103:2020/api/v1/order/create-transaction";
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
public SysUsdtDemoController() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(60000);
|
||||
factory.setReadTimeout(60000);
|
||||
this.restTemplate = new RestTemplate(factory);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "notify")
|
||||
@ResponseBody
|
||||
@PostMapping("/notify")
|
||||
public String notify(HttpServletRequest request, HttpServletResponse response, @RequestBody String body) {
|
||||
System.out.println(body);
|
||||
log.info(body);
|
||||
return "SUCCESS";
|
||||
public String notify(HttpServletRequest request, HttpServletResponse response,
|
||||
@RequestBody(required = false) String body) {
|
||||
// 回调正文可能包含订单数据,只记录收到事件,避免在日志中扩散业务报文。
|
||||
log.info("支付演示回调已接收");
|
||||
return "ok";
|
||||
}
|
||||
|
||||
@GetMapping("/redirect")
|
||||
@ResponseBody
|
||||
public String redirect(HttpServletRequest request, HttpServletResponse response) {
|
||||
System.out.println("----- Request Parameters -----");
|
||||
Map<String, String[]> params = request.getParameterMap();
|
||||
for (String key : params.keySet()) {
|
||||
System.out.println(key + " = " + Arrays.toString(params.get(key)));
|
||||
}
|
||||
public String redirect() {
|
||||
return "redirect SUCCESS";
|
||||
}
|
||||
@GetMapping("pay")
|
||||
public AjaxResult pay (@RequestParam("amount") String amount)
|
||||
{
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("order_id", System.currentTimeMillis()+"");
|
||||
params.put("app_id", "1");
|
||||
params.put("amount", amount);
|
||||
params.put("notify_url", "http://yougc.com/admin/api/system/demoUsdt/notify");
|
||||
params.put("redirect_url", "http://yougc.com/admin/api/system/demoUsdt/redirect"); //pay/checkout-counter/xxx 支付成功后得回调地址
|
||||
|
||||
String token = "lqj";
|
||||
String signature = SignatureUtil.generateSignature(params, token);
|
||||
HashMap<String, Object> headers = new HashMap<>();
|
||||
params.put("signature", signature);
|
||||
String result = null;
|
||||
/** 使用 RSA-AES-HMAC 协议创建支付订单。 */
|
||||
@PostMapping("/pay")
|
||||
public AjaxResult pay(@RequestParam("amount") String amount,
|
||||
@RequestParam(value = "walletUserName", required = false) String walletUserName) {
|
||||
BigDecimal paymentAmount = parseAmount(amount);
|
||||
String apiUrl = optionalEnv("PAYMENT_API_URL", DEFAULT_API_URL);
|
||||
String apiKey = requiredEnvWithAlias("PAYMENT_API_KEY", "PAYMENT_API_KEK");
|
||||
String apiSecret = requiredEnv("PAYMENT_API_SECRET");
|
||||
String publicKeyText = requiredEnv("PAYMENT_RSA_PUBLIC_KEY").replace("\\n", "\n");
|
||||
|
||||
try {
|
||||
result = httpHelper.playLoad("post","http://yougc.com/usdt/api/v1/order/create-transaction"
|
||||
,headers,params,"application/json","utf-8");
|
||||
JSONObject jsonObject = JSONObject.parseObject(result);
|
||||
return AjaxResult.success(jsonObject.getJSONObject("data").get("payment_url"));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
PublicKey publicKey = RsaKeyUtil.loadPublicKey(publicKeyText);
|
||||
String contextPath = ServletUriComponentsBuilder.fromCurrentContextPath()
|
||||
.build().toUriString();
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
params.put("order_id", "demo-" + System.currentTimeMillis() + '-'
|
||||
+ UUID.randomUUID().toString().substring(0, 8));
|
||||
params.put("walletUserName", normalizeWalletUserName(walletUserName));
|
||||
params.put("amount", paymentAmount.toPlainString());
|
||||
params.put("notify_url", optionalEnv("PAYMENT_NOTIFY_URL",
|
||||
contextPath + "/system/demoUsdt/notify"));
|
||||
params.put("redirect_url", optionalEnv("PAYMENT_REDIRECT_URL",
|
||||
contextPath + "/system/demoUsdt/redirect"));
|
||||
|
||||
EncryptedRequest encrypted = SecureClient.encrypt(apiKey, apiSecret, publicKey, params);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.setAccept(java.util.Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||
ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.POST,
|
||||
new HttpEntity<EncryptedRequest>(encrypted, headers), String.class);
|
||||
JSONObject result = JSON.parseObject(response.getBody());
|
||||
if (result == null || result.getIntValue("code") != 200 || result.get("data") == null) {
|
||||
throw new CustomException(result == null ? "创建支付订单失败" : result.getString("msg"));
|
||||
}
|
||||
return AjaxResult.success(result.get("data"));
|
||||
} catch (RestClientResponseException ex) {
|
||||
log.warn("支付演示请求失败,HTTP状态={}", ex.getRawStatusCode());
|
||||
throw new CustomException("支付服务暂时不可用,请稍后重试");
|
||||
} catch (CustomException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.warn("支付演示创建订单失败,异常类型={}", ex.getClass().getSimpleName());
|
||||
throw new CustomException("创建支付订单失败,请检查服务端支付配置");
|
||||
}
|
||||
}
|
||||
|
||||
private BigDecimal parseAmount(String amount) {
|
||||
try {
|
||||
BigDecimal value = new BigDecimal(amount);
|
||||
if (value.compareTo(BigDecimal.ZERO) <= 0 || value.scale() > 2) {
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
return value;
|
||||
} catch (Exception ex) {
|
||||
throw new CustomException("支付金额必须大于0且最多保留2位小数");
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeWalletUserName(String value) {
|
||||
if (StringUtils.isBlank(value)) {
|
||||
return "demo-user-" + UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
String normalized = value.trim();
|
||||
if (normalized.length() > 128 || !normalized.matches("[A-Za-z0-9_.@-]+")) {
|
||||
throw new CustomException("支付用户标识格式不正确");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String requiredEnv(String name) {
|
||||
String value = System.getenv(name);
|
||||
if (StringUtils.isBlank(value)) {
|
||||
throw new CustomException("服务端缺少环境变量 " + name);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private String requiredEnvWithAlias(String name, String alias) {
|
||||
String value = System.getenv(name);
|
||||
if (StringUtils.isBlank(value)) {
|
||||
value = System.getenv(alias);
|
||||
}
|
||||
if (StringUtils.isBlank(value)) {
|
||||
throw new CustomException("服务端缺少环境变量 " + name);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private String optionalEnv(String name, String defaultValue) {
|
||||
String value = System.getenv(name);
|
||||
return StringUtils.isBlank(value) ? defaultValue : value.trim();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user