> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Java

> Use the Dodo Payments Java SDK to create checkout sessions, customers, subscriptions, meters, and usage events from Java 8+, with sync and async clients.

The Java SDK gives Java applications typed access to the Dodo Payments REST API. It uses Java types throughout: `Optional` for fields that can be missing, `Stream` for iterating results, and `CompletableFuture` for asynchronous calls.

## Installation

### Maven

Add the dependency to your `pom.xml`:

```xml pom.xml theme={null}
<dependency>
  <groupId>com.dodopayments.api</groupId>
  <artifactId>dodo-payments-java</artifactId>
  <version>1.118.0</version>
</dependency>
```

### Gradle

Add the dependency to your `build.gradle.kts`:

```kotlin build.gradle.kts theme={null}
implementation("com.dodopayments.api:dodo-payments-java:1.118.0")
```

<Tip>
  SDK releases add support for API changes. To find the most recent version, check [Maven Central](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-java).
</Tip>

<Info>
  The SDK requires Java 8 or later, so it also runs on Java 11, 17, and 21.
</Info>

## Quick Start

Create a client, then create a checkout session:

```java theme={null}
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;
import com.dodopayments.api.models.checkoutsessions.ProductItemReq;

// Configure using environment variables (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY, DODO_PAYMENTS_BASE_URL)
// Or system properties (dodopayments.apiKey, dodopayments.webhookKey, dodopayments.baseUrl)
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();

CheckoutSessionRequest params = CheckoutSessionRequest.builder()
    .addProductCart(ProductItemReq.builder()
        .productId("pdt_123")
        .quantity(1)
        .build())
    .build();
    
CheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params);
System.out.println(checkoutSessionResponse.sessionId());
```

`fromEnv()` connects to live mode unless `DODO_PAYMENTS_BASE_URL` or `dodopayments.baseUrl` says otherwise. To use test mode, see [Test Mode](#test-mode). A test mode API key works only in test mode.

<Warning>
  Keep API keys in environment variables, system properties, or a secrets manager. Never hardcode them in your source code.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="Type Safety" icon="shield-check">
    Typed request and response classes for compile-time checks.
  </Card>

  <Card title="Shared Client" icon="bolt">
    Create one client and reuse it across requests: it holds the connection and thread pools. Request and response objects are immutable.
  </Card>

  <Card title="Builder Pattern" icon="layer-group">
    Every request class has a builder, and `toBuilder()` makes a modified copy.
  </Card>

  <Card title="Async Support" icon="arrows-rotate">
    `client.async()` returns a client whose methods return `CompletableFuture`.
  </Card>
</CardGroup>

## Configuration

### Environment Variables

`fromEnv()` reads these environment variables, or the matching system properties. System properties take precedence:

```bash .env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
DODO_PAYMENTS_BASE_URL=https://live.dodopayments.com
```

```java theme={null}
// Automatically reads from environment variables
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
```

The API key comes from `DODO_PAYMENTS_API_KEY` or `dodopayments.apiKey`. The webhook signing secret comes from `DODO_PAYMENTS_WEBHOOK_KEY` or `dodopayments.webhookKey`, and the base URL from `DODO_PAYMENTS_BASE_URL` or `dodopayments.baseUrl`. Create one client and reuse it, because each client has its own connection pool and thread pools.

To verify a webhook, pass the raw request body and headers to `client.webhooks().unwrap(UnwrapWebhookParams.builder().body(rawBody).headers(headers).build())`, where `headers` is a `com.dodopayments.api.core.http.Headers`. It checks the signature with your webhook key and returns the parsed event, or throws `DodoPaymentsWebhookException`. Without headers, `unwrap` doesn't verify the signature. `client.webhooks().unsafeUnwrap(rawBody)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks).

### Manual Configuration

Set each option on the builder:

```java theme={null}
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();
```

By default, the client retries twice and times out after 1 minute. It retries connection errors and responses with status 408, 409, 429, or 500 and above. To override the timeout for one call, pass `RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()` as the method's second argument. `responseValidation(true)` checks that the whole response matches the expected types up front. Without it, the SDK throws `DodoPaymentsInvalidDataException` only when you read a property with an unexpected type.

### Test Mode

To use test mode (`https://test.dodopayments.com`), call `testMode()` on the builder:

```java theme={null}
DodoPaymentsClient testClient = DodoPaymentsOkHttpClient.builder()
    .fromEnv()
    .testMode()
    .build();
```

## Common Operations

The examples in this section use the `client` from [Quick Start](#quick-start).

### Create a Checkout Session

Create a checkout session, then redirect the customer to the returned checkout URL:

```java theme={null}
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().orElse(""));
```

`checkoutUrl()` returns an `Optional<String>`. Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session).

### Manage Customers

Create a customer with an email address, name, and metadata, then retrieve it by ID:

```java theme={null}
import com.dodopayments.api.core.JsonValue;
import com.dodopayments.api.models.customers.Customer;
import com.dodopayments.api.models.customers.CustomerCreateParams;
import com.dodopayments.api.models.misc.Metadata;

// Create a customer
CustomerCreateParams createParams = CustomerCreateParams.builder()
    .email("customer@example.com")
    .name("John Doe")
    .metadata(Metadata.builder()
        .putAdditionalProperty("user_id", JsonValue.from("12345"))
        .build())
    .build();

Customer customer = client.customers().create(createParams);

// Retrieve customer
Customer retrieved = client.customers().retrieve("cus_123");
System.out.println("Customer: " + retrieved.name() + " (" + retrieved.email() + ")");
```

### Handle Subscriptions

Create a subscription with a payment link, then charge it if it's an on-demand subscription.

<Warning>
  `POST /subscriptions` (the SDK's `subscriptions().create()` method) is **deprecated**. It still works for existing integrations, but new integrations should create subscriptions through a [Checkout Session](/developer-resources/checkout-session).
</Warning>

```java theme={null}
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());
```

<Info>
  `productPrice` is in the smallest currency unit, such as cents for USD or paise for INR. To charge \$25.00, pass `2500`.
</Info>

<Tip>
  `subscriptions().charge(...)` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions). Dodo Payments bills other subscriptions automatically on the product's billing schedule.
</Tip>

## Usage-Based Billing

### Configure Meters

Create a meter that counts events, then list your meters. `autoPager()` iterates over every meter and fetches more pages as needed:

```java theme={null}
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()));
```

### Ingest Usage Events

Send a usage event for a customer. Event metadata values are `JsonValue` objects:

```java theme={null}
import com.dodopayments.api.core.JsonValue;
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())
        .metadata(EventInput.Metadata.builder()
            .putAdditionalProperty("endpoint", JsonValue.from("/api/v1/users"))
            .putAdditionalProperty("method", JsonValue.from("GET"))
            .putAdditionalProperty("tokens_used", JsonValue.from("150"))
            .build())
        .build())
    .build();

UsageEventIngestResponse response = client.usageEvents().ingest(singleEventParams);
System.out.println("Processed: " + response.ingestedCount());
```

The `eventId` is the idempotency key, so give each event a unique value. A `timestamp` more than 1 hour in the past or more than 5 minutes in the future is rejected.

### Batch Ingest Events

Send up to 1,000 events in one request. This example uses the imports from the previous one:

```java theme={null}
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))
        .metadata(EventInput.Metadata.builder()
            .putAdditionalProperty("video_id", JsonValue.from("video_" + i))
            .putAdditionalProperty("duration_seconds", JsonValue.from(String.valueOf(120 + i)))
            .build())
        .build());
}

UsageEventIngestResponse batchResponse = client.usageEvents().ingest(batchBuilder.build());
System.out.println("Batch processed: " + batchResponse.ingestedCount() + " events");
```

## Error Handling

The SDK throws unchecked exceptions. For an error status, it throws a subclass of `DodoPaymentsServiceException`, which has `statusCode()`, `headers()`, and `body()`. Catch the specific classes you want to handle before the base class:

```java theme={null}
import com.dodopayments.api.errors.*;
import com.dodopayments.api.models.payments.Payment;

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());
    // Thrown after the SDK's automatic retries are used up
} catch (InternalServerException e) {
    System.err.println("Server error: " + e.getMessage());
} catch (DodoPaymentsServiceException e) {
    System.err.println("API error: " + e.statusCode() + " - " + e.getMessage());
}
```

Statuses without their own class, such as 409, throw `UnexpectedStatusCodeException`. Network failures throw `DodoPaymentsIoException`, and responses the SDK can't interpret throw `DodoPaymentsInvalidDataException`. All of these extend `DodoPaymentsException`.

<Tip>
  The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above, twice by default, with exponential backoff.
</Tip>

## Async Operations

Call `async()` on the client to get an asynchronous client. Its methods return a `CompletableFuture`:

```java theme={null}
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;
});
```

To create an asynchronous client from the start, use `DodoPaymentsOkHttpClientAsync.fromEnv()`.

## Spring Boot Integration

### Configuration Class

Register one client as a bean, and choose the environment from a property:

```java theme={null}
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();
    }
}
```

### Service Layer

Inject the client into a service:

```java theme={null}
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.models.checkoutsessions.*;
import java.util.List;
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);
    }
}
```

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-java">
    Source code, releases, and the full method list.
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Every endpoint, parameter, and response.
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Ask questions and talk with other developers.
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-java/issues">
    Report bugs or request features.
  </Card>
</CardGroup>

## Support

For help with the Java SDK:

* **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help.
* **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com).
* **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-java).

## Contributing

To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-java/blob/main/CONTRIBUTING.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.