fix:支付宝小程序登录以及支付宝支付
This commit is contained in:
@@ -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>
|
||||
+58
@@ -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();
|
||||
}
|
||||
}
|
||||
+157
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -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+", "");
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+182
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+161
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+88
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
com.central.alipay.config.AlipayAutoConfiguration
|
||||
Reference in New Issue
Block a user