package com.stylefeng.guns.modular.system.utils;
|
|
import com.stripe.Stripe;
|
import com.stripe.exception.SignatureVerificationException;
|
import com.stripe.exception.StripeException;
|
import com.stripe.model.Customer;
|
import com.stripe.model.PaymentIntent;
|
import com.stripe.net.Webhook;
|
import com.stripe.param.CustomerCreateParams;
|
import com.stripe.param.PaymentIntentCreateParams;
|
import com.stripe.param.PaymentIntentUpdateParams;
|
|
import java.util.HashMap;
|
import java.util.logging.Logger;
|
|
public class PaymentProcessor {
|
|
// 定义 Stripe API 密钥
|
private static final String STRIPE_API_KEY = "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";
|
|
public PaymentProcessor() {
|
// 初始化 Stripe 对象并设置 API 密钥
|
Stripe.apiKey = STRIPE_API_KEY;
|
}
|
|
/**
|
* 创建一个 Stripe 客户,并保存他们的信用卡信息,以备将来使用。
|
* 支持多种付款方式,例如支付宝、微信等。这里只是演示如何使用信用卡进行支付。
|
*
|
* @param email 客户电子邮件地址
|
* @param cardToken 由 Stripe.js 获取的信用卡令牌
|
* @return Stripe 客户对象
|
* @throws StripeException 如果创建客户或付款交易时出现错误
|
*/
|
public Customer createCustomer(String email, String cardToken) throws StripeException {
|
|
// 构造付款交易参数
|
PaymentIntentCreateParams params = PaymentIntentCreateParams.builder()
|
.setAmount(1000L) // 设置要收取的金额,以美分为单位(例如 $10.00 = 1000 美分)
|
.setCurrency("usd") // 设置货币类型:USD(美元)
|
.setPaymentMethod(cardToken) // 设置由 Stripe.js 获取的信用卡令牌
|
.build();
|
|
// 创建付款交易
|
PaymentIntent paymentIntent = PaymentIntent.create(params);
|
|
// 创建一个 Stripe 客户,将他们的付款方法与 Stripe 帐户关联在一起
|
Customer customer = Customer.create(
|
CustomerCreateParams.builder()
|
.setEmail(email) // 设置客户的电子邮件地址
|
.setPaymentMethod(paymentIntent.getPaymentMethod()) // 将付款方法与客户端 Stripe 帐户相关联
|
.build()
|
);
|
|
// 返回创建的 Stripe 客户对象
|
return customer;
|
}
|
|
/**
|
* 从一个 Stripe 客户处收取付款。
|
*
|
* @param customerId Stripe 客户 ID
|
* @param amount 要收取的金额,以美分为单位
|
* @return Stripe 付款交易对象
|
* @throws StripeException 如果捕获到 Stripe API 返回的错误
|
*/
|
public static PaymentIntent charge(String customerId, long amount) throws StripeException {
|
|
// 构造付款交易参数
|
PaymentIntentCreateParams params = PaymentIntentCreateParams.builder()
|
.setCustomer(customerId) // 使用客户 ID 作为付款目标
|
.setAmount(amount) // 设置要收取的金额,以美分为单位
|
.setCurrency("usd").setDescription("1").setReturnUrl("") // 设置货币类型:USD(美元)
|
.build();
|
|
// 创建付款交易
|
PaymentIntent paymentIntent = PaymentIntent.create(params);
|
|
// 确认付款
|
paymentIntent.confirm();
|
|
// 返回创建的 Stripe 付款交易对象
|
return paymentIntent;
|
}
|
|
|
}
|