Spring Boot 怎么接入 Stripe 支付?

简介: 本文介绍了如何在 Spring Boot 应用中接入 Stripe 支付,提供了一个基本框架,并展示了处理 Webhook 的代码示例。通过捕获异常返回错误信息,成功处理事件则返回确认消息。作者 JustinNeil 在文中还提到可根据需求扩展更多功能,如订阅管理和优惠券应用等。

前言

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

环境准备

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

集成步骤

1. 添加 Stripe 依赖

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

xml

代码解读

复制代码

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

2. 配置 Stripe API 密钥

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

ini

代码解读

复制代码

stripe.api.key=sk_test_你的密钥

3. 创建 Stripe 服务

创建一个服务类,用于封装 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;
    }
}

4. 创建控制器

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

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

5. 处理回调

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

转载来源:https://juejin.cn/post/7418363736413601802

相关文章
|
监控 安全 机器人
SpringBoot 实现自定义钉钉机器人
SpringBoot 实现自定义钉钉机器人
|
Java 测试技术 数据安全/隐私保护
一步步教你如何在SpringBoot项目中引入支付功能
支付功能如今已经成为一个需要盈利的网站的基本功能了,如今的网站如果想要做支付功能,往往都是将支付宝或者微信的支付功能集成进来。尽管支付宝已经给出了许多文档和代码,但是这项工作并没有那么简单。今天我就一步步带大家去实现在SpringBoot项目中对支付宝的功能引入。
1152 0
|
监控 API
Grafana+Prometheus系统监控之webhook
概述 Webhook是一个API概念,并且变得越来越流行。我们能用事件描述的事物越多,webhook的作用范围也就越大。Webhook作为一个轻量的事件处理应用,正变得越来越有用。 准确的说webhoo是一种web回调或者http的push API,是向APP或者其他应用提供实时信息的一种方式。
7667 0
|
前端开发 Java Maven
96.【SpringBoot接入支付宝-thymeleaf-springBoot】
96.【SpringBoot接入支付宝-thymeleaf-springBoot】
529 0
|
Web App开发 前端开发 Java
SpringBoot之请求的详细解析
SpringBoot之请求的详细解析
539 0
|
存储 Java API
java 时区时间转为UTC
通过以上方法和代码示例,你可以轻松地在Java中将特定时区的时间转换为UTC时间。确保理解每一步的实现细节,应用到实际项目中时能有效地处理时区转换问题。
698 18
支付宝境外(海外)问题方案集锦
说明:   境外和境内接口不同签约等不同,如果要接入境外请按照境外方式接入 。   境外接口官网:[url]https://global.alipay.com[/url] 声明:  业务和技术方案可能会有变动最终以境外业务和技术支持回复为准,下面问题仅供参考。
6901 12
|
存储 NoSQL Redis
基于SpringBoot+Redis实现点赞/排行榜功能,可同理实现收藏/关注功能,可拓展实现共同好友/共同关注/关注推送功能
在SpringBoot项目中使用Redis的Set和ZSet集合实现点赞和排行榜功能,并通过示例代码展示了如何使用`stringRedisTemplate`操作Redis来完成这些功能。
1247 0
|
6月前
|
人工智能 开发框架 JSON
【RuoYi-SpringBoot3-Pro】:AI 能力再扩展,一个方法打通 n8n 工作流
RuoYi-SpringBoot3-Pro 集成 n8n,通过一个 Webhook 方法实现 AI 能力扩展。Java 端轻量触发,复杂 AI 工作流由 n8n 可视化编排,支持文本处理、文件上传等场景,灵活高效,助力企业级应用快速集成自动化能力。
556 5
|
Java
Springboot集成第三方jar快速实现微信、支付宝等支付场景
Springboot集成第三方jar快速实现微信、支付宝等支付场景
1775 0
Springboot集成第三方jar快速实现微信、支付宝等支付场景

热门文章

最新文章