springboot集成PayPal支付
Spring Boot 整合 PayPal 支付,可以使用 PayPal 的 REST API。以下是一个基本的集成步骤和示例代码:
- 添加依赖到你的
pom.xml
文件中:
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>checkout-sdk</artifactId>
<version>1.0.2</version>
</dependency>
- 配置 PayPal 客户端:
@Configuration
public class PayPalConfig {
@Value("${paypal.client.id}")
private String clientId;
@Value("${paypal.client.secret}")
private String clientSecret;
public PayPalHttpClient createHttpClient() {
return new PayPalHttpClient(createBuilder());
}
private HttpClient.Builder createBuilder() {
return new OkHttpClient.Builder()
.setRequestTimeout(0, TimeUnit.SECONDS)
.addInterceptor(new HttpBasicAuthInterceptor(clientId, clientSecret, ""));
}
}
- 创建一个服务来发起支付:
@Service
public class PayPalPaymentService {
@Autowired
private PayPalConfig payPalConfig;
public String createPayment(String orderId, BigDecimal amount) throws IOException {
Payment payment = new Payment();
payment.setIntent("sale");
...
Request request = new Request();
request.setMethod("POST");
request.setBody(payment);
request.setUri("/v2/checkout/orders");
PayPalHttpClient client = payPalConfig.createHttpClient();
Response response = client.execute(request);
if (response.statusCode() == 201) {
// 支付创建成功,返回支付ID
return response.result().getId();
} else {
// 处理错误
throw new RuntimeException("支付创建失败");
}
}
}
- 创建一个控制器来处理支付请求:
@RestController
public class PayPalController {
@Autowired
private PayPalPaymentService paymentService;
@PostMapping("/api/paypal/create-payment")
public String createPayment(@RequestParam BigDecimal amount) {
try {
return paymentService.createPayment("12345", amount);
} catch (IOException e) {
throw new RuntimeException("支付请求失败", e);
}
}
}
确保你已经在 PayPal 开发者控制台配置好应用,并获取到了 clientId
和 clientSecret
。
以上代码仅为示例,实际集成时需要根据自己的业务逻辑进行相应的调整,比如填充完整的 Payment
对象,处理不同的业务逻辑等。
评论已关闭