fix:支付宝小程序登录以及支付宝支付

This commit is contained in:
2026-06-16 16:55:49 +08:00
parent 815b0e3731
commit 0ac3bece42
80 changed files with 5841 additions and 30 deletions
@@ -52,7 +52,7 @@ public class CtripDistConsumeTask {
log.info("开始自动核销携程分销订单");
try {
// 1. 查询2天前创建且未核销的CtripDistOrder
List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(2);
List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(3);
log.info("待核销的携程分销订单数量: {}", pendingOrders.size());
for (CtripDistOrder distOrder : pendingOrders) {
+10 -6
View File
@@ -90,12 +90,6 @@
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
@@ -121,6 +115,16 @@
<artifactId>zlt-wechat-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-alipay-common-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-alipay-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
@@ -0,0 +1,404 @@
package com.central.order.controller;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.notify.AlipayNotifyVerifier;
import com.central.alipay.service.AlipayPayService;
import com.central.alipay.service.AlipayRefundService;
import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysUser;
import com.central.common.utils.SecurityTenantUtils;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.enums.RefundState;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
import com.central.order.service.ICtripDistOrderService;
import com.central.order.service.IOrderService;
import com.central.order.service.IQrCodeService;
import com.central.order.service.IRefundService;
import com.central.order.service.IAlipayConfigService;
import com.central.order.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* 支付宝支付控制器(对标 WxPayController)
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@RestController
@Tag(name = "支付宝支付管理", description = "支付宝小程序下单、支付/退款异步回调")
@RequestMapping("/alipay")
public class AliPayController {
@Autowired
private IOrderService orderService;
@Autowired
private IRefundService refundService;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private IAlipayConfigService alipayConfigService;
@Autowired
private AlipayPayService alipayPayService;
@Autowired
private AlipayRefundService alipayRefundService;
@Autowired
private AlipayNotifyVerifier alipayNotifyVerifier;
@Autowired
private ICtripDistOrderService ctripDistOrderService;
@Autowired
private UserService userService;
// ==================== 小程序下单 ====================
@Operation(summary = "支付宝小程序下单",
description = "调用 alipay.trade.create 获取 tradeNo,前端用 my.tradePay({tradeNo}) 拉起支付。"
+ "请求需携带 Authorization: Bearer <access_token>。"
+ "入参 JSON:orderId(必填)+buyerId(可选)。出参成功返回 { tradeNo, outTradeNo }")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "{\"orderId\": 订单ID(必填), \"buyerId\": 支付宝userId(可选)}",
required = true,
content = @Content(schema = @Schema(example = "{\"orderId\": 1001, \"buyerId\": \"2088xxxxxxxxxxxx\"}")))
@PostMapping("/order/pay")
public Map<String, Object> payOrder(@RequestBody Map<String, Object> body) {
Object rawOrderId = body.get("orderId");
Assert.notNull(rawOrderId, "orderId 不能为空");
Long orderId = Long.valueOf(rawOrderId.toString());
Order order = orderService.getById(orderId);
Assert.notNull(order, "订单不存在: " + orderId);
// 校验当前登录用户拥有该订单(防止替他人订单发起支付)
LoginAppUser currentUser = SecurityTenantUtils.getCurrentUser();
Assert.notNull(currentUser, "未登录或登录已过期");
if (order.getUserId() == null || !order.getUserId().equals(currentUser.getId())) {
throw new IllegalStateException("无权操作他人订单, orderId: " + orderId);
}
// 租户边界校验:订单租户必须与当前用户当前租户一致
String currentTenantId = SecurityTenantUtils.getCurrentTenantId();
if (currentTenantId != null && order.getTenantId() != null
&& !currentTenantId.equals(order.getTenantId())
&& !SecurityTenantUtils.isSuperAdmin()) {
throw new IllegalStateException("订单与当前租户不一致, orderId: " + orderId);
}
// 业务校验:订单必须为待支付状态,避免重复下单
if (!OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) {
throw new IllegalStateException("订单状态不允许支付,orderId: " + orderId
+ ", status: " + order.getOrderStatus());
}
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", order.getTenantId());
Assert.notNull(config, "支付宝支付配置不存在,tenantId: " + order.getTenantId());
// buyerId 不信任前端传入:以服务端 sys_user_third_openid 映射为准
String buyerId = order.getUserId() != null
? userService.getAlipayOpenIdByUserId(order.getUserId(), config.getAppId())
: null;
Object rawBuyerId = body.get("buyerId");
if (rawBuyerId != null && !rawBuyerId.toString().isEmpty()) {
// 客户端传入 buyerId 时必须与服务端映射结果一致
if (buyerId == null || !buyerId.equals(rawBuyerId.toString())) {
throw new IllegalStateException("buyerId 与当前登录用户不匹配");
}
}
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
String subject = qrCode != null && qrCode.getName() != null
? qrCode.getName() : "景区订单-" + order.getOrderNo();
AlipayPayService.AlipayPayRequest req = new AlipayPayService.AlipayPayRequest();
req.setOutTradeNo(order.getOrderNo());
if (order.getOrderAmount() == null) {
throw new IllegalArgumentException("订单金额不能为空, orderId: " + orderId);
}
// Order.orderAmount 以"分"存储,支付宝 SDK total_amount 需要"元"
req.setTotalAmount(StringUtils.fenToYuanAmount(order.getOrderAmount()));
req.setSubject(subject);
req.setBuyerId(buyerId);
if (Boolean.TRUE.equals(config.getIsServiceMode()) && config.getSubMerchantId() != null) {
req.setSubMerchantId(config.getSubMerchantId());
}
AlipayTradeCreateResponse response = alipayPayService.create(config, req);
Map<String, Object> result = new HashMap<>();
if (response.isSuccess()) {
result.put("tradeNo", response.getTradeNo());
result.put("outTradeNo", response.getOutTradeNo());
} else {
result.put("error", response.getSubMsg());
result.put("code", response.getCode());
}
return result;
}
// ==================== 支付异步回调 ====================
@Operation(summary = "支付宝支付异步通知(支付宝服务器回调)",
description = "Content-Type: application/x-www-form-urlencoded。"
+ "支付宝以 POST form 方式回调,验签后更新订单状态为已支付。"
+ "关键入参:app_id、out_trade_no、trade_no、trade_status、total_amount、sign。"
+ "出参:纯文本 success 或 failure")
@PostMapping("/pay/notify")
public String handleAlipayPayNotify(HttpServletRequest request) {
Map<String, String> params = toMap(request);
log.info("------收到支付宝支付回调通知------, summary: {}", summarizeNotify(params));
try {
String appId = params.get("app_id");
// ISV(服务商)模式下应优先使用 auth_app_id 定位商家应用
String authAppId = params.get("auth_app_id");
String lookupAppId = (authAppId != null && !authAppId.isEmpty()) ? authAppId : appId;
AlipayConfig config = alipayConfigService.getConfigByAppId(lookupAppId);
if (config == null) {
log.error("支付宝配置不存在,appId: {}, authAppId: {}", appId, authAppId);
return "failure";
}
TenantContextHolder.setTenant(config.getTenantId());
if (!alipayNotifyVerifier.verify(params, config)) {
log.warn("支付宝回调验签失败, summary:{}", summarizeNotify(params));
return "failure";
}
String tradeStatus = params.get("trade_status");
if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
handleAlipayPaymentResult(params, config);
} else {
log.info("支付宝支付回调忽略非成功状态: {}", tradeStatus);
}
return "success";
} catch (Exception e) {
// 关键步骤异常时返回 failure,触发支付宝重试(最多重试 8 次,间隔 2m/10m/10m/1h/2h/6h/15h)
log.error("处理支付宝支付回调失败,将由支付宝重试", e);
return "failure";
} finally {
TenantContextHolder.clear();
}
}
private void handleAlipayPaymentResult(Map<String, String> params, AlipayConfig config) {
String outTradeNo = params.get("out_trade_no");
String tradeNo = params.get("trade_no");
log.info("处理支付宝支付结果, 交易号:{}, 商户订单号:{}", tradeNo, outTradeNo);
Order order = orderService.getOrderByNumberAndTenant(outTradeNo, config.getTenantId());
if (order == null) {
// 订单不存在通常是数据落库延迟或脏数据,记录后让外层返回 failure 触发支付宝重试
log.error("支付宝回调订单不存在: {}, tenantId:{}", outTradeNo, config.getTenantId());
throw new IllegalStateException("订单不存在: " + outTradeNo);
}
if (OrderStatus.PAID.getId().equals(order.getOrderStatus())) {
log.info("订单已支付,跳过: {}", outTradeNo);
return;
}
// ===== 业务验真:避免回调被重放/串租户/金额不一致 =====
// 1) 订单租户必须与回调定位到的支付宝配置租户一致
if (order.getTenantId() != null && config.getTenantId() != null
&& !order.getTenantId().equals(config.getTenantId())) {
log.error("支付宝回调租户不一致, orderTenantId:{}, configTenantId:{}, outTradeNo:{}",
order.getTenantId(), config.getTenantId(), outTradeNo);
throw new IllegalStateException("回调租户与订单租户不一致");
}
// 2) 金额一致:DB 以"分"存储,支付宝回调 total_amount 为"元"
String expectedYuan = StringUtils.fenToYuanAmount(order.getOrderAmount());
String notifyTotal = params.get("total_amount");
if (expectedYuan == null || notifyTotal == null
|| !expectedYuan.equals(notifyTotal.trim())) {
log.error("支付宝回调金额不一致, expected:{}, notify:{}, outTradeNo:{}",
expectedYuan, notifyTotal, outTradeNo);
throw new IllegalStateException("回调金额与订单金额不一致");
}
// 3) 应用身份一致:优先校验 auth_app_id(ISV),否则校验 app_id
String notifyAuthAppId = params.get("auth_app_id");
String notifyAppId = params.get("app_id");
String expectedAppId = config.getAppId();
if (notifyAuthAppId != null && !notifyAuthAppId.isEmpty()) {
if (!notifyAuthAppId.equals(expectedAppId)) {
log.error("支付宝回调 auth_app_id 不匹配配置, notify:{}, config:{}",
notifyAuthAppId, expectedAppId);
throw new IllegalStateException("回调应用身份不匹配");
}
} else if (notifyAppId == null || !notifyAppId.equals(expectedAppId)) {
log.error("支付宝回调 app_id 不匹配配置, notify:{}, config:{}", notifyAppId, expectedAppId);
throw new IllegalStateException("回调应用身份不匹配");
}
// 4) 商家身份(卖家)一致:ISV 模式下 seller_id 应等于配置的 PID;直连模式下 seller_id 等于配置 PID 也成立
String notifySellerId = params.get("seller_id");
if (config.getPid() != null && !config.getPid().isEmpty()
&& notifySellerId != null && !notifySellerId.isEmpty()
&& !config.getPid().equals(notifySellerId)) {
log.error("支付宝回调 seller_id 与配置 pid 不一致, notify:{}, configPid:{}",
notifySellerId, config.getPid());
throw new IllegalStateException("回调商家身份不匹配");
}
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.ALIPAY_PAY.getCode());
order.setPayTime(new Date());
orderService.updateOrder(order);
// 携程分销订单为旁路异步任务,失败不影响本地订单完成
if (qrCode != null && Integer.valueOf(1).equals(qrCode.getEnableCtripOrder())) {
log.info("二维码已开启携程分销,异步创建携程订单,orderNo: {}", order.getOrderNo());
try {
String mobile = null;
if (Objects.nonNull(order.getUserId())) {
SysUser sysUser = userService.findUserById(order.getUserId());
if (Objects.nonNull(sysUser) && StringUtil.isNotEmpty(sysUser.getMobile())) {
mobile = sysUser.getMobile();
}
}
ctripDistOrderService.createCtripDistOrder(
order.getOrderNo(), order.getOrderAmount(),
qrCode.getCtripProductId(), order.getTenantId(), mobile);
} catch (Exception e) {
log.error("异步创建携程分销订单失败,orderNo: {},不影响本地订单", order.getOrderNo(), e);
}
}
}
// ==================== 退款异步回调 ====================
@Operation(summary = "支付宝退款异步通知(支付宝服务器回调)",
description = "Content-Type: application/x-www-form-urlencoded。"
+ "支付宝 POST form 方式回调退款结果,验签后更新退款单和订单状态。"
+ "关键入参:app_id、out_trade_no、out_biz_no、refund_fee、sign。"
+ "出参:纯文本 success 或 failure")
@PostMapping("/refund/notify")
public String handleAlipayRefundNotify(HttpServletRequest request) {
Map<String, String> params = toMap(request);
log.info("------收到支付宝退款回调通知------, summary: {}", summarizeNotify(params));
try {
String appId = params.get("app_id");
// ISV 模式下应使用 auth_app_id 定位商家应用
String authAppId = params.get("auth_app_id");
String lookupAppId = (authAppId != null && !authAppId.isEmpty()) ? authAppId : appId;
AlipayConfig config = alipayConfigService.getConfigByAppId(lookupAppId);
if (config == null) {
log.error("支付宝配置不存在,appId: {}, authAppId: {}", appId, authAppId);
return "failure";
}
TenantContextHolder.setTenant(config.getTenantId());
if (!alipayNotifyVerifier.verify(params, config)) {
log.warn("支付宝退款回调验签失败");
return "failure";
}
handleAlipayRefundResult(params, config);
return "success";
} catch (Exception e) {
log.error("处理支付宝退款回调失败,将由支付宝重试", e);
return "failure";
} finally {
TenantContextHolder.clear();
}
}
private void handleAlipayRefundResult(Map<String, String> params, AlipayConfig config) {
String outRefundNo = params.get("out_biz_no");
String outTradeNo = params.get("out_trade_no");
log.info("处理支付宝退款结果, 退款单号:{}, 商户订单号:{}", outRefundNo, outTradeNo);
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
if (refund == null) {
log.error("退款订单不存在: {}", outRefundNo);
throw new IllegalStateException("退款订单不存在: " + outRefundNo);
}
// 租户一致性校验
if (refund.getTenantId() != null && config.getTenantId() != null
&& !refund.getTenantId().equals(config.getTenantId())) {
log.error("退款回调租户不一致, refundTenant:{}, configTenant:{}, outRefundNo:{}",
refund.getTenantId(), config.getTenantId(), outRefundNo);
throw new IllegalStateException("退款回调租户不一致");
}
if (refund.getState().equals(RefundState.PART.getId())) {
refund.setStatus(OrderStatus.PART_REFUNDED.getId());
} else {
refund.setStatus(OrderStatus.REFUNDED.getId());
}
refund.setRefundTime(new Date());
refundService.updateById(refund);
Order order = orderService.getOrderByNumberAndTenant(refund.getOrderNo(), config.getTenantId());
if (order != null) {
if (refund.getState().equals(RefundState.PART.getId())) {
order.setOrderStatus(OrderStatus.PART_REFUNDED.getId());
} else {
order.setOrderStatus(OrderStatus.REFUNDED.getId());
}
orderService.updateOrder(order);
}
}
// ==================== 工具方法 ====================
private Map<String, String> toMap(HttpServletRequest request) {
// 支付宝 form 回调按 biz 参数 charset 编码(默认 UTF-8)。
// 必须在容器解析参数前 setCharacterEncoding;这里在读取任何参数前先尝试设置 UTF-8,
// 避免先 getParameter 触发解析后再 setCharacterEncoding 不生效的问题。
try {
request.setCharacterEncoding("UTF-8");
} catch (java.io.UnsupportedEncodingException ignored) {
}
Map<String, String> params = new HashMap<>();
Map<String, String[]> requestParams = request.getParameterMap();
for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
String name = entry.getKey();
String[] values = entry.getValue();
String valueStr = (values != null && values.length > 0) ? values[0] : "";
params.put(name, valueStr);
}
return params;
}
/**
* 仅保留排查必需的非敏感字段,避免回调日志泄露 buyer/sign 等信息
*/
private Map<String, String> summarizeNotify(Map<String, String> params) {
Set<String> safeKeys = Set.of(
"out_trade_no", "trade_no", "trade_status",
"app_id", "auth_app_id", "out_biz_no",
"refund_status", "gmt_payment", "gmt_refund");
Map<String, String> safe = new LinkedHashMap<>();
for (String k : safeKeys) {
String v = params.get(k);
if (v != null) {
safe.put(k, v);
}
}
return safe;
}
}
@@ -0,0 +1,210 @@
package com.central.order.controller;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.service.IAlipayConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* 支付宝配置管理控制器
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "支付宝配置管理", description = "alipay_config 表 CRUD,供管理后台和 Feign 内部调用")
@RequestMapping("/alipay/config")
public class AlipayConfigController {
@Resource
private IAlipayConfigService alipayConfigService;
@Resource
private AlipayClientFactory alipayClientFactory;
// ==================== 管理后台 CRUD 端点 ====================
@Operation(summary = "分页查询支付宝配置",
description = "支持按 type/tenantId/appId/status 筛选,出参 PageResult<AlipayConfig>,敏感字段已脱敏")
@Parameter(name = "page", description = "页码", in = ParameterIn.QUERY, example = "1")
@Parameter(name = "limit", description = "每页条数", in = ParameterIn.QUERY, example = "10")
@Parameter(name = "searchKey", description = "检索字段:type/appId/tenantId", in = ParameterIn.QUERY)
@Parameter(name = "searchValue", description = "检索关键字", in = ParameterIn.QUERY)
@GetMapping("/list")
public Result<PageResult<AlipayConfig>> list(@RequestParam Map<String, Object> params) {
PageResult<AlipayConfig> pageResult = alipayConfigService.findList(params);
if (pageResult != null && pageResult.getData() != null) {
pageResult.getData().forEach(this::maskSensitive);
}
return Result.succeed(pageResult);
}
@Operation(summary = "根据ID查询支付宝配置",
description = "返回单条 AlipayConfig,敏感字段(私钥/公钥/authToken/encryptKey)已脱敏")
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
@GetMapping("/{id}")
public Result<AlipayConfig> getById(@PathVariable Long id) {
AlipayConfig config = alipayConfigService.getById(id);
maskSensitive(config);
return Result.succeed(config);
}
@Operation(summary = "新增支付宝配置",
description = "Body 为 AlipayConfig JSON,必填:tenantId/type/appId")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "支付宝配置对象", required = true,
content = @Content(schema = @Schema(implementation = AlipayConfig.class)))
@PostMapping
public Result<Boolean> save(@RequestBody AlipayConfig config) {
boolean result = alipayConfigService.saveConfig(config);
if (result) {
// 新增配置可能复用现有 appId(同 appId 不同 subMerchantId / 不同 type),保险起见清空全部缓存
alipayClientFactory.clearAllCache();
}
return Result.succeed(result);
}
@Operation(summary = "更新支付宝配置",
description = "Body 为 AlipayConfig JSON(含 id),增量更新;敏感字段(appPrivateKey/alipayPublicKey/authToken/encryptKey)传入掩码 ****** 表示保留原值")
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "支付宝配置对象(含 id)", required = true)
@PutMapping
public Result<Boolean> update(@RequestBody AlipayConfig config) {
// 当字段值为掩码时,保留库中原值,避免管理后台误覆盖为 ******
if (config.getId() != null) {
AlipayConfig original = alipayConfigService.getById(config.getId());
if (original != null) {
if (isMasked(config.getAppPrivateKey())) {
config.setAppPrivateKey(original.getAppPrivateKey());
}
if (isMasked(config.getAlipayPublicKey())) {
config.setAlipayPublicKey(original.getAlipayPublicKey());
}
if (isMasked(config.getAuthToken())) {
config.setAuthToken(original.getAuthToken());
}
if (isMasked(config.getEncryptKey())) {
config.setEncryptKey(original.getEncryptKey());
}
}
}
boolean result = alipayConfigService.updateConfig(config);
if (result) {
// 更新后清理缓存:可能改了密钥/证书/subMerchantId/启停,必须使旧 AlipayClient 失效
alipayClientFactory.clearCache(config);
}
return Result.succeed(result);
}
@Operation(summary = "删除支付宝配置")
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
@DeleteMapping("/{id}")
public Result<Boolean> delete(@PathVariable Long id) {
AlipayConfig original = alipayConfigService.getById(id);
boolean result = alipayConfigService.deleteConfig(id);
if (result && original != null) {
alipayClientFactory.clearCache(original);
}
return Result.succeed(result);
}
@Operation(summary = "切换配置启用/禁用状态",
description = "Body: {\"status\": 0|1}")
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "{\"status\": 1} 启用, {\"status\": 0} 禁用", required = true)
@PatchMapping("/{id}/status")
public Result<Boolean> toggleStatus(@PathVariable Long id, @RequestBody Map<String, Object> body) {
AlipayConfig config = alipayConfigService.getById(id);
if (config == null) {
return Result.failed("配置不存在");
}
config.setStatus(Integer.valueOf(body.get("status").toString()));
boolean result = alipayConfigService.updateConfig(config);
if (result) {
// 启停切换后必须清理缓存,避免禁用配置仍被复用
alipayClientFactory.clearCache(config);
}
return Result.succeed(result);
}
// ==================== Feign 调用端点(返回原始实体,无 Result 包装) ====================
@Operation(summary = "根据类型+租户ID查询配置(Feign内部调用)",
description = "供 AlipayClientFactory 调用,出参为原始 AlipayConfig 或 null")
@Parameter(name = "type", description = "MINI(小程序登录)/ PAY(交易支付)", required = true, in = ParameterIn.PATH)
@Parameter(name = "tenantId", description = "租户ID", required = true, in = ParameterIn.QUERY, example = "tenant-001")
@GetMapping("/type/{type}")
public AlipayConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
return alipayConfigService.getConfigByTypeAndTenantId(type, tenantId);
}
@Operation(summary = "根据AppId+类型查询配置(Feign内部调用)",
description = "供 AlipayAuthenticationProvider 调用")
@Parameter(name = "appId", description = "支付宝 AppId", required = true, in = ParameterIn.PATH, example = "2021000000000001")
@Parameter(name = "type", description = "MINI / PAY", in = ParameterIn.QUERY)
@GetMapping("/app/{appId}")
public AlipayConfig getConfigByAppId(@PathVariable("appId") String appId,
@RequestParam(required = false) String type) {
if (type != null && !type.isEmpty()) {
return alipayConfigService.getConfigByAppIdAndType(appId, type);
}
return alipayConfigService.getConfigByAppId(appId);
}
@Operation(summary = "根据AppId查询配置不区分类型(Feign内部调用)",
description = "供回调验签使用")
@Parameter(name = "appId", description = "支付宝 AppId", required = true, in = ParameterIn.PATH, example = "2021000000000001")
@GetMapping("/app/{appId}/any")
public AlipayConfig getConfigByAppIdAny(@PathVariable("appId") String appId) {
return alipayConfigService.getConfigByAppId(appId);
}
@Operation(summary = "根据子商户号查询配置(Feign内部调用,ISV模式)")
@Parameter(name = "subMerchantId", description = "间连商户号 smid", required = true, in = ParameterIn.PATH, example = "2088xxxx")
@GetMapping("/sub/{subMerchantId}")
public AlipayConfig getConfigBySubMerchantId(@PathVariable("subMerchantId") String subMerchantId) {
return alipayConfigService.getConfigBySubMerchantId(subMerchantId);
}
// ==================== 内部工具:敏感字段脱敏 ====================
private static final String MASK = "******";
private void maskSensitive(AlipayConfig config) {
if (config == null) {
return;
}
if (config.getAppPrivateKey() != null && !config.getAppPrivateKey().isEmpty()) {
config.setAppPrivateKey(MASK);
}
if (config.getAlipayPublicKey() != null && !config.getAlipayPublicKey().isEmpty()) {
config.setAlipayPublicKey(MASK);
}
if (config.getAuthToken() != null && !config.getAuthToken().isEmpty()) {
config.setAuthToken(MASK);
}
if (config.getEncryptKey() != null && !config.getEncryptKey().isEmpty()) {
config.setEncryptKey(MASK);
}
}
private boolean isMasked(String value) {
return MASK.equals(value);
}
}
@@ -5,7 +5,10 @@ import com.central.common.feign.UserService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.service.AlipayRefundService;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.enums.RefundState;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
@@ -64,6 +67,15 @@ public class RefundController {
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private com.central.order.service.ICtripDistOrderService ctripDistOrderService;
@Autowired
private com.central.order.service.IAlipayConfigService alipayConfigService;
@Autowired
private AlipayRefundService alipayRefundService;
@Value("${tencent.refund-notify-url}")
private String refundNotifyUrl;
@@ -153,6 +165,12 @@ public class RefundController {
// 检查订单是否存在
Order order = orderService.getOrderByNumber(refund.getOrderNo());
Assert.notNull(order, "ORDER DATA不存在");
// 校验退款单存在并与订单一致
com.central.order.model.Refund refundDb = refundService.getRefundByNo(refund.getRefundNo());
Assert.notNull(refundDb, "退款订单不存在");
if (!order.getOrderNo().equals(refundDb.getOrderNo())) {
return Result.failed("退款单与订单不匹配");
}
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
return Result.failed("请重试");
}
@@ -160,14 +178,23 @@ public class RefundController {
return Result.failed("该状态不支持审核");
}
if (refund.getState().equals(RefundState.APPROVED.getId())){
dealRefundRequest(order);
// 同步退款(支付宝/微信)成功后,立即推进本地退款单与订单为已退款,避免长期停留在退款中
routeRefundByPayType(order, null);
refundDb.setState(RefundState.APPROVED.getId());
refundDb.setStatus(OrderStatus.REFUNDED.getId());
refundDb.setRefundTime(new java.util.Date());
refundService.updateById(refundDb);
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
return Result.succeed("已处理退款");
}
if (refund.getState().equals(RefundState.REFUSED.getId())){
order.setOrderStatus(OrderStatus.REFUND_FAILED.getId());
refund.setStatus(OrderStatus.REFUND_FAILED.getId());
refundDb.setStatus(OrderStatus.REFUND_FAILED.getId());
refundDb.setState(RefundState.REFUSED.getId());
refundDb.setApproveReason(refund.getApproveReason());
orderService.updateOrder(order);
refundService.updateById(refund);
refundService.updateById(refundDb);
return Result.succeed("处理成功");
}
return Result.failed("处理退款失败");
@@ -183,7 +210,19 @@ public class RefundController {
Order order = orderService.getOrderByNumber(refundRequest.getOrderNo());
Assert.notNull(order, "ORDER DATA不存在");
com.central.order.model.Refund refundorder = refundService.getRefundByNo(refundRequest.getRefundNo());
Assert.notNull(order, "退款订单不存在");
Assert.notNull(refundorder, "退款订单不存在");
// 退款单必须与订单匹配(订单号、租户、用户)
if (!order.getOrderNo().equals(refundorder.getOrderNo())) {
return Result.failed("退款单与订单不匹配");
}
if (order.getTenantId() != null && refundorder.getTenantId() != null
&& !order.getTenantId().equals(refundorder.getTenantId())) {
return Result.failed("退款单与订单租户不一致");
}
if (order.getUserId() != null && refundorder.getUserId() != null
&& !order.getUserId().equals(refundorder.getUserId())) {
return Result.failed("退款单与订单用户不一致");
}
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
return Result.failed("订单状态不支持退款");
}
@@ -192,10 +231,20 @@ public class RefundController {
}
if (refundRequest.getState().equals(RefundState.APPROVED.getId())){
dealCustomRefundAmountRequest(order,null);
routeRefundByPayType(order, null);
refundorder.setApproveReason(refundRequest.getApproveReason());
refundorder.setState(refundRequest.getState()); //全额退款
// 同步全额退款成功后,推进本地状态到已退款
refundorder.setStatus(OrderStatus.REFUNDED.getId());
refundorder.setRefundTime(new java.util.Date());
refundService.updateById(refundorder);
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
// 全额退款成功后,根据二维码配置判断是否需要异步退订携程分销订单
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
if (qrCode != null && qrCode.getEnableCtripOrder() != null && qrCode.getEnableCtripOrder() == 1) {
ctripDistOrderService.cancelCtripDistOrder(order.getOrderNo(), "用户申请全额退款");
}
return Result.succeed("已处理全额退款");
}
if (refundRequest.getState().equals(RefundState.PART.getId())){
@@ -205,7 +254,12 @@ public class RefundController {
if(refundRequest.getRefundAmount()!=null){
refundorder.setRefundAmount(refundRequest.getRefundAmount());
}
// 同步部分退款成功后,推进本地状态到部分已退款
refundorder.setStatus(OrderStatus.PART_REFUNDED.getId());
refundorder.setRefundTime(new java.util.Date());
refundService.updateById(refundorder);
order.setOrderStatus(OrderStatus.PART_REFUNDED.getId());
orderService.updateOrder(order);
return Result.succeed("已处理部分退款");
}
if (refundRequest.getState().equals(RefundState.REFUSED.getId())){
@@ -302,6 +356,88 @@ public class RefundController {
}
}
/**
* 按 payType 路由退款到对应渠道
*
* @param order 订单
* @param customAmount 自定义退款金额(null 表示全额退款)
*/
private void routeRefundByPayType(Order order, String customAmount) {
PayTypeEnum channel = PayTypeEnum.getByCode(order.getPayType());
// 历史订单 payType 为 null 的兜底:走微信退款
if (channel == null) {
log.warn("订单 payType 为空,兜底走微信退款,orderNo: {}", order.getOrderNo());
if (customAmount != null) {
dealCustomRefundAmountRequest(order, customAmount);
} else {
dealRefundRequest(order);
}
return;
}
switch (channel) {
case WECHAT_PAY:
if (customAmount != null) {
dealCustomRefundAmountRequest(order, customAmount);
} else {
dealRefundRequest(order);
}
break;
case ALIPAY_PAY:
alipayRefund(order, customAmount);
break;
case COUPON_PAY:
log.info("优惠券支付退款,orderNo: {}", order.getOrderNo());
// 优惠券退款逻辑由现有流程处理
break;
case FEIPAI_VERIFY:
throw new RuntimeException("第三方核销订单不支持系统退款");
default:
throw new RuntimeException("未知支付类型: " + order.getPayType());
}
}
/**
* 支付宝退款
*/
private void alipayRefund(Order order, String customAmount) {
try {
TenantContextHolder.setTenant(order.getTenantId());
// 获取支付宝配置
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", order.getTenantId());
if (config == null) {
log.error("支付宝支付配置不存在,租户ID: {}", order.getTenantId());
throw new RuntimeException("支付宝支付配置不存在");
}
AlipayRefundService.AlipayRefundRequest req = new AlipayRefundService.AlipayRefundRequest();
req.setOutTradeNo(order.getOrderNo());
req.setOutRequestNo("RF" + order.getOrderNo());
req.setRefundReason("用户申请退款");
// 退款金额:DB 与 customAmount 均以"分"存储,支付宝 SDK refund_amount 需要"元"
String refundAmountFen = customAmount != null ? customAmount : order.getOrderAmount();
String refundAmount = StringUtils.fenToYuanAmount(refundAmountFen);
req.setRefundAmount(refundAmount);
com.alipay.api.response.AlipayTradeRefundResponse response = alipayRefundService.refund(config, req);
if (!response.isSuccess()) {
log.error("支付宝退款失败, subCode: {}, subMsg: {}", response.getSubCode(), response.getSubMsg());
throw new RuntimeException("支付宝退款失败: " + response.getSubMsg());
}
log.info("支付宝退款成功,订单号: {}, 退款金额: {}, fundChange: {}",
order.getOrderNo(), refundAmount, response.getFundChange());
} catch (Exception e) {
log.error("支付宝退款请求失败,订单号: {}, 异常: {}", order.getOrderNo(), e.getMessage(), e);
throw new RuntimeException("支付宝退款失败: " + e.getMessage(), e);
} finally {
TenantContextHolder.clear();
}
}
/**
* 微信退款申请
* @param order
@@ -4,6 +4,7 @@ import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.SysUser;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.enums.RefundState;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
@@ -158,6 +159,7 @@ public class WxPayController {
// 2. 更新订单状态
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.WECHAT_PAY.getCode());
order.setPayTime(new Date());
orderService.updateOrder(order);
@@ -220,6 +222,7 @@ public class WxPayController {
// 2. 更新订单状态
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.WECHAT_PAY.getCode());
order.setPayTime(new Date());
orderService.updateOrder(order);
@@ -19,7 +19,17 @@ public enum PayTypeEnum {
/**
* 优惠券支付
*/
COUPON_PAY(2, "优惠券支付");
COUPON_PAY(2, "优惠券支付"),
/**
* 第三方聚到核销(补齐遗留常量)
*/
FEIPAI_VERIFY(3, "第三方聚到核销"),
/**
* 支付宝支付(本期新增)
*/
ALIPAY_PAY(4, "支付宝支付");
private final Integer code;
private final String desc;
@@ -4,8 +4,10 @@ import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.Result;
import com.central.order.feign.fallback.CouponCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
@@ -17,4 +19,10 @@ public interface CouponCenterService {
*/
@PostMapping("/ctrip/dist/order/create")
Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params);
/**
* 退订携程分销订单
*/
@PostMapping("/ctrip/dist/order/cancel/{orderNo}")
Result<String> cancelCtripDistOrder(@PathVariable("orderNo") String orderNo, @RequestParam("reason") String reason);
}
@@ -20,6 +20,12 @@ public class CouponCenterServiceFallbackFactory implements FallbackFactory<Coupo
log.error("调用coupon-center创建携程分销订单失败,params: {}", params, cause);
return Result.failed("调用coupon-center失败: " + cause.getMessage());
}
@Override
public Result<String> cancelCtripDistOrder(String orderNo, String reason) {
log.error("调用coupon-center退订携程分销订单失败,orderNo: {}, reason: {}", orderNo, reason, cause);
return Result.failed("调用coupon-center退订失败: " + cause.getMessage());
}
};
}
}
@@ -0,0 +1,25 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.alipay.entity.AlipayConfig;
import com.central.db.mapper.SuperMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 支付宝配置 Mapper
*
* @author duzhichao
* @date 2026-05-12
*/
@Mapper
public interface AlipayConfigMapper extends SuperMapper<AlipayConfig> {
/**
* 分页查询(支持按 type / tenantId / appId / status 筛选)
*/
List<AlipayConfig> findList(Page<AlipayConfig> page, @Param("p") Map<String, Object> params);
}
@@ -45,6 +45,10 @@ public interface OrderMapper extends SuperMapper<Order> {
// 根据订单编号查询订单信息
Order getOrderByNumber(@Param("orderNumber") String orderNumber);
// 根据订单编号+租户ID查询订单信息(用于支付/退款回调严格隔离)
Order getOrderByNumberAndTenant(@Param("orderNumber") String orderNumber,
@Param("tenantId") String tenantId);
List<Order> findListByUser(Page<Order> page, @Param("p") Map<String, Object> params);
@Select("SELECT \n" +
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
@Schema(description = "订单状态")
private Integer orderStatus;
@Schema(description = "支付类型(1:微信支付,2:优惠券支付, 3: 第三方聚到核销)")
@Schema(description = "支付类型(1:微信支付,2:优惠券支付,3:第三方聚到核销,4:支付宝支付)")
private Integer payType;
private Date payTime;
@@ -0,0 +1,56 @@
package com.central.order.service;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.model.PageResult;
import com.central.common.service.ISuperService;
import java.util.Map;
/**
* 支付宝配置 Service 接口
*
* @author duzhichao
* @date 2026-05-12
*/
public interface IAlipayConfigService extends ISuperService<AlipayConfig> {
/**
* 分页查询
*/
PageResult<AlipayConfig> findList(Map<String, Object> params);
/**
* 根据类型和租户ID查询配置
*/
AlipayConfig getConfigByTypeAndTenantId(String type, String tenantId);
/**
* 根据 AppId 和类型查询配置
*/
AlipayConfig getConfigByAppIdAndType(String appId, String type);
/**
* 根据 AppId 查询配置(不区分类型)
*/
AlipayConfig getConfigByAppId(String appId);
/**
* 根据子商户号查询配置(ISV 模式)
*/
AlipayConfig getConfigBySubMerchantId(String subMerchantId);
/**
* 保存配置
*/
boolean saveConfig(AlipayConfig config);
/**
* 更新配置
*/
boolean updateConfig(AlipayConfig config);
/**
* 删除配置
*/
boolean deleteConfig(Long id);
}
@@ -14,4 +14,12 @@ public interface ICtripDistOrderService {
* @param mobile 用户手机号(可为null,为null时使用默认值)
*/
void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile);
/**
* 异步退订携程分销订单
*
* @param orderNo 本地订单号
* @param reason 退订原因
*/
void cancelCtripDistOrder(String orderNo, String reason);
}
@@ -57,6 +57,11 @@ public interface IOrderService extends ISuperService<Order> {
*/
Order getOrderByNumber(String orderNumber);
/**
* 订单编号+租户ID 查询订单(支付/退款回调严格隔离)
*/
Order getOrderByNumberAndTenant(String orderNumber, String tenantId);
/**
* 订单信息更新
* @param order
@@ -0,0 +1,88 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.mapper.AlipayConfigMapper;
import com.central.order.service.IAlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;
/**
* 支付宝配置 Service 实现
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Service
public class AlipayConfigServiceImpl
extends SuperServiceImpl<AlipayConfigMapper, AlipayConfig>
implements IAlipayConfigService {
@Override
public PageResult<AlipayConfig> findList(Map<String, Object> params) {
Page<AlipayConfig> page = new Page<>(
MapUtils.getInteger(params, "page", 1),
MapUtils.getInteger(params, "limit", 10));
List<AlipayConfig> list = baseMapper.findList(page, params);
return PageResult.<AlipayConfig>builder()
.data(list).resp_code(0).count(page.getTotal()).build();
}
@Override
public AlipayConfig getConfigByTypeAndTenantId(String type, String tenantId) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getType, type)
.eq(AlipayConfig::getTenantId, tenantId)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public AlipayConfig getConfigByAppIdAndType(String appId, String type) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getAppId, appId)
.eq(AlipayConfig::getType, type)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public AlipayConfig getConfigByAppId(String appId) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getAppId, appId)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public AlipayConfig getConfigBySubMerchantId(String subMerchantId) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getSubMerchantId, subMerchantId)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public boolean saveConfig(AlipayConfig config) {
return save(config);
}
@Override
public boolean updateConfig(AlipayConfig config) {
return updateById(config);
}
@Override
public boolean deleteConfig(Long id) {
return removeById(id);
}
}
@@ -41,4 +41,20 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
log.error("携程分销订单创建异常,orderNo: {}", orderNo, e);
}
}
@Async
@Override
public void cancelCtripDistOrder(String orderNo, String reason) {
log.info("开始异步退订携程分销订单,orderNo: {}, reason: {}", orderNo, reason);
try {
Result<String> result = couponCenterService.cancelCtripDistOrder(orderNo, reason);
if (result != null && result.getResp_code() == 0) {
log.info("携程分销订单退订成功,orderNo: {}", orderNo);
} else {
log.error("携程分销订单退订失败,orderNo: {}, result: {}", orderNo, result);
}
} catch (Exception e) {
log.error("携程分销订单退订异常,orderNo: {}", orderNo, e);
}
}
}
@@ -279,6 +279,11 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
return baseMapper.getOrderByNumber(orderNumber);
}
@Override
public Order getOrderByNumberAndTenant(String orderNumber, String tenantId) {
return baseMapper.getOrderByNumberAndTenant(orderNumber, tenantId);
}
@Override
public boolean updateOrder(Order order) {
try {
@@ -1,7 +1,7 @@
package com.central.order.util;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -26,4 +26,16 @@ public class StringUtils {
return "0.00元";
}
}
/**
* 分(字符串)转元(字符串,纯数字,保留两位小数),用于支付宝 SDK total_amount/refund_amount。
*/
public static String fenToYuanAmount(String fenStr) {
if (fenStr == null || fenStr.isEmpty()) {
return "0.00";
}
long fen = Long.parseLong(fenStr.trim());
return new java.math.BigDecimal(fen).movePointLeft(2)
.setScale(2, java.math.RoundingMode.HALF_UP).toPlainString();
}
}
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.order.mapper.AlipayConfigMapper">
<select id="findList" resultType="com.central.alipay.entity.AlipayConfig">
SELECT * FROM alipay_config
<where>
<if test='p.type != null and p.type != ""'>
AND type = #{p.type}
</if>
<if test='p.tenantId != null and p.tenantId != ""'>
AND tenant_id = #{p.tenantId}
</if>
<if test='p.appId != null and p.appId != ""'>
AND app_id = #{p.appId}
</if>
<if test='p.status != null'>
AND status = #{p.status}
</if>
<if test='p.searchKey != null and p.searchKey != "" and p.searchValue != null and p.searchValue != ""'>
<choose>
<when test='p.searchKey == "type"'>
AND type = #{p.searchValue}
</when>
<when test='p.searchKey == "appId"'>
AND app_id LIKE CONCAT('%', #{p.searchValue}, '%')
</when>
<when test='p.searchKey == "tenantId"'>
AND tenant_id LIKE CONCAT('%', #{p.searchValue}, '%')
</when>
</choose>
</if>
</where>
ORDER BY create_time DESC
</select>
</mapper>
@@ -108,4 +108,9 @@
SELECT * FROM orders WHERE order_no = #{orderNumber}
</select>
<!-- 根据订单编号 + 租户ID 查询订单信息(用于支付/退款回调按配置租户严格定位订单) -->
<select id="getOrderByNumberAndTenant" resultMap="OrderResultMap">
SELECT * FROM orders WHERE order_no = #{orderNumber} AND tenant_id = #{tenantId}
</select>
</mapper>
@@ -145,11 +145,53 @@ public class SysUserController {
return appUserService.findByWxOpenid(openId,mobile,unionId);
}
/**
* 根据支付宝userId查询用户信息(Feign内部调用)
* <p>
* 已有用户按 openId 匹配后更新信息返回;新用户自动注册。
*
* @param alipayUserId 支付宝 userId(alipay.system.oauth.token 返回,必填)
* @param unionId 支付宝 union_id(同 PID 下唯一,可选)
* @param mobile 手机号(自动注册时填入,可选)
* @param appId 支付宝应用ID(预留,可选)
* @return SysUser 系统用户对象(含 id/username/mobile/openId/enabled)
*/
@GetMapping(value = "/users-anon/alipayOpenId")
@Operation(summary = "根据支付宝userId查询或注册用户(Feign内部)",
description = "入参:alipayUserId(必填)+unionId+mobile+appId(可选)。"
+ "出参:SysUser 对象。逻辑:已有用户更新信息,新用户自动创建。")
@Parameter(name = "alipayUserId", description = "支付宝 userId(alipay.system.oauth.token 返回)", required = true, example = "2088xxxxxxxxxxxx")
@Parameter(name = "unionId", description = "支付宝 union_id(同 PID 下唯一)")
@Parameter(name = "mobile", description = "手机号(注册时填入)", example = "138xxxx1234")
@Parameter(name = "appId", description = "支付宝应用ID(预留)", example = "2021000000000001")
public SysUser findByAlipayOpenId(@RequestParam("alipayUserId") String alipayUserId,
@RequestParam(required = false) String unionId,
@RequestParam(required = false) String mobile,
@RequestParam(required = false) String appId) throws Exception {
return appUserService.findByAlipayOpenid(alipayUserId, unionId, mobile, appId);
}
@GetMapping("/users/{id}")
public SysUser findUserById(@PathVariable Long id) {
return appUserService.getById(id);
}
/**
* 根据系统用户ID查询支付宝 openId(供 order-center 下单时获取 buyerId)
*
* @param userId 系统用户ID
* @param appId 支付宝应用ID
* @return 支付宝 userId,无映射时返回 null
*/
@GetMapping("/users/{userId}/alipay-openid")
@Operation(summary = "根据系统用户ID查询支付宝openId",
description = "查询 sys_user_third_openid 映射表,获取该用户在指定支付宝应用下的 openId")
@Parameter(name = "userId", description = "系统用户ID", required = true, example = "1001")
@Parameter(name = "appId", description = "支付宝应用ID", required = true, example = "2021000000000001")
public String getAlipayOpenIdByUserId(@PathVariable Long userId, @RequestParam String appId) {
return appUserService.getAlipayOpenIdByUserId(userId, appId);
}
/**
* 管理后台修改用户
*
@@ -0,0 +1,15 @@
package com.central.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.user.model.SysUserThirdOpenid;
import org.apache.ibatis.annotations.Mapper;
/**
* 第三方用户 OpenId 映射 Mapper
*
* @author duzhichao
* @date 2026-05-12
*/
@Mapper
public interface SysUserThirdOpenidMapper extends BaseMapper<SysUserThirdOpenid> {
}
@@ -0,0 +1,43 @@
package com.central.user.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 第三方用户 OpenId 映射表
* <p>
* 统一管理微信/支付宝等各家 openId/userId,与 SysUser.openId 解耦。
*
* @author duzhichao
* @date 2026-05-12
*/
@Data
@TableName("sys_user_third_openid")
@Schema(description = "第三方用户OpenId映射")
public class SysUserThirdOpenid {
@TableId(type = IdType.AUTO)
@Schema(description = "主键")
private Long id;
@Schema(description = "系统用户ID")
private Long userId;
@Schema(description = "第三方平台:WECHAT / ALIPAY", example = "ALIPAY")
private String provider;
@Schema(description = "第三方应用ID")
private String appId;
@Schema(description = "第三方用户唯一标识", example = "2088123456789012")
private String openId;
@Schema(description = "第三方 unionId(微信 unionId / 支付宝 union_id)")
private String unionId;
@Schema(description = "手机号")
private String mobile;
}
@@ -31,6 +31,16 @@ public interface ISysUserService extends ISuperService<SysUser> {
SysUser findByWxOpenid(String wxOpenid,String mobile,String unionId) throws Exception;
/**
* 根据支付宝userId查询用户(关联或自动注册)
*/
SysUser findByAlipayOpenid(String alipayUserId, String unionId, String mobile, String appId) throws Exception;
/**
* 根据系统用户ID查询支付宝 openId(从 sys_user_third_openid 映射表)
*/
String getAlipayOpenIdByUserId(Long userId, String appId);
/**
* 通过SysUser 把roles和permissions也查询出来
* @param sysUser
@@ -5,9 +5,9 @@ import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.lock.DistributedLock;
import com.central.common.lock.ZLock;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysRole;
@@ -22,8 +22,10 @@ import com.central.common.context.LoginUserContextHolder;
import com.central.user.feign.OrderCenterService;
import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserMapper;
import com.central.user.mapper.SysUserThirdOpenidMapper;
import com.central.user.model.SysRoleUser;
import com.central.user.model.SysUserExcel;
import com.central.user.model.SysUserThirdOpenid;
import com.central.user.service.ISysRoleUserService;
import com.central.user.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
@@ -58,6 +60,9 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Resource
private SysRoleMenuMapper roleMenuMapper;
@Resource
private SysUserThirdOpenidMapper sysUserThirdOpenidMapper;
@Autowired
private DistributedLock lock;
@@ -106,15 +111,34 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
sysUser.setMobile(mobile);
}
} else {
// 创建新用户
sysUser = new SysUser();
sysUser.setOpenId(wxOpenid);
sysUser.setUsername(wxOpenid);
sysUser.setType(UserType.APP.name());
sysUser.setPassword(wxOpenid);
sysUser.setEnabled(Boolean.TRUE);
sysUser.setMobile(mobile);
sysUser.setUnionId(unionId);
// 未找到 → 先按手机号匹配已有账号(支付宝用户改用微信登录时自动关联)
sysUser = null;
if (StringUtils.isNotEmpty(mobile)) {
sysUser = this.selectByMobile(mobile);
if (ObjectUtil.isNotEmpty(sysUser)) {
log.info("微信登录按手机号关联已有用户: userId={}, mobile={}", sysUser.getId(), mobile);
// 将微信 openId 写入已有用户
sysUser.setOpenId(wxOpenid);
if (StringUtils.isNotEmpty(unionId)) {
sysUser.setUnionId(unionId);
}
if (StringUtils.isNotEmpty(mobile)) {
sysUser.setMobile(mobile);
}
}
}
if (sysUser == null) {
// 全新用户
sysUser = new SysUser();
sysUser.setOpenId(wxOpenid);
sysUser.setUsername(wxOpenid);
sysUser.setType(UserType.APP.name());
sysUser.setPassword(wxOpenid);
sysUser.setEnabled(Boolean.TRUE);
sysUser.setMobile(mobile);
sysUser.setUnionId(unionId);
}
}
String username = sysUser.getUsername();
@@ -126,6 +150,118 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
return result ? sysUser : new SysUser();
}
@Override
public SysUser findByAlipayOpenid(String alipayUserId, String unionId, String mobile, String appId) throws Exception {
log.info("支付宝登录: alipayUserId={}, unionId={}, mobile={}, appId={}", alipayUserId, unionId, mobile, appId);
// 1. 查 sys_user_third_openid 映射表(不走 SysUser.openId,避免与 grantType=openId 冲突)
QueryWrapper<SysUserThirdOpenid> mappingQuery = new QueryWrapper<SysUserThirdOpenid>()
.eq("provider", "ALIPAY")
.eq("app_id", appId)
.eq("open_id", alipayUserId);
SysUserThirdOpenid mapping = sysUserThirdOpenidMapper.selectOne(mappingQuery);
SysUser sysUser = null;
if (mapping != null) {
// 已有映射 → 查到对应的 SysUser
sysUser = baseMapper.selectById(mapping.getUserId());
if (sysUser == null) {
log.error("sys_user_third_openid 映射存在但 SysUser 不存在: userId={}", mapping.getUserId());
throw new RuntimeException("用户数据异常");
}
// 更新映射信息
if (StringUtils.isNotEmpty(mobile)) {
sysUser.setMobile(mobile);
mapping.setMobile(mobile);
}
if (StringUtils.isNotEmpty(unionId)) {
mapping.setUnionId(unionId);
}
sysUserThirdOpenidMapper.updateById(mapping);
log.info("支付宝用户已存在: userId={}, alipayUserId={}", sysUser.getId(), alipayUserId);
} else {
// 无映射 → 先按手机号匹配已有账号(分布式锁防并发重复创建)
String lockKey = "alipay:user:" + alipayUserId;
ZLock zLock = null;
try {
zLock = lock.tryLock(lockKey, 5, java.util.concurrent.TimeUnit.SECONDS);
if (zLock == null) {
log.warn("获取分布式锁失败,可能并发登录: {}", alipayUserId);
throw new RuntimeException("系统繁忙,请稍后重试");
}
// 双重检查:获取锁后再查一次映射表
SysUserThirdOpenid recheck = sysUserThirdOpenidMapper.selectOne(mappingQuery);
if (recheck != null) {
sysUser = baseMapper.selectById(recheck.getUserId());
} else if (StringUtils.isNotEmpty(mobile)) {
sysUser = selectByMobile(mobile);
if (ObjectUtil.isNotEmpty(sysUser)) {
log.info("按手机号关联已有用户: userId={}, mobile={}", sysUser.getId(), mobile);
sysUser.setMobile(mobile);
super.saveOrUpdateIdempotency(sysUser, lock,
LOCK_KEY_USERNAME + sysUser.getUsername(),
new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()),
sysUser.getUsername() + "已存在");
insertThirdOpenidMapping(sysUser.getId(), "ALIPAY", appId, alipayUserId, unionId, mobile);
}
}
if (sysUser == null) {
sysUser = new SysUser();
sysUser.setUsername("alipay_" + alipayUserId);
sysUser.setType(UserType.APP.name());
sysUser.setPassword(alipayUserId);
sysUser.setEnabled(Boolean.TRUE);
sysUser.setMobile(mobile);
boolean saved = super.saveOrUpdateIdempotency(sysUser, lock,
LOCK_KEY_USERNAME + sysUser.getUsername(),
new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()),
sysUser.getUsername() + "已存在");
if (!saved) { return new SysUser(); }
log.info("创建支付宝新用户: userId={}, alipayUserId={}", sysUser.getId(), alipayUserId);
insertThirdOpenidMapping(sysUser.getId(), "ALIPAY", appId, alipayUserId, unionId, mobile);
}
} catch (Exception e) {
log.error("支付宝用户关联加锁异常", e);
throw new RuntimeException("登录失败: " + e.getMessage(), e);
} finally {
if (zLock != null) {
try { lock.unlock(zLock); } catch (Exception ignored) {}
}
}
}
return sysUser;
}
@Override
public String getAlipayOpenIdByUserId(Long userId, String appId) {
QueryWrapper<SysUserThirdOpenid> query = new QueryWrapper<SysUserThirdOpenid>()
.eq("user_id", userId)
.eq("provider", "ALIPAY")
.eq("app_id", appId);
SysUserThirdOpenid mapping = sysUserThirdOpenidMapper.selectOne(query);
return mapping != null ? mapping.getOpenId() : null;
}
/**
* 插入 sys_user_third_openid 映射记录(依赖 DB 唯一索引 uk_provider_appid_openid 保证幂等)
*/
private void insertThirdOpenidMapping(Long userId, String provider, String appId,
String openId, String unionId, String mobile) {
try {
SysUserThirdOpenid mapping = new SysUserThirdOpenid();
mapping.setUserId(userId);
mapping.setProvider(provider);
mapping.setAppId(appId);
mapping.setOpenId(openId);
mapping.setUnionId(unionId);
mapping.setMobile(mobile);
sysUserThirdOpenidMapper.insert(mapping);
} catch (org.springframework.dao.DuplicateKeyException e) {
log.info("sys_user_third_openid 映射已存在, userId={}, provider={}, openId={}", userId, provider, openId);
}
}
@Override
public void setUserPermission(SysUser sysUser) {
if (sysUser != null) {