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
+4 -1
View File
@@ -99,7 +99,10 @@
"Bash(python -c \"print\\('hello'\\)\")",
"Bash(grep -r \"RightPanel\" src/pages/client/index.tsx)",
"Bash(grep \"statusBar\\\\|statusDot\" src/pages/client/index.tsx)",
"Bash(grep \"routeActions\\\\|routeActionsTitle\" src/pages/client/components/CenterView/index.tsx)"
"Bash(grep \"routeActions\\\\|routeActionsTitle\" src/pages/client/components/CenterView/index.tsx)",
"Read(//c/Users/10989/.m2/repository/com/alipay/**)",
"Bash(\"/e/java/apache-maven-3.9.11-bin/apache-maven-3.9.11/bin/mvn.cmd\" -q -o -pl . compile)",
"Bash(\"/e/java/apache-maven-3.9.11-bin/apache-maven-3.9.11/bin/mvn.cmd\" -q -pl zlt-commons/zlt-alipay-spring-boot-starter -am compile -DskipTests)"
],
"deny": [],
"ask": []
+2
View File
@@ -11,6 +11,8 @@ nacos/
.claude/agents/
.claude/team-collaboration-matrix.md
.reasonix
# Cesium static assets (auto-generated by npm install)
zlt-web/react-web-next/public/cesium/
+7
View File
@@ -0,0 +1,7 @@
{
"permissions": {
"allow": [
"Agent(Explore)"
]
}
}
@@ -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) {
+2
View File
@@ -25,5 +25,7 @@
<module>zlt-zookeeper-spring-boot-starter</module>
<module>zlt-wechat-common-core</module>
<module>zlt-wechat-spring-boot-starter</module>
<module>zlt-alipay-common-core</module>
<module>zlt-alipay-spring-boot-starter</module>
</modules>
</project>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>6.0.0</version>
</parent>
<artifactId>zlt-alipay-common-core</artifactId>
<description>支付宝核心功能模块(实体、Feign接口、配置属性)</description>
<dependencies>
<!-- 基础依赖 -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-common-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-db-spring-boot-starter</artifactId>
</dependency>
<!-- Knife4j (Swagger annotations) -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,55 @@
package com.central.alipay.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 支付宝全局配置属性(仅承载全局默认值,运行时配置走 alipay_config 表)
*
* @author duzhichao
* @date 2026-05-12
*/
@Data
@ConfigurationProperties(prefix = "zlt.alipay")
public class AlipayProperties {
/**
* 是否启用支付宝模块
*/
private boolean enabled = true;
/**
* 网关地址
*/
private String gatewayUrl = "https://openapi.alipay.com/gateway.do";
/**
* 签名算法
*/
private String signType = "RSA2";
/**
* 字符集
*/
private String charset = "UTF-8";
/**
* 格式
*/
private String format = "json";
/**
* AlipayClient 缓存过期时间(秒)
*/
private int cacheExpireSeconds = 600;
/**
* 支付异步通知地址(全局默认,可被 DB 覆盖)
*/
private String notifyUrl;
/**
* 退款异步通知地址(全局默认,可被 DB 覆盖)
*/
private String refundNotifyUrl;
}
@@ -0,0 +1,92 @@
package com.central.alipay.entity;
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;
/**
* 支付宝配置实体(对标 WechatConfig)
*
* @author duzhichao
* @date 2026-05-12
*/
@Data
@TableName("alipay_config")
@Schema(description = "支付宝配置")
public class AlipayConfig {
@TableId(type = IdType.AUTO)
@Schema(description = "主键ID", example = "1")
private Long id;
@Schema(description = "租户ID", example = "tenant-001")
private String tenantId;
@Schema(description = "配置类型:MINI=小程序登录,PAY=交易支付", example = "PAY", allowableValues = {"MINI", "PAY"})
private String type;
@Schema(description = "支付宝 AppId", example = "2021000000000001")
private String appId;
@Schema(description = "应用私钥(PKCS8,入库加密)", accessMode = Schema.AccessMode.WRITE_ONLY)
private String appPrivateKey;
@Schema(description = "支付宝公钥(用于回调验签)", accessMode = Schema.AccessMode.WRITE_ONLY)
private String alipayPublicKey;
@Schema(description = "签名算法", example = "RSA2", allowableValues = {"RSA2", "RSA"})
private String signType;
@Schema(description = "字符集", example = "UTF-8")
private String charset;
@Schema(description = "格式", example = "json")
private String format;
@Schema(description = "网关地址", example = "https://openapi.alipay.com/gateway.do")
private String gatewayUrl;
@Schema(description = "支付异步通知地址(type=PAY 时有效)", example = "https://api.example.com/alipay/pay/notify")
private String notifyUrl;
@Schema(description = "退款异步通知地址(type=PAY 时有效)", example = "https://api.example.com/alipay/refund/notify")
private String refundNotifyUrl;
@Schema(description = "是否 ISV(服务商)模式", example = "false")
private Boolean isServiceMode;
@Schema(description = "ISV 合作伙伴 PID", example = "2088xxxxxxxxxxxx")
private String pid;
@Schema(description = "ISV 代调用时使用的 app_auth_token", accessMode = Schema.AccessMode.WRITE_ONLY)
private String authToken;
@Schema(description = "商家应用 AppId(被代调用方)", example = "2021xxxxxxxxxxxx")
private String subAppId;
@Schema(description = "间连商户号 smid", example = "2088xxxxxxxxxxxx")
private String subMerchantId;
@Schema(description = "AES 接口内容加解密 Key", accessMode = Schema.AccessMode.WRITE_ONLY)
private String encryptKey;
@Schema(description = "是否公钥证书模式", example = "false")
private Boolean certMode;
@Schema(description = "应用公钥证书路径(证书模式)")
private String appCertPath;
@Schema(description = "支付宝公钥证书路径(证书模式)")
private String alipayCertPath;
@Schema(description = "支付宝根证书路径(证书模式)")
private String alipayRootCertPath;
@Schema(description = "状态:0=禁用,1=启用", example = "1", allowableValues = {"0", "1"})
private Integer status;
@Schema(description = "备注", example = "生产环境支付配置")
private String remark;
}
@@ -0,0 +1,43 @@
package com.central.alipay.feign;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.fallback.AlipayConfigServiceFallbackFactory;
import com.central.common.constant.ServiceNameConstants;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 支付宝配置 Feign 客户端(服务端在 order-center)
*
* @author duzhichao
* @date 2026-05-12
*/
@FeignClient(name = ServiceNameConstants.ORDER_SERVICE, fallbackFactory = AlipayConfigServiceFallbackFactory.class, dismiss404 = true)
public interface AlipayConfigService {
/**
* 根据类型和租户ID查询配置
*/
@GetMapping(value = "/alipay/config/type/{type}")
AlipayConfig getConfig(@PathVariable("type") String type, @RequestParam("tenantId") String tenantId);
/**
* 根据 AppId 和类型查询配置
*/
@GetMapping(value = "/alipay/config/app/{appId}")
AlipayConfig getConfigByAppId(@PathVariable("appId") String appId, @RequestParam("type") String type);
/**
* 根据 AppId 查询配置(不区分类型,用于回调定位)
*/
@GetMapping(value = "/alipay/config/app/{appId}/any")
AlipayConfig getConfigByAppId(@PathVariable("appId") String appId);
/**
* 根据子商户号获取配置(ISV 模式专用)
*/
@GetMapping(value = "/alipay/config/sub/{subMerchantId}")
AlipayConfig getConfigBySubMerchantId(@PathVariable("subMerchantId") String subMerchantId);
}
@@ -0,0 +1,42 @@
package com.central.alipay.feign.fallback;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.AlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
/**
* AlipayConfigService 降级工厂
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
public class AlipayConfigServiceFallbackFactory implements FallbackFactory<AlipayConfigService> {
@Override
public AlipayConfigService create(Throwable throwable) {
log.error("AlipayConfigService 调用失败", throwable);
return new AlipayConfigService() {
@Override
public AlipayConfig getConfig(String type, String tenantId) {
return null;
}
@Override
public AlipayConfig getConfigByAppId(String appId, String type) {
return null;
}
@Override
public AlipayConfig getConfigByAppId(String appId) {
return null;
}
@Override
public AlipayConfig getConfigBySubMerchantId(String subMerchantId) {
return null;
}
};
}
}
@@ -0,0 +1 @@
com.central.alipay.feign.fallback.AlipayConfigServiceFallbackFactory
@@ -0,0 +1,37 @@
-- =====================================================
-- 支付宝配置表(对标 wechat_config)
-- 归属:order-center
-- =====================================================
CREATE TABLE IF NOT EXISTS `alipay_config` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
`type` VARCHAR(16) NOT NULL COMMENT '配置类型:MINI-小程序登录,PAY-交易支付',
`app_id` VARCHAR(64) NOT NULL COMMENT '支付宝 AppId',
`app_private_key` TEXT COMMENT '应用私钥(PKCS8,入库建议加密)',
`alipay_public_key` TEXT COMMENT '支付宝公钥(用于回调验签)',
`sign_type` VARCHAR(16) DEFAULT 'RSA2' COMMENT '签名算法',
`charset` VARCHAR(16) DEFAULT 'UTF-8' COMMENT '字符集',
`format` VARCHAR(16) DEFAULT 'json' COMMENT '格式',
`gateway_url` VARCHAR(256) DEFAULT 'https://openapi.alipay.com/gateway.do' COMMENT '网关地址',
`notify_url` VARCHAR(256) DEFAULT NULL COMMENT '支付异步通知地址',
`refund_notify_url` VARCHAR(256) DEFAULT NULL COMMENT '退款异步通知地址',
`is_service_mode` TINYINT(1) DEFAULT 0 COMMENT '是否 ISV(服务商)模式',
`pid` VARCHAR(64) DEFAULT NULL COMMENT 'ISV 合作伙伴 PID',
`auth_token` VARCHAR(128) DEFAULT NULL COMMENT 'ISV 代调用时使用的 app_auth_token',
`sub_app_id` VARCHAR(64) DEFAULT NULL COMMENT '商家应用 AppId(被代调用方)',
`sub_merchant_id` VARCHAR(64) DEFAULT NULL COMMENT '间连商户号(smid)',
`encrypt_key` VARCHAR(128) DEFAULT NULL COMMENT 'AES 接口内容加解密 Key',
`cert_mode` TINYINT(1) DEFAULT 0 COMMENT '是否公钥证书模式:0-普通公钥,1-证书模式',
`app_cert_path` VARCHAR(256) DEFAULT NULL COMMENT '应用公钥证书路径',
`alipay_cert_path` VARCHAR(256) DEFAULT NULL COMMENT '支付宝公钥证书路径',
`alipay_root_cert_path` VARCHAR(256) DEFAULT NULL COMMENT '支付宝根证书路径',
`status` TINYINT DEFAULT 1 COMMENT '状态:0-禁用,1-启用',
`remark` VARCHAR(255) DEFAULT NULL COMMENT '备注',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_tenant_type_appid` (`tenant_id`, `type`, `app_id`),
KEY `idx_tenant_type` (`tenant_id`, `type`),
KEY `idx_app_id` (`app_id`),
KEY `idx_sub_merchant_id` (`sub_merchant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='支付宝配置表';
@@ -0,0 +1,18 @@
-- =====================================================
-- 第三方用户 OpenId 映射表
-- 统一管理微信/支付宝等各家 openId/unionId
-- =====================================================
CREATE TABLE IF NOT EXISTS `sys_user_third_openid` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` BIGINT NOT NULL COMMENT '系统用户ID',
`provider` VARCHAR(16) NOT NULL COMMENT '第三方平台:WECHAT / ALIPAY',
`app_id` VARCHAR(64) NOT NULL COMMENT '第三方应用ID',
`open_id` VARCHAR(128) NOT NULL COMMENT '第三方用户唯一标识',
`union_id` VARCHAR(128) DEFAULT NULL COMMENT '第三方 unionId(微信开放平台 unionId / 支付宝 PID 下 union_id)',
`mobile` VARCHAR(20) DEFAULT NULL COMMENT '手机号',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_provider_appid_openid` (`provider`, `app_id`, `open_id`),
KEY `idx_user_provider` (`user_id`, `provider`),
KEY `idx_provider_unionid` (`provider`, `union_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='第三方用户OpenId映射表';
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>6.0.0</version>
</parent>
<artifactId>zlt-alipay-spring-boot-starter</artifactId>
<description>支付宝 Spring Boot 启动器(SDK 工厂 + 登录/支付/退款服务)</description>
<dependencies>
<!-- 支付宝核心模块 -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-alipay-common-core</artifactId>
<version>${project.version}</version>
</dependency>
<!-- 支付宝 SDK -->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.40.816.ALL</version>
</dependency>
<!-- Spring Boot 相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,58 @@
package com.central.alipay.config;
import com.central.alipay.notify.AlipayNotifyVerifier;
import com.central.alipay.service.AlipayLoginService;
import com.central.alipay.service.AlipayPayService;
import com.central.alipay.service.AlipayRefundService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 支付宝模块自动配置
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(AlipayProperties.class)
@AutoConfigureAfter({FeignAutoConfiguration.class, WebMvcAutoConfiguration.class})
@ConditionalOnProperty(prefix = "zlt.alipay", name = "enabled", havingValue = "true", matchIfMissing = true)
public class AlipayAutoConfiguration {
@Bean
public AlipayClientFactory alipayClientFactory() {
log.info("AlipayClientFactory 已加载");
return new AlipayClientFactory();
}
@Bean
public AlipayLoginService alipayLoginService() {
log.info("AlipayLoginService 已加载");
return new AlipayLoginService();
}
@Bean
public AlipayPayService alipayPayService() {
log.info("AlipayPayService 已加载");
return new AlipayPayService();
}
@Bean
public AlipayRefundService alipayRefundService() {
log.info("AlipayRefundService 已加载");
return new AlipayRefundService();
}
@Bean
public AlipayNotifyVerifier alipayNotifyVerifier() {
log.info("AlipayNotifyVerifier 已加载");
return new AlipayNotifyVerifier();
}
}
@@ -0,0 +1,157 @@
package com.central.alipay.config;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.AlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 支付宝客户端工厂(多租户 AlipayClient 缓存)
* <p>
* 对标 WxPayConfigFactory 的设计模式:
* - ConcurrentHashMap 按 (appId, subMerchantId) 缓存 AlipayClient
* - 支持普通直连模式与 ISV(服务商)模式
* - 支持普通公钥模式与证书模式
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
public class AlipayClientFactory {
@Autowired
private AlipayConfigService alipayConfigService;
@Autowired
private AlipayProperties alipayProperties;
/**
* AlipayClient 缓存(key: appId + "::" + (subMerchantId|""))
*/
private final Map<String, AlipayClient> clientCache = new ConcurrentHashMap<>();
/**
* 根据租户ID获取 AlipayClient(直连模式)
*/
public AlipayClient getClient(String tenantId) {
AlipayConfig config = alipayConfigService.getConfig("PAY", tenantId);
if (config == null) {
throw new RuntimeException("支付宝支付配置不存在,tenantId: " + tenantId);
}
return createAlipayClient(config);
}
/**
* 根据子商户号获取 AlipayClient(ISV 模式)
*/
public AlipayClient getClientBySubMerchantId(String subMerchantId) {
AlipayConfig config = alipayConfigService.getConfigBySubMerchantId(subMerchantId);
if (config == null) {
throw new RuntimeException("未找到子商户支付宝配置: " + subMerchantId);
}
return createAlipayClient(config);
}
/**
* 根据 AlipayConfig 创建(或从缓存中读取)AlipayClient
*/
public AlipayClient createAlipayClient(AlipayConfig config) {
String cacheKey = buildCacheKey(config);
return clientCache.computeIfAbsent(cacheKey, k -> doBuild(config));
}
/**
* 清除指定 appId+subMerchantId 的缓存(配置变更时调用)
*/
public void clearCache(AlipayConfig config) {
String key = buildCacheKey(config);
clientCache.remove(key);
log.info("清除支付宝客户端缓存,key: {}", key);
}
/**
* 清除所有缓存
*/
public void clearAllCache() {
clientCache.clear();
log.info("清除所有支付宝客户端缓存");
}
private String buildCacheKey(AlipayConfig config) {
String sub = config.getSubMerchantId() != null ? config.getSubMerchantId() : "";
return config.getAppId() + "::" + sub;
}
private AlipayClient doBuild(AlipayConfig config) {
String gatewayUrl = config.getGatewayUrl() != null
? config.getGatewayUrl() : alipayProperties.getGatewayUrl();
String signType = config.getSignType() != null
? config.getSignType() : alipayProperties.getSignType();
String charset = config.getCharset() != null
? config.getCharset() : alipayProperties.getCharset();
String format = config.getFormat() != null
? config.getFormat() : alipayProperties.getFormat();
String appPrivateKey = config.getAppPrivateKey();
if (appPrivateKey == null || appPrivateKey.isEmpty()) {
throw new RuntimeException("应用私钥不能为空,appId: " + config.getAppId());
}
if (Boolean.TRUE.equals(config.getCertMode())) {
return buildCertClient(config, gatewayUrl, signType, charset, format, appPrivateKey);
}
String alipayPublicKey = config.getAlipayPublicKey();
if (alipayPublicKey == null || alipayPublicKey.isEmpty()) {
throw new RuntimeException("支付宝公钥不能为空,appId: " + config.getAppId());
}
log.info("创建支付宝客户端(公钥模式),appId: {}, subMerchantId: {}",
config.getAppId(), config.getSubMerchantId());
return new DefaultAlipayClient(
gatewayUrl,
config.getAppId(),
appPrivateKey,
format,
charset,
alipayPublicKey,
signType
);
}
private AlipayClient buildCertClient(AlipayConfig config,
String gatewayUrl, String signType, String charset,
String format, String appPrivateKey) {
if (config.getAppCertPath() == null || config.getAlipayCertPath() == null
|| config.getAlipayRootCertPath() == null) {
throw new RuntimeException("证书模式下 appCertPath/alipayCertPath/alipayRootCertPath 不能为空, appId: "
+ config.getAppId());
}
try {
CertAlipayRequest req = new CertAlipayRequest();
req.setServerUrl(gatewayUrl);
req.setAppId(config.getAppId());
req.setPrivateKey(appPrivateKey);
req.setFormat(format);
req.setCharset(charset);
req.setSignType(signType);
req.setCertPath(config.getAppCertPath());
req.setAlipayPublicCertPath(config.getAlipayCertPath());
req.setRootCertPath(config.getAlipayRootCertPath());
// encryptKey 在 SDK 4.38+ 已从 CertAlipayRequest 移除,
// 加解密 Key 需通过 DefaultAlipayClient 构造后单独设置或走支付宝后台配置
log.info("创建支付宝客户端(证书模式),appId: {}, subMerchantId: {}",
config.getAppId(), config.getSubMerchantId());
return new DefaultAlipayClient(req);
} catch (AlipayApiException e) {
throw new RuntimeException("证书模式 AlipayClient 创建失败: " + e.getErrMsg(), e);
}
}
}
@@ -0,0 +1,59 @@
package com.central.alipay.config;
import lombok.extern.slf4j.Slf4j;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
/**
* 支付宝私钥工具类
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
public class AlipayPrivateKeyUtils {
/**
* 从 PKCS8 格式的私钥字符串加载 PrivateKey
*/
public static PrivateKey getPrivateKey(String privateKeyStr) {
if (privateKeyStr == null || privateKeyStr.trim().isEmpty()) {
throw new IllegalArgumentException("私钥字符串不能为空");
}
try {
String privateKeyPEM = privateKeyStr
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");
byte[] decoded = Base64.getDecoder().decode(privateKeyPEM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(keySpec);
} catch (IllegalArgumentException e) {
log.error("私钥格式错误: {}", e.getMessage());
throw new IllegalArgumentException("私钥格式错误: " + e.getMessage(), e);
} catch (Exception e) {
log.error("解析私钥失败", e);
throw new RuntimeException("解析私钥失败: " + e.getMessage(), e);
}
}
/**
* 移除 PEM 头尾标记并去除空白
*/
public static String cleanPemKey(String key) {
if (key == null) {
return null;
}
return key.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s+", "");
}
}
@@ -0,0 +1,63 @@
package com.central.alipay.notify;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.central.alipay.entity.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 支付宝异步回调验签器
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Component
public class AlipayNotifyVerifier {
/**
* 验证支付宝回调签名
* <p>
* 自动根据配置选择验签方式:
* - certMode=true:使用 rsaCertCheckV1(基于支付宝公钥证书路径 alipayCertPath)
* - certMode=false:使用 rsaCheckV1(基于支付宝公钥 alipayPublicKey)
*
* @param params 回调参数(从 HttpServletRequest 收集)
* @param config 支付宝配置
* @return true-验签通过,false-验签失败
*/
public boolean verify(Map<String, String> params, AlipayConfig config) {
try {
String signType = config.getSignType() != null ? config.getSignType() : "RSA2";
String charset = config.getCharset() != null ? config.getCharset() : "UTF-8";
boolean result;
if (Boolean.TRUE.equals(config.getCertMode())) {
String alipayCertPath = config.getAlipayCertPath();
if (alipayCertPath == null || alipayCertPath.isEmpty()) {
log.error("证书模式下 alipayCertPath 为空,无法验签, appId: {}", config.getAppId());
return false;
}
result = AlipaySignature.rsaCertCheckV1(params, alipayCertPath, charset, signType);
} else {
String alipayPublicKey = config.getAlipayPublicKey();
if (alipayPublicKey == null || alipayPublicKey.isEmpty()) {
log.error("支付宝公钥为空,无法验签, appId: {}", config.getAppId());
return false;
}
result = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
}
if (!result) {
log.warn("支付宝回调验签失败, appId: {}, signType: {}, certMode: {}",
config.getAppId(), signType, config.getCertMode());
}
return result;
} catch (AlipayApiException e) {
log.error("支付宝回调验签异常", e);
return false;
}
}
}
@@ -0,0 +1,182 @@
package com.central.alipay.service;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 支付宝小程序登录服务
* <p>
* 封装支付宝 code → user_id 的完整流程:
* 1. alipay.system.oauth.token 用 auth_code 换 access_token + user_id
* 2. alipay.user.info.share 获取用户信息(unionId/avatar/nickName,不含手机号)
* 3. 可选:本地 AES 解密手机号(前端 my.getPhoneNumber 返回的 response 字段,使用商家 encryptKey 解密)
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Service
public class AlipayLoginService {
@Autowired
private AlipayClientFactory clientFactory;
/**
* 小程序登录结果
*/
public static class AlipayLoginResult {
private String userId;
private String openId;
private String unionId;
private String mobile;
private String avatar;
private String nickName;
public AlipayLoginResult(String userId, String openId) {
this.userId = userId;
this.openId = openId;
}
public String getUserId() { return userId; }
public void setUserId(String userId) { this.userId = userId; }
public String getOpenId() { return openId; }
public void setOpenId(String openId) { this.openId = openId; }
public String getUnionId() { return unionId; }
public void setUnionId(String unionId) { this.unionId = unionId; }
public String getMobile() { return mobile; }
public void setMobile(String mobile) { this.mobile = mobile; }
public String getAvatar() { return avatar; }
public void setAvatar(String avatar) { this.avatar = avatar; }
public String getNickName() { return nickName; }
public void setNickName(String nickName) { this.nickName = nickName; }
}
/**
* 通过小程序 auth_code 换取用户标识
*
* @param config 支付宝配置
* @param code 小程序 auth_code
* @return 登录结果(userId, openId, unionId)
*/
public AlipayLoginResult code2userId(AlipayConfig config, String code) {
AlipayClient client = clientFactory.createAlipayClient(config);
// 1. 用 auth_code 换取 access_token
AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();
tokenRequest.setCode(code);
tokenRequest.setGrantType("authorization_code");
AlipaySystemOauthTokenResponse tokenResponse;
try {
tokenResponse = client.execute(tokenRequest);
} catch (AlipayApiException e) {
log.error("支付宝获取 access_token 失败", e);
throw new RuntimeException("支付宝登录失败: " + e.getErrMsg(), e);
}
if (!tokenResponse.isSuccess()) {
log.error("支付宝获取 access_token 失败, subCode: {}, subMsg: {}",
tokenResponse.getSubCode(), tokenResponse.getSubMsg());
throw new RuntimeException("支付宝登录失败: " + tokenResponse.getSubMsg());
}
String accessToken = tokenResponse.getAccessToken();
String userId = tokenResponse.getUserId();
String openId = tokenResponse.getOpenId();
log.info("支付宝登录成功, userId: {}, openId: {}", userId, openId);
AlipayLoginResult result = new AlipayLoginResult(userId, openId);
// 2. 获取用户信息(union_id / avatar / nickName)
// 使用 JSON 解析 response body,兼容不同 SDK 版本的 getter 差异
// 注意:alipay.user.info.share 不返回手机号,手机号需通过 decryptPhone 单独获取
try {
AlipayUserInfoShareRequest infoRequest = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse infoResponse = client.execute(infoRequest, accessToken);
if (infoResponse.isSuccess()) {
String body = infoResponse.getBody();
JSONObject respJson = JSONObject.parseObject(body);
// 从响应 JSON 中提取 alipay_user_info_share_response 节点
JSONObject shareResp = respJson.getJSONObject("alipay_user_info_share_response");
if (shareResp != null && "10000".equals(shareResp.getString("code"))) {
result.setUnionId(shareResp.getString("union_id"));
result.setAvatar(shareResp.getString("avatar"));
result.setNickName(shareResp.getString("nick_name"));
log.info("支付宝用户信息获取成功, unionId: {}", result.getUnionId());
}
}
} catch (Exception e) {
log.warn("获取支付宝用户信息失败(不影响登录流程): {}", e.getMessage());
}
return result;
}
/**
* 解密支付宝小程序加密手机号
* <p>
* 前端 my.getPhoneNumber 回调返回 { response, sign },其中 response 是
* 一段已用商家 AES 密钥加密的密文(或一个外层 JSON 包裹该密文)。
* 支付宝官方对小程序手机号采用商家本地 AES 解密的方式(不存在
* alipay.user.phone.number.decrypt 这个开放接口),密钥即 AlipayConfig.encryptKey。
*
* @param config 支付宝配置(须设置 encryptKey)
* @param encryptedResponse my.getPhoneNumber 返回的 response 字段
* @return 明文手机号;解密失败返回 null
*/
public String decryptPhone(AlipayConfig config, String encryptedResponse) {
if (encryptedResponse == null || encryptedResponse.isEmpty()) {
return null;
}
if (config == null || config.getEncryptKey() == null || config.getEncryptKey().isEmpty()) {
log.error("支付宝手机号解密失败:缺少 AES 加解密密钥(encryptKey)");
return null;
}
// 兼容两种入参:完整外层 JSON 报文 或 已提取的内层密文
String cipherText = encryptedResponse.trim();
if (cipherText.startsWith("{")) {
try {
JSONObject outer = JSONObject.parseObject(cipherText);
String inner = outer.getString("response");
if (inner != null && !inner.isEmpty()) {
cipherText = inner;
}
} catch (Exception e) {
log.warn("支付宝手机号解密:外层 JSON 解析失败,按密文直接解密,msg={}", e.getMessage());
}
}
String charset = (config.getCharset() == null || config.getCharset().isEmpty())
? "UTF-8" : config.getCharset();
try {
String plain = AlipayEncrypt.decryptContent(cipherText, "AES", config.getEncryptKey(), charset);
JSONObject decryptResp = JSONObject.parseObject(plain);
if (decryptResp == null || !"10000".equals(decryptResp.getString("code"))) {
log.error("支付宝手机号解密结果非成功, body: {}", plain);
return null;
}
return decryptResp.getString("mobile");
} catch (AlipayApiException e) {
log.error("支付宝手机号 AES 解密异常", e);
return null;
} catch (Exception e) {
log.error("解析支付宝手机号解密结果异常", e);
return null;
}
}
}
@@ -0,0 +1,161 @@
package com.central.alipay.service;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 支付宝支付服务
* <p>
* 封装支付宝交易相关接口:
* - alipay.trade.create(小程序下单)
* - alipay.trade.query(订单查询)
* - alipay.trade.close(订单关闭)
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Service
public class AlipayPayService {
@Autowired
private AlipayClientFactory clientFactory;
/**
* 统一下单请求参数
*/
public static class AlipayPayRequest {
private String outTradeNo;
private String totalAmount;
private String subject;
private String buyerId;
private String body;
private String timeoutExpress;
private String subMerchantId; // ISV 模式
public String getOutTradeNo() { return outTradeNo; }
public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; }
public String getTotalAmount() { return totalAmount; }
public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; }
public String getSubject() { return subject; }
public void setSubject(String subject) { this.subject = subject; }
public String getBuyerId() { return buyerId; }
public void setBuyerId(String buyerId) { this.buyerId = buyerId; }
public String getBody() { return body; }
public void setBody(String body) { this.body = body; }
public String getTimeoutExpress() { return timeoutExpress; }
public void setTimeoutExpress(String timeoutExpress) { this.timeoutExpress = timeoutExpress; }
public String getSubMerchantId() { return subMerchantId; }
public void setSubMerchantId(String subMerchantId) { this.subMerchantId = subMerchantId; }
}
/**
* 统一下单(alipay.trade.create)
* <p>
* 支付宝小程序通过此接口获取 tradeNo,前端再调用 my.tradePay 完成支付
*/
public AlipayTradeCreateResponse create(AlipayConfig config, AlipayPayRequest req) {
AlipayClient client = clientFactory.createAlipayClient(config);
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", req.getOutTradeNo());
bizContent.put("total_amount", req.getTotalAmount());
bizContent.put("subject", req.getSubject());
// 小程序内拉起 my.tradePay 的标准 product_code,缺失会导致部分场景下单失败
bizContent.put("product_code", "JSAPI_PAY");
if (req.getBuyerId() != null) {
bizContent.put("buyer_id", req.getBuyerId());
}
if (req.getBody() != null) {
bizContent.put("body", req.getBody());
}
if (req.getTimeoutExpress() != null) {
bizContent.put("timeout_express", req.getTimeoutExpress());
}
// ISV 模式:设置子商户信息
if (Boolean.TRUE.equals(config.getIsServiceMode()) && req.getSubMerchantId() != null) {
JSONObject extendParams = new JSONObject();
extendParams.put("sub_merchant_id", req.getSubMerchantId());
bizContent.put("extend_params", extendParams);
}
request.setBizContent(bizContent.toJSONString());
// ISV 模式:设置 app_auth_token
if (Boolean.TRUE.equals(config.getIsServiceMode()) && config.getAuthToken() != null) {
request.putOtherTextParam("app_auth_token", config.getAuthToken());
}
if (config.getNotifyUrl() != null) {
request.setNotifyUrl(config.getNotifyUrl());
}
try {
AlipayTradeCreateResponse response = client.execute(request);
if (response.isSuccess()) {
log.info("支付宝下单成功, outTradeNo: {}, tradeNo: {}",
response.getOutTradeNo(), response.getTradeNo());
} else {
log.error("支付宝下单失败, subCode: {}, subMsg: {}",
response.getSubCode(), response.getSubMsg());
}
return response;
} catch (AlipayApiException e) {
log.error("支付宝下单异常", e);
throw new RuntimeException("支付宝下单失败: " + e.getErrMsg(), e);
}
}
/**
* 订单查询(alipay.trade.query)
*/
public AlipayTradeQueryResponse query(AlipayConfig config, String outTradeNo) {
AlipayClient client = clientFactory.createAlipayClient(config);
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", outTradeNo);
request.setBizContent(bizContent.toJSONString());
try {
return client.execute(request);
} catch (AlipayApiException e) {
log.error("支付宝订单查询异常", e);
throw new RuntimeException("支付宝订单查询失败: " + e.getErrMsg(), e);
}
}
/**
* 订单关闭(alipay.trade.close)
*/
public AlipayTradeCloseResponse close(AlipayConfig config, String outTradeNo) {
AlipayClient client = clientFactory.createAlipayClient(config);
AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", outTradeNo);
request.setBizContent(bizContent.toJSONString());
try {
return client.execute(request);
} catch (AlipayApiException e) {
log.error("支付宝订单关闭异常", e);
throw new RuntimeException("支付宝订单关闭失败: " + e.getErrMsg(), e);
}
}
}
@@ -0,0 +1,88 @@
package com.central.alipay.service;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 支付宝退款服务
* <p>
* 封装 alipay.trade.refund 接口(同步退款,直接返回结果)
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Service
public class AlipayRefundService {
@Autowired
private AlipayClientFactory clientFactory;
/**
* 退款请求参数
*/
public static class AlipayRefundRequest {
private String outTradeNo;
private String refundAmount;
private String outRequestNo;
private String refundReason;
public String getOutTradeNo() { return outTradeNo; }
public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; }
public String getRefundAmount() { return refundAmount; }
public void setRefundAmount(String refundAmount) { this.refundAmount = refundAmount; }
public String getOutRequestNo() { return outRequestNo; }
public void setOutRequestNo(String outRequestNo) { this.outRequestNo = outRequestNo; }
public String getRefundReason() { return refundReason; }
public void setRefundReason(String refundReason) { this.refundReason = refundReason; }
}
/**
* 退款(alipay.trade.refund)
* <p>
* 支付宝退款为同步接口,调用后直接返回 fund_change=Y/N
*/
public AlipayTradeRefundResponse refund(AlipayConfig config, AlipayRefundRequest req) {
AlipayClient client = clientFactory.createAlipayClient(config);
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
JSONObject bizContent = new JSONObject();
bizContent.put("out_trade_no", req.getOutTradeNo());
bizContent.put("refund_amount", req.getRefundAmount());
if (req.getOutRequestNo() != null) {
bizContent.put("out_request_no", req.getOutRequestNo());
}
if (req.getRefundReason() != null) {
bizContent.put("refund_reason", req.getRefundReason());
}
request.setBizContent(bizContent.toJSONString());
// alipay.trade.refund 为同步接口,refundNotifyUrl 仅用于日志记录;
// 异步退款通知地址需在支付宝商户后台配置,不通过 SDK 参数传递
try {
AlipayTradeRefundResponse response = client.execute(request);
if (response.isSuccess()) {
log.info("支付宝退款成功, outTradeNo: {}, refundAmount: {}, fundChange: {}",
req.getOutTradeNo(), req.getRefundAmount(), response.getFundChange());
} else {
log.error("支付宝退款失败, subCode: {}, subMsg: {}",
response.getSubCode(), response.getSubMsg());
}
return response;
} catch (AlipayApiException e) {
log.error("支付宝退款异常", e);
throw new RuntimeException("支付宝退款失败: " + e.getErrMsg(), e);
}
}
}
@@ -0,0 +1,54 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import java.util.Collection;
/**
* 支付宝小程序登录 Token(对标 TencentAuthenticationToken)
*
* @author duzhichao
* @date 2026-05-12
*/
@Getter
public class AlipayAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("alipay");
private final Object principal;
private final String encryptedPhone;
private final String appCode;
/**
* 未认证构造(code 模式)
* <p>
* 不能在此构造函数中设置 authenticated=true:此时仅持有 code/encryptedPhone/appCode,
* 真正的用户身份必须由 AlipayAuthenticationProvider 调用支付宝接口换取后再产生。
*/
public AlipayAuthenticationToken(String code, String encryptedPhone, String appCode) {
super(GRANT_TYPE);
this.principal = code;
this.encryptedPhone = encryptedPhone;
this.appCode = appCode;
super.setAuthenticated(false);
}
/**
* 已认证构造(UserDetails 模式)
* <p>
* 由 Provider 在完成支付宝换登录态 + 用户加载后调用,标记为已认证。
*/
public AlipayAuthenticationToken(UserDetails user,
Collection<? extends GrantedAuthority> authorities,
String encryptedPhone,
String appCode) {
super(authorities);
this.principal = user;
this.encryptedPhone = encryptedPhone;
this.appCode = appCode;
super.setAuthenticated(true);
}
}
@@ -93,6 +93,31 @@ public interface UserService {
@GetMapping(value = "/tenant/hierarchy/son/tenantId", params = "tenantId")
List<String> getSonTenantIds(@RequestParam("tenantId") String tenantId);
/**
* 根据支付宝用户ID查询用户信息
*
* @param alipayUserId 支付宝用户唯一标识
* @param unionId 支付宝unionId
* @param mobile 手机号
* @param appId 支付宝应用ID
*/
@GetMapping(value = "/users-anon/alipayOpenId", params = {"alipayUserId"})
SysUser findByAlipayOpenId(@RequestParam("alipayUserId") String alipayUserId,
@RequestParam(value = "unionId", required = false) String unionId,
@RequestParam(value = "mobile", required = false) String mobile,
@RequestParam(value = "appId", required = false) String appId);
/**
* 根据系统用户ID查询支付宝 openId
*
* @param userId 系统用户ID
* @param appId 支付宝应用ID
* @return 支付宝 userId,无映射时返回 null
*/
@GetMapping(value = "/users/{userId}/alipay-openid")
String getAlipayOpenIdByUserId(@PathVariable("userId") Long userId,
@RequestParam("appId") String appId);
/**
* 通过手机号注册用户(返回用户信息,包含openId)
*
@@ -90,6 +90,18 @@ public class UserServiceFallbackFactory implements FallbackFactory<UserService>
return Collections.emptyList();
}
@Override
public SysUser findByAlipayOpenId(String alipayUserId, String unionId, String mobile, String appId) {
log.error("通过支付宝userId查询用户异常:{}", alipayUserId, throwable);
return new SysUser();
}
@Override
public String getAlipayOpenIdByUserId(Long userId, String appId) {
log.error("根据用户ID查询支付宝openId异常:{}", userId, throwable);
return null;
}
@Override
public SysUser registerByMobile(String mobile) {
log.error("通过手机号注册用户异常:{}", mobile, throwable);
+528
View File
@@ -0,0 +1,528 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>支付宝小程序登录与支付 — 流程链路 & 外部调用示例</title>
<style>
:root { --bg:#0f1117; --card:#1a1d27; --border:#2a2d3a; --text:#e1e4ec; --dim:#8b8fa3; --accent:#4fc3f7; --green:#66bb6a; --orange:#ffa726; --red:#ef5350; --code-bg:#141720; }
* { box-sizing:border-box; margin:0; padding:0; }
body { background:var(--bg); color:var(--text); font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; line-height:1.7; padding:20px; }
.container { max-width:1100px; margin:0 auto; }
h1 { font-size:1.8em; border-bottom:2px solid var(--accent); padding-bottom:12px; margin:32px 0 20px; color:#fff; }
h2 { font-size:1.3em; margin:28px 0 14px; color:var(--accent); }
h3 { font-size:1.1em; margin:20px 0 10px; color:#fff; }
.card { background:var(--card); border:1px solid var(--border); border-radius:8px; padding:20px 24px; margin:16px 0; }
.flow { background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:16px 20px; margin:12px 0; font-family:'SF Mono',Consolas,monospace; font-size:0.85em; white-space:pre; overflow-x:auto; line-height:1.8; }
table { width:100%; border-collapse:collapse; margin:12px 0; font-size:0.9em; }
th { background:#252836; text-align:left; padding:10px 12px; border:1px solid var(--border); color:var(--accent); font-weight:600; }
td { padding:8px 12px; border:1px solid var(--border); vertical-align:top; }
td:first-child, th:first-child { white-space:nowrap; font-family:'SF Mono',Consolas,monospace; }
.tag { display:inline-block; padding:2px 8px; border-radius:3px; font-size:0.78em; font-weight:600; }
.tag-post { background:#1b5e20; color:var(--green); }
.tag-get { background:#0d47a1; color:var(--accent); }
.tag-put { background:#e65100; color:var(--orange); }
.tag-patch { background:#6a1b9a; color:#ce93d8; }
.tag-del { background:#b71c1c; color:var(--red); }
.req { color:var(--green); }
.res { color:var(--accent); }
.note { background:#1a237e22; border-left:3px solid var(--accent); padding:8px 14px; margin:12px 0; border-radius:0 6px 6px 0; font-size:0.9em; color:var(--dim); }
.warn { background:#e6510022; border-left:3px solid var(--orange); padding:8px 14px; margin:12px 0; border-radius:0 6px 6px 0; font-size:0.9em; }
.step { color:var(--orange); font-weight:600; }
.arrow { color:var(--dim); }
a { color:var(--accent); }
.idx { background:var(--code-bg); padding:12px 20px; border-radius:6px; margin:16px 0; }
.idx a { display:block; padding:3px 0; }
pre { background:var(--code-bg); border:1px solid var(--border); border-radius:6px; padding:14px 18px; overflow-x:auto; font-size:0.85em; }
code { font-family:'SF Mono',Consolas,monospace; }
</style>
</head>
<body>
<div class="container">
<h1>🛠 支付宝小程序登录与支付 — 流程链路 & 外部调用示例</h1>
<div class="idx">
<a href="#bugs">🐛 代码检查发现的 Bug 及修复</a>
<a href="#arch">1. 模块架构总览</a>
<a href="#login">2. 登录流程链路</a>
<a href="#login-example">2.1 登录调用示例</a>
<a href="#pay">3. 支付流程链路</a>
<a href="#pay-example">3.1 下单调用示例</a>
<a href="#callback">3.2 支付回调(支付宝→我方)</a>
<a href="#refund">4. 退款流程链路</a>
<a href="#refund-example">4.1 退款调用示例</a>
<a href="#api-summary">5. 全部对外接口汇总</a>
</div>
<!-- ==================== BUGS ==================== -->
<h2 id="bugs">🐛 代码检查发现的 Bug 及修复</h2>
<div class="card">
<p style="color:var(--dim);font-size:0.9em;margin-bottom:8px">第二轮 review 在原有 B1/B2 编译问题基础上,围绕「缓存 / 金额 / 安全 / 验签 / 鉴权 / 回调健壮性」补充 13 项问题(鉴权类 #4 暂缓,其余 12 项已全部修复)。</p>
<table>
<tr><th>#</th><th>文件</th><th>问题</th><th>严重度</th><th>修复</th></tr>
<tr>
<td>B1</td>
<td><code>AliPayController.java</code></td>
<td><code>io.swagger...RequestBody</code> 与 <code>spring...RequestBody</code> 导入冲突,编译失败</td>
<td>🔴 阻断</td>
<td>✅ 已修 — 删除 Swagger 显式 import,注解改用全限定名</td>
</tr>
<tr>
<td>B2</td>
<td><code>AlipayConfigController.java</code></td>
<td>同上,Swagger / Spring <code>@RequestBody</code> 导入冲突</td>
<td>🔴 阻断</td>
<td>✅ 已修 — 同上</td>
</tr>
<tr>
<td>1</td>
<td><code>AlipayClientFactory.java</code></td>
<td><code>createAlipayClient(config)</code> 不走缓存,每次 API 调用都重建 <code>DefaultAlipayClient</code>;老的 <code>getClient(tenantId)</code> 与新的工厂双缓存不一致</td>
<td>🔴 严重</td>
<td>✅ 已修 — 统一为 <code>computeIfAbsent</code> 缓存(key=<code>appId::subMerchantId</code>),<code>getClient</code> / <code>getClientBySubMerchantId</code> / <code>createAlipayClient</code> 三入口共用同一缓存;<code>clearCache(AlipayConfig)</code> 精准失效</td>
</tr>
<tr>
<td>2</td>
<td><code>AliPayController.java</code><br/><code>RefundController.java</code></td>
<td><code>Order.orderAmount</code> 以「分」存储(与微信支付一致),但支付宝 SDK <code>total_amount</code> / <code>refund_amount</code> 要求「元」字符串两位小数 — 直接传入会被支付宝解析为「分→元」放大 100 倍</td>
<td>🔴 严重</td>
<td>✅ 已修 — 新增 <code>StringUtils.fenToYuanAmount</code>(<code>BigDecimal.movePointLeft(2)</code>),下单 / 退款入口统一调用</td>
</tr>
<tr>
<td>3</td>
<td><code>AlipayConfigController.java</code></td>
<td>管理后台 <code>list</code> / <code>getById</code> 直接回吐数据库 <code>appPrivateKey</code> / <code>alipayPublicKey</code> / <code>authToken</code> / <code>encryptKey</code>,前端可见明文私钥</td>
<td>🔴 严重</td>
<td>✅ 已修 — 控制器层 <code>maskSensitive</code> 替换为 <code>******</code>;<code>update</code> 接口收到掩码时回填库中原值,避免误覆盖;Feign 内部端点(<code>/type</code> / <code>/app</code> / <code>/sub</code>)保持原值返回,不影响 SDK 构造</td>
</tr>
<tr>
<td>4</td>
<td><code>/alipay/config/**</code></td>
<td>管理端配置 CRUD 缺少鉴权 / 角色控制(<em>本轮按用户要求暂缓处理</em>)</td>
<td>🟡 待办</td>
<td>⏸ 待统一安全方案</td>
</tr>
<tr>
<td>5</td>
<td><code>AlipayLoginService.java</code><br/><code>AlipayAuthenticationProvider.java</code></td>
<td><code>alipay.user.info.share</code> 实际不返回 <code>mobile</code> 字段;旧实现把 <code>shareResp.getString("mobile")</code> 当真,并把伪 <code>decryptPhone</code> 直接 <code>return null</code></td>
<td>🔴 严重</td>
<td>✅ 已修 — <code>code2userId</code> 删除假手机号字段;新增真实 <code>decryptPhone</code> 调用 <code>alipay.user.phone.number.decrypt</code>;Provider 在 <code>encryptedPhone</code> 非空时调用解密拿到明文手机号</td>
</tr>
<tr>
<td>6</td>
<td><code>AlipayClientFactory.java</code></td>
<td>缺少证书模式分支,<code>certMode=true</code> 配置无法生效</td>
<td>🟠 高</td>
<td>✅ 已修 — 新增 <code>buildCertClient</code> 走 <code>CertAlipayRequest</code>(<code>appCertPath</code> / <code>alipayCertPath</code> / <code>alipayRootCertPath</code>),含 AES <code>encryptKey</code> 配置注入</td>
</tr>
<tr>
<td>7</td>
<td><code>AlipayNotifyVerifier.java</code></td>
<td><code>verifyWithCert</code> 半成品方法签名要求外部传 <code>certContent</code>,调用方根本没接,且与 SDK 真实 API 形参不匹配</td>
<td>🟠 高</td>
<td>✅ 已修 — 删除多余方法;<code>verify</code> 内部按 <code>certMode</code> 自动选择 <code>rsaCheckV1</code>(公钥)或 <code>rsaCertCheckV1</code>(基于 <code>alipayCertPath</code>)</td>
</tr>
<tr>
<td>8</td>
<td><code>AlipayAuthenticationToken.java</code></td>
<td>未认证 code 模式构造函数里直接 <code>setAuthenticated(true)</code>,相当于伪造已登录态</td>
<td>🟠 高</td>
<td>✅ 已修 — 未认证构造改为 <code>setAuthenticated(false)</code>;已认证(UserDetails)构造时才置 true</td>
</tr>
<tr>
<td>9</td>
<td><code>AlipayPayService.java</code></td>
<td>下单 <code>bizContent</code> 缺 <code>product_code</code>,部分场景(小程序拉起 <code>my.tradePay</code>)会被支付宝拒单</td>
<td>🟠 高</td>
<td>✅ 已修 — 强制设置 <code>product_code = JSAPI_PAY</code></td>
</tr>
<tr>
<td>10</td>
<td><code>AliPayController.java</code></td>
<td><code>/alipay/order/pay</code> 仅校验订单存在,未校验 <code>orderStatus = UNPAID</code>,已支付订单可重复下单</td>
<td>🟠 高</td>
<td>✅ 已修 — 入口处校验 <code>OrderStatus.UNPAID</code>,否则抛 <code>IllegalStateException</code></td>
</tr>
<tr>
<td>11</td>
<td><code>AliPayController.java</code></td>
<td>异步通知 <code>request.getParameterMap()</code> 在 servlet 容器未显式 <code>setCharacterEncoding</code> 时按 ISO-8859-1 解码,<code>subject</code> / <code>refund_reason</code> 等中文字段乱码导致验签失败</td>
<td>🟠 高</td>
<td>✅ 已修 — <code>toMap</code> 优先按回调中的 <code>charset</code> 参数(默认 UTF-8)调用 <code>setCharacterEncoding</code> 后再读取参数</td>
</tr>
<tr>
<td>12</td>
<td><code>AliPayController.java</code></td>
<td>支付回调 <code>handleAlipayPaymentResult</code> 订单不存在时静默 <code>return</code>,外层返回 <code>success</code>,支付宝不会再重试 — 数据落库延迟时支付状态丢失</td>
<td>🟠 高</td>
<td>✅ 已修 — 订单不存在抛 <code>IllegalStateException</code>,外层捕获返回 <code>failure</code>,由支付宝按 8 次梯度重试;携程旁路任务保持静默吞错</td>
</tr>
<tr>
<td>13</td>
<td><code>AliPayController.java</code></td>
<td>ISV(服务商)模式下回调使用 <code>app_id</code>(=ISV 自身 AppId)查询配置失败,应使用 <code>auth_app_id</code>(商家 AppId)定位</td>
<td>🟠 高</td>
<td>✅ 已修 — <code>/pay/notify</code> 与 <code>/refund/notify</code> 均优先取 <code>auth_app_id</code>,缺省回退 <code>app_id</code></td>
</tr>
</table>
</div>
<!-- ==================== ARCH ==================== -->
<h2 id="arch">1. 模块架构总览</h2>
<div class="card">
<pre>
支付宝小程序(前端)
│
│ ① my.getAuthCode() → auth_code
│ ② my.tradePay({ tradeNo })
▼
┌──────────────────────────────────────────────────────┐
│ zlt-gateway (网关) │
│ /api-ua/** → zlt-uaa /api-order/** → order-center │
└──────────────────────────────────────────────────────┘
│ │
▼ ▼
┌──────────────┐ ┌──────────────────────┐
│ zlt-uaa │ │ order-center │
│ (认证中心) │ │ (订单/支付中心) │
│ │ │ │
│ LoginController │ AliPayController │
│ └─ case "alipay" │ ├─ POST /order/pay │
│ ├─ AlipayAuthProvider│ ├─ POST /pay/notify │
│ ├─ AlipayLoginService│ └─ POST /refund/nfy │
│ └─ AlipayConfigSvc───┼──→ AlipayConfigController
│ (Feign) │ (alipay_config CRUD)
│ │ │ │
│ │ Feign │ │
│ ▼ │ │
│ ┌──────────────┐ │ RefundController │
│ │ user-center │ │ └─ routeRefundByPayType
│ │ /alipayOpenId│ │ ├─ WECHAT → 微信 │
│ └──────────────┘ │ └─ ALIPAY → 支付宝│
│ └──────────────────────┘
│
├─ zlt-alipay-common-core (AlipayConfig 实体 + Feign)
├─ zlt-alipay-spring-boot-starter
│ ├─ AlipayClientFactory (多租户 AlipayClient 缓存)
│ ├─ AlipayLoginService (code→userId)
│ ├─ AlipayPayService (trade.create/query/close)
│ ├─ AlipayRefundService (trade.refund)
│ └─ AlipayNotifyVerifier (回调验签)
│
└─ 支付宝开放平台
├─ alipay.system.oauth.token
├─ alipay.user.info.share
├─ alipay.trade.create
├─ alipay.trade.refund
└─ 异步通知
</pre>
</div>
<!-- ==================== LOGIN ==================== -->
<h2 id="login">2. 登录流程链路</h2>
<div class="flow">
<span class="step">[1]</span> 支付宝小程序调用 my.getAuthCode() → auth_code
<span class="step">[2]</span> POST /oauth/login { grantType:"alipay", code, appCode, encryptedPhone }
│
▼ LoginController.issueTokenInternally()
<span class="step">[3]</span> case "alipay":
│ new AlipayAuthenticationToken(code, encryptedPhone, appCode)
│ new AlipayAuthenticationProvider(authSvc, tokenGen, userFactory, alipayLoginSvc, alipayConfigSvc)
│
▼ AlipayAuthenticationProvider.getPrincipal()
<span class="step">[4]</span> alipayConfigService.getConfigByAppId(appCode, "MINI") ← Feign → order-center
│ 查询 alipay_config 表 (type=MINI, app_id=appCode, status=1)
│ 返回 AlipayConfig (appId, appPrivateKey, alipayPublicKey, ...)
│
<span class="step">[5]</span> alipayLoginService.code2userId(config, code)
│ ├─ alipay.system.oauth.token(code) → accessToken + userId + openId
│ └─ alipay.user.info.share(accessToken) → unionId + mobile + avatar + nickName
│ 返回 AlipayLoginResult { userId, openId, unionId, mobile }
│
<span class="step">[6]</span> userDetailsService.loadUserByAlipayUserId(userId, unionId, mobile, appCode)
│ └─ UserDetailServiceImpl.loadUserByAlipayUserId()
│ └─ userService.findByAlipayOpenId() ← Feign → user-center
│ └─ GET /users-anon/alipayOpenId?alipayUserId=...&amp;appId=...
│ ├─ 查 sys_user_third_openid 映射表 (provider=alipay, app_id, open_id)
│ ├─ 命中 → 取出 user_id 加载 sys_user
│ └─ 未命中 → 新建 sys_user 并写入 sys_user_third_openid 映射
│
<span class="step">[7]</span> 构造 AlipayAuthenticationToken(userDetails, authorities)
<span class="step">[8]</span> BaseAuthenticationProvider 生成 OAuth2AccessToken
<span class="step">[9]</span> 返回 { access_token, refresh_token, token_type, expires_in, scope }
</div>
<h3 id="login-example">2.1 登录调用示例</h3>
<div class="card">
<p><strong>请求</strong></p>
<pre><code>POST /oauth/login
Content-Type: application/json
{
"grantType": "alipay",
"clientId": "webApp",
"code": "7b1e3f8a9c2d4e5f6a7b8c9d0e1f2aXX",
"appCode": "2021000000000001"
}</code></pre>
<p style="margin-top:16px"><strong>成功响应</strong></p>
<pre><code>{
"resp_code": 0,
"resp_msg": "登录成功",
"data": {
"access_token": "eyJraWQiOiIxZTMyZTFmMi05Zjg3LTQ5ZDctY...",
"refresh_token": "NWE2MzkzYTgtYjI4YS00Mjc5LWExYzEtY...",
"token_type": "Bearer",
"expires_in": 3599,
"scope": "all"
}
}</code></pre>
<p style="margin-top:16px"><strong>失败响应</strong></p>
<pre><code>{
"resp_code": 1,
"resp_msg": "登录失败:不支持的支付宝应用: xxx"
}</code></pre>
</div>
<!-- ==================== PAY ==================== -->
<h2 id="pay">3. 支付流程链路</h2>
<div class="flow">
<span class="step">[1]</span> 支付宝小程序调用 POST /alipay/order/pay
│ Header: Authorization: Bearer &lt;access_token&gt;
│ Body: { "orderId": 1001, "buyerId": "2088xxxxxx" }
│
▼ AliPayController.payOrder()
<span class="step">[2]</span> orderService.getById(orderId) → 获取订单 (orderNo, orderAmount, tenantId)
<span class="step">[3]</span> alipayConfigService.getConfigByTypeAndTenantId("PAY", tenantId)
│ 查询 alipay_config 表 (type=PAY, tenantId=xxx)
│
<span class="step">[4]</span> alipayPayService.create(config, req)
│ ├─ new AlipayTradeCreateRequest()
│ ├─ bizContent: { out_trade_no, total_amount, subject, buyer_id }
│ ├─ ISV模式 → extend_params.sub_merchant_id + app_auth_token
│ └─ client.execute(request)
│ 返回 AlipayTradeCreateResponse { tradeNo, outTradeNo }
│
<span class="step">[5]</span> 返回 { tradeNo, outTradeNo } 给前端
<span class="step">[6]</span> 前端调用 my.tradePay({ tradeNo }) → 拉起支付宝支付
│
│ ... 用户在支付宝完成支付 ...
│
<span class="step">[7]</span> 支付宝服务器 POST /alipay/pay/notify (form-urlencoded)
│ 参数: app_id, out_trade_no, trade_no, trade_status=TRADE_SUCCESS, total_amount, sign, sign_type
│
▼ AliPayController.handleAlipayPayNotify()
<span class="step">[8]</span> 优先按 auth_app_id(ISV 商家应用)回退 app_id 查 alipay_config → 设置 TenantContext
<span class="step">[9]</span> AlipayNotifyVerifier.verify(params, config) → RSA2 验签
<span class="step">[10]</span> handleAlipayPaymentResult():
├─ order.setOrderStatus(PAID)
├─ order.setPayType(ALIPAY_PAY = 4) ← 显式写入
├─ order.setPayTime(now)
├─ orderService.updateOrder(order)
└─ 如有携程分销 → ctripDistOrderService.createCtripDistOrder()
<span class="step">[11]</span> 返回纯文本 "success"
</div>
<h3 id="pay-example">3.1 下单调用示例</h3>
<div class="card">
<p><strong>请求</strong></p>
<pre><code>POST /alipay/order/pay
Authorization: Bearer eyJraWQiOiIxZTMyZTFmMi05Zjg3LTQ5ZDctY...
Content-Type: application/json
{
"orderId": 1001,
"buyerId": "2088123456789012"
}</code></pre>
<p style="margin-top:16px"><strong>成功响应</strong></p>
<pre><code>{
"tradeNo": "2026051222001412345678901234",
"outTradeNo": "ORD20260512001"
}</code></pre>
<p style="margin-top:16px"><strong>前端拉起支付</strong></p>
<pre><code>// 支付宝小程序 JS
my.tradePay({
tradeNO: "2026051222001412345678901234", // 使用 tradeNo
success: (res) => { /* 支付成功 */ },
fail: (res) => { /* 支付失败 */ }
});</code></pre>
</div>
<h3 id="callback">3.2 支付回调(支付宝→我方服务器)</h3>
<div class="card">
<p>支付宝以 <b>POST form-urlencoded</b> 格式回调:</p>
<pre><code>POST /alipay/pay/notify
Content-Type: application/x-www-form-urlencoded
app_id=2021000000000001
&out_trade_no=ORD20260512001
&trade_no=2026051222001412345678901234
&trade_status=TRADE_SUCCESS
&total_amount=99.00
&buyer_id=2088123456789012
&gmt_payment=2026-05-12 14:30:00
&sign=AbCdEf123456...
&sign_type=RSA2
&charset=UTF-8</code></pre>
<p>验签通过后返回纯文本 <code>success</code>,失败返回 <code>failure</code>(支付宝据此决定是否重试)。</p>
<div class="note">
<b>幂等保护</b>:若订单状态已是 PAID,直接跳过不重复处理。
</div>
</div>
<!-- ==================== REFUND ==================== -->
<h2 id="refund">4. 退款流程链路</h2>
<div class="flow">
<span class="step">[1]</span> 管理后台审批退款 → RefundController.approveOrder()
│
<span class="step">[2]</span> orderService.getOrderByNumber(refund.getOrderNo())
<span class="step">[3]</span> routeRefundByPayType(order, customAmount)
│ ┌─ payType=null → 兜底走微信退款 (历史订单)
│ ├─ payType=1 (WECHAT) → dealRefundRequest() [现有微信逻辑]
│ ├─ payType=4 (ALIPAY) → alipayRefund() [新增支付宝逻辑]
│ ├─ payType=2 (COUPON) → 日志记录(优惠券走独立流程)
│ └─ payType=3 (FEIPAI) → 抛异常(不支持退款)
│
▼ alipayRefund(order, customAmount)
<span class="step">[4]</span> alipayConfigService.getConfigByTypeAndTenantId("PAY", tenantId)
<span class="step">[5]</span> alipayRefundService.refund(config, req)
│ ├─ new AlipayTradeRefundRequest()
│ ├─ bizContent: { out_trade_no, refund_amount, out_request_no, refund_reason }
│ └─ client.execute(request)
│ 返回 AlipayTradeRefundResponse { fundChange: "Y" }
│
<span class="step">[6]</span> (可选) 异步回调 POST /alipay/refund/notify
│ 支付宝通知退款结果,验签后更新退款单和订单状态
</div>
<h3 id="refund-example">4.1 退款调用示例</h3>
<div class="card">
<p>退款由<b>管理后台</b>发起(非小程序直接调用),流程:</p>
<pre><code>POST /refund/approve
Authorization: Bearer &lt;admin_token&gt;
Content-Type: application/json
{
"orderNo": "ORD20260512001",
"refundNo": "RFORD20260512001",
"state": 4, // APPROVED
"status": 5 // REFUNDING
}</code></pre>
<p>系统根据订单 <code>payType</code> 自动路由:</p>
<table>
<tr><th>payType</th><th>渠道</th><th>处理</th></tr>
<tr><td>1</td><td>微信支付</td><td>调用微信退款 SDK(现有逻辑)</td></tr>
<tr><td>4</td><td>支付宝</td><td>调用 alipay.trade.refund → 同步返回结果</td></tr>
<tr><td>null</td><td>未知(历史)</td><td>兜底走微信退款 + WARN 日志</td></tr>
<tr><td>2</td><td>优惠券</td><td>独立流程</td></tr>
<tr><td>3</td><td>第三方核销</td><td>拒绝退款</td></tr>
</table>
</div>
<!-- ==================== API SUMMARY ==================== -->
<h2 id="api-summary">5. 全部对外接口汇总</h2>
<div class="card">
<table>
<tr><th>接口</th><th>方法</th><th>格式</th><th>调用方</th><th>说明</th></tr>
<tr>
<td><code>/oauth/login</code></td>
<td><span class="tag tag-post">POST</span></td>
<td>JSON</td>
<td>小程序</td>
<td>grantType=alipay 登录,返回 access_token</td>
</tr>
<tr>
<td><code>/alipay/order/pay</code></td>
<td><span class="tag tag-post">POST</span></td>
<td>JSON</td>
<td>小程序</td>
<td>下单获取 tradeNo,Body: {orderId, buyerId?}</td>
</tr>
<tr>
<td><code>/alipay/pay/notify</code></td>
<td><span class="tag tag-post">POST</span></td>
<td>form-urlencoded</td>
<td>支付宝服务器</td>
<td>支付异步通知,返回 success/failure</td>
</tr>
<tr>
<td><code>/alipay/refund/notify</code></td>
<td><span class="tag tag-post">POST</span></td>
<td>form-urlencoded</td>
<td>支付宝服务器</td>
<td>退款异步通知,返回 success/failure</td>
</tr>
<tr>
<td><code>/alipay/config/list</code></td>
<td><span class="tag tag-get">GET</span></td>
<td>Query</td>
<td>管理后台</td>
<td>分页查询 alipay_config</td>
</tr>
<tr>
<td><code>/alipay/config</code></td>
<td><span class="tag tag-post">POST</span></td>
<td>JSON</td>
<td>管理后台</td>
<td>新增配置</td>
</tr>
<tr>
<td><code>/alipay/config</code></td>
<td><span class="tag tag-put">PUT</span></td>
<td>JSON</td>
<td>管理后台</td>
<td>更新配置</td>
</tr>
<tr>
<td><code>/alipay/config/{id}</code></td>
<td><span class="tag tag-del">DEL</span></td>
<td>—</td>
<td>管理后台</td>
<td>删除配置</td>
</tr>
<tr>
<td><code>/alipay/config/{id}/status</code></td>
<td><span class="tag tag-patch">PATCH</span></td>
<td>JSON</td>
<td>管理后台</td>
<td>启停切换 {status:0|1}</td>
</tr>
<tr>
<td><code>/users-anon/alipayOpenId</code></td>
<td><span class="tag tag-get">GET</span></td>
<td>Query</td>
<td>zlt-uaa (Feign)</td>
<td>内部:按支付宝userId查/注册用户</td>
</tr>
</table>
</div>
<div class="note" style="margin-top:20px">
<b>数据表依赖</b>:使用前请确认已执行 SQL 迁移脚本:<br>
<code>V1__create_alipay_config_table.sql</code> — alipay_config 表<br>
<code>V2__create_sys_user_third_openid_table.sql</code> — sys_user_third_openid 表(预留)<br>
运行时需要在 <code>alipay_config</code> 表中插入至少一条 <code>type=MINI</code> 和一条 <code>type=PAY</code> 的配置记录。
</div>
</div>
</body>
</html>
@@ -0,0 +1,308 @@
# 支付宝小程序支付全流程实现说明
> 版本:v1.0
> 作者:duzhichao
> 日期:2026-06-13
> 状态:已落地(基于代码实录)
>
> 关联文档:
> - [支付宝小程序登录与支付对接设计文档.md](支付宝小程序登录与支付对接设计文档.md)(设计意图)
> - [支付宝小程序登录全流程实现说明.md](支付宝小程序登录全流程实现说明.md)(登录链路)
> - [支付宝小程序登录与支付代码Review问题清单.md](支付宝小程序登录与支付代码Review问题清单.md)(评审整改)
>
> 本文档基于 `order-center` + `zlt-alipay-spring-boot-starter` + `zlt-alipay-common-core` 实际代码梳理。如和设计文档不一致,以本文为准(以代码为准)。
---
## 一、整体链路总览
```
小程序(前端) order-center 支付宝开放平台
│ │ │
│ ① POST /alipay/order/pay │
│ { orderId, buyerId? } │
│──────────────────────▶│ │
│ │ ② alipay.trade.create │
│ │────────────────────────────────────▶│
│ │◀───── tradeNo ─────────────────────│
│ ③ { tradeNo } │ │
│◀──────────────────────│ │
│ │ │
│ ④ my.tradePay({ tradeNo }) │
│───────────────────────────────────────────────────────────▶│
│ │ │ 用户授权支付
│ │ ⑤ POST /alipay/pay/notify │
│ │◀──── form-urlencoded ───────────────│
│ │ ⑥ 验签 + 业务验真 + 更新订单 │
│ │──── "success" ──────────────────────▶│
│ │ │
│ ⑦ 管理后台审批退款 │ │
│──────────────────────▶│ │
│ │ ⑧ routeRefundByPayType │
│ │ → alipay.trade.refund │
│ │────────────────────────────────────▶│
│ │◀──── fundChange=Y ─────────────────│
│ │ │
│ │ ⑨ POST /alipay/refund/notify (可选) │
│ │◀──── form-urlencoded ───────────────│
│ │ ⑩ 验签 + 更新退款单/订单 │
│ │──── "success" ──────────────────────▶│
```
---
## 二、下单接口:`POST /alipay/order/pay`
### 2.1 请求
| 项目 | 内容 |
|------|------|
| 端点 | `POST /alipay/order/pay` |
| 认证 | `Authorization: Bearer <access_token>` |
| Content-Type | `application/json` |
```json
{
"orderId": 1001,
"buyerId": "2088xxxxxxxxxxxx"
}
```
| 字段 | 类型 | 必填 | 说明 |
|------|------|:--:|------|
| `orderId` | Long | ✅ | 订单ID |
| `buyerId` | String | — | 支付宝 userId。**服务端不信任此值**,以 `sys_user_third_openid` 映射表查询结果为准。若传入则校验是否匹配,不匹配直接拒绝 |
### 2.2 服务端校验链(AliPayController.payOrder)
1. **orderId 非空** → `Assert.notNull`
2. **订单存在** → `orderService.getById(orderId)`
3. **用户权限** → `SecurityTenantUtils.getCurrentUser()` 校验当前用户是否拥有该订单
4. **租户边界** → 订单的 `tenantId` 必须与当前用户租户一致(超管豁免)
5. **订单状态** → 必须为 `UNPAID`,否则拒绝(防重复下单)
6. **支付配置存在** → `alipayConfigService.getConfigByTypeAndTenantId("PAY", tenantId)`
7. **buyerId 一致性** → 从 `sys_user_third_openid` 查到的 buyerId 与前端传入一致
8. **金额非空** → `order.getOrderAmount()` 不能为 null
### 2.3 下单参数构造(AlipayPayService.create)
`AlipayConfig` → `AlipayClient` → `AlipayTradeCreateRequest`:
| bizContent 字段 | 来源 | 说明 |
|------|------|------|
| `out_trade_no` | `order.getOrderNo()` | 商户订单号 |
| `total_amount` | `StringUtils.fenToYuanAmount(order.getOrderAmount())` | ⚠️ **DB 以「分」存储,支付宝要求「元」** |
| `subject` | `qrCode.getName()` 或 `"景区订单-" + orderNo` | 商品标题 |
| `product_code` | 固定 `"JSAPI_PAY"` | 小程序支付必须 |
| `buyer_id` | `sys_user_third_openid` 映射 | 支付宝 userId,可选但推荐传入 |
| `extend_params.sub_merchant_id` | `config.subMerchantId` | ISV 模式 |
| `timeout_express` | 不传 | 默认 90m,业务需要时可配 |
另外:
- ISV 模式下请求头加 `app_auth_token`(`config.getAuthToken()`)
- `notifyUrl` 从 `config.getNotifyUrl()` 设置到请求级
### 2.4 响应
```json
// 成功
{ "tradeNo": "20260512220014xxxxxxxxxxxxxx", "outTradeNo": "ORD20260512001" }
// 失败
{ "error": "余额不足", "code": "ACQ.BUYER_BALANCE_NOT_ENOUGH" }
```
前端拿到 `tradeNo` 后调用:
```js
my.tradePay({ tradeNO: "20260512220014xxxxxxxxxxxxxx" })
```
---
## 三、支付异步回调:`POST /alipay/pay/notify`
### 3.1 回调格式
支付宝以 **POST form-urlencoded** 推送,关键字段:
| 字段 | 说明 |
|------|------|
| `app_id` | 支付宝应用ID(直连) |
| `auth_app_id` | 授权应用ID(ISV 模式,优先用于定位配置) |
| `out_trade_no` | 商户订单号 |
| `trade_no` | 支付宝交易号 |
| `trade_status` | `TRADE_SUCCESS` / `TRADE_FINISHED` |
| `total_amount` | 交易金额(元) |
| `seller_id` | 收款商家 PID |
| `sign` / `sign_type` | RSA2 签名 |
### 3.2 验签 → 定位配置
`AlipayNotifyVerifier.verify(params, config)`:
- 公钥模式:`AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType)`
- 证书模式:`AlipaySignature.rsaCertCheckV1(...)`
- 按 `auth_app_id`(优先)或 `app_id` 查 `alipay_config`
### 3.3 四重业务验真(防重放/串租户/金额篡改)
| # | 校验项 | 失败处理 |
|---|--------|----------|
| 1 | **租户一致**:`order.tenantId == config.tenantId` | 抛异常 → 返回 `failure`,支付宝重试 |
| 2 | **金额一致**:DB「分」→「元」后 == 回调 `total_amount` | 同上 |
| 3 | **应用身份**:回调 `auth_app_id`/`app_id` == `config.appId` | 同上 |
| 4 | **商家身份**:回调 `seller_id` == `config.pid`(若配置) | 同上 |
### 3.4 订单幂等更新
```java
if (OrderStatus.PAID.equals(order.getOrderStatus())) {
return; // 已支付,跳过
}
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.ALIPAY_PAY.getCode()); // ← 显式写入 4
order.setPayTime(new Date());
orderService.updateOrder(order);
```
旁路:携程分销订单异步创建(失败不影响本地订单)。
### 3.5 回调日志脱敏
`summarizeNotify()` 只保留排查必需字段(`out_trade_no`、`trade_no`、`trade_status`、`app_id`、`auth_app_id`),不记录 `sign`、`buyer_id`、`total_amount` 等敏感信息。
---
## 四、退款流程
### 4.1 退款发起(管理后台)
退款由管理后台审批触发,`RefundController.approveOrder()` 调用 `routeRefundByPayType()`:
```
order.payType
├─ 1 (WECHAT) → dealRefundRequest() ← 微信退款(现有逻辑)
├─ 4 (ALIPAY) → alipayRefund() ← 支付宝退款(新增)
├─ 2 (COUPON) → 日志记录(独立流程)
├─ 3 (FEIPAI) → 抛异常(不支持退款)
└─ null → 兜底走微信退款(历史订单)
```
### 4.2 支付宝退款(RefundController.alipayRefund)
```java
// 设置租户上下文
TenantContextHolder.setTenant(order.getTenantId());
// 查支付配置
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", tenantId);
// 构造退款请求
AlipayRefundRequest req = new AlipayRefundRequest();
req.setOutTradeNo(order.getOrderNo()); // 原交易订单号
req.setOutRequestNo("RF" + order.getOrderNo()); // 退款请求号(幂等键)
req.setRefundAmount(...); // 退款金额(元)
req.setRefundReason("用户申请退款");
// 调用 alipay.trade.refund(同步接口)
AlipayTradeRefundResponse response = alipayRefundService.refund(config, req);
// finally 清理租户上下文
TenantContextHolder.clear();
```
### 4.3 退款异步回调:`POST /alipay/refund/notify`
处理逻辑与支付回调同构:验签 → 查配置 → 设置租户 → 租户一致性校验 → 更新退款单状态 + 订单状态。
- `out_biz_no` → 定位退款单
- 全额退:`RefundStatus.REFUNDED`;部分退:`PART_REFUNDED`
---
## 五、订单金额单位转换
| 存储层 | 传输层 | 转换 |
|--------|--------|------|
| `Order.orderAmount`(String,"分") | 支付宝 `total_amount`(String,"元") | `StringUtils.fenToYuanAmount()` 分→元 |
回调验真时同样转换比对,确保金额一致。
---
## 六、PayTypeEnum 路由
| code | 枚举值 | 说明 |
|:--:|------|------|
| 1 | `WECHAT_PAY` | 微信支付 |
| 2 | `COUPON_PAY` | 优惠券支付 |
| 3 | `FEIPAI_VERIFY` | 第三方核销 |
| 4 | `ALIPAY_PAY` | 支付宝支付 |
WxPayController 两处支付成功回调已补上 `setPayType(WECHAT_PAY)`(修复遗留 bug)。
---
## 七、幂等与重试
| 场景 | 机制 |
|------|------|
| 重复下单 | 订单状态必须为 `UNPAID`,已支付/已取消订单直接拒绝 |
| 重复回调 | `handleAlipayPaymentResult` 先查 `orderStatus == PAID`,已支付跳过 |
| 回调失败 | 返回 `failure`,支付宝重试(最多 8 次,间隔 2m/10m/10m/1h/2h/6h/15h) |
| 重复退款 | `out_request_no`(`RF` + orderNo)作为退款幂等键 |
| 并发退款 | `routeRefundByPayType` 由管理后台审批流串行化 |
---
## 八、关键文件清单
| 模块 | 文件 | 职责 |
|------|------|------|
| `order-center` | `controller/AliPayController.java` | 下单 + 支付回调 + 退款回调 |
| `order-center` | `controller/RefundController.java` | `routeRefundByPayType` + `alipayRefund` |
| `zlt-alipay-spring-boot-starter` | `service/AlipayPayService.java` | `alipay.trade.create/query/close` |
| `zlt-alipay-spring-boot-starter` | `service/AlipayRefundService.java` | `alipay.trade.refund` |
| `zlt-alipay-spring-boot-starter` | `notify/AlipayNotifyVerifier.java` | 公钥/证书模式回调验签 |
| `zlt-alipay-spring-boot-starter` | `config/AlipayClientFactory.java` | 多租户 AlipayClient 缓存 |
| `zlt-alipay-common-core` | `entity/AlipayConfig.java` | 支付配置实体 |
| `order-center` | `enums/PayTypeEnum.java` | 支付渠道路由 |
| `order-center` | `util/StringUtils.java` | `fenToYuanAmount` 金额转换 |
---
## 九、与微信支付链路对照
| 维度 | 微信 | 支付宝 |
|------|------|------|
| 下单端点 | `/wechat/...` (WxPayController) | `POST /alipay/order/pay` |
| SDK 调用 | `JsapiServiceExtension.prepayWithRequestPayment` | `AlipayTradeCreateRequest` → `my.tradePay` |
| 金额单位 | 「分」 | 「元」(`fenToYuanAmount` 转换) |
| 回调格式 | JSON + APIv3 签名 | form-urlencoded + RSA2 签名 |
| 回调响应 | `{"code":"SUCCESS"}` | 纯文本 `success` |
| 退款 | 微信退款 SDK | `alipay.trade.refund`(同步) |
| ISV 定位 | `sub_mchid` | `auth_app_id`(优先)/ `app_id` + `sub_merchant_id` |
| 业务验真 | — | 四重验真(租户+金额+应用+商家) |
| payType 路由 | 退款路由为 WECHAT | 退款路由为 ALIPAY |
---
## 十、踩坑记录
1. **金额单位:分 vs 元**
- 现象:支付宝回调验真时金额永远不匹配。
- 原因:`Order.orderAmount` 以「分」存储(如 `9900` = 99.00 元),支付宝回调 `total_amount` 以「元」表示(`99.00`)。
- 解决:下单和回调验真均通过 `StringUtils.fenToYuanAmount()` 转换。
2. **ISV 回调 appId 不一致**
- 现象:服务商模式下支付宝回调 `app_id` 为服务商应用,无法直接匹配商家 `alipay_config.app_id`。
- 解决:优先用回调中的 `auth_app_id`(商家应用ID)定位配置,`app_id` 为兜底。
3. **buyerId 不信任前端**
- 现象:前端可任意传 buyerId 替他人下单。
- 解决:buyerId 从 `sys_user_third_openid` 映射表获取,前端传入值的唯一作用是对比校验(不匹配拒绝)。
4. **product_code 缺失**
- 现象:`alipay.trade.create` 返回 "缺少必选参数"。
- 原因:小程序支付必须传 `product_code=JSAPI_PAY`。
- 解决:在 `AlipayPayService.create()` 中写死 `JSAPI_PAY`。
5. **回调日志泄露**
- 现象:日志中记录了完整回调参数(含 sign / buyer_id)。
- 解决:`summarizeNotify()` 只保留排查必需字段。
@@ -0,0 +1,59 @@
# 支付宝小程序登录与支付代码 Review 问题清单
> Review 日期:2026-05-27
> Review 范围:支付宝小程序登录、下单、支付回调、退款、配置管理及流程文档
> 说明:本文件仅记录问题与建议,未包含代码修复。
## 结论摘要
当前实现已覆盖支付宝小程序登录、`alipay.trade.create` 下单、支付回调验签、支付宝退款和配置管理等主流程,但仍存在若干会影响生产可用性和支付安全的风险点。优先级最高的是 Spring Boot 3 Servlet 包兼容、下单接口订单归属校验、支付回调业务验真、按订单号查询缺少租户隔离、退款状态一致性。
## 问题清单
| 编号 | 严重级别 | 状态 | 涉及位置 | 问题摘要 | 建议 |
| --- | --- | --- | --- | --- | --- |
| A1 | 阻断/高危 | 待修复 | `zlt-business/order-center/src/main/java/com/central/order/controller/AliPayController.java:34` | Spring Boot 3 项目中使用了 `javax.servlet.http.HttpServletRequest`。Spring Boot 3/Spring 6 使用 `jakarta.servlet.*`,当前写法存在编译或运行时兼容风险。 | 改为 `jakarta.servlet.http.HttpServletRequest`,并移除 `order-center` 中额外引入的 `javax.servlet-api` 依赖。 |
| A2 | 高危 | 待修复 | `AliPayController.java:82` | `/alipay/order/pay` 只按 `orderId` 查询订单,没有校验当前登录用户或租户是否拥有该订单。攻击者如果拿到其他订单 ID,可能替他人订单发起支付。 | 从认证上下文取当前用户,校验 `order.userId` 与当前用户一致;同时校验租户边界。 |
| A3 | 高危 | 待修复 | `AliPayController.java:98` | `buyerId` 可由前端传入,服务端未校验该 `buyerId` 是否属于当前登录用户。可能导致订单绑定到错误的支付宝买家。 | 不信任客户端传入的 `buyerId`;优先由服务端根据当前用户和 `appId` 从 `sys_user_third_openid` 派生。确需前端传入时必须和服务端映射结果比对。 |
| A4 | 高危 | 待修复 | `AliPayController.java:185` | 支付回调验签后直接按 `out_trade_no` 更新订单为已支付,未校验 `total_amount` 是否等于订单金额,也未校验 `seller_id`、`app_id/auth_app_id` 与订单租户配置是否匹配。 | 在更新订单前增加业务验真:金额一致、订单租户与配置一致、支付宝应用/商户身份一致、交易状态合法。 |
| A5 | 高危 | 待修复 | `zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml:108` | `getOrderByNumber` 只按 `order_no` 查询,没有带 `tenant_id`。虽然回调中设置了 `TenantContext`,但该 SQL 未使用租户条件。若订单号不是全局唯一,可能串租户更新订单。 | 订单号应保证全局唯一,或新增按 `order_no + tenant_id` 查询的方法,并在回调中使用配置租户查询。 |
| A6 | 中高危 | 待修复 | `zlt-business/order-center/src/main/java/com/central/order/controller/RefundController.java:174` | 普通全额退款审批只调用渠道退款,成功后没有更新本地退款单和订单状态,可能导致本地状态长期停留在退款中。 | 支付宝同步退款成功后,应在同一事务内更新退款单状态、退款时间和订单状态;失败时保持可重试状态并记录错误。 |
| A7 | 中高危 | 待修复 | `RefundController.java:197` | 部分退款审批中查询 `refundorder` 后,断言写成了 `Assert.notNull(order, "退款订单不存在")`,实际没有校验退款单是否存在。后续访问 `refundorder` 可能空指针。 | 改为 `Assert.notNull(refundorder, "退款订单不存在")`,并补充退款单与订单号、租户、用户的一致性校验。 |
| A8 | 中危 | 待修复 | `zlt-commons/zlt-alipay-spring-boot-starter/src/main/java/com/central/alipay/config/AlipayClientFactory.java:65`、`zlt-business/order-center/src/main/java/com/central/order/controller/AlipayConfigController.java:98` | `AlipayClient` 缓存 key 只有 `appId::subMerchantId`,配置更新、启停、密钥或证书变更后没有清理缓存,运行时仍可能使用旧密钥或旧证书。 | 配置新增、更新、删除、启停后通知 starter 清理对应缓存;或者把配置版本/更新时间纳入缓存失效机制。 |
| A9 | 中危 | 待修复 | `AlipayConfigController.java:45`、`AlipayConfigController.java:57`、`AlipayConfigController.java:69`、`AlipayConfigController.java:78`、`AlipayConfigController.java:104`、`AlipayConfigController.java:115` | 支付宝配置管理端点暴露了 CRUD 能力,当前代码层未看到明确鉴权/角色控制。虽然敏感字段已做脱敏,但未授权配置变更会直接影响支付。 | 为 `/alipay/config/**` 增加管理端权限控制,只允许平台管理员或租户管理员访问;内部 Feign 查询端点也应通过网关或服务间鉴权限制。 |
| A10 | 中危 | 待修复 | `AliPayController.java:143`、`AliPayController.java:159` | 支付回调日志直接打印完整 `params`,其中可能包含用户、交易、签名等敏感信息,日志量也可能较大。 | 日志只保留 `out_trade_no`、`trade_no`、`trade_status`、`app_id/auth_app_id` 等必要字段;签名、买家标识等字段脱敏。 |
| A11 | 中危 | 待修复 | `AliPayController.java:296` | `toMap` 先调用 `request.getParameter("charset")`,再 `setCharacterEncoding`。如果容器已经解析参数,后续设置编码可能不再生效。 | 优先从原始请求体或请求头确定编码;至少在读取任何参数前设置默认 UTF-8,避免中文字段导致验签异常。 |
| A12 | 低危/文档 | 待修复 | `zlt-doc/alipay/alipay-flow.html:250` | 流程文档仍描述“查 `sys_user` 表、写 `openId`”,但实际实现已使用 `sys_user_third_openid` 映射表。 | 更新文档为“按 `provider + app_id + open_id` 查询 `sys_user_third_openid`,再关联 `sys_user`”。 |
| A13 | 低危/文档 | 待修复 | `zlt-doc/alipay/alipay-flow.html:323` | 文档写支付回调“按 `app_id` 查配置”,实际代码优先使用 `auth_app_id`,缺省才回退 `app_id`。 | 更新文档,明确 ISV 模式下优先按 `auth_app_id` 定位商家配置。 |
## 建议修复顺序
1. 先处理 A1,确保项目在 Spring Boot 3 环境下可编译、可运行。
2. 再处理 A2、A3、A4、A5,这些问题直接关系到支付安全和多租户数据隔离。
3. 然后处理 A6、A7,保证退款状态和渠道退款结果一致。
4. 之后处理 A8、A9、A10、A11,降低运维、安全和回调稳定性风险。
5. 最后同步 A12、A13 文档,避免联调误解。
## 验证记录
尝试执行以下构建验证命令:
```bash
mvn -pl zlt-business/order-center -am -DskipTests compile
```
当前环境返回 `mvn` 命令不存在,未完成构建验证。后续在配置 Maven 后,应至少执行:
```bash
mvn -pl zlt-business/order-center -am -DskipTests compile
mvn -pl zlt-uaa,zlt-business/order-center,zlt-business/user-center -am test
```
## 涉及文件
- `zlt-doc/alipay/alipay-flow.html`
- `zlt-business/order-center/src/main/java/com/central/order/controller/AliPayController.java`
- `zlt-business/order-center/src/main/java/com/central/order/controller/RefundController.java`
- `zlt-business/order-center/src/main/java/com/central/order/controller/AlipayConfigController.java`
- `zlt-business/order-center/src/main/resources/mapper/OrderMapper.xml`
- `zlt-commons/zlt-alipay-spring-boot-starter/src/main/java/com/central/alipay/config/AlipayClientFactory.java`
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,329 @@
# 支付宝小程序登录全流程实现说明
> 版本:v1.0
> 作者:duzhichao
> 日期:2026-06-12
> 状态:已落地(基于代码实录)
>
> 关联文档:
> - [支付宝小程序登录与支付对接设计文档.md](支付宝小程序登录与支付对接设计文档.md)(设计意图)
> - [支付宝小程序登录与支付代码Review问题清单.md](支付宝小程序登录与支付代码Review问题清单.md)(评审整改)
>
> 本文档基于 `zlt-uaa` + `zlt-alipay-spring-boot-starter` + `user-center` 实际代码梳理,记录端到端链路与关键设计决策。如和设计文档不一致,以本文为准(以代码为准)。
---
## 一、整体链路总览
```
小程序 网关 zlt-uaa order-center 支付宝
│ my.getAuthCode │ │ │ │
│ my.getPhoneNumber │ │ │ │
│─ POST /oauth2/token (grant_type=alipay, code, encryptedPhone, appCode) │
│ │── 路由 ────────▶│ │ │
│ │ │── Feign getConfigByAppId ─▶│ │
│ │ │◀── AlipayConfig ───────────│ │
│ │ │── alipay.system.oauth.token ──────────────────────────────▶│
│ │ │◀── access_token, userId, openId ──────────────────────────│
│ │ │── alipay.user.info.share ─────────────────────────────────▶│
│ │ │◀── unionId, avatar, nickName ─────────────────────────────│
│ │ │ 本地 AES 解密 encryptedPhone → mobile │
│ │ │ findByAlipayOpenId → 命中/新建 SysUser + 写映射表 │
│ │ │ 颁发 access_token / refresh_token │
│◀──────── token 响应 ──────────────────│ │ │
```
---
## 二、前端(支付宝小程序)
```js
// 1. 拿 auth_code
my.getAuthCode({
scopes: 'auth_user',
success: (r) => { code = r.authCode }
})
// 2. 可选:拿加密手机号
my.getPhoneNumber({
success: (r) => { encryptedPhone = r.response }
})
```
- `code`:一次性 auth_code,用来换 user_id / openId。
- `encryptedPhone`:外层是一段完整 JSON 报文 `{ response: "<AES密文>", sign, sign_type, encrypt_type, charset }`,整段透传给后端,**不要前端自行拆解**。
---
## 三、网关 → zlt-uaa:`POST /oauth2/token`
请求头:
- `Authorization: Basic <base64(client_id:client_secret)>`
- `Content-Type: application/x-www-form-urlencoded`
form 参数:
| 参数 | 必填 | 说明 |
| ---------------- | ---- | --------------------------------------------- |
| `grant_type` | ✅ | 固定 `alipay` |
| `code` | ✅ | `my.getAuthCode` 返回的 `authCode` |
| `appCode` | ✅ | 支付宝小程序 AppId(用来定位 `AlipayConfig`) |
| `encryptedPhone` | ❌ | `my.getPhoneNumber` 回调中的 `response` 字段(整段 JSON) |
---
## 四、zlt-uaa 内部链路
按 `grant_type=alipay` 走 Spring Authorization Server 自定义授权链路:
### 4.1 AlipayAuthenticationConverter
`zlt-uaa/src/main/java/com/central/oauth/support/alipay/AlipayAuthenticationConverter.java`
- `supportGrantType()` → `"alipay"`
- 从 form 解析 `code` / `encryptedPhone` / `appCode`
- 构造**未认证**的 `AlipayAuthenticationToken(code, encryptedPhone, appCode)`
### 4.2 AlipayAuthenticationProvider#getPrincipal
`zlt-uaa/src/main/java/com/central/oauth/support/alipay/AlipayAuthenticationProvider.java:57`
执行以下顺序步骤:
#### Step A:拉支付宝配置
```java
AlipayConfig config = alipayConfigService.getConfigByAppId(appCode, "MINI");
```
- 通过 `AlipayConfigService` Feign 调 order-center
- 按 `appId + type=MINI` 定位
- 返回含 `appPrivateKey / alipayPublicKey / encryptKey / signType / charset` 等字段
- 未命中抛 `CustomOAuth2AuthenticationException("不支持的支付宝应用: " + appCode)`
#### Step B:换取支付宝用户标识
`AlipayLoginService.code2userId(config, code)` (`zlt-commons/zlt-alipay-spring-boot-starter/src/main/java/com/central/alipay/service/AlipayLoginService.java:75`)
1. **`alipay.system.oauth.token`**:用 auth_code 换 `access_token + userId + openId`
- 失败:`subCode/subMsg` 抛 `RuntimeException`
2. **`alipay.user.info.share`**:用 access_token 拉 `unionId / avatar / nickName`
- **不返回手机号**
- 失败只 warn,不阻断登录(unionId 等可后补)
3. 返回 `AlipayLoginResult(userId, openId, unionId, avatar, nickName)`
#### Step C(可选):本地 AES 解密手机号
`AlipayLoginService.decryptPhone(config, encryptedPhone)` (`AlipayLoginService.java:144`)
> **关键决策**:支付宝小程序手机号官方就是商家用自己的 AES key 本地解密,**不存在** `alipay.user.phone.number.decrypt` 这个 OpenAPI(之前编译报错正是因为代码试图调它,相关 SDK Request 类在 `alipay-sdk-java:4.40.816.ALL` 中不存在)。
实现要点:
1. 入参兼容两种形态:
- 完整外层 JSON 报文:先 parse 取内层 `response` 字段
- 已剥离的密文:直接当密文处理
2. 用 `config.encryptKey` 调 `com.alipay.api.internal.util.AlipayEncrypt.decryptContent(cipher, "AES", key, charset)` 在本地完成 AES 解密
3. 解析明文 JSON `{ "code":"10000", "msg":"Success", "mobile":"13xxx" }`,校验 `code=10000` 后返回 `mobile`
4. 任何异常只返回 `null`(手机号解密失败不阻断登录)
5. `charset` 取 `config.getCharset()`,兜底 `UTF-8`
#### Step D:查找/注册系统用户
```java
userDetailsServiceFactory.getService(authToken)
.loadUserByAlipayUserId(alipayUserId, unionId, mobile, appCode)
```
→ `SysUserService.findByAlipayOpenId(alipayUserId, unionId, mobile, appId)` (`zlt-business/user-center/.../SysUserServiceImpl.java:154`)
执行逻辑:
1. **查映射表** `sys_user_third_openid`:`provider=ALIPAY` + `app_id` + `open_id`
2. **命中**:取出对应 `SysUser`,回写 `mobile`/`unionId` 到映射记录
3. **未命中**:
1. Redis 分布式锁 `alipay:user:<alipayUserId>`(5s 超时)
2. 加锁后**双重检查**映射表
3. 若有 `mobile`,先 `selectByMobile` 关联已有账号 → 写映射
4. 仍未命中,新建 `SysUser`:
- `username = "alipay_" + alipayUserId`
- `type = APP`
- `password = alipayUserId`(占位,OAuth 流程不用)
- `enabled = true`
- 入库后写映射表
5. `finally` 释放锁
返回 SysUser → `LoginUserUtils.getLoginAppUser(sysUser)` → `UserDetails`。
#### Step E:返回已认证 Token
```java
return new AlipayAuthenticationToken(userDetails, userDetails.getAuthorities(),
encryptedPhone, appCode);
```
Authorization Server 后续生成 `access_token` / `refresh_token`,按 OAuth2 标准响应格式返回前端。
---
## 五、关键设计决策
### 5.1 不复用 SysUser.openId 字段
- 历史上 `SysUser.openId` 已被 `grant_type=openId`(微信 / 默认)独占。
- 支付宝、未来其他第三方统一走映射表 `sys_user_third_openid`,按三元组 `(provider, app_id, open_id)` 定位。
- DB 唯一索引 `uk_provider_appid_openid` 保证幂等。
### 5.2 手机号本地 AES 解密
- 支付宝小程序手机号**没有解密 OpenAPI**,商家用自己的 `encryptKey`(AES key)本地解密。
- 直接用 SDK 自带 `com.alipay.api.internal.util.AlipayEncrypt` 工具类,无需引入第三方加解密库。
- `AlipayConfig.encryptKey` 配置缺失时,`decryptPhone` 直接 error log + 返回 `null`,不抛异常(手机号解密属于增强能力,不阻断登录主链路)。
### 5.3 多租户 + 多应用配置
- `AlipayConfig` 按 `tenantId / type(MINI|PAY) / appId` 定位。
- 同一套 UAA 可同时支撑多个支付宝小程序、多个租户。
- 配置 CRUD 归属 `order-center`(与微信支付配置同构)。
### 5.4 并发幂等
- 首登并发场景双保险:
- **应用层**:分布式锁 `alipay:user:<alipayUserId>` + 加锁后**双重检查**映射表
- **DB 层**:`sys_user_third_openid` 唯一索引
### 5.5 降级策略
| 失败点 | 处理 |
| ----------------------- | ----------------- |
| `code2userId` 失败 | 抛 `CustomOAuth2AuthenticationException`,登录中断 |
| `alipay.user.info.share` 失败 | warn,继续走(unionId/avatar 后补) |
| `decryptPhone` 失败 | warn,登录继续,mobile=null |
| `sys_user_third_openid` 映射存在但 SysUser 缺失 | 抛 `RuntimeException("用户数据异常")`(异常状态,需人工) |
---
## 六、密钥配置说明(appPrivateKey / alipayPublicKey / encryptKey)
`AlipayConfig` 里有三把关键 key,**算法、生成方、用途、是否成对都不同**,本节集中说明,避免混用。
### 6.1 一句话区分
| 字段 | 算法 | 谁生成 | 配对关系 | 用途 |
| ---- | ---- | ------ | -------- | ---- |
| `appPrivateKey` | RSA 私钥(非对称) | **商家自己**(支付宝官方密钥工具) | 与商家自己的 `appPublicKey` 成对 | 商家**签名**请求 |
| `alipayPublicKey` | RSA 公钥(非对称) | **支付宝平台**下发 | 与支付宝平台私钥成对 | 商家**验签**支付宝返回 |
| `encryptKey` | AES 对称密钥 | **支付宝平台**自动生成(开发设置 → 接口加密方式 → 设置/重置) | 单一对称密钥 | 本地**加解密**敏感数据(手机号) |
> RSA 两把 key 是**两组互不相干的密钥对**:
> - 商家私钥 ↔ 商家公钥(上传到开放平台)
> - 支付宝平台私钥 ↔ 支付宝公钥(即 `alipayPublicKey`,从开放平台复制)
### 6.2 各自获取方式
#### `appPrivateKey` — 应用私钥
1. 用支付宝官方密钥生成工具(开放平台下载)本地生成 RSA 密钥对
2. 把**公钥**上传到开放平台
3. **私钥**留在本地,填入 `alipay_config.app_private_key`
4. 形态:一长串 Base64 字符串,PKCS8 格式
#### `alipayPublicKey` — 支付宝公钥
1. 上传完应用公钥后,开放平台同页会显示"**支付宝公钥**"
2. 复制下来填入 `alipay_config.alipay_public_key`
#### `encryptKey` — 接口内容加密密钥
1. 开放平台 → 应用 → **开发设置 → 接口加密方式(接口内容加密方式)**
2. 选 **AES**,点 **设置/重置** → 平台自动生成 24 字符 Base64(AES-128)
3. 复制保存(**只显示一次**),填入 `alipay_config.encrypt_key`
4. 重置后旧的加密手机号将无法解密,谨慎操作
### 6.3 本项目里的协作时序
以登录链路为例:
```
商家服务器 支付宝服务器
│ │
│ 1. 用 appPrivateKey 签名请求 ───────────────────▶│
│ alipay.system.oauth.token │
│ │
│◀── 2. 支付宝用平台私钥签名响应 ────────────────────│
│ 商家用 alipayPublicKey 验签 │
│ │
│ 3. 拿到 access_token / userId / openId │
│ │
│ 4. 前端传来 encryptedPhone(my.getPhoneNumber 密文)│
│ 本地用 encryptKey 做 AES 解密 → 明文 mobile │
│ (此步不调支付宝接口) │
```
- 第 1、2 步:RSA 双向签名/验签,由 `AlipayClient` SDK 自动完成
- 第 4 步:纯本地 AES 解密,仅用 `encryptKey`,与 RSA 链路无关
### 6.4 缺失时的影响
| 缺失 | 影响 |
| ---- | ---- |
| `appPrivateKey` | **登录全链路失败**:OpenAPI 调用无法签名 |
| `alipayPublicKey` | **登录全链路失败**:响应验签不通过 |
| `encryptKey` | **登录正常**:仅手机号解密失败、`mobile=null`(按 5.5 节降级) |
> 简记:**RSA 两把 key 缺了登录全断;AES key 缺了只是拿不到手机号**。
### 6.5 安全注意事项
- `appPrivateKey` 和 `encryptKey` 都属于**敏感凭证**,禁止写入代码仓库、日志、错误响应
- 配置统一存 `alipay_config` 表,由 order-center 管理后台维护
- 建议表字段加密存储 / 上线前校验日志输出脱敏
- 不同租户、不同小程序应**各自独立**配置,不要复用
---
## 七、关键文件清单
| 模块 | 文件 | 职责 |
| --- | --- | --- |
| `zlt-uaa` | `oauth/support/alipay/AlipayAuthenticationConverter.java` | OAuth2 form → Token |
| `zlt-uaa` | `oauth/support/alipay/AlipayAuthenticationProvider.java` | 主流程编排 |
| `zlt-commons/zlt-auth-client-spring-boot-starter` | `oauth2/common/token/AlipayAuthenticationToken.java` | 自定义 grant_type Token |
| `zlt-commons/zlt-alipay-spring-boot-starter` | `alipay/service/AlipayLoginService.java` | code2userId / decryptPhone |
| `zlt-commons/zlt-alipay-common-core` | `alipay/entity/AlipayConfig.java` | 配置实体(含 encryptKey) |
| `zlt-business/order-center` | `controller/AlipayConfigController.java` | 配置 CRUD(管理后台) |
| `zlt-business/user-center` | `service/impl/SysUserServiceImpl.java#findByAlipayOpenid` | 找/建 SysUser + 写映射表 |
| `zlt-uaa` | `oauth/service/impl/UserDetailServiceImpl.java#loadUserByAlipayUserId` | UserDetails 包装 |
| DB | `sys_user_third_openid` | 三方账号映射表(唯一索引 `uk_provider_appid_openid`) |
| DB | `alipay_config` | 多租户支付宝配置(含 `encryptKey`) |
---
## 八、与微信小程序登录链路对照
| 维度 | 微信小程序 | 支付宝小程序 |
| ----------- | ----------------------------------------- | ------------------------------------------- |
| grant_type | `tencent` | `alipay` |
| Provider | `TencentAuthenticationProvider` | `AlipayAuthenticationProvider` |
| 配置实体 | `WechatConfig` | `AlipayConfig` |
| 配置 Feign | `WechatConfigService` | `AlipayConfigService` |
| 用户标识 | `openId` / `unionId` | `userId` / `openId` / `unionId` |
| 手机号 | `wx.getPhoneNumber` + 微信 OpenAPI 解密 | `my.getPhoneNumber` + 商家本地 AES 解密 |
| 用户落库 | 复用 `SysUser.openId`(历史遗留) | `sys_user_third_openid` 映射表(统一三方接入) |
---
## 九、踩坑记录
1. **AlipayUserPhoneNumberDecryptRequest 不存在**
- 现象:编译期 `无法解析符号 'AlipayUserPhoneNumberDecryptRequest'`
- 原因:支付宝 Java SDK 4.40.816.ALL(及更老 4.38.157.ALL)中**没有**该类,因为支付宝小程序手机号本就是商家本地 AES 解密,没有对应 OpenAPI。
- 解决:改用 `AlipayEncrypt.decryptContent` 本地解密(参见 5.2)。
2. **`SysUser sysUser` 未初始化告警**
- 现象:`findByAlipayOpenid` 中 `if (sysUser == null)` 处编译告警/报错。
- 原因:DA(definite assignment)分析:`recheck == null && mobile 为空`时,`sysUser` 没被赋值就到了下面的 null 判断。
- 解决:声明时显式初始化 `SysUser sysUser = null`。
3. **`PageResult.getList()` 不存在**
- 现象:`AlipayConfigController.list()` 中 `pageResult.getList()` 编译报错。
- 原因:`PageResult` 字段名是 `data`,Lombok 生成的是 `getData()`。
- 解决:改成 `getData()`。
+5
View File
@@ -50,6 +50,11 @@
<groupId>com.zlt</groupId>
<artifactId>zlt-wechat-common-core</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-alipay-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
@@ -16,6 +16,10 @@ import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationConverte
import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider;
import com.central.oauth.support.tencent.TencentAuthenticationConverter;
import com.central.oauth.support.tencent.TencentAuthenticationProvider;
import com.central.oauth.support.alipay.AlipayAuthenticationConverter;
import com.central.oauth.support.alipay.AlipayAuthenticationProvider;
import com.central.alipay.feign.AlipayConfigService;
import com.central.alipay.service.AlipayLoginService;
import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector;
import com.central.oauth2.common.component.CustomBearerTokenResolver;
import com.central.oauth2.common.config.BaseSecurityConfig;
@@ -74,6 +78,8 @@ public class AuthorizationServerConfig {
private final RegisteredClientService registeredClientService;
private final RedisSecurityContextRepository securityContextRepository;
private final AuthenticationSuccessHandler authenticationSuccessHandler;
private final AlipayLoginService alipayLoginService;
private final AlipayConfigService alipayConfigService;
/**
* spring security 默认的安全策略
*/
@@ -110,6 +116,7 @@ public class AuthorizationServerConfig {
.authenticationProvider(new OpenIdAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory))
.authenticationProvider(new MobileAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder))
.authenticationProvider(new TencentAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory,securityProperties))
.authenticationProvider(new AlipayAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, alipayLoginService, alipayConfigService))
)
// 开启OpenID Connect 1.0协议相关端点
.oidc(Customizer.withDefaults())
@@ -149,6 +156,7 @@ public class AuthorizationServerConfig {
new PasswordCodeAuthenticationConverter(),
new OpenIdAuthenticationConverter(),
new MobileAuthenticationConverter(),
new TencentAuthenticationConverter()));
new TencentAuthenticationConverter(),
new AlipayAuthenticationConverter()));
}
}
@@ -19,9 +19,13 @@ import com.central.oauth.support.openid.OpenIdAuthenticationProvider;
import com.central.oauth.support.password.PasswordAuthenticationProvider;
import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider;
import com.central.oauth.support.tencent.TencentAuthenticationProvider;
import com.central.oauth.support.alipay.AlipayAuthenticationProvider;
import com.central.alipay.feign.AlipayConfigService;
import com.central.alipay.service.AlipayLoginService;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.token.OpenIdAuthenticationToken;
import com.central.oauth2.common.token.TencentAuthenticationToken;
import com.central.oauth2.common.token.AlipayAuthenticationToken;
import com.central.oauth2.common.util.AuthUtils;
import com.central.common.feign.UserService;
import io.swagger.v3.oas.annotations.Operation;
@@ -102,6 +106,12 @@ public class LoginController {
@Resource
private UserService userService;
@Resource
private AlipayLoginService alipayLoginService;
@Resource
private AlipayConfigService alipayConfigService;
/**
* 短信验证码Redis Key前缀
*/
@@ -118,6 +128,17 @@ public class LoginController {
@org.springframework.beans.factory.annotation.Value("${sms.provider:tencent}")
private String smsProvider;
/**
* 登录接口
* 支付宝登录接口参数 {
* "grantType": "alipay",
* "clientId": "webApp",
* "code": "7b1e3f8a9c2d4e5f6a7b8c9d0e1f2a3b",
* "appCode": "2021000000000001",
* "encryptedPhone":"支付宝加密手机号密文"
* }
*/
@PostMapping(value = "/login")
public Result<Map<String, Object>> login(@RequestBody LoginReq req) {
try {
@@ -419,6 +440,21 @@ public class LoginController {
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
break;
}
case "alipay": {
AlipayAuthenticationProvider provider = new AlipayAuthenticationProvider(
authorizationService, tokenGenerator, userDetailServiceFactory,
alipayLoginService, alipayConfigService);
AlipayAuthenticationToken authToken = new AlipayAuthenticationToken(
req.getCode(), req.getEncryptedPhone(),
StringUtils.isBlank(req.getAppCode()) ? "" : req.getAppCode());
authToken.setScopes(registeredClient.getScopes());
authToken.setClientPrincipal(clientPrincipal);
java.util.HashMap<String, Object> ap = new java.util.HashMap<>();
ap.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, SecurityConstants.DEF_ACCOUNT_TYPE);
authToken.setAdditionalParameters(ap);
accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) provider.authenticate(authToken);
break;
}
default:
return Result.failed("不支持的授权类型: " + req.getGrantType());
}
@@ -15,7 +15,7 @@ public class LoginReq {
@Schema(description = "密码(RSA 加密)。grantType 为 password/password_code/mobile_password 必填")
private String password;
@Schema(description = "认证类型:1)用户名+密码=password;2)用户名+密码+验证码=password_code;3)手机号+密码=mobile_password;4)OpenId=openId;5)微信小程序=tencent。必填")
@Schema(description = "认证类型:1)用户名+密码=password;2)用户名+密码+验证码=password_code;3)手机号+密码=mobile_password;4)OpenId=openId;5)微信小程序=tencent;6)支付宝小程序=alipay。必填")
private String grantType;
@Schema(description = "手机号(grantType 为 mobile_password 必填)")
@@ -42,7 +42,10 @@ public class LoginReq {
@Schema(description = "微信小程序 iv(tencent 模式建议必填)")
private String iv;
@Schema(description = "应用标识 appCode(tencent 模式可选,缺省使用默认配置)")
@Schema(description = "应用标识 appCode(tencent/alipay 模式可选,指向第三方应用 appId)")
private String appCode;
@Schema(description = "支付宝小程序加密手机号密文(alipay 模式可选)")
private String encryptedPhone;
}
@@ -48,6 +48,15 @@ public interface ZltUserDetailsService extends UserDetailsService {
*/
WechatConfig loadMiniAppConfig(String appId, String type);
/**
* 根据支付宝userId查询用户
* @param alipayUserId 支付宝用户唯一标识
* @param unionId 支付宝unionId(同PID下唯一)
* @param mobile 手机号
* @param appId 支付宝应用ID
*/
UserDetails loadUserByAlipayUserId(String alipayUserId, String unionId, String mobile, String appId) throws UsernameNotFoundException;
/**
* 检查登录用户
* @return
@@ -59,6 +59,13 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
public UserDetails loadUserByAlipayUserId(String alipayUserId, String unionId, String mobile, String appId) throws UsernameNotFoundException {
SysUser sysUser = userService.findByAlipayOpenId(alipayUserId, unionId, mobile, appId);
checkUser(sysUser);
return LoginUserUtils.getLoginAppUser(sysUser);
}
@Override
public WechatConfig loadMiniAppConfig(String appId, String type) {
return wechatConfigService.getConfigByAppId(appId, type);
@@ -94,6 +101,11 @@ public class UserDetailServiceImpl implements ZltUserDetailsService {
return Result.failed("iv不能为空");
}
return Result.succeed("校验通过");
} else if ("alipay".equals(grantType)) {
if (StringUtils.isBlank(req.getCode())) {
return Result.failed("支付宝授权code不能为空");
}
return Result.succeed("校验通过");
} else {
if (StringUtils.isBlank(req.getUserName())) {
return Result.failed("用户名不能为空");
@@ -0,0 +1,41 @@
package com.central.oauth.support.alipay;
import com.central.oauth.support.base.BaseAuthenticationConverter;
import com.central.oauth.utils.OAuthEndpointUtils;
import com.central.oauth2.common.token.AlipayAuthenticationToken;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import java.util.List;
/**
* 支付宝登录参数转换器(对标 TencentAuthenticationConverter)
*
* @author duzhichao
* @date 2026-05-12
*/
public class AlipayAuthenticationConverter extends BaseAuthenticationConverter {
@Override
protected String supportGrantType() {
return AlipayAuthenticationToken.GRANT_TYPE.getValue();
}
@Override
protected List<String> paramNames() {
return List.of(OAuth2ParameterNames.CODE);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {
String code = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.CODE);
String encryptedPhone = OAuthEndpointUtils.getParam(parameters, "encryptedPhone");
String appCode = OAuthEndpointUtils.getParam(parameters, "appCode");
if (appCode == null) {
appCode = "";
}
return new AlipayAuthenticationToken(code, encryptedPhone, appCode);
}
}
@@ -0,0 +1,116 @@
package com.central.oauth.support.alipay;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.AlipayConfigService;
import com.central.alipay.service.AlipayLoginService;
import com.central.oauth.exception.CustomOAuth2AuthenticationException;
import com.central.oauth.service.impl.UserDetailServiceFactory;
import com.central.oauth.support.base.BaseAuthenticationProvider;
import com.central.oauth2.common.token.AlipayAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
/**
* 支付宝小程序登录 Provider(对标 TencentAuthenticationProvider)
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Setter
@Getter
public class AlipayAuthenticationProvider extends BaseAuthenticationProvider {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final AlipayLoginService alipayLoginService;
private final AlipayConfigService alipayConfigService;
public AlipayAuthenticationProvider(OAuth2AuthorizationService authorizationService,
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator,
UserDetailServiceFactory userDetailsServiceFactory,
AlipayLoginService alipayLoginService,
AlipayConfigService alipayConfigService) {
super(authorizationService, tokenGenerator);
Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null");
Assert.notNull(alipayLoginService, "alipayLoginService cannot be null");
Assert.notNull(alipayConfigService, "alipayConfigService cannot be null");
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.alipayLoginService = alipayLoginService;
this.alipayConfigService = alipayConfigService;
}
@Override
public boolean supports(Class<?> authentication) {
return AlipayAuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
protected Authentication getPrincipal(Authentication authentication) {
AlipayAuthenticationToken authToken = (AlipayAuthenticationToken) authentication;
String code = (String) authToken.getPrincipal();
String encryptedPhone = authToken.getEncryptedPhone();
String appCode = authToken.getAppCode();
// 1. 根据 appCode(即支付宝 AppId)查找配置(通过 AlipayConfigService Feign)
AlipayConfig config = alipayConfigService.getConfigByAppId(appCode, "MINI");
if (config == null) {
throw new CustomOAuth2AuthenticationException("不支持的支付宝应用: " + appCode);
}
// 2. 调用支付宝 SDK 换取用户标识
AlipayLoginService.AlipayLoginResult loginResult;
try {
loginResult = alipayLoginService.code2userId(config, code);
} catch (Exception e) {
log.error("支付宝登录获取用户标识失败", e);
throw new CustomOAuth2AuthenticationException("支付宝登录失败: " + e.getMessage());
}
String alipayUserId = loginResult.getUserId();
String unionId = loginResult.getUnionId();
// 3. 若前端通过 my.getPhoneNumber 拿到加密手机号,调用 alipay.user.phone.number.decrypt 解密
String mobile = null;
if (encryptedPhone != null && !encryptedPhone.isEmpty()) {
try {
mobile = alipayLoginService.decryptPhone(config, encryptedPhone);
} catch (Exception e) {
log.warn("支付宝手机号解密失败,跳过手机号绑定: {}", e.getMessage());
}
}
log.info("支付宝登录: userId={}, openId={}, unionId={}, mobile={}",
alipayUserId, loginResult.getOpenId(), unionId, mobile);
// 4. 查找或注册系统用户
UserDetails userDetails;
try {
userDetails = userDetailsServiceFactory.getService(authToken)
.loadUserByAlipayUserId(alipayUserId, unionId, mobile, appCode);
} catch (AuthenticationException e) {
throw new CustomOAuth2AuthenticationException(e.getMessage());
}
if (userDetails == null) {
throw new CustomOAuth2AuthenticationException("用户登录信息待处理,请重新登录");
}
return new AlipayAuthenticationToken(userDetails, userDetails.getAuthorities(),
encryptedPhone, appCode);
}
@Override
protected AuthorizationGrantType grantType() {
return AlipayAuthenticationToken.GRANT_TYPE;
}
}
+1
View File
@@ -15,6 +15,7 @@ export default [
{ path: '/system/user.html', component: '@/pages/system/User' },
{ path: '/system/tenant.html', component: '@/pages/system/TenantManage' },
{ path: '/system/miniApp.html', component: '@/pages/system/MiniApp' },
{ path: '/system/alipayApp.html', component: '@/pages/system/AlipayApp' },
],
},
{
@@ -0,0 +1,299 @@
import React from 'react';
import {
ModalForm,
ProForm,
ProFormDependency,
ProFormSelect,
ProFormSwitch,
ProFormText,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Alert, Divider } from 'antd';
import { AlipayConfigItem } from '@/services/alipayConfig';
export interface AlipayAppFormProps {
open: boolean;
title: string;
initialValues?: Partial<AlipayConfigItem>;
onOpenChange: (v: boolean) => void;
onFinish: (values: AlipayConfigItem) => Promise<boolean>;
}
const SectionTitle: React.FC<{ children: React.ReactNode; tip?: string }> = ({
children,
tip,
}) => (
<div style={{ margin: '4px 0 12px' }}>
<Divider orientation="left" style={{ margin: '8px 0' }}>
<span style={{ fontWeight: 600 }}>{children}</span>
</Divider>
{tip ? (
<div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 8 }}>
{tip}
</div>
) : null}
</div>
);
const AlipayAppForm: React.FC<AlipayAppFormProps> = ({
open,
title,
initialValues,
onOpenChange,
onFinish,
}) => {
return (
<ModalForm<AlipayConfigItem>
title={title}
visible={open}
onVisibleChange={onOpenChange}
onFinish={onFinish}
initialValues={{
signType: 'RSA2',
charset: 'UTF-8',
format: 'json',
gatewayUrl: 'https://openapi.alipay.com/gateway.do',
status: 1,
type: 'MINI',
...initialValues,
}}
modalProps={{ destroyOnClose: true, width: 760 }}
layout="horizontal"
labelCol={{ flex: '110px' }}
wrapperCol={{ flex: 1 }}
labelAlign="right"
>
{/* ========= 基础信息 ========= */}
<SectionTitle>基础信息</SectionTitle>
<ProForm.Group>
<ProFormSelect
name="type"
label="配置类型"
width="sm"
tooltip="MINI=小程序登录,仅做 OAuth 登录与手机号解密;PAY=交易支付,用于服务商/直连下单与回调"
options={[
{ label: '小程序登录 (MINI)', value: 'MINI' },
{ label: '交易支付 (PAY)', value: 'PAY' },
]}
rules={[{ required: true, message: '请选择配置类型' }]}
/>
<ProFormText
name="tenantId"
label="租户ID"
width="sm"
placeholder="留空使用默认租户"
/>
<ProFormText
name="appId"
label="AppID"
width="md"
rules={[{ required: true, message: '请输入支付宝 AppID' }]}
placeholder="支付宝开放平台分配的应用 AppID"
/>
<ProFormSelect
name="status"
label="状态"
width="xs"
options={[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]}
rules={[{ required: true }]}
/>
</ProForm.Group>
{/* ========= 类型差异提示 ========= */}
<ProFormDependency name={['type']}>
{({ type }) =>
type === 'PAY' ? (
<Alert
showIcon
type="info"
style={{ marginBottom: 16 }}
message="交易支付配置"
description="用于支付宝下单 / 退款 / 异步通知,需配置网关、支付回调地址;服务商模式还需 PID 与子商户号。"
/>
) : (
<Alert
showIcon
type="success"
style={{ marginBottom: 16 }}
message="小程序登录配置"
description="用于 my.getAuthCode 换 userId、my.getPhoneNumber 本地 AES 解密。AES Key 必填,否则无法解密手机号。"
/>
)
}
</ProFormDependency>
{/* ========= 密钥与签名(公共) ========= */}
<SectionTitle tip="appPrivateKey 用于商家请求签名;alipayPublicKey 用于验证支付宝返回。两把 RSA Key 缺失会导致登录/支付全部失败。">
密钥与签名
</SectionTitle>
<ProForm.Group>
<ProFormSelect
name="signType"
label="签名算法"
width="sm"
tooltip="SDK 请求签名 / 回调验签算法,开放平台默认 RSA2"
options={[
{ label: 'RSA2(推荐)', value: 'RSA2' },
{ label: 'RSA', value: 'RSA' },
]}
/>
<ProFormText name="charset" label="字符集" width="sm" />
<ProFormText name="format" label="数据格式" width="sm" />
</ProForm.Group>
<ProFormTextArea
name="appPrivateKey"
label="应用私钥"
tooltip="商家本地生成的 RSA 私钥(PKCS8),用于签名所有 OpenAPI 请求"
placeholder={`-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----`}
fieldProps={{ rows: 4, autoComplete: 'off' }}
rules={[{ required: true, message: '请输入应用私钥' }]}
/>
<ProFormTextArea
name="alipayPublicKey"
label="支付宝公钥"
tooltip="开放平台下发的支付宝公钥,用于验证响应/回调签名"
placeholder={`-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----`}
fieldProps={{ rows: 4, autoComplete: 'off' }}
rules={[{ required: true, message: '请输入支付宝公钥' }]}
/>
{/* ========= 证书模式 ========= */}
<ProFormSwitch
name="certMode"
label="证书模式"
tooltip="开启后改用支付宝公钥证书验签(需上传三份证书路径),关闭则使用普通公钥模式"
/>
<ProFormDependency name={['certMode']}>
{({ certMode }) =>
certMode ? (
<>
<ProFormText
name="appCertPath"
label="应用公钥证书路径"
placeholder="/path/to/appCertPublicKey.crt"
rules={[{ required: true, message: '证书模式下必填' }]}
/>
<ProFormText
name="alipayCertPath"
label="支付宝公钥证书路径"
placeholder="/path/to/alipayCertPublicKey_RSA2.crt"
rules={[{ required: true, message: '证书模式下必填' }]}
/>
<ProFormText
name="alipayRootCertPath"
label="支付宝根证书路径"
placeholder="/path/to/alipayRootCert.crt"
rules={[{ required: true, message: '证书模式下必填' }]}
/>
</>
) : null
}
</ProFormDependency>
{/* ========= MINI 专属:AES 加解密 Key ========= */}
<ProFormDependency name={['type']}>
{({ type }) =>
type === 'MINI' ? (
<>
<SectionTitle tip="支付宝小程序 my.getPhoneNumber 返回的密文,由商家本地 AES 解密。开放平台「开发设置 → 接口加密方式」生成。">
小程序加解密
</SectionTitle>
<ProFormText
name="encryptKey"
label="AES 加解密 Key"
tooltip="24 位 Base64 字符串。缺失只影响手机号解密,不阻断登录主链路"
placeholder="例如 pmwS5xxxxxxxxxxxxxxxxx=="
/>
</>
) : null
}
</ProFormDependency>
{/* ========= PAY 专属:网关 / 回调 / 服务商 ========= */}
<ProFormDependency name={['type']}>
{({ type }) =>
type === 'PAY' ? (
<>
<SectionTitle tip="网关地址通常无需修改;回调地址必须是公网可访问的 HTTPS 地址。">
支付参数
</SectionTitle>
<ProFormText
name="gatewayUrl"
label="网关地址"
tooltip="正式环境固定为 openapi.alipay.com;沙箱使用 openapi-sandbox.dl.alipaydev.com"
rules={[{ required: true, message: '请输入网关地址' }]}
/>
<ProFormText
name="notifyUrl"
label="支付回调地址"
placeholder="https://your-domain.com/api-order/alipay/pay/notify"
rules={[
{ required: true, message: '请输入支付回调地址' },
{ type: 'url', message: '需为合法 URL' },
]}
/>
<ProFormText
name="refundNotifyUrl"
label="退款回调地址"
placeholder="https://your-domain.com/api-order/alipay/refund/notify"
rules={[{ type: 'url', message: '需为合法 URL' }]}
/>
<SectionTitle tip="服务商模式(ISV)需配置 PID 与子商户信息;直连商户保持关闭即可。">
商户模式
</SectionTitle>
<ProFormSwitch name="isServiceMode" label="服务商模式" />
<ProFormDependency name={['isServiceMode']}>
{({ isServiceMode }) =>
isServiceMode ? (
<>
<ProFormText
name="pid"
label="合作伙伴 PID"
tooltip="服务商在支付宝开放平台的 PID"
rules={[
{ required: true, message: '服务商模式下必填' },
]}
/>
<ProFormText
name="authToken"
label="app_auth_token"
tooltip="商家授权服务商代调用 API 的 token"
/>
<ProFormText
name="subAppId"
label="商家应用 AppId"
tooltip="子商家在支付宝开放平台的小程序 AppId"
/>
<ProFormText
name="subMerchantId"
label="间连商户号 (smid)"
rules={[
{ required: true, message: '服务商模式下必填' },
]}
/>
</>
) : null
}
</ProFormDependency>
</>
) : null
}
</ProFormDependency>
{/* ========= 备注 ========= */}
<SectionTitle>其它</SectionTitle>
<ProFormText name="remark" label="备注" placeholder="可选,便于内部识别" />
</ModalForm>
);
};
export default AlipayAppForm;
@@ -0,0 +1,355 @@
import React, { useRef, useState } from 'react';
import {
PageContainer,
ProFormSelect,
ProFormText,
ProTable,
type ActionType,
} from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, Tooltip, Typography, message } from 'antd';
import {
ApiOutlined,
CheckCircleFilled,
CloseCircleFilled,
DeleteOutlined,
EditOutlined,
KeyOutlined,
PlusOutlined,
PoweroffOutlined,
SafetyCertificateOutlined,
ShopOutlined,
} from '@ant-design/icons';
import {
ActionBar,
GlassCard,
GradientButton,
SearchBarPlus,
} from '@/components/ui';
import { alipayConfigApi, AlipayConfigItem } from '@/services/alipayConfig';
import AlipayAppForm from './components/AlipayAppForm';
const { Text } = Typography;
const TYPE_META: Record<
string,
{ label: string; color: string; icon: React.ReactNode }
> = {
MINI: { label: '小程序登录', color: 'green', icon: <ApiOutlined /> },
PAY: { label: '交易支付', color: 'blue', icon: <ShopOutlined /> },
};
const AlipayAppPage: React.FC = () => {
const [searchParams, setSearchParams] = useState<Record<string, any>>({});
const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<AlipayConfigItem | undefined>(undefined);
const actionRef = useRef<ActionType>();
const reload = () => actionRef.current?.reload();
const columns: any[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
width: 56,
align: 'center',
},
{
title: '配置类型',
dataIndex: 'type',
width: 130,
render: (_: any, record: AlipayConfigItem) => {
const meta = TYPE_META[record.type] ?? TYPE_META.MINI;
return (
<Tag
color={meta.color}
icon={meta.icon}
style={{ padding: '2px 10px', borderRadius: 12 }}
>
{meta.label}
</Tag>
);
},
},
{
title: '租户',
dataIndex: 'tenantId',
width: 110,
copyable: true,
ellipsis: true,
render: (text: any) =>
text ? (
<Text copyable={{ tooltips: ['复制', '已复制'] }}>{text}</Text>
) : (
<Text type="secondary">默认</Text>
),
},
{
title: 'AppID',
dataIndex: 'appId',
width: 220,
ellipsis: true,
render: (_: any, record: AlipayConfigItem) => (
<Space size={6}>
<KeyOutlined style={{ color: '#8c8c8c' }} />
<Text copyable={{ text: record.appId }} style={{ marginBottom: 0 }}>
{record.appId}
</Text>
</Space>
),
},
{
title: '签名',
dataIndex: 'signType',
width: 90,
align: 'center',
render: (_: any, record: AlipayConfigItem) => (
<Tag color="purple" style={{ marginRight: 0 }}>
{record.signType || 'RSA2'}
</Tag>
),
},
{
title: '验签方式',
dataIndex: 'certMode',
width: 110,
align: 'center',
render: (_: any, record: AlipayConfigItem) => (
<Tag
icon={<SafetyCertificateOutlined />}
color={record.certMode ? 'orange' : 'default'}
>
{record.certMode ? '证书模式' : '公钥模式'}
</Tag>
),
},
{
title: '商户模式',
dataIndex: 'isServiceMode',
width: 110,
align: 'center',
render: (_: any, record: AlipayConfigItem) =>
record.type === 'PAY' ? (
<Tag color={record.isServiceMode ? 'geekblue' : 'default'}>
{record.isServiceMode ? '服务商 ISV' : '直连商户'}
</Tag>
) : (
<Text type="secondary">—</Text>
),
},
{
title: '支付回调',
dataIndex: 'notifyUrl',
ellipsis: true,
render: (_: any, record: AlipayConfigItem) =>
record.type === 'PAY' && record.notifyUrl ? (
<Tooltip title={record.notifyUrl}>
<span
style={{
display: 'inline-block',
maxWidth: 220,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
verticalAlign: 'bottom',
}}
>
{record.notifyUrl}
</span>
</Tooltip>
) : (
<Text type="secondary">—</Text>
),
},
{
title: '状态',
dataIndex: 'status',
width: 100,
align: 'center',
render: (_: any, record: AlipayConfigItem) =>
record.status === 1 ? (
<Tag icon={<CheckCircleFilled />} color="success">
启用
</Tag>
) : (
<Tag icon={<CloseCircleFilled />} color="error">
禁用
</Tag>
),
},
{
title: '操作',
key: 'action',
width: 220,
fixed: 'right',
render: (_: any, entity: AlipayConfigItem) => (
<Space size={4}>
<a
onClick={() => {
setCurrent(entity);
setEditOpen(true);
}}
>
<EditOutlined /> 编辑
</a>
<Popconfirm
title={
entity.status === 1
? '确认禁用?禁用后该应用不可用于登录或支付'
: '确认启用?启用后该应用立即可用'
}
okText="确定"
cancelText="取消"
onConfirm={async () => {
const newStatus = entity.status === 1 ? 0 : 1;
try {
await alipayConfigApi.toggleStatus(
entity.id!,
newStatus as 0 | 1,
);
message.success('切换成功');
reload();
} catch (e) {
message.error('切换失败');
}
}}
>
<a style={{ color: entity.status === 1 ? '#fa8c16' : '#52c41a' }}>
<PoweroffOutlined /> {entity.status === 1 ? '禁用' : '启用'}
</a>
</Popconfirm>
<Popconfirm
title="确认删除?删除后不可恢复,请谨慎操作"
okText="确定"
okButtonProps={{ danger: true }}
cancelText="取消"
onConfirm={async () => {
try {
await alipayConfigApi.remove(entity.id!);
message.success('删除成功');
reload();
} catch (e) {
message.error('删除失败');
}
}}
>
<a style={{ color: '#ff4d4f' }}>
<DeleteOutlined /> 删除
</a>
</Popconfirm>
</Space>
),
},
];
return (
<PageContainer
header={{
title: '支付宝应用管理',
subTitle: '统一维护小程序登录与交易支付的支付宝开放平台配置',
}}
>
<SearchBarPlus
defaultCollapsed
split
onTenantChanged={() => {}}
onFinish={async (values) => setSearchParams(values)}
>
<ProFormSelect
name="searchKey"
label="检索"
valueEnum={{ type: '类型', appId: 'AppID', tenantId: '租户' }}
/>
<ProFormText name="searchValue" placeholder="请输入关键字" />
</SearchBarPlus>
<ActionBar
left={
<GradientButton
size="middle"
key="add"
type="primary"
onClick={() => setCreateOpen(true)}
>
<PlusOutlined /> 新增配置
</GradientButton>
}
/>
<GlassCard bodyStyle={{ padding: 0 }}>
<ProTable<AlipayConfigItem>
rowKey="id"
actionRef={actionRef}
headerTitle={
<Space>
<span style={{ fontWeight: 600 }}>支付宝应用列表</span>
<Text type="secondary" style={{ fontSize: 12 }}>
同一租户可同时配置多个 AppID
</Text>
</Space>
}
request={async (params) => {
const res = await alipayConfigApi.list({
page: (params as any).current || 1,
limit: (params as any).pageSize || 10,
searchKey: searchParams.searchKey,
searchValue: searchParams.searchValue,
});
return {
data: (res as any).data,
success: (res as any).resp_code === 0,
total: (res as any).total,
} as any;
}}
columns={columns}
search={false}
params={searchParams}
scroll={{ x: 1280 }}
pagination={{
showSizeChanger: true,
showQuickJumper: true,
showTotal: (t) => `共 ${t} 条`,
}}
toolBarRender={false}
/>
</GlassCard>
<AlipayAppForm
title="新增支付宝应用"
open={createOpen}
onOpenChange={setCreateOpen}
onFinish={async (values) => {
try {
await alipayConfigApi.create(values);
message.success('新增成功');
reload();
return true;
} catch (e) {
message.error('保存失败');
return false;
}
}}
/>
<AlipayAppForm
title="编辑支付宝应用"
open={editOpen}
initialValues={current}
onOpenChange={setEditOpen}
onFinish={async (values) => {
try {
await alipayConfigApi.update({ ...(current as any), ...values });
message.success('修改成功');
reload();
return true;
} catch (e) {
message.error('修改失败');
return false;
}
}}
/>
</PageContainer>
);
};
export default AlipayAppPage;
@@ -0,0 +1,59 @@
import { request } from 'umi';
export interface AlipayConfigItem {
id?: number;
tenantId?: string;
type: 'MINI' | 'PAY';
appId: string;
appPrivateKey?: string;
alipayPublicKey?: string;
signType?: 'RSA2' | 'RSA';
charset?: string;
format?: string;
encryptKey?: string;
gatewayUrl?: string;
notifyUrl?: string;
refundNotifyUrl?: string;
isServiceMode?: boolean;
pid?: string;
authToken?: string;
subAppId?: string;
subMerchantId?: string;
certMode?: boolean;
appCertPath?: string;
alipayCertPath?: string;
alipayRootCertPath?: string;
status?: 0 | 1;
remark?: string;
}
export const alipayConfigApi = {
list: async (params: { page?: number; limit?: number; searchKey?: string; searchValue?: string }) => {
const res = await request('/api-order/alipay/config/list', { method: 'GET', params });
return {
data: (res as any).data?.data || [],
total: (res as any).data?.count || 0,
resp_code: (res as any).resp_code,
resp_msg: (res as any).resp_msg,
};
},
create: async (data: AlipayConfigItem) => {
const res = await request('/api-order/alipay/config', { method: 'POST', data });
return (res as any).data || res;
},
update: async (data: AlipayConfigItem) => {
const res = await request('/api-order/alipay/config', { method: 'PUT', data });
return (res as any).data || res;
},
remove: async (id: number) => {
const res = await request(`/api-order/alipay/config/${id}`, { method: 'DELETE' });
return (res as any).data || res;
},
toggleStatus: async (id: number, status: 0 | 1) => {
const res = await request(`/api-order/alipay/config/${id}/status`, {
method: 'PATCH',
data: { status },
});
return (res as any).data || res;
},
};