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
+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);