メインコンテンツへスキップ
Java SDKは、Javaで書かれたアプリケーション向けにDodo Payments REST APIへの便利でエルゴノミックなアクセスを提供します。Optional、Stream、CompletableFutureなどのJava特有の機能を利用して、モダンなJava開発を実現します。

インストール

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")
最新のDodo Payments機能にアクセスするために、常に最新のSDKバージョンを使用してください。最新バージョンについては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に関してヘルプが必要ですか?

貢献

貢献を歓迎します!始めるための貢献ガイドラインを確認してください。