安装
Maven
将依赖添加到您的pom.xml:
pom.xml
<dependency>
<groupId>com.dodopayments.api</groupId>
<artifactId>dodo-payments-java</artifactId>
<version>1.86.3</version>
</dependency>
Gradle
将依赖添加到您的build.gradle:
build.gradle.kts
implementation("com.dodopayments.api:dodo-payments-java:1.86.3")
始终使用最新的 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.CheckoutSessionCreateParams;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;
import com.dodopayments.api.models.checkoutsessions.ProductItemReq;
// 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(ProductItemReq.builder()
.productId("product_id")
.quantity(1)
.build())
.build();
CheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params);
System.out.println(checkoutSessionResponse.sessionId());
请始终通过环境变量、系统属性或安全的配置管理系统安全地存储您的 API 密钥,切勿将其硬编码在源代码中。
核心功能
Type Safety
强类型 API,提供编译时安全性
Thread-Safe
支持多线程应用中的并发安全使用
Builder Pattern
构建请求的直观构建器模式
Async Support
支持 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();
测试模式
为 Test Mode 环境进行配置:DodoPaymentsClient testClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.testMode()
.build();
常见操作
创建结账会话
生成结账会话:CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(ProductItemReq.builder()
.productId("pdt_123")
.quantity(1)
.build())
.returnUrl("https://yourdomain.com/return")
.build();
CheckoutSessionResponse session = client.checkoutSessions().create(params);
System.out.println("Checkout URL: " + session.checkoutUrl());
管理客户
创建和检索客户信息:import com.dodopayments.api.models.customers.Customer;
import com.dodopayments.api.models.customers.CustomerCreateParams;
// Create a customer
CustomerCreateParams createParams = CustomerCreateParams.builder()
.email("customer@example.com")
.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() + ")");
处理订阅
创建和管理定期订阅:POST /subscriptions(SDK 的 subscriptions.create 方法)已被弃用。对于现有集成,它仍然有效,但新集成应通过 Checkout Session 创建订阅。import com.dodopayments.api.models.payments.AttachExistingCustomer;
import com.dodopayments.api.models.payments.BillingAddress;
import com.dodopayments.api.models.misc.CountryCode;
import com.dodopayments.api.models.subscriptions.SubscriptionChargeParams;
import com.dodopayments.api.models.subscriptions.SubscriptionChargeResponse;
import com.dodopayments.api.models.subscriptions.SubscriptionCreateParams;
import com.dodopayments.api.models.subscriptions.SubscriptionCreateResponse;
// Create a subscription
SubscriptionCreateParams subscriptionParams = SubscriptionCreateParams.builder()
.billing(BillingAddress.builder()
.city("San Francisco")
.country(CountryCode.US)
.state("CA")
.street("1 Market St")
.zipcode("94105")
.build())
.customer(AttachExistingCustomer.builder()
.customerId("cus_123")
.build())
.productId("pdt_456")
.quantity(1)
.paymentLink(true)
.returnUrl("https://yourdomain.com/return")
.build();
SubscriptionCreateResponse subscription = client.subscriptions().create(subscriptionParams);
System.out.println("Subscription ID: " + subscription.subscriptionId());
// Charge an on-demand subscription
// product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
SubscriptionChargeParams chargeParams = SubscriptionChargeParams.builder()
.subscriptionId(subscription.subscriptionId())
.productPrice(2500)
.build();
SubscriptionChargeResponse chargeResponse = client.subscriptions().charge(chargeParams);
System.out.println("Payment ID: " + chargeResponse.paymentId());
productPrice 以货币的最小面额表示(例如,USD 的分、INR 的派萨)。要收取 $25.00,请传入 2500。通过
subscriptions().charge(...) 收费适用于按需订阅。标准的定时订阅会根据产品的定价计划自动计费。基于用量的计费
配置计量器
创建和管理用于跟踪用量的计量器:import com.dodopayments.api.models.meters.*;
// Create API calls meter
MeterCreateParams apiMeterParams = MeterCreateParams.builder()
.name("API Requests")
.eventName("api_request")
.aggregation(MeterAggregation.builder()
.type(MeterAggregation.Type.COUNT)
.build())
.measurementUnit("calls")
.build();
Meter apiMeter = client.meters().create(apiMeterParams);
System.out.println("Meter created: " + apiMeter.id());
// List all meters
client.meters().list()
.autoPager()
.forEach(m -> System.out.println("Meter: " + m.name() + " - " + m.aggregation()));
摄取用量事件
跟踪自定义事件:import com.dodopayments.api.models.usageevents.EventInput;
import com.dodopayments.api.models.usageevents.*;
import java.time.OffsetDateTime;
// Ingest single event
UsageEventIngestParams singleEventParams = UsageEventIngestParams.builder()
.addEvent(EventInput.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.ingestedCount());
批量摄取事件
高效摄取多个事件(每个请求最多 1000 个):UsageEventIngestParams.Builder batchBuilder = UsageEventIngestParams.builder();
for (int i = 0; i < 100; i++) {
batchBuilder.addEvent(EventInput.builder()
.eventId("batch_event_" + i + "_" + System.currentTimeMillis())
.customerId("cus_abc123")
.eventName("video_transcode")
.timestamp(OffsetDateTime.now().minusSeconds(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.ingestedCount() + " 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:test}")
private String environment;
@Bean
public DodoPaymentsClient dodoPayments() {
return DodoPaymentsOkHttpClient.builder()
.bearerToken(apiKey)
.baseUrl(environment.equals("live")
? "https://live.dodopayments.com"
: "https://test.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<ProductItemReq> items) {
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.productCart(items)
.returnUrl("https://yourdomain.com/return")
.build();
return client.checkoutSessions().create(params);
}
}
资源
GitHub Repository
查看源代码并参与贡献
API Reference
完整的 API 文档
Discord Community
获取帮助并与开发者交流
Report Issues
报告错误或请求新功能
支持
需要 Java SDK 方面的帮助?- Discord:加入我们的社区服务器以获取实时支持
- Email:通过 support@dodopayments.com 联系我们
- GitHub:在代码仓库中提交 issue