### Configure Dodo Payments Java Client from Environment
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
This Java code shows how to initialize the Dodo Payments client using environment variables or system properties for API key and base URL. This is a convenient way to configure the client without manual setup.
```java
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
// Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties
// Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
```
--------------------------------
### Install Dodo Payments Java SDK via Gradle
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
This snippet shows how to add the Dodo Payments Java SDK as a dependency in a Gradle project. It requires Gradle build tools and specifies the library artifact and version.
```kotlin
implementation("com.dodopayments.api:dodo-payments-java:1.53.4")
```
--------------------------------
### List Payments with Pagination in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Demonstrates how to list payments using both automatic and manual pagination strategies. It includes examples of filtering and limiting results using streams and controlling page size for manual iteration.
```java
import com.dodopayments.api.models.payments.PaymentListPage;
import com.dodopayments.api.models.payments.PaymentListResponse;
import com.dodopayments.api.models.payments.PaymentListParams;
// Auto-pagination - iterates through all pages automatically
PaymentListPage page = client.payments().list();
for (PaymentListResponse payment : page.autoPager()) {
System.out.println("Payment " + payment.paymentId() + ": " +
payment.totalAmount() + " " + payment.currency());
}
// Stream processing with limits
page.autoPager()
.stream()
.filter(p -> p.status() == IntentStatus.SUCCEEDED)
.limit(50)
.forEach(payment -> System.out.println(payment.paymentId()));
// Manual pagination with page size control
PaymentListParams params = PaymentListParams.builder()
.pageSize(25)
.build();
PaymentListPage currentPage = client.payments().list(params);
while (true) {
for (PaymentListResponse payment : currentPage.items()) {
System.out.println("Payment: " + payment.paymentId());
}
if (!currentPage.hasNextPage()) {
break;
}
currentPage = currentPage.nextPage();
}
// Access pagination metadata
System.out.println("Items in page: " + currentPage.items().size());
```
--------------------------------
### Create Checkout Session with Dodo Payments Java SDK
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
This Java code example demonstrates how to create a checkout session using the Dodo Payments Java SDK. It initializes the client from environment variables or system properties and constructs a CheckoutSessionRequest with product details.
```java
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.CheckoutSessionResponse;
// Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties
// Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("product_id")
.quantity(0)
.build())
.build();
CheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params);
```
--------------------------------
### Create Dodo Payments Checkout Session
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Shows how to create a hosted checkout session for customer payments. This involves building a `CheckoutSessionRequest` with product details, currency, allowed payment methods, return URL, discount codes, and then calling the `create` method on the `client.checkoutSessions()` object. Includes example error handling for common API exceptions.
```java
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;
import com.dodopayments.api.models.checkoutsessions.PaymentMethodTypes;
import com.dodopayments.api.models.checkoutsessions.Currency;
import com.dodopayments.api.client.exception.BadRequestException;
import com.dodopayments.api.client.exception.UnauthorizedException;
import com.dodopayments.api.client.exception.DodoPaymentsServiceException;
import java.util.List;
try {
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("prod_abc123")
.quantity(2)
.build())
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("prod_xyz789")
.quantity(1)
.build())
.billingCurrency(Currency.USD)
.allowedPaymentMethodTypes(List.of(
PaymentMethodTypes.CREDIT,
PaymentMethodTypes.DEBIT
))
.returnUrl("https://yoursite.com/payment/success")
.discountCode("SAVE20")
.confirm(true)
.showSavedPaymentMethods(true)
.build();
CheckoutSessionResponse response = client.checkoutSessions().create(params);
String checkoutUrl = response.checkoutUrl();
String sessionId = response.sessionId();
// Redirect customer to checkoutUrl
System.out.println("Checkout URL: " + checkoutUrl);
System.out.println("Session ID: " + sessionId);
} catch (BadRequestException e) {
System.err.println("Invalid request: " + e.getMessage());
} catch (UnauthorizedException e) {
System.err.println("Invalid API key");
} catch (DodoPaymentsServiceException e) {
System.err.println("API error: " + e.statusCode() + " - " + e.getMessage());
}
```
--------------------------------
### Enable Test Mode for DodoPayments Java SDK
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
Switch the DodoPayments SDK to send requests to a testing environment instead of the live environment. This is configured using the `testMode()` method during client setup.
```java
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
DodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.testMode()
.build();
```
--------------------------------
### Install Dodo Payments Java SDK via Maven
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
This snippet demonstrates how to include the Dodo Payments Java SDK in a Maven project's dependencies. It specifies the group ID, artifact ID, and version of the library.
```xml
com.dodopayments.api
dodo-payments-java
1.53.4
```
--------------------------------
### Asynchronous API Request with CompletableFuture - Java
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
Execute Dodo Payments API requests asynchronously using the `async()` method on a client. This example demonstrates creating a checkout session and receiving the response as a `CompletableFuture`. Configuration can be done via system properties or environment variables.
```java
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.CheckoutSessionResponse;
import java.util.concurrent.CompletableFuture;
// Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties
// Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("product_id")
.quantity(0)
.build())
.build();
CompletableFuture checkoutSessionResponse = client.async().checkoutSessions().create(params);
```
--------------------------------
### Configure Dodo Payments Java Client with Environment and Token
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
This Java example shows how to configure the Dodo Payments client by combining environment variable/system property settings with a manually provided bearer token. The bearer token set via the builder will override any environment or system property values.
```java
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
DodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()
// Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties
// Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables
.fromEnv()
.bearerToken("My Bearer Token")
.build();
```
--------------------------------
### Manage Disputes with DodoPayments Java API
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This snippet shows how to monitor and handle payment disputes using the DodoPayments Java API. It includes examples for retrieving specific disputes, listing all disputes, and filtering disputes that require action.
```java
import com.dodopayments.api.models.disputes.GetDispute;
import com.dodopayments.api.models.disputes.DisputeListPage;
// Retrieve specific dispute
String disputeId = "disp_abc123";
GetDispute dispute = client.disputes().retrieve(disputeId);
System.out.println("Dispute ID: " + dispute.disputeId());
System.out.println("Status: " + dispute.status());
System.out.println("Amount: " + dispute.amount() + " " + dispute.currency());
System.out.println("Reason: " + dispute.reason());
System.out.println("Created: " + dispute.createdAt());
System.out.println("Payment ID: " + dispute.paymentId());
dispute.evidenceDueBy().ifPresent(date ->
System.out.println("Evidence due by: " + date)
);
// List all disputes
DisputeListPage disputes = client.disputes().list();
for (GetDispute disp : disputes.autoPager()) {
System.out.println("Dispute " + disp.disputeId() +
" for payment " + disp.paymentId() +
" - Status: " + disp.status());
}
// Filter open disputes requiring action
disputes.autoPager()
.stream()
.filter(d -> d.status().equals("needs_response"))
.forEach(d -> {
System.out.println("Action required for dispute: " + d.disputeId());
System.out.println("Reason: " + d.reason());
System.out.println("Amount: " + d.amount());
});
```
--------------------------------
### Configure and Manage Meters with DodoPayments Java SDK
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This snippet illustrates how to create, retrieve, list, archive, and unarchive meters using the DodoPayments Java SDK. It covers setting up meters for different aggregation types like 'count' and 'sum', and managing their lifecycle. Ensure the DodoPayments client is initialized.
```java
import com.dodopayments.api.models.meters.Meter;
import com.dodopayments.api.models.meters.MeterCreateParams;
// 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);
String meterId = apiMeter.meterId();
System.out.println("Meter created: " + meterId);
System.out.println("Name: " + apiMeter.name());
System.out.println("Event: " + apiMeter.eventName());
System.out.println("Aggregation: " + apiMeter.aggregation());
// Create storage meter with sum aggregation
MeterCreateParams storageMeterParams = MeterCreateParams.builder()
.name("Storage Used (GB)")
.eventName("storage_update")
.aggregation("sum")
.aggregationKey("storage_gb")
.build();
Meter storageMeter = client.meters().create(storageMeterParams);
// Retrieve meter
Meter meter = client.meters().retrieve(meterId);
System.out.println("Meter: " + meter.name());
// List all meters
client.meters().list()
.autoPager()
.forEach(m -> System.out.println("Meter: " + m.name() + " - " + m.aggregation()));
// Archive meter (soft delete)
client.meters().archive(meterId);
System.out.println("Meter archived");
// Unarchive meter
client.meters().unarchive(meterId);
System.out.println("Meter restored");
```
--------------------------------
### Initialize Dodo Payments Java Client
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Demonstrates various ways to initialize the Dodo Payments Java client. It covers initialization from environment variables, manual configuration with specific options like API key, base URL, retries, and timeouts, as well as test mode configuration and temporary option modifications.
```java
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
import java.time.Duration;
// Initialize from environment variables (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_BASE_URL)
// or system properties (dodopayments.apiKey, dodopayments.baseUrl)
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
// Manual configuration with all options
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 configuration
DodoPaymentsClient testClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.testMode()
.build();
// Temporary configuration modifications (shares connection pool)
DodoPaymentsClient customClient = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(5);
});
```
--------------------------------
### Create Subscription in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Sets up a new recurring subscription with specified product, customer, billing details, and trial period. Includes error handling for invalid parameters and general service failures.
```java
import com.dodopayments.api.models.subscriptions.SubscriptionCreateParams;
import com.dodopayments.api.models.subscriptions.SubscriptionCreateResponse;
import com.dodopayments.api.models.subscriptions.TimeInterval;
import com.dodopayments.api.models.checkoutsessions.Currency;
try {
SubscriptionCreateParams params = SubscriptionCreateParams.builder()
.productId("prod_premium_plan")
.customerId("cus_abc123")
.quantity(1)
.billingCurrency(Currency.USD)
.paymentFrequencyInterval(TimeInterval.MONTH)
.paymentFrequencyCount(1)
.trialPeriodDays(14)
.putMetadata("plan_type", "premium")
.putMetadata("referral_code", "FRIEND2024")
.build();
SubscriptionCreateResponse subscription = client.subscriptions().create(params);
System.out.println("Subscription ID: " + subscription.subscriptionId());
System.out.println("Status: " + subscription.status());
System.out.println("Next billing date: " + subscription.nextBillingDate());
System.out.println("Trial ends: " + subscription.trialPeriodDays());
} catch (UnprocessableEntityException e) {
System.err.println("Invalid subscription parameters: " + e.getMessage());
} catch (DodoPaymentsServiceException e) {
System.err.println("Subscription creation failed: " + e.getMessage());
}
```
--------------------------------
### Create, Update, Archive, and List Products in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This Java code demonstrates how to interact with the DodoPayments API to manage products. It covers creating new products with pricing and licensing details, updating existing product information, archiving products for soft deletion, unarchiving them, and listing all active products. It utilizes builder patterns for creating and updating product parameters and streams for filtering and processing product lists. Key dependencies include models for products, currencies, and subscription intervals.
```java
import com.dodopayments.api.models.products.Product;
import com.dodopayments.api.models.products.ProductCreateParams;
import com.dodopayments.api.models.products.ProductUpdateParams;
import com.dodopayments.api.models.checkoutsessions.Currency;
import com.dodopayments.api.models.subscriptions.TimeInterval;
// Create a digital product with license keys
ProductCreateParams createParams = ProductCreateParams.builder()
.name("Professional Software License")
.description("Annual license for professional edition")
.price(29900) // $299.00 in cents
.currency(Currency.USD)
.isRecurring(true)
.paymentFrequencyInterval(TimeInterval.YEAR)
.paymentFrequencyCount(1)
.generateLicenseKeys(true)
.licenseKeyActivationMessage("Thank you for your purchase! Your license key is: {license_key}")
.putMetadata("product_category", "software")
.putMetadata("sku", "PRO-ANNUAL-2024")
.build();
Product product = client.products().create(createParams);
String productId = product.productId();
System.out.println("Product created: " + productId);
System.out.println("Name: " + product.name());
System.out.println("Price: " + product.price() + " " + product.currency());
// Update product details
ProductUpdateParams updateParams = ProductUpdateParams.builder()
.description("Annual license for professional edition - Now with premium support")
.price(34900) // $349.00
.build();
client.products().update(productId, updateParams);
// Archive product (soft delete)
client.products().archive(productId);
System.out.println("Product archived");
// Unarchive product
client.products().unarchive(productId);
System.out.println("Product restored");
// List all active products
client.products().list()
.autoPager()
.stream()
.filter(p -> !p.archived())
.forEach(p -> System.out.println(p.name() + " - " + p.price()));
```
--------------------------------
### Client Initialization
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Initialize and configure the Dodo Payments client for interacting with the API. Supports initialization from environment variables, manual configuration, test mode, and temporary option modifications.
```APIDOC
## Client Initialization
### Description
Create and configure the Dodo Payments client for API access.
### Method
N/A (Client Initialization)
### Endpoint
N/A (Client Initialization)
### Parameters
N/A
### Request Example
```java
import com.dodopayments.api.client.DodoPaymentsClient;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;
import java.time.Duration;
// Initialize from environment variables (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_BASE_URL)
// or system properties (dodopayments.apiKey, dodopayments.baseUrl)
DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();
// Manual configuration with all options
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 configuration
DodoPaymentsClient testClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.testMode()
.build();
// Temporary configuration modifications (shares connection pool)
DodoPaymentsClient customClient = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(5);
});
```
### Response
#### Success Response (200)
N/A (Client Initialization returns a client object, not a typical API response)
#### Response Example
N/A
```
--------------------------------
### Create and Manage Customers in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This snippet illustrates how to create new customers, update their details, and generate customer portal sessions for self-service management using the DodoPayments Java SDK. It also shows how to list customers with pagination. Requires the DodoPayments Java SDK.
```java
import com.dodopayments.api.models.customers.Customer;
import com.dodopayments.api.models.customers.CustomerCreateParams;
import com.dodopayments.api.models.customers.CustomerUpdateParams;
import com.dodopayments.api.models.customers.CustomerPortalSession;
import com.dodopayments.api.models.customers.customerportal.CustomerPortalCreateParams;
// Create customer
CustomerCreateParams createParams = CustomerCreateParams.builder()
.email("customer@example.com")
.name("Jane Smith")
.phoneNumber("+14155551234")
.putMetadata("source", "website")
.putMetadata("customer_tier", "gold")
.build();
Customer customer = client.customers().create(createParams);
String customerId = customer.customerId();
System.out.println("Customer created: " + customerId);
System.out.println("Email: " + customer.email());
// Update customer information
CustomerUpdateParams updateParams = CustomerUpdateParams.builder()
.name("Jane Smith-Johnson")
.phoneNumber("+14155559876")
.putMetadata("customer_tier", "platinum")
.build();
Customer updatedCustomer = client.customers().update(customerId, updateParams);
// Create customer portal session for self-service management
CustomerPortalCreateParams portalParams = CustomerPortalCreateParams.builder()
.customerId(customerId)
.build();
CustomerPortalSession portalSession = client.customers()
.customerPortal()
.create(portalParams);
String portalUrl = portalSession.url();
System.out.println("Customer portal URL: " + portalUrl);
// List all customers with pagination
client.customers().list()
.autoPager()
.stream()
.limit(100)
.forEach(cust -> System.out.println(cust.email()));
```
--------------------------------
### Create Asynchronous Client and Make Request - Java
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
Instantiate an asynchronous DodoPayments client directly using `DodoPaymentsOkHttpClientAsync.fromEnv()` and make API requests. Similar to the synchronous client, this returns `CompletableFuture`s for all operations. Configuration can be sourced from system properties or environment variables.
```java
import com.dodopayments.api.client.DodoPaymentsClientAsync;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;
import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;
import java.util.concurrent.CompletableFuture;
// Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties
// Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables
DodoPaymentsClientAsync client = DodoPaymentsOkHttpClientAsync.fromEnv();
CheckoutSessionRequest params = CheckoutSessionRequest.builder()
.addProductCart(CheckoutSessionRequest.ProductCart.builder()
.productId("product_id")
.quantity(0)
.build())
.build();
CompletableFuture checkoutSessionResponse = client.checkoutSessions().create(params);
```
--------------------------------
### Create JsonValue Objects in Java
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
Provides examples of creating `JsonValue` objects in Java for various data types, including null, boolean, number, string, arrays, and complex nested objects. The `JsonValue.from(...)` method is used for straightforward conversion from standard Java types to JSON representations.
```java
import com.dodopayments.api.core.JsonValue;
import java.util.List;
import java.util.Map;
// Create primitive JSON values
JsonValue nullValue = JsonValue.from(null);
JsonValue booleanValue = JsonValue.from(true);
JsonValue numberValue = JsonValue.from(42);
JsonValue stringValue = JsonValue.from("Hello World!");
// Create a JSON array value equivalent to `["Hello", "World"]`
JsonValue arrayValue = JsonValue.from(List.of(
"Hello", "World"
));
// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`
JsonValue objectValue = JsonValue.from(Map.of(
"a", 1,
"b", 2
));
// Create an arbitrarily nested JSON equivalent to:
// {
// "a": [1, 2],
// "b": [3, 4]
// }
JsonValue complexValue = JsonValue.from(Map.of(
"a", List.of(
1, 2
),
"b", List.of(
3, 4
)
));
```
--------------------------------
### Add and Access Undocumented API Parameters with JsonValue (Java)
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This Java code snippet demonstrates how to add undocumented headers, query parameters, and body properties to a CheckoutSessionCreateParams object using the Dodo Payments Java SDK. It also shows how to access these additional properties from both the request parameters and the CheckoutSessionResponse. The example utilizes JsonValue to create and manipulate complex JSON structures for undocumented fields.
```java
import com.dodopayments.api.core.JsonValue;
import com.dodopayments.api.core.JsonMissing;
import java.util.Map;
import java.util.List;
// Add undocumented headers, query params, or body properties
CheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()
.putAdditionalHeader("X-Custom-Header", "custom_value")
.putAdditionalQueryParam("experimental_feature", "true")
.putAdditionalBodyProperty("undocumented_field", JsonValue.from("value"))
.build();
// Access additional properties later
Map> additionalHeaders = params._additionalHeaders();
Map> additionalQueryParams = params._additionalQueryParams();
Map additionalBody = params._additionalBodyProperties();
// Set undocumented values using JsonValue
JsonValue customValue = JsonValue.from(Map.of(
"nested_field", "value",
"array_field", List.of(1, 2, 3)
));
// Create various JsonValue types
JsonValue nullValue = JsonValue.from(null);
JsonValue boolValue = JsonValue.from(true);
JsonValue numberValue = JsonValue.from(42);
JsonValue stringValue = JsonValue.from("text");
JsonValue arrayValue = JsonValue.from(List.of("a", "b", "c"));
JsonValue objectValue = JsonValue.from(Map.of("key", "value"));
// Forcibly omit required parameter (advanced usage)
CheckoutSessionCreateParams omittedParams = CheckoutSessionCreateParams.builder()
.productCart(JsonMissing.of())
.build();
// Access undocumented response properties
CheckoutSessionResponse response = client.checkoutSessions().create(params);
Map additionalProps = response._additionalProperties();
JsonValue secretProperty = additionalProps.get("undocumented_field");
// Visit JsonValue to extract type
String result = secretProperty.accept(new JsonValue.Visitor<>() {
@Override
public String visitNull() {
return "null";
}
@Override
public String visitBoolean(boolean value) {
return String.valueOf(value);
}
@Override
public String visitNumber(Number value) {
return value.toString();
}
@Override
public String visitString(String value) {
return value;
}
@Override
public String visitArray(List value) {
return "array";
}
@Override
public String visitObject(Map value) {
return "object";
}
});
```
--------------------------------
### Configure Proxies, SSL, and Custom Base URL in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Shows how to configure advanced settings for the DodoPayments Java SDK client, including HTTP proxies, SSL/TLS certificates, disabling compatibility checks, and setting a custom base URL. Resource cleanup is also mentioned as optional.
```java
import java.net.InetSocketAddress;
import java.net.Proxy;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HostnameVerifier;
// Configure HTTP proxy
DodoPaymentsClient proxyClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.proxy(new Proxy(
Proxy.Type.HTTP,
new InetSocketAddress("proxy.example.com", 8080)
))
.build();
// Configure SSL/TLS (advanced - usually not needed)
DodoPaymentsClient sslClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.sslSocketFactory(yourSSLSocketFactory)
.trustManager(yourTrustManager)
.hostnameVerifier(yourHostnameVerifier)
.build();
// Enable debug logging via environment variable
// export DODO_PAYMENTS_LOG=debug
// Disable Jackson version compatibility check (not recommended)
DodoPaymentsClient uncheckedClient = DodoPaymentsOkHttpClient.builder()
.fromEnv()
.checkJacksonVersionCompatibility(false)
.build();
// Configure custom base URL (for testing or regional endpoints)
DodoPaymentsClient customBaseClient = DodoPaymentsOkHttpClient.builder()
.bearerToken("your_api_key")
.baseUrl("https://custom-api.dodopayments.com")
.build();
// Resource cleanup (optional - resources auto-release when idle)
client.close();
```
--------------------------------
### Enable Logging with Environment Variable (Shell)
Source: https://github.com/dodopayments/dodopayments-java/blob/main/README.md
Configures SDK logging by setting the DODO_PAYMENTS_LOG environment variable. Supports 'info' level for standard logging and 'debug' for verbose output.
```sh
$ export DODO_PAYMENTS_LOG=info
```
```sh
$ export DODO_PAYMENTS_LOG=debug
```
--------------------------------
### Manage Discount Codes with DodoPayments Java SDK
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This snippet demonstrates creating, updating, retrieving, listing, and deleting discount codes using the DodoPayments Java SDK. It covers both percentage and fixed amount discounts, as well as auto-generating codes. Requires an initialized DodoPayments client and appropriate imports.
```java
import com.dodopayments.api.models.discounts.Discount;
import com.dodopayments.api.models.discounts.DiscountCreateParams;
import com.dodopayments.api.models.discounts.DiscountType;
import com.dodopayments.api.models.discounts.DiscountUpdateParams;
import com.dodopayments.api.Currency; // Assuming Currency is imported correctly
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
// Assume 'client' is an initialized DodoPayments client instance
// Create percentage discount
DiscountCreateParams percentageParams = DiscountCreateParams.builder()
.code("SUMMER2024")
.type(DiscountType.PERCENTAGE)
.percentageOff(25) // 25% off
.currency(Currency.USD)
.maxRedemptions(1000)
.expiresAt(OffsetDateTime.now().plus(30, ChronoUnit.DAYS))
.putMetadata("campaign", "summer_sale")
.build();
Discount percentageDiscount = client.discounts().create(percentageParams);
System.out.println("Discount code: " + percentageDiscount.code());
System.out.println("Type: " + percentageDiscount.type());
System.out.println("Percentage off: " + percentageDiscount.percentageOff() + "%");
// Create fixed amount discount
DiscountCreateParams fixedParams = DiscountCreateParams.builder()
.code("SAVE10")
.type(DiscountType.FIXED_AMOUNT)
.amountOff(1000) // $10.00 off
.currency(Currency.USD)
.maxRedemptions(500)
.putMetadata("campaign", "new_customer")
.build();
Discount fixedDiscount = client.discounts().create(fixedParams);
// Auto-generate discount code (16 characters)
DiscountCreateParams autoCodeParams = DiscountCreateParams.builder()
.type(DiscountType.PERCENTAGE)
.percentageOff(15)
.currency(Currency.USD)
.maxRedemptions(100)
.build();
Discount autoDiscount = client.discounts().create(autoCodeParams);
System.out.println("Auto-generated code: " + autoDiscount.code());
// Update discount
DiscountUpdateParams updateParams = DiscountUpdateParams.builder()
.maxRedemptions(2000)
.build();
String discountId = percentageDiscount.discountId(); // Get the ID for update/retrieve/delete
Discount updated = client.discounts().update(discountId, updateParams);
// Retrieve discount
Discount discount = client.discounts().retrieve(discountId);
System.out.println("Redemptions: " + discount.timesRedeemed() + "/" + discount.maxRedemptions());
discount.expiresAt().ifPresent(exp -> System.out.println("Expires: " + exp));
// List active discounts
client.discounts().list()
.autoPager()
.stream()
.filter(d -> d.timesRedeemed() < d.maxRedemptions())
.forEach(d -> System.out.println("Active code: " + d.code()));
// Delete discount
client.discounts().delete(discountId);
System.out.println("Discount deleted");
```
--------------------------------
### Ingest and Retrieve Usage Events with DodoPayments Java SDK
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This snippet demonstrates how to ingest single and batched usage events using the DodoPayments Java SDK. It also shows how to retrieve a specific event and list events with filtering capabilities. Ensure the DodoPayments client is initialized before use.
```java
import com.dodopayments.api.models.usageevents.UsageEventIngestParams;
import com.dodopayments.api.models.usageevents.UsageEventIngestResponse;
import com.dodopayments.api.models.usageevents.Event;
import java.time.OffsetDateTime;
// Ingest single API usage 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")
.putMetadata("response_time_ms", "245")
.build())
.build();
try {
UsageEventIngestResponse response = client.usageEvents().ingest(singleEventParams);
System.out.println("Event ingested successfully");
System.out.println("Processed: " + response.processedEvents());
} catch (UnprocessableEntityException e) {
System.err.println("Event ingestion failed: " + e.getMessage());
}
// Batch ingest multiple events (max 1000 per request)
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))
.putMetadata("resolution", "1080p")
.putMetadata("format", "mp4")
.build());
}
UsageEventIngestResponse batchResponse = client.usageEvents().ingest(batchBuilder.build());
System.out.println("Batch processed: " + batchResponse.processedEvents() + " events");
// Retrieve event details
String eventId = "evt_xyz789";
Event event = client.usageEvents().retrieve(eventId);
System.out.println("Event ID: " + event.eventId());
System.out.println("Customer: " + event.customerId());
System.out.println("Event name: " + event.eventName());
System.out.println("Timestamp: " + event.timestamp());
System.out.println("Metadata: " + event.metadata());
// List usage events with filtering
client.usageEvents().list()
.autoPager()
.stream()
.filter(e -> e.eventName().equals("api_request"))
.limit(1000)
.forEach(e -> System.out.println("API call at " + e.timestamp()));
```
--------------------------------
### Activate, Validate, Deactivate, and Retrieve License Keys in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
This Java code illustrates how to manage software license keys using the DodoPayments API. It includes functionalities for activating a license key for a specific machine with associated metadata, validating the status of a license key, deactivating a license instance, and retrieving detailed information about a specific license key. Error handling for activation failures is demonstrated using a try-catch block for `UnprocessableEntityException`. Dependencies include models for license activation, validation, deactivation, and license key retrieval.
```java
import com.dodopayments.api.models.licenses.LicenseActivateParams;
import com.dodopayments.api.models.licenses.LicenseActivateResponse;
import com.dodopayments.api.models.licenses.LicenseValidateParams;
import com.dodopayments.api.models.licenses.LicenseValidateResponse;
import com.dodopayments.api.models.licenses.LicenseDeactivateParams;
import com.dodopayments.api.models.licenseskeys.LicenseKey;
// Activate license key for a machine
LicenseActivateParams activateParams = LicenseActivateParams.builder()
.licenseKey("XXXX-XXXX-XXXX-XXXX")
.name("Production Server 01")
.putMetadata("machine_id", "srv-prod-01")
.putMetadata("os", "Ubuntu 22.04")
.putMetadata("ip_address", "203.0.113.42")
.build();
try {
LicenseActivateResponse activation = client.licenses().activate(activateParams);
System.out.println("License activated successfully");
System.out.println("Instance ID: " + activation.licenseKeyInstanceId());
System.out.println("License Key: " + activation.licenseKey());
} catch (UnprocessableEntityException e) {
System.err.println("Activation failed: " + e.getMessage());
// Common reasons: max activations reached, key expired, invalid key
}
// Validate license key status
LicenseValidateParams validateParams = LicenseValidateParams.builder()
.licenseKey("XXXX-XXXX-XXXX-XXXX")
.build();
LicenseValidateResponse validation = client.licenses().validate(validateParams);
if (validation.valid()) {
System.out.println("License is valid");
System.out.println("Product: " + validation.productName());
System.out.println("Customer: " + validation.customerEmail());
System.out.println("Activations: " + validation.activations() + "/" + validation.maxActivations());
} else {
System.out.println("License is invalid or expired");
}
// Deactivate license instance
LicenseDeactivateParams deactivateParams = LicenseDeactivateParams.builder()
.licenseKey("XXXX-XXXX-XXXX-XXXX")
.licenseKeyInstanceId("lki_abc123")
.build();
client.licenses().deactivate(deactivateParams);
System.out.println("License deactivated for instance");
// Retrieve license key details
String licenseKeyId = "lic_xyz789";
LicenseKey licenseKey = client.licenseKeys().retrieve(licenseKeyId);
System.out.println("Key: " + licenseKey.key());
System.out.println("Status: " + licenseKey.status());
System.out.println("Customer: " + licenseKey.customerEmail());
```
--------------------------------
### Async API Calls with CompletableFuture in Java
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Demonstrates how to execute API calls asynchronously using CompletableFuture. It covers initializing the async client, handling individual responses with .thenAccept() and .exceptionally(), and managing potential errors.
```java
import com.dodopayments.api.client.DodoPaymentsClientAsync;
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync;
import com.dodopayments.api.models.payments.Payment;
import java.util.concurrent.CompletableFuture;
// Create async client
DodoPaymentsClientAsync asyncClient = DodoPaymentsOkHttpClientAsync.fromEnv();
// Or convert sync client to async
CompletableFuture paymentFuture = client.async()
.payments()
.retrieve("pay_1234567890");
// Handle async response
paymentFuture.thenAccept(payment -> {
System.out.println("Payment amount: " + payment.totalAmount());
System.out.println("Status: " + payment.status());
}).exceptionally(error -> {
System.err.println("Error: " + error.getMessage());
return null;
});
```
--------------------------------
### Meter Configuration API
Source: https://context7.com/dodopayments/dodopayments-java/llms.txt
Create and manage meters for tracking usage metrics. This API allows for creating, retrieving, listing, archiving, and unarchiving meters.
```APIDOC
## POST /v1/meters
### Description
Creates a new meter for tracking usage metrics.
### Method
POST
### Endpoint
/v1/meters
### Parameters
#### Request Body
- **name** (string) - Required - The name of the meter.
- **eventName** (string) - Required - The name of the usage event this meter tracks.
- **aggregation** (string) - Required - The aggregation method (e.g., 'count', 'sum').
- **aggregationKey** (string) - Optional - The key within the event metadata to use for 'sum' aggregation.
- **metadata** (object) - Optional - A key-value map of additional metadata for the meter.
### Request Example
```json
{
"name": "API Requests",
"eventName": "api_request",
"aggregation": "count",
"metadata": {
"category": "api_usage"
}
}
```
### Response
#### Success Response (200)
- **meterId** (string) - The unique identifier for the newly created meter.
- **name** (string) - The name of the meter.
- **eventName** (string) - The name of the usage event this meter tracks.
- **aggregation** (string) - The aggregation method.
- **aggregationKey** (string) - The key used for aggregation.
- **metadata** (object) - Metadata associated with the meter.
#### Response Example
```json
{
"meterId": "mtr_abc123",
"name": "API Requests",
"eventName": "api_request",
"aggregation": "count",
"metadata": {
"category": "api_usage"
}
}
```
## GET /v1/meters/{meterId}
### Description
Retrieves details for a specific meter.
### Method
GET
### Endpoint
/v1/meters/{meterId}
### Parameters
#### Path Parameters
- **meterId** (string) - Required - The ID of the meter to retrieve.
### Response
#### Success Response (200)
- Returns a meter object with details.
#### Response Example
```json
{
"meterId": "mtr_abc123",
"name": "API Requests",
"eventName": "api_request",
"aggregation": "count",
"metadata": {
"category": "api_usage"
}
}
```
## GET /v1/meters
### Description
Lists all available meters.
### Method
GET
### Endpoint
/v1/meters
### Response
#### Success Response (200)
- Returns a paginated list of meter objects.
#### Response Example
```json
[
{
"meterId": "mtr_abc123",
"name": "API Requests",
"eventName": "api_request",
"aggregation": "count"
}
]
```
## DELETE /v1/meters/{meterId}
### Description
Archives a meter (soft delete).
### Method
DELETE
### Endpoint
/v1/meters/{meterId}
### Parameters
#### Path Parameters
- **meterId** (string) - Required - The ID of the meter to archive.
### Response
#### Success Response (200)
- Indicates successful archiving of the meter.
## POST /v1/meters/{meterId}/unarchive
### Description
Unarchives a previously archived meter.
### Method
POST
### Endpoint
/v1/meters/{meterId}/unarchive
### Parameters
#### Path Parameters
- **meterId** (string) - Required - The ID of the meter to unarchive.
### Response
#### Success Response (200)
- Indicates successful restoration of the meter.
```