SpringBoot项目集成支付宝
在 Spring Boot 项目中对接支付宝的第三方支付接口涉及几个主要步骤:集成支付宝 SDK、配置支付宝相关信息、实现支付和退款逻辑。
1. 添加依赖
首先,你需要在项目的 pom.xml
文件中添加支付宝 SDK 的依赖。如果使用 Maven,可以添加如下依赖:
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.14.37.ALL</version> <!-- 使用最新的版本 -->
</dependency>
2. 配置支付宝信息
在 application.properties
或 application.yml
文件中配置支付宝相关的信息,包括商户 ID、应用 ID、私钥和支付宝公钥等。
# application.properties
alipay.app-id=YOUR_APP_ID
alipay.merchant-private-key=YOUR_PRIVATE_KEY
alipay.alipay-public-key=ALIPAY_PUBLIC_KEY
alipay.gateway-url=https://openapi.alipay.com/gateway.do
3. 创建支付服务
创建一个服务类来处理支付宝支付和退款请求。首先是支付请求的构造和发送:
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.response.AlipayTradePagePayResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class AlipayService {
@Value("${alipay.gateway-url}")
private String gatewayUrl;
@Value("${alipay.app-id}")
private String appId;
@Value("${alipay.merchant-private-key}")
private String privateKey;
@Value("${alipay.alipay-public-key}")
private String alipayPublicKey;
private AlipayClient alipayClient;
public AlipayService() {
alipayClient = new DefaultAlipayClient(
gatewayUrl,
appId,
privateKey,
"json",
"UTF-8",
alipayPublicKey,
"RSA2"
);
}
public String createPaymentUrl(String outTradeNo, String totalAmount, String subject) throws AlipayApiException {
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
request.setReturnUrl("http://yourdomain.com/return_url");
request.setNotifyUrl("http://yourdomain.com/notify_url");
StringBuilder bizContent = new StringBuilder();
bizContent.append("{")
.append("\"out_trade_no\":\"").append(outTradeNo).append("\",")
.append("\"total_amount\":\"").append(totalAmount).append("\",")
.append("\"subject\":\"").append(subject).append("\",")
.append("\"product_code\":\"FAST_INSTANT_TRADE_PAY\"")
.append("}");
request.setBizContent(bizContent.toString());
AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
if (response.isSuccess()) {
return response.getBody(); // 这是支付宝返回的支付页面的 HTML 内容
} else {
throw new RuntimeException("Alipay request failed: " + response.getSubMsg());
}
}
}
4. 创建退款服务
退款服务类处理退款请求:
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class AlipayRefundService {
@Value("${alipay.gateway-url}")
private String gatewayUrl;
@Value("${alipay.app-id}")
private String appId;
@Value("${alipay.merchant-private-key}")
private String privateKey;
@Value("${alipay.alipay-public-key}")
private String alipayPublicKey;
private AlipayClient alipayClient;
public AlipayRefundService() {
alipayClient = new DefaultAlipayClient(
gatewayUrl,
appId,
privateKey,
"json",
"UTF-8",
alipayPublicKey,
"RSA2"
);
}
public String refund(String outTradeNo, String refundAmount) throws AlipayApiException {
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
request.setBizContent("{"
+ "\"out_trade_no\":\"" + outTradeNo + "\","
+ "\"refund_amount\":\"" + refundAmount + "\""
+ "}");
AlipayTradeRefundResponse response = alipayClient.execute(request);
if (response.isSuccess()) {
return "Refund successful";
} else {
throw new RuntimeException("Alipay refund failed: " + response.getSubMsg());
}
}
}
5. 创建控制器
在控制器中创建端点来处理支付和退款请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayApiException;
@RestController
public class AlipayController {
@Autowired
private AlipayService alipayService;
@Autowired
private AlipayRefundService alipayRefundService;
@GetMapping("/pay")
public String pay(@RequestParam String outTradeNo, @RequestParam String totalAmount, @RequestParam String subject) {
try {
String paymentUrl = alipayService.createPaymentUrl(outTradeNo, totalAmount, subject);
return paymentUrl; // 返回支付页面的 HTML 内容
} catch (AlipayApiException e) {
return "Error occurred: " + e.getMessage();
}
}
@PostMapping("/refund")
public String refund(@RequestParam String outTradeNo, @RequestParam String refundAmount) {
try {
return alipayRefundService.refund(outTradeNo, refundAmount);
} catch (AlipayApiException e) {
return "Error occurred: " + e.getMessage();
}
}
}
6. 处理异步通知
支付宝支付和退款成功后会向你配置的 notify_url
发送异步通知。你需要在应用中创建一个处理这些通知的端点:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
@RestController
public class AlipayNotifyController {
@PostMapping("/notify_url")
public String notifyUrl(@RequestParam Map<String, String> params) {
// 验证通知的真实性
// 处理支付或退款成功后的逻辑
String outTradeNo = params.get("out_trade_no");
// 处理支付逻辑
// ...
return "success"; // 返回给支付宝,确认收到通知
}
}