auto(2b9ed1c9fb01): session end @ 2026-07-07T15:53:31 (+11f)
This commit is contained in:
1 parent
558a39a5bf
commit
bc2706aa7c
11 files changed
-1295
No files matched your search
@@ -1,42 +0,0 @@
|
||||
package ssw.common.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Stripe 支付配置
|
||||
* 从 application-dev.yml 读取 stripe.* 配置
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "stripe")
|
||||
public class StripeConfig {
|
||||
|
||||
/** Stripe Secret Key(sk_test_xxx 或 sk_live_xxx) */
|
||||
private String secretKey = "";
|
||||
|
||||
/** Stripe Publishable Key(pk_test_xxx,用于前端) */
|
||||
private String publishableKey = "";
|
||||
|
||||
/** 是否启用沙箱模式 */
|
||||
private boolean sandbox = true;
|
||||
|
||||
/** 支付成功回调地址 */
|
||||
private String successUrl = "http://127.0.0.1:3000/jnpf_app_dr/payment/success";
|
||||
|
||||
/** 支付取消回调地址 */
|
||||
private String cancelUrl = "http://127.0.0.1:3000/jnpf_app_dr/payment/cancel";
|
||||
|
||||
/** Webhook 签名密钥 */
|
||||
private String webhookSecret = "";
|
||||
|
||||
/** 商户订单号前缀 */
|
||||
private String orderPrefix = "DR";
|
||||
|
||||
public String getApiBase() {
|
||||
return sandbox
|
||||
? "https://api.stripe.com/v1"
|
||||
: "https://api.stripe.com/v1";
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package ssw.common.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 数据库连接服务接口
|
||||
*/
|
||||
public interface DbLinkService {
|
||||
|
||||
/**
|
||||
* 创建数据库连接
|
||||
*
|
||||
* @param fullName 连接名称
|
||||
* @param dbType 数据库类型 (MySQL/PostgreSQL/Oracle/SQLServer)
|
||||
* @param host 主机地址
|
||||
* @param port 端口
|
||||
* @param userName 用户名
|
||||
* @param password 密码
|
||||
* @param serviceName 服务名/数据库名
|
||||
* @param description 描述
|
||||
* @return 创建成功返回数据源ID
|
||||
*/
|
||||
String createDbLink(String fullName, String dbType, String host, Integer port,
|
||||
String userName, String password, String serviceName, String description);
|
||||
|
||||
/**
|
||||
* 根据编码获取数据库连接信息
|
||||
*
|
||||
* @param enCode 连接编码
|
||||
* @return 连接ID
|
||||
*/
|
||||
String getIdByEnCode(String enCode);
|
||||
|
||||
/**
|
||||
* 测试数据库连接
|
||||
*
|
||||
* @param dbType 数据库类型
|
||||
* @param host 主机地址
|
||||
* @param port 端口
|
||||
* @param userName 用户名
|
||||
* @param password 密码
|
||||
* @param serviceName 服务名/数据库名
|
||||
* @return 测试结果
|
||||
*/
|
||||
Map<String, Object> testConnection(String dbType, String host, Integer port,
|
||||
String userName, String password, String serviceName);
|
||||
|
||||
/**
|
||||
* 创建数据库
|
||||
*
|
||||
* @param host 主机地址
|
||||
* @param port 端口
|
||||
* @param userName 用户名
|
||||
* @param password 密码
|
||||
* @param dbName 数据库名
|
||||
* @param dbType 数据库类型 (MySQL/PostgreSQL)
|
||||
* @return 创建结果
|
||||
*/
|
||||
boolean createDatabase(String host, Integer port, String userName, String password,
|
||||
String dbName, String dbType);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package ssw.common.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文档管理服务接口
|
||||
* 提供 docs 目录下的文件浏览和编辑功能
|
||||
*/
|
||||
public interface DocsService {
|
||||
|
||||
/**
|
||||
* 获取所有应用目录列表
|
||||
*
|
||||
* @return 应用目录名列表
|
||||
*/
|
||||
List<String> listAppCodes();
|
||||
|
||||
/**
|
||||
* 获取指定应用下的文件列表
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param path 子目录路径(相对路径,可为空)
|
||||
* @return 文件列表 [{name, path, isDir, size, modifiedTime}]
|
||||
*/
|
||||
List<Map<String, Object>> listFiles(String appCode, String path);
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param filePath 文件路径(相对于 app_code 目录)
|
||||
* @return 文件内容
|
||||
*/
|
||||
String readFile(String appCode, String filePath);
|
||||
|
||||
/**
|
||||
* 保存文件内容
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param filePath 文件路径
|
||||
* @param content 文件内容
|
||||
* @return 保存结果
|
||||
*/
|
||||
boolean saveFile(String appCode, String filePath, String content);
|
||||
|
||||
/**
|
||||
* 获取文件信息
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param filePath 文件路径
|
||||
* @return 文件信息
|
||||
*/
|
||||
Map<String, Object> getFileInfo(String appCode, String filePath);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package ssw.common.service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Stripe 支付服务接口
|
||||
*/
|
||||
public interface StripeService {
|
||||
|
||||
/**
|
||||
* 创建支付会话(Payment Intent)
|
||||
* @param amount 金额(单位:元,Stripe 内部转为分)
|
||||
* @param currency 币种,默认 CNY
|
||||
* @param orderNo 商户订单号
|
||||
* @param description 描述
|
||||
* @return 包含 clientSecret 的 Map
|
||||
*/
|
||||
Map<String, Object> createPaymentIntent(BigDecimal amount, String currency, String orderNo, String description);
|
||||
|
||||
/**
|
||||
* 查询支付状态
|
||||
* @param paymentIntentId Stripe PaymentIntent ID
|
||||
* @return 支付状态
|
||||
*/
|
||||
Map<String, Object> retrievePaymentIntent(String paymentIntentId);
|
||||
|
||||
/**
|
||||
* 确认支付(用于测试/模拟)
|
||||
* @param paymentIntentId Stripe PaymentIntent ID
|
||||
* @return 确认结果
|
||||
*/
|
||||
Map<String, Object> confirmPaymentIntent(String paymentIntentId);
|
||||
|
||||
/**
|
||||
* 退款
|
||||
* @param paymentIntentId Stripe PaymentIntent ID
|
||||
* @param amount 退款金额(分),null 表示全额退款
|
||||
* @return 退款结果
|
||||
*/
|
||||
Map<String, Object> refundPaymentIntent(String paymentIntentId, Long amount);
|
||||
|
||||
/**
|
||||
* 验证 Webhook 签名
|
||||
* @param payload 原始 payload
|
||||
* @param sigHeader Stripe-Signature 头
|
||||
* @return 解析后的事件 Map,验证失败返回 null
|
||||
*/
|
||||
Map<String, Object> verifyWebhookSignature(String payload, String sigHeader);
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package ssw.common.service.impl;
|
||||
|
||||
import ssw.common.service.DocsService;
|
||||
import ssw.common.util.DocsPathUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 文档管理服务实现
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class DocsServiceImpl implements DocsService {
|
||||
|
||||
@Override
|
||||
public List<String> listAppCodes() {
|
||||
Path docsPath = Paths.get(DocsPathUtil.getDocsBaseDir());
|
||||
if (!docsPath.toFile().exists()) {
|
||||
log.warn("Docs directory not found: {}", docsPath);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
try {
|
||||
return java.nio.file.Files.list(docsPath)
|
||||
.filter(p -> p.toFile().isDirectory())
|
||||
.map(p -> p.getFileName().toString())
|
||||
.filter(name -> !name.startsWith("."))
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to list app codes", e);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> listFiles(String appCode, String path) {
|
||||
Path dirPath = DocsPathUtil.resolvePath(appCode, path);
|
||||
if (dirPath == null || !dirPath.toFile().exists()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
try {
|
||||
List<Map<String, Object>> files = DocsPathUtil.listDirectory(dirPath);
|
||||
return files != null ? files : new ArrayList<>();
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to list files for appCode={}, path={}", appCode, path, e);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String readFile(String appCode, String filePath) {
|
||||
if (!DocsPathUtil.isSafePath(appCode, filePath)) {
|
||||
log.warn("Unsafe file path access attempt: appCode={}, filePath={}", appCode, filePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
Path path = DocsPathUtil.resolvePath(appCode, filePath);
|
||||
if (path == null || !path.toFile().exists()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return DocsPathUtil.readFileContent(path);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to read file: appCode={}, filePath={}", appCode, filePath, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveFile(String appCode, String filePath, String content) {
|
||||
if (!DocsPathUtil.isSafePath(appCode, filePath)) {
|
||||
log.warn("Unsafe file path access attempt: appCode={}, filePath={}", appCode, filePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
Path path = DocsPathUtil.resolvePath(appCode, filePath);
|
||||
if (path == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
Path parent = path.getParent();
|
||||
if (parent != null && !parent.toFile().exists()) {
|
||||
java.nio.file.Files.createDirectories(parent);
|
||||
}
|
||||
DocsPathUtil.writeFileContent(path, content);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to save file: appCode={}, filePath={}", appCode, filePath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getFileInfo(String appCode, String filePath) {
|
||||
Path path = DocsPathUtil.resolvePath(appCode, filePath);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
if (path == null || !path.toFile().exists()) {
|
||||
result.put("exists", false);
|
||||
result.put("name", filePath != null ? Paths.get(filePath).getFileName().toString() : "");
|
||||
result.put("path", filePath != null ? filePath : "");
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
BasicFileAttributes attrs = java.nio.file.Files.readAttributes(path, BasicFileAttributes.class);
|
||||
result.put("exists", true);
|
||||
result.put("name", path.getFileName().toString());
|
||||
result.put("path", filePath);
|
||||
result.put("isDir", java.nio.file.Files.isDirectory(path));
|
||||
result.put("size", attrs.size());
|
||||
result.put("sizeText", DocsPathUtil.formatSize(attrs.size()));
|
||||
result.put("modifiedTime", formatTime(attrs.lastModifiedTime().toMillis()));
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to get file info: appCode={}, filePath={}", appCode, filePath, e);
|
||||
result.put("exists", false);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private String formatTime(long timestamp) {
|
||||
return java.time.Instant.ofEpochMilli(timestamp)
|
||||
.atZone(java.time.ZoneId.systemDefault())
|
||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
}
|
||||
-174
@@ -1,174 +0,0 @@
|
||||
package ssw.common.service.impl;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ssw.common.service.DbLinkService;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 数据库连接服务实现
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ExtDbLinkServiceImpl implements DbLinkService {
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
@Override
|
||||
public String createDbLink(String fullName, String dbType, String host, Integer port,
|
||||
String userName, String password, String serviceName, String description) {
|
||||
// 检查是否已存在
|
||||
String checkSql = "SELECT F_Id FROM base_db_link WHERE F_Full_Name = ?";
|
||||
try {
|
||||
Map<String, Object> existResult = jdbcTemplate.queryForMap(checkSql, fullName);
|
||||
String existId = (String) existResult.get("F_Id");
|
||||
log.warn("数据源已存在: {}, id={}", fullName, existId);
|
||||
return existId;
|
||||
} catch (Exception e) {
|
||||
// 不存在,继续创建
|
||||
}
|
||||
|
||||
// 创建新数据源(使用雪花ID)
|
||||
String id = String.valueOf(IdUtil.getSnowflakeNextId());
|
||||
String insertSql = "INSERT INTO base_db_link " +
|
||||
"(F_Id, F_Full_Name, F_Db_Type, F_Host, F_Port, F_User_Name, F_Password, F_Service_Name, " +
|
||||
"F_Description, F_Db_Schema, F_Table_Space, F_Oracle_Param, F_Sort_Code, " +
|
||||
"F_Creator_Time, F_Creator_User_Id, F_Last_Modify_Time, F_Last_Modify_User_Id, " +
|
||||
"F_Delete_Mark, F_Tenant_Id) " +
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, '', '', '{}', 0, NOW(), '349057407209541', NOW(), '349057407209541', 1, '0')";
|
||||
|
||||
jdbcTemplate.update(insertSql, id, fullName, dbType, host, port, userName, password, serviceName, description);
|
||||
log.info("数据源创建成功: id={}, fullName={}", id, fullName);
|
||||
|
||||
// 输出需要手动添加的配置信息 (URL/driver 动态按 dbType, 不再硬编码 MySQL)
|
||||
log.info("========== 请手动添加到 application-dev.yml ==========");
|
||||
log.info("在 datasource 配置块后添加:");
|
||||
log.info(" {}:", fullName);
|
||||
log.info(" url: {}", buildJdbcUrl(dbType, port, host, serviceName));
|
||||
log.info(" username: ${{spring.datasource.username}}");
|
||||
log.info(" password: ${{spring.datasource.password}}");
|
||||
log.info(" driver-class-name: {}", getDriverClassName(dbType));
|
||||
log.info("======================================================");
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdByEnCode(String enCode) {
|
||||
String sql = "SELECT F_Id FROM base_db_link WHERE F_Full_Name = ?";
|
||||
try {
|
||||
Map<String, Object> result = jdbcTemplate.queryForMap(sql, enCode);
|
||||
return (String) result.get("F_Id");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> testConnection(String dbType, String host, Integer port,
|
||||
String userName, String password, String serviceName) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", false);
|
||||
result.put("message", "");
|
||||
|
||||
Connection conn = null;
|
||||
try {
|
||||
Class.forName(getDriverClassName(dbType));
|
||||
String url = buildJdbcUrl(dbType, port, host, serviceName);
|
||||
conn = DriverManager.getConnection(url, userName, password);
|
||||
result.put("success", true);
|
||||
result.put("message", "连接成功");
|
||||
} catch (Exception e) {
|
||||
log.error("数据库连接测试失败", e);
|
||||
result.put("success", false);
|
||||
result.put("message", e.getMessage());
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean createDatabase(String host, Integer port, String userName, String password,
|
||||
String dbName, String dbType) {
|
||||
Connection conn = null;
|
||||
try {
|
||||
Class.forName(getDriverClassName(dbType));
|
||||
// 连接时不指定数据库
|
||||
String url = buildJdbcUrl(dbType, port, host, null);
|
||||
conn = DriverManager.getConnection(url, userName, password);
|
||||
|
||||
String sql;
|
||||
if ("MySQL".equalsIgnoreCase(dbType)) {
|
||||
sql = "CREATE DATABASE IF NOT EXISTS `" + dbName + "` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
|
||||
} else if ("PostgreSQL".equalsIgnoreCase(dbType)) {
|
||||
sql = "CREATE DATABASE \"" + dbName + "\"";
|
||||
} else {
|
||||
throw new RuntimeException("不支持的数据库类型: " + dbType);
|
||||
}
|
||||
|
||||
try (PreparedStatement ps = conn.prepareStatement(sql)) {
|
||||
ps.executeUpdate();
|
||||
}
|
||||
log.info("数据库创建成功: {}", dbName);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("数据库创建失败: dbName={}", dbName, e);
|
||||
return false;
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getDriverClassName(String dbType) {
|
||||
switch (dbType.toLowerCase()) {
|
||||
case "mysql":
|
||||
return "com.mysql.cj.jdbc.Driver";
|
||||
case "postgresql":
|
||||
return "org.postgresql.Driver";
|
||||
case "oracle":
|
||||
return "oracle.jdbc.OracleDriver";
|
||||
case "sqlserver":
|
||||
return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
||||
default:
|
||||
return "com.mysql.cj.jdbc.Driver";
|
||||
}
|
||||
}
|
||||
|
||||
private String buildJdbcUrl(String dbType, Integer port, String host, String database) {
|
||||
if ("MySQL".equalsIgnoreCase(dbType)) {
|
||||
return String.format("jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
|
||||
host, port, database != null ? database : "");
|
||||
} else if ("PostgreSQL".equalsIgnoreCase(dbType)) {
|
||||
return String.format("jdbc:postgresql://%s:%d/%s", host, port, database != null ? database : "postgres");
|
||||
} else if ("Oracle".equalsIgnoreCase(dbType)) {
|
||||
return String.format("jdbc:oracle:thin:@%s:%d:%s", host, port, database);
|
||||
} else if ("SQLServer".equalsIgnoreCase(dbType)) {
|
||||
return String.format("jdbc:sqlserver://%s:%d;databaseName=%s", host, port, database);
|
||||
}
|
||||
return String.format("jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=utf8", host, port, database);
|
||||
}
|
||||
}
|
||||
-260
@@ -1,260 +0,0 @@
|
||||
package ssw.common.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ssw.common.config.StripeConfig;
|
||||
import ssw.common.service.StripeService;
|
||||
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Stripe 支付服务实现
|
||||
* 使用 OkHttp 调用 Stripe REST API
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class StripeServiceImpl implements StripeService {
|
||||
|
||||
private static final MediaType JSON_MEDIA = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
|
||||
|
||||
@Autowired
|
||||
private StripeConfig stripeConfig;
|
||||
|
||||
private final OkHttpClient httpClient = new OkHttpClient.Builder()
|
||||
.connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
@Override
|
||||
public Map<String, Object> createPaymentIntent(BigDecimal amount, String currency, String orderNo, String description) {
|
||||
try {
|
||||
// 金额转为分
|
||||
long amountCent = amount.multiply(new BigDecimal("100")).longValue();
|
||||
|
||||
String apiUrl = stripeConfig.getApiBase() + "/payment_intents";
|
||||
|
||||
// 构建表单参数
|
||||
StringBuilder bodyBuilder = new StringBuilder();
|
||||
bodyBuilder.append("amount=").append(amountCent);
|
||||
bodyBuilder.append("¤cy=").append(currency != null ? currency.toLowerCase() : "cny");
|
||||
bodyBuilder.append("&description=").append(urlEncode(description != null ? description : ""));
|
||||
bodyBuilder.append("&metadata[order_no]=").append(urlEncode(orderNo));
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(apiUrl)
|
||||
.addHeader("Authorization", "Bearer " + stripeConfig.getSecretKey())
|
||||
.addHeader("Content-Type", "application/x-www-form-urlencoded")
|
||||
.post(RequestBody.create(bodyBuilder.toString(), JSON_MEDIA))
|
||||
.build();
|
||||
|
||||
try (Response response = httpClient.newCall(request).execute()) {
|
||||
String respBody = response.body() != null ? response.body().string() : "";
|
||||
if (response.isSuccessful()) {
|
||||
JSONObject json = JSON.parseObject(respBody);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("paymentIntentId", json.getString("id"));
|
||||
result.put("clientSecret", json.getString("client_secret"));
|
||||
result.put("status", json.getString("status"));
|
||||
result.put("amount", json.getLong("amount"));
|
||||
result.put("currency", json.getString("currency"));
|
||||
log.info("Stripe PaymentIntent 创建成功: id={}, orderNo={}", json.getString("id"), orderNo);
|
||||
return result;
|
||||
} else {
|
||||
log.error("Stripe API 错误: {}, body={}", response.code(), respBody);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", respBody);
|
||||
return error;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Stripe 调用异常", e);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", e.getMessage());
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> retrievePaymentIntent(String paymentIntentId) {
|
||||
try {
|
||||
String apiUrl = stripeConfig.getApiBase() + "/payment_intents/" + paymentIntentId;
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(apiUrl)
|
||||
.addHeader("Authorization", "Bearer " + stripeConfig.getSecretKey())
|
||||
.get()
|
||||
.build();
|
||||
|
||||
try (Response response = httpClient.newCall(request).execute()) {
|
||||
String respBody = response.body() != null ? response.body().string() : "";
|
||||
if (response.isSuccessful()) {
|
||||
JSONObject json = JSON.parseObject(respBody);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("paymentIntentId", json.getString("id"));
|
||||
result.put("status", json.getString("status"));
|
||||
result.put("amount", json.getLong("amount"));
|
||||
result.put("currency", json.getString("currency"));
|
||||
result.put("description", json.getString("description"));
|
||||
JSONObject metadata = json.getJSONObject("metadata");
|
||||
if (metadata != null) {
|
||||
result.put("orderNo", metadata.getString("order_no"));
|
||||
}
|
||||
return result;
|
||||
} else {
|
||||
log.error("Stripe 查询错误: {}, body={}", response.code(), respBody);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", respBody);
|
||||
return error;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Stripe 查询异常", e);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", e.getMessage());
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> confirmPaymentIntent(String paymentIntentId) {
|
||||
try {
|
||||
String apiUrl = stripeConfig.getApiBase() + "/payment_intents/" + paymentIntentId + "/confirm";
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(apiUrl)
|
||||
.addHeader("Authorization", "Bearer " + stripeConfig.getSecretKey())
|
||||
.addHeader("Content-Type", "application/x-www-form-urlencoded")
|
||||
.post(RequestBody.create("", JSON_MEDIA))
|
||||
.build();
|
||||
|
||||
try (Response response = httpClient.newCall(request).execute()) {
|
||||
String respBody = response.body() != null ? response.body().string() : "";
|
||||
if (response.isSuccessful()) {
|
||||
JSONObject json = JSON.parseObject(respBody);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("status", json.getString("status"));
|
||||
return result;
|
||||
} else {
|
||||
log.error("Stripe 确认错误: {}, body={}", response.code(), respBody);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", respBody);
|
||||
return error;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Stripe 确认异常", e);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", e.getMessage());
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> refundPaymentIntent(String paymentIntentId, Long amount) {
|
||||
try {
|
||||
String apiUrl = stripeConfig.getApiBase() + "/refunds";
|
||||
|
||||
StringBuilder bodyBuilder = new StringBuilder();
|
||||
bodyBuilder.append("payment_intent=").append(paymentIntentId);
|
||||
if (amount != null) {
|
||||
bodyBuilder.append("&amount=").append(amount);
|
||||
}
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(apiUrl)
|
||||
.addHeader("Authorization", "Bearer " + stripeConfig.getSecretKey())
|
||||
.addHeader("Content-Type", "application/x-www-form-urlencoded")
|
||||
.post(RequestBody.create(bodyBuilder.toString(), JSON_MEDIA))
|
||||
.build();
|
||||
|
||||
try (Response response = httpClient.newCall(request).execute()) {
|
||||
String respBody = response.body() != null ? response.body().string() : "";
|
||||
if (response.isSuccessful()) {
|
||||
JSONObject json = JSON.parseObject(respBody);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("refundId", json.getString("id"));
|
||||
result.put("status", json.getString("status"));
|
||||
result.put("amount", json.getLong("amount"));
|
||||
return result;
|
||||
} else {
|
||||
log.error("Stripe 退款错误: {}, body={}", response.code(), respBody);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", respBody);
|
||||
return error;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Stripe 退款异常", e);
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("error", e.getMessage());
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> verifyWebhookSignature(String payload, String sigHeader) {
|
||||
try {
|
||||
if (stripeConfig.getWebhookSecret() == null || stripeConfig.getWebhookSecret().isEmpty()) {
|
||||
log.warn("Stripe webhook secret 未配置,跳过验签");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 解析 Stripe-Signature 头: t=timestamp,v1=signature
|
||||
String timestamp = null;
|
||||
String signature = null;
|
||||
String[] parts = sigHeader.split(",");
|
||||
for (String part : parts) {
|
||||
String[] kv = part.split("=", 2);
|
||||
if (kv.length == 2) {
|
||||
if ("t".equals(kv[0])) timestamp = kv[1];
|
||||
if ("v1".equals(kv[0])) signature = kv[1];
|
||||
}
|
||||
}
|
||||
|
||||
if (timestamp == null || signature == null) {
|
||||
log.warn("Stripe-Signature 解析失败");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 计算签名:HMAC-SHA256(timestamp + "." + payload, webhookSecret)
|
||||
String signedPayload = timestamp + "." + payload;
|
||||
SecretKeySpec secretKey = new SecretKeySpec(
|
||||
stripeConfig.getWebhookSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
||||
MessageDigest md = MessageDigest.getInstance("HmacSHA256");
|
||||
md.update(secretKey.getEncoded());
|
||||
byte[] hash = md.digest(signedPayload.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// 转换为十六进制字符串
|
||||
StringBuilder hexHash = new StringBuilder();
|
||||
for (byte b : hash) {
|
||||
hexHash.append(String.format("%02x", b));
|
||||
}
|
||||
|
||||
if (!hexHash.toString().equals(signature)) {
|
||||
log.warn("Stripe webhook 签名不匹配");
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parseObject(payload);
|
||||
} catch (Exception e) {
|
||||
log.error("Stripe webhook 验签异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String urlEncode(String value) {
|
||||
try {
|
||||
return java.net.URLEncoder.encode(value, "UTF-8");
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
package ssw.common.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文档路径工具类
|
||||
* 安全处理 docs 目录下的文件访问
|
||||
*/
|
||||
public final class DocsPathUtil {
|
||||
|
||||
private static final String DOCS_BASE_DIR;
|
||||
|
||||
static {
|
||||
String ccWorkDir = System.getenv("ccWorkDir");
|
||||
DOCS_BASE_DIR = (ccWorkDir != null ? ccWorkDir : "/home/ubuntu/ccWorkDir") + "/docs";
|
||||
}
|
||||
|
||||
private DocsPathUtil() {
|
||||
}
|
||||
|
||||
public static String getDocsBaseDir() {
|
||||
return DOCS_BASE_DIR;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地解析文件路径,防止目录遍历攻击
|
||||
*/
|
||||
public static Path resolvePath(String appCode, String filePath) {
|
||||
if (appCode == null || filePath == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 去除潜在的路径遍历字符
|
||||
String safeFilePath = filePath.replace("..", "").replace("//", "/");
|
||||
|
||||
Path resolvedPath = Paths.get(DOCS_BASE_DIR, appCode, safeFilePath);
|
||||
|
||||
// 验证路径在DOCS_BASE_DIR下
|
||||
try {
|
||||
Path normalizedPath = resolvedPath.normalize();
|
||||
if (!normalizedPath.startsWith(DOCS_BASE_DIR)) {
|
||||
return null;
|
||||
}
|
||||
return normalizedPath;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证路径访问是否安全
|
||||
*/
|
||||
public static boolean isSafePath(String appCode, String filePath) {
|
||||
if (appCode == null || filePath == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查路径遍历
|
||||
if (filePath.contains("..") || filePath.contains("//")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否是绝对路径
|
||||
if (filePath.startsWith("/")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
*/
|
||||
public static String readFileContent(Path path) throws IOException {
|
||||
return new String(Files.readAllBytes(path), "UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件内容
|
||||
*/
|
||||
public static void writeFileContent(Path path, String content) throws IOException {
|
||||
Files.write(path, content.getBytes("UTF-8"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出目录下的文件和文件夹
|
||||
*/
|
||||
public static List<Map<String, Object>> listDirectory(Path dirPath) throws IOException {
|
||||
if (!Files.isDirectory(dirPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
Files.list(dirPath)
|
||||
.forEach(path -> {
|
||||
try {
|
||||
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
|
||||
Map<String, Object> fileInfo = new HashMap<>();
|
||||
fileInfo.put("name", path.getFileName().toString());
|
||||
fileInfo.put("path", dirPath.relativize(path).toString().replace("\\", "/"));
|
||||
fileInfo.put("isDir", Files.isDirectory(path));
|
||||
fileInfo.put("size", attrs.size());
|
||||
fileInfo.put("sizeText", formatSize(attrs.size()));
|
||||
fileInfo.put("modifiedTime", formatTime(attrs.lastModifiedTime().toMillis()));
|
||||
result.add(fileInfo);
|
||||
} catch (IOException e) {
|
||||
// skip
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化文件大小
|
||||
*/
|
||||
public static String formatSize(long size) {
|
||||
if (size < 1024) {
|
||||
return size + " B";
|
||||
} else if (size < 1024 * 1024) {
|
||||
return String.format("%.1f KB", size / 1024.0);
|
||||
} else if (size < 1024 * 1024 * 1024) {
|
||||
return String.format("%.1f MB", size / (1024.0 * 1024));
|
||||
} else {
|
||||
return String.format("%.1f GB", size / (1024.0 * 1024 * 1024));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatTime(long timestamp) {
|
||||
return Instant.ofEpochMilli(timestamp)
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
}
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
package ssw.common.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jnpf.base.ActionResult;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ssw.common.service.DocsService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文档管理控制器
|
||||
* 提供 docs 目录的浏览和编辑 API
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/common/docs")
|
||||
@Tag(name = "文档管理", description = "文档管理接口")
|
||||
public class DocsController {
|
||||
|
||||
@Autowired
|
||||
private DocsService docsService;
|
||||
|
||||
/**
|
||||
* 获取所有应用目录列表
|
||||
*/
|
||||
@GetMapping("/appCodes")
|
||||
@Operation(summary = "获取应用目录列表", description = "返回 docs 下的所有应用目录")
|
||||
public ActionResult<List<String>> listAppCodes() {
|
||||
List<String> appCodes = docsService.listAppCodes();
|
||||
return ActionResult.success(appCodes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定应用下的文件列表
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param path 子目录路径(可选)
|
||||
*/
|
||||
@GetMapping("/files")
|
||||
@Operation(summary = "获取文件列表", description = "返回指定应用目录下的文件和文件夹")
|
||||
public ActionResult<List<Map<String, Object>>> listFiles(
|
||||
@RequestParam String appCode,
|
||||
@RequestParam(required = false) String path) {
|
||||
List<Map<String, Object>> files = docsService.listFiles(appCode, path);
|
||||
return ActionResult.success(files);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param filePath 文件路径(相对于 app_code 目录)
|
||||
*/
|
||||
@GetMapping("/read")
|
||||
@Operation(summary = "读取文件内容", description = "读取指定文件的内容")
|
||||
public ActionResult<Map<String, Object>> readFile(
|
||||
@RequestParam String appCode,
|
||||
@RequestParam String filePath) {
|
||||
String content = docsService.readFile(appCode, filePath);
|
||||
if (content == null) {
|
||||
return ActionResult.fail("文件不存在或无法读取");
|
||||
}
|
||||
Map<String, Object> fileInfo = docsService.getFileInfo(appCode, filePath);
|
||||
fileInfo.put("content", content);
|
||||
return ActionResult.success(fileInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存文件内容
|
||||
*
|
||||
* @param appCode 应用编码
|
||||
* @param filePath 文件路径
|
||||
* @param content 文件内容
|
||||
*/
|
||||
@PostMapping("/save")
|
||||
@Operation(summary = "保存文件", description = "保存编辑后的文件内容")
|
||||
public ActionResult<Boolean> saveFile(
|
||||
@RequestParam String appCode,
|
||||
@RequestParam String filePath,
|
||||
@RequestBody String content) {
|
||||
boolean success = docsService.saveFile(appCode, filePath, content);
|
||||
if (success) {
|
||||
return ActionResult.success("保存成功");
|
||||
} else {
|
||||
return ActionResult.fail("保存失败,请检查路径和权限");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件信息
|
||||
*/
|
||||
@GetMapping("/info")
|
||||
@Operation(summary = "获取文件信息", description = "获取文件的大小、修改时间等信息")
|
||||
public ActionResult<Map<String, Object>> getFileInfo(
|
||||
@RequestParam String appCode,
|
||||
@RequestParam String filePath) {
|
||||
Map<String, Object> info = docsService.getFileInfo(appCode, filePath);
|
||||
return ActionResult.success(info);
|
||||
}
|
||||
}
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
package ssw.common.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jnpf.base.ActionResult;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ssw.common.service.DbLinkService;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 数据库连接控制器
|
||||
* 提供应用初始化所需的数据库连接和创建功能
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/common/dblinkExt")
|
||||
public class ExtDbLinkController {
|
||||
|
||||
@Autowired
|
||||
private DbLinkService dbLinkService;
|
||||
|
||||
// 默认数据源配置(从 application-dev.yml 读取,避免密码泄漏)
|
||||
@Value("${spring.datasource.host:127.0.0.1}")
|
||||
private String defaultHost;
|
||||
|
||||
@Value("${spring.datasource.port:166}")
|
||||
private Integer defaultPort;
|
||||
|
||||
@Value("${spring.datasource.username:root}")
|
||||
private String defaultUserName;
|
||||
|
||||
@Value("${spring.datasource.password:}")
|
||||
private String defaultPassword;
|
||||
|
||||
/**
|
||||
* 创建数据库连接(数据源)
|
||||
* 默认使用系统配置的数据源参数,无需传入敏感信息
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@Operation(summary = "创建数据库连接", description = "创建新的数据库连接(数据源),默认使用系统配置")
|
||||
public ActionResult<String> createDbLink(@RequestBody Map<String, Object> params) {
|
||||
String fullName = (String) params.get("fullName");
|
||||
// 如果未提供参数,使用系统默认配置
|
||||
String dbType = (String) params.getOrDefault("dbType", "MySQL");
|
||||
String host = (String) params.getOrDefault("host", defaultHost);
|
||||
Integer port = params.get("port") != null ? ((Number) params.get("port")).intValue() : defaultPort;
|
||||
String userName = (String) params.getOrDefault("userName", defaultUserName);
|
||||
String password = (String) params.getOrDefault("password", defaultPassword);
|
||||
String serviceName = (String) params.get("serviceName");
|
||||
String description = (String) params.getOrDefault("description", "");
|
||||
|
||||
String id = dbLinkService.createDbLink(fullName, dbType, host, port, userName, password, serviceName, description);
|
||||
return ActionResult.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称获取数据源ID
|
||||
*/
|
||||
@GetMapping("/id/{enCode}")
|
||||
@Operation(summary = "获取数据源ID", description = "根据编码获取数据源ID")
|
||||
public ActionResult<String> getIdByEnCode(@PathVariable String enCode) {
|
||||
String id = dbLinkService.getIdByEnCode(enCode);
|
||||
return ActionResult.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试数据库连接
|
||||
* 默认使用系统配置的数据源参数
|
||||
*/
|
||||
@PostMapping("/test")
|
||||
@Operation(summary = "测试数据库连接", description = "测试数据库连接是否成功")
|
||||
public ActionResult<Map<String, Object>> testConnection(@RequestBody Map<String, Object> params) {
|
||||
String dbType = (String) params.getOrDefault("dbType", "MySQL");
|
||||
String host = (String) params.getOrDefault("host", defaultHost);
|
||||
Integer port = params.get("port") != null ? ((Number) params.get("port")).intValue() : defaultPort;
|
||||
String userName = (String) params.getOrDefault("userName", defaultUserName);
|
||||
String password = (String) params.getOrDefault("password", defaultPassword);
|
||||
String serviceName = (String) params.get("serviceName");
|
||||
|
||||
Map<String, Object> result = dbLinkService.testConnection(dbType, host, port, userName, password, serviceName);
|
||||
return ActionResult.success(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建数据库
|
||||
* 默认使用系统配置的数据源参数
|
||||
*/
|
||||
@PostMapping("/createDatabase")
|
||||
@Operation(summary = "创建数据库", description = "在指定数据库服务器上创建新数据库")
|
||||
public ActionResult<Boolean> createDatabase(@RequestBody Map<String, Object> params) {
|
||||
String host = (String) params.getOrDefault("host", defaultHost);
|
||||
Integer port = params.get("port") != null ? ((Number) params.get("port")).intValue() : defaultPort;
|
||||
String userName = (String) params.getOrDefault("userName", defaultUserName);
|
||||
String password = (String) params.getOrDefault("password", defaultPassword);
|
||||
String dbName = (String) params.get("dbName");
|
||||
String dbType = (String) params.getOrDefault("dbType", "MySQL");
|
||||
|
||||
boolean success = dbLinkService.createDatabase(host, port, userName, password, dbName, dbType);
|
||||
return ActionResult.success(success);
|
||||
}
|
||||
}
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
package ssw.common.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jnpf.base.ActionResult;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ssw.common.config.StripeConfig;
|
||||
import ssw.common.service.StripeService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Stripe 支付控制器
|
||||
* 提供支付下单、查询、退款、Webhook 回调等接口
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/common/pay")
|
||||
@Tag(name = "支付管理", description = "Stripe 支付接口")
|
||||
public class PayController {
|
||||
|
||||
@Autowired
|
||||
private StripeService stripeService;
|
||||
|
||||
@Autowired
|
||||
private StripeConfig stripeConfig;
|
||||
|
||||
@Value("${stripe.enabled:false}")
|
||||
private boolean stripeEnabled;
|
||||
|
||||
/**
|
||||
* 创建支付会话
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@Operation(summary = "创建支付", description = "创建 Stripe PaymentIntent,返回 clientSecret 给前端")
|
||||
public ActionResult<Map<String, Object>> createPayment(
|
||||
@RequestParam BigDecimal amount,
|
||||
@RequestParam(required = false, defaultValue = "CNY") String currency,
|
||||
@RequestParam(required = false) String orderNo,
|
||||
@RequestParam(required = false) String description) {
|
||||
|
||||
if (!stripeEnabled) {
|
||||
return ActionResult.fail("支付功能未启用,请联系管理员配置 Stripe");
|
||||
}
|
||||
|
||||
if (orderNo == null || orderNo.isEmpty()) {
|
||||
orderNo = stripeConfig.getOrderPrefix() + System.currentTimeMillis();
|
||||
}
|
||||
|
||||
Map<String, Object> result = stripeService.createPaymentIntent(amount, currency, orderNo, description);
|
||||
if (result.containsKey("error")) {
|
||||
return ActionResult.fail(result.get("error").toString());
|
||||
}
|
||||
return ActionResult.success(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询支付状态
|
||||
*/
|
||||
@GetMapping("/query/{paymentIntentId}")
|
||||
@Operation(summary = "查询支付", description = "查询 Stripe PaymentIntent 状态")
|
||||
public ActionResult<Map<String, Object>> queryPayment(@PathVariable String paymentIntentId) {
|
||||
if (!stripeEnabled) {
|
||||
return ActionResult.fail("支付功能未启用");
|
||||
}
|
||||
|
||||
Map<String, Object> result = stripeService.retrievePaymentIntent(paymentIntentId);
|
||||
if (result.containsKey("error")) {
|
||||
return ActionResult.fail(result.get("error").toString());
|
||||
}
|
||||
return ActionResult.success(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认支付(测试用)
|
||||
*/
|
||||
@PostMapping("/confirm/{paymentIntentId}")
|
||||
@Operation(summary = "确认支付", description = "确认支付(测试用)")
|
||||
public ActionResult<Map<String, Object>> confirmPayment(@PathVariable String paymentIntentId) {
|
||||
if (!stripeEnabled) {
|
||||
return ActionResult.fail("支付功能未启用");
|
||||
}
|
||||
|
||||
Map<String, Object> result = stripeService.confirmPaymentIntent(paymentIntentId);
|
||||
if (result.containsKey("error")) {
|
||||
return ActionResult.fail(result.get("error").toString());
|
||||
}
|
||||
return ActionResult.success(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 申请退款
|
||||
*/
|
||||
@PostMapping("/refund/{paymentIntentId}")
|
||||
@Operation(summary = "申请退款", description = "对指定支付申请退款")
|
||||
public ActionResult<Map<String, Object>> refundPayment(
|
||||
@PathVariable String paymentIntentId,
|
||||
@RequestParam(required = false) Long amount) {
|
||||
|
||||
if (!stripeEnabled) {
|
||||
return ActionResult.fail("支付功能未启用");
|
||||
}
|
||||
|
||||
Map<String, Object> result = stripeService.refundPaymentIntent(paymentIntentId, amount);
|
||||
if (result.containsKey("error")) {
|
||||
return ActionResult.fail(result.get("error").toString());
|
||||
}
|
||||
return ActionResult.success(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Webhook 回调(Stripe 通知)
|
||||
*/
|
||||
@PostMapping("/webhook")
|
||||
@Operation(summary = "Webook回调", description = "接收 Stripe Webhook 事件通知")
|
||||
public ActionResult<String> webhook(
|
||||
@RequestBody String payload,
|
||||
@RequestHeader("Stripe-Signature") String sigHeader) {
|
||||
|
||||
Map<String, Object> event = stripeService.verifyWebhookSignature(payload, sigHeader);
|
||||
if (event == null) {
|
||||
return ActionResult.fail("验签失败");
|
||||
}
|
||||
|
||||
String eventType = (String) event.get("type");
|
||||
log.info("Stripe Webhook 事件: type={}", eventType);
|
||||
|
||||
Map<String, Object> dataObj = (Map<String, Object>) event.get("data");
|
||||
Map<String, Object> dataObject = dataObj != null ? (Map<String, Object>) dataObj.get("object") : null;
|
||||
|
||||
if ("payment_intent.succeeded".equals(eventType)) {
|
||||
log.info("支付成功: {}", dataObject);
|
||||
} else if ("payment_intent.payment_failed".equals(eventType)) {
|
||||
log.warn("支付失败: {}", dataObject);
|
||||
} else if ("charge.refunded".equals(eventType)) {
|
||||
log.info("退款完成: {}", dataObject);
|
||||
}
|
||||
|
||||
return ActionResult.success("OK");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取支付配置(公开信息)
|
||||
*/
|
||||
@GetMapping("/config")
|
||||
@Operation(summary = "获取支付配置", description = "返回前端所需的支付公开配置")
|
||||
public ActionResult<Map<String, Object>> getConfig() {
|
||||
Map<String, Object> config = new HashMap<>();
|
||||
config.put("enabled", stripeEnabled);
|
||||
config.put("publishableKey", stripeConfig.getPublishableKey());
|
||||
config.put("sandbox", stripeConfig.isSandbox());
|
||||
return ActionResult.success(config);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user