Stripe 是一个全球知名的支付处理平台,它为个人或企业提供了一种简单、安全的方式来接收和处理在线支付。Stripe 提供了丰富的API,支持多种支付方式,包括信用卡、借记卡、电子钱包等。在本教程中,我们将介绍如何在 Spring Boot 应用程序中集成 Stripe 支付,并实现常见的支付操作。
在 Spring Boot 项目的 pom.xml
文件中添加 Stripe 的 Java 库依赖:xml
代码解读复制代码<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>22.29.0</version> <!-- 请使用最新版本 -->
</dependency>
在 application.properties
或 application.yml
中配置 Stripe 的 API 密钥:ini
代码解读复制代码stripe.api.key=sk_test_你的密钥
创建一个服务类,用于封装 Stripe API 的调用:java
代码解读复制代码@Service
public class StripeService {
private final String apiKey;
@Autowired
public StripeService(@Value("${stripe.api.key}") String apiKey) {
this.apiKey = apiKey;
}
public Customer createCustomer(String email, String token) throws StripeException {
Stripe.apiKey = apiKey;
Map<String, Object> customerParams = new HashMap<>();
customerParams.put("description", "Customer for " + email);
customerParams.put("email", email);
customerParams.put("source", token); // 通过 Stripe.js 获取
return Customer.create(customerParams);
}
public Charge createCharge(String customerId, int amount) throws StripeException {
Stripe.apiKey = apiKey;
Map<String, Object> chargeParams = new HashMap<>();
chargeParams.put("amount", amount);
chargeParams.put("currency", "usd");
chargeParams.put("customer", customerId);
return Charge.create(chargeParams);
}
public Refund createRefund(String chargeId, int amount) throws StripeException {
Stripe.apiKey = apiKey;
Map<String, Object> refundParams = new HashMap<>();
refundParams.put("charge", chargeId);
refundParams.put("amount", amount);
return Refund.create(refundParams);
}
// 添加失败重试机制
@Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 2000))
public Charge createChargeWithRetry(String customerId, int amount) throws StripeException {
return createCharge(customerId, amount);
}
// 重试失败后的恢复方法
@Recover
public Charge recoverFromChargeFailure(Exception e) {
// 记录日志、发送警报或执行其他恢复操作
return null;
}
}
创建一个控制器,用于处理支付请求:java
代码解读复制代码@RestController
@RequestMapping("/api/payments")
public class PaymentController {
private final StripeService stripeService;
@Autowired
public PaymentController(StripeService stripeService) {
this.stripeService = stripeService;
}
@PostMapping("/create-customer")
public ResponseEntity<?> createCustomer(@RequestBody Map<String, String> payload) {
try {
String customerId = stripeService.createCustomer(payload.get("email"), payload.get("token"));
return ResponseEntity.ok(customerId);
} catch (StripeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping("/create-charge")
public ResponseEntity<?> createCharge(@RequestBody Map<String, Object> payload) {
try {
String chargeId = stripeService.createChargeWithRetry((String) payload.get("customerId"), (int) payload.get("amount"));
return ResponseEntity.ok(chargeId);
} catch (StripeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@PostMapping("/refund")
public ResponseEntity<?> createRefund(@RequestBody Map<String, Object> payload) {
try {
String refundId = stripeService.createRefund((String) payload.get("chargeId"), (int) payload.get("amount"));
return ResponseEntity.ok(refundId);
} catch (StripeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
// 其他支付 API 的端点...
}
Stripe 通过 Webhook 发送支付事件通知。你需要创建一个端点来接收这些事件:java
代码解读复制代码@RestController
public class WebhookController {
private final StripeService stripeService;
@Autowired
public WebhookController(StripeService stripeService) {
this.stripeService = stripeService;
}
@PostMapping("/webhook")
public ResponseEntity<String> handleWebhook(@RequestBody String payload, @RequestParam String signature) {
Event event = null;
try {
event = Webhook.constructEvent(payload, signature, apiKey);
switch (event.getType()) {
case "payment_intent.succeeded":
stripeService.handlePaymentIntentSuccess(event);
break;
case "charge.refunded":
stripeService.handleChargeRefunded(event);
break;
// 其他事件处理...
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Webhook error: " + e.getMessage());
}
return ResponseEntity.ok("Event processed successfully");
}
}
以上步骤提供了一个基本的 Spring Boot 应用接入 Stripe 支付的框架。你可以根据具体需求,添加更多的 Stripe API 功能,如订阅管理、优惠券应用等。