安装
Maven
将依赖项添加到您的pom.xml:
pom.xml
复制
<dependency>
<groupId>com.dodopayments.api</groupId>
<artifactId>dodo-payments-java</artifactId>
<version>1.61.5</version>
</dependency>
Gradle
将依赖项添加到您的build.gradle:
build.gradle.kts
复制
implementation("com.dodopayments.api:dodo-payments-java:1.61.5")
始终使用最新的 SDK 版本以访问最新的 Dodo Payments 功能。请查看 Maven Central 以获取最新版本。
该 SDK 支持 Java 8 及所有后续版本,包括 Java 11、17 和 21。
快速开始
初始化客户端并创建结账会话:复制
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;
// Configure using environment variables (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_BASE_URL)
// Or system properties (dodopayments.apiKey, dodopayments.baseUrl)
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("product_id")
.quantity(1)
.build())
.build();
CheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params);
System.out.println(checkoutSessionResponse.sessionId());
始终通过环境变量、系统属性或安全配置管理系统安全存储您的 API 密钥。切勿在源代码中硬编码它们。
核心功能
类型安全
强类型 API,具有编译时安全性
线程安全
在多线程应用程序中安全并发使用
构建者模式
直观的构建者模式用于构建请求
异步支持
支持 CompletableFuture 进行异步操作
配置
环境变量
使用环境变量或系统属性进行配置:.env
复制
DODO_PAYMENTS_API_KEY=your_api_key_here
DODO_PAYMENTS_BASE_URL=https://live.dodopayments.com
复制
// Automatically reads from environment variables
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
手动配置
手动配置所有选项:复制
import java.time.Duration;
DodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()
.bearerToken("your_api_key_here")
.baseUrl("https://live.dodopayments.com")
.maxRetries(4)
.timeout(Duration.ofSeconds(30))
.responseValidation(true)
.build();
测试模式
为测试/沙盒环境配置:复制
DodoPaymentsClient testClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.testMode()
.build();
常见操作
创建结账会话
生成结账会话:复制
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("prod_123")
.quantity(1)
.build())
.returnUrl("https://yourdomain.com/return")
.build();
CheckoutSessionResponse session = client.checkoutSessions().create(params);
System.out.println("Checkout URL: " + session.url());
管理客户
创建和检索客户信息:复制
import com.dodopayments.api.models.customers.Customer;
import com.dodopayments.api.models.customers.CustomerCreateParams;
// Create a customer
CustomerCreateParams createParams = CustomerCreateParams.builder()
.email("[email protected]")
.name("John Doe")
.putMetadata("user_id", "12345")
.build();
Customer customer = client.customers().create(createParams);
// Retrieve customer
Customer retrieved = client.customers().retrieve("cus_123");
System.out.println("Customer: " + retrieved.name() + " (" + retrieved.email() + ")");
处理订阅
创建和管理定期订阅:复制
import com.dodopayments.api.models.subscriptions.*;
// Create a subscription
SubscriptionNewParams subscriptionParams = SubscriptionNewParams.builder()
.customerId("cus_123")
.productId("prod_456")
.priceId("price_789")
.build();
Subscription subscription = client.subscriptions().create(subscriptionParams);
// Charge subscription
SubscriptionChargeParams chargeParams = SubscriptionChargeParams.builder()
.amount(1000)
.build();
SubscriptionChargeResponse chargeResponse = client.subscriptions()
.charge(subscription.id(), chargeParams);
基于使用的计费
配置计量器
创建和管理用于跟踪使用情况的计量器:复制
import com.dodopayments.api.models.meters.*;
// Create API calls meter
MeterCreateParams apiMeterParams = MeterCreateParams.builder()
.name("API Requests")
.eventName("api_request")
.aggregation("count")
.putMetadata("category", "api_usage")
.build();
Meter apiMeter = client.meters().create(apiMeterParams);
System.out.println("Meter created: " + apiMeter.meterId());
// List all meters
client.meters().list()
.autoPager()
.forEach(m -> System.out.println("Meter: " + m.name() + " - " + m.aggregation()));
记录使用事件
跟踪自定义事件:复制
import com.dodopayments.api.models.usageevents.*;
import java.time.OffsetDateTime;
// Ingest single event
UsageEventIngestParams singleEventParams = UsageEventIngestParams.builder()
.addEvent(UsageEventIngestParams.Event.builder()
.eventId("api_call_" + System.currentTimeMillis())
.customerId("cus_abc123")
.eventName("api_request")
.timestamp(OffsetDateTime.now())
.putMetadata("endpoint", "/api/v1/users")
.putMetadata("method", "GET")
.putMetadata("tokens_used", "150")
.build())
.build();
UsageEventIngestResponse response = client.usageEvents().ingest(singleEventParams);
System.out.println("Processed: " + response.processedEvents());
批量记录事件
高效记录多个事件(每个请求最多 1000 个):复制
UsageEventIngestParams.Builder batchBuilder = UsageEventIngestParams.builder();
for (int i = 0; i < 100; i++) {
batchBuilder.addEvent(UsageEventIngestParams.Event.builder()
.eventId("batch_event_" + i + "_" + System.currentTimeMillis())
.customerId("cus_abc123")
.eventName("video_transcode")
.timestamp(OffsetDateTime.now().minusMinutes(i))
.putMetadata("video_id", "video_" + i)
.putMetadata("duration_seconds", String.valueOf(120 + i))
.build());
}
UsageEventIngestResponse batchResponse = client.usageEvents().ingest(batchBuilder.build());
System.out.println("Batch processed: " + batchResponse.processedEvents() + " events");
错误处理
针对不同场景的全面错误处理:复制
import com.dodopayments.api.errors.*;
try {
Payment payment = client.payments().retrieve("pay_invalid");
} catch (NotFoundException e) {
System.err.println("Payment not found: " + e.getMessage());
} catch (UnauthorizedException e) {
System.err.println("Authentication failed: " + e.getMessage());
} catch (PermissionDeniedException e) {
System.err.println("Permission denied: " + e.getMessage());
} catch (BadRequestException e) {
System.err.println("Invalid request: " + e.getMessage());
} catch (UnprocessableEntityException e) {
System.err.println("Validation error: " + e.getMessage());
} catch (RateLimitException e) {
System.err.println("Rate limit exceeded: " + e.getMessage());
// SDK automatically retries with backoff
} catch (InternalServerException e) {
System.err.println("Server error: " + e.getMessage());
} catch (DodoPaymentsServiceException e) {
System.err.println("API error: " + e.statusCode() + " - " + e.getMessage());
}
SDK 在连接错误、408、409、429 和 5xx 错误时会自动重试请求,并采用指数退避策略。
异步操作
使用 CompletableFuture 进行异步操作:复制
import java.util.concurrent.CompletableFuture;
CompletableFuture<CheckoutSessionResponse> future = client.async()
.checkoutSessions()
.create(params);
// Handle response asynchronously
future.thenAccept(response -> {
System.out.println("Session created: " + response.sessionId());
}).exceptionally(ex -> {
System.err.println("Error: " + ex.getMessage());
return null;
});
Spring Boot 集成
配置类
复制
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DodoPaymentsConfig {
@Value("${dodo.api.key}")
private String apiKey;
@Value("${dodo.environment:sandbox}")
private String environment;
@Bean
public DodoPaymentsClient dodoPayments() {
return DodoPaymentsOkHttpClient.builder()
.bearerToken(apiKey)
.baseUrl(environment.equals("live")
? "https://live.dodopayments.com"
: "https://sandbox.dodopayments.com")
.build();
}
}
服务层
复制
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.models.checkoutsessions.*;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
private final DodoPaymentsClient client;
public PaymentService(DodoPaymentsClient client) {
this.client = client;
}
public CheckoutSessionResponse createCheckout(List<CheckoutSessionRequest.ProductCart> items) {
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.productCart(items)
.returnUrl("https://yourdomain.com/return")
.build();
return client.checkoutSessions().create(params);
}
}
资源
支持
需要 Java SDK 的帮助吗?- Discord:加入我们的 社区服务器 获取实时支持
- 电子邮件:通过 [email protected] 联系我们
- GitHub:在 仓库 上打开一个问题