Spring Boot 接入 Stripe 支付

0 阅读2分钟

前言

Stripe 是一个全球知名的支付处理平台,它为个人或企业提供了一种简单、安全的方式来接收和处理在线支付。Stripe 提供了丰富的API,支持多种支付方式,包括信用卡、借记卡、电子钱包等。在本教程中,我们将介绍如何在 Spring Boot 应用程序中集成 Stripe 支付,并实现常见的支付操作。

环境准备

  1. 注册 Stripe 账号并获取 API 密钥。
  2. 在 Stripe Dashboard 中配置 Webhook 以接收支付事件通知。

集成步骤

1. 添加 Stripe 依赖

在 Spring Boot 项目的 pom.xml 文件中添加 Stripe 的 Java 库依赖:

<dependency>
    <groupId>com.stripe</groupId>
    <artifactId>stripe-java</artifactId>
    <version>22.29.0</version> <!-- 请使用最新版本 -->
</dependency>

2. 配置 Stripe API 密钥

application.propertiesapplication.yml 中配置 Stripe 的 API 密钥:

stripe.api.key=sk_test_你的密钥

3. 创建 Stripe 服务

创建一个服务类,用于封装 Stripe API 的调用:

@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;
    }
}

4. 创建控制器

创建一个控制器,用于处理支付请求:

@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 的端点...
}

5. 处理回调

Stripe 通过 Webhook 发送支付事件通知。你需要创建一个端点来接收这些事件:

@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 功能,如订阅管理、优惠券应用等。