Springboot接入PayPal支付

1,251 阅读2分钟

前言

在本文中,我们将探讨如何在Springboot应用中集成PayPal支付。PayPal是全球领先的在线支付平台,支持多种支付方式,包括信用卡、借记卡、PayPal账户余额等。通过集成PayPal,我们可以为全球用户提供便捷、安全的支付体验。

PayPal提供了两种主要的支付方式:标准支付和快速支付。标准支付通过PayPal按钮实现,用户支付流程由PayPal控制。快速支付则需要调用多个API接口来实现支付流程的控制。本文将介绍如何使用标准支付方式集成PayPal。

环境准备

  1. 注册PayPal账号,并登录PayPal开发者中心
  2. 在沙箱环境中创建测试账号,包括个人和商家账号。
  3. 创建应用,并获取clientIdclientSecret

Maven依赖配置

pom.xml文件中添加PayPal SDK的依赖:

<dependency>
    <groupId>com.paypal.sdk</groupId>
    <artifactId>rest-api-sdk</artifactId>
    <version>1.4.2</version>
</dependency>
<dependency>
    <groupId>com.paypal.sdk</groupId>
    <artifactId>checkout-sdk</artifactId>
    <version>1.0.2</version>
</dependency>

配置文件

application.properties中添加PayPal配置信息:

paypal.client.id=YOUR_CLIENT_ID
paypal.client.secret=YOUR_CLIENT_SECRET
paypal.mode=sandbox

PayPal客户端配置

创建PayPalConfig类,配置PayPal客户端:

import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PayPalConfig {

    @Value("${paypal.client.id}")
    private String clientId;

    @Value("${paypal.client.secret}")
    private String clientSecret;

    @Value("${paypal.mode}")
    private String mode;

    public APIContext getApiContext() {
        PayPalEnvironment environment = mode.equalsIgnoreCase("live") ?
                new PayPalEnvironment.Live(clientId, clientSecret) :
                new PayPalEnvironment.Sandbox(clientId, clientSecret);
        return new APIContext(new OAuthTokenCredential(clientId, clientSecret), environment);
    }
}

创建支付订单

创建PayPalPaymentService类,用于创建支付订单:

import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayPalPaymentService {

    @Autowired
    private PayPalConfig payPalConfig;

    public String createPaymentOrder(String paymentAmount) throws Exception {
        Amount amount = new Amount();
        amount.setCurrency("USD");
        amount.setTotal(paymentAmount);

        Transaction transaction = new Transaction();
        transaction.setAmount(amount);
        transaction.setDescription("Payment description");

        Payer payer = new Payer();
        payer.setPaymentMethod("paypal");

        Payment payment = new Payment();
        payment.setIntent("sale");
        payment.setPayer(payer);
        payment.setTransactions(Arrays.asList(transaction));

        return payment.create(payPalConfig.getApiContext());
    }
}

支付确认

创建支付确认方法:

import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.Capture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayPalPaymentService {

    // ... other methods ...

    public String capturePayment(String authorizationId) throws Exception {
        Authorization authorization = new Authorization();
        authorization.setId(authorizationId);
        Capture capture = new Capture();
        capture.setIsFinalCapture(true);
        capture.setAmount(new Amount().setCurrency("USD").setTotal("100.00"));
        capture.setAuthorization(authorization);
        return capture.create(payPalConfig.getApiContext());
    }
}

支付退款

创建支付退款方法:

import com.paypal.api.payments.Refund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayPalPaymentService {

    // ... other methods ...

    public String createRefund(String captureId) throws Exception {
        Refund refund = new Refund();
        refund.setAmount(new Amount().setCurrency("USD").setTotal("100.00"));
        refund.setInvoiceNumber("INV12345");
        refund.setCaptureId(captureId);
        return refund.create(payPalConfig.getApiContext());
    }
}

回调处理

创建PayPalWebhookListener类,用于处理支付回调:

import com.paypal.api.Webhook;
import com.paypal.api.WebhookList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PayPalWebhookListener {

    @Autowired
    private PayPalConfig payPalConfig;

    @PostMapping("/webhook")
    public String handleWebhookNotification(@RequestBody String body) {
        try {
            WebhookList webhookEvents = Webhook.parseWebhookEvents(body, payPalConfig.getApiContext().getHttpClient());
            for (WebhookEvent event : webhookEvents) {
                String eventName = event.getEventTypeName();
                String resourceId = event.getResource().getId();
                handleEvent(eventName, resourceId);
            }
            return "VERIFIED";
        } catch (Exception e) {
            e.printStackTrace();
            return "INVALID";
        }
    }

    private void handleEvent(String eventName, String resourceId) {
        // Handle different events, e.g., payment captured, payment refunded
    }
}

总结

本文详细介绍了如何在Springboot应用中集成PayPal支付,包括创建支付订单、支付确认、支付退款以及处理支付回调。通过这些步骤,开发者可以轻松地为他们的应用程序添加PayPal支付功能。

请确保替换YOUR_CLIENT_IDYOUR_CLIENT_SECRET为您的实际API凭证,并根据需要添加适当的异常处理逻辑。