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.
L’SDK Java fornisce un accesso conveniente ed ergonomico all’API REST di Dodo Payments per le applicazioni scritte in Java. Utilizza funzionalità specifiche di Java come Optional, Stream e CompletableFuture per lo sviluppo moderno in Java.
Installazione
Maven
Add the dependency to your pom.xml:
< dependency >
< groupId > com.dodopayments.api </ groupId >
< artifactId > dodo-payments-java </ artifactId >
< version > 1.97.1 </ version >
</ dependency >
Gradle
Add the dependency to your build.gradle:
implementation ( "com.dodopayments.api:dodo-payments-java:1.97.1" )
Usa sempre l’ultima versione dell’SDK per accedere alle funzionalità più recenti di Dodo Payments. Verifica su Maven Central la versione più recente.
L’SDK supporta Java 8 e tutte le versioni successive, incluse Java 11, 17 e 21.
Inizio Veloce
Inizializza il client e crea una sessione di checkout:
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 ());
Conserva sempre le chiavi API in modo sicuro utilizzando variabili d’ambiente, proprietà di sistema o un sistema di gestione delle configurazioni sicuro. Non inserirle mai direttamente nel codice sorgente.
Caratteristiche Principali
Type Safety API fortemente tipizzata con sicurezza a tempo di compilazione
Thread-Safe Sicuro per l’uso concorrente in applicazioni multi-thread
Builder Pattern Pattern builder intuitivo per costruire le richieste
Async Support Supporto CompletableFuture per operazioni asincrone
Configurazione
Variabili d’Ambiente
Configura utilizzando variabili d’ambiente o proprietà di sistema:
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 ();
Configurazione Manuale
Configura manualmente con tutte le opzioni:
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 ();
Modalità di Test
Configura per l’ambiente di test/sandbox:
DodoPaymentsClient testClient = DodoPaymentsOkHttpClient . builder ()
. fromEnv ()
. testMode ()
. build ();
Operazioni Comuni
Crea una Sessione di Checkout
Genera una sessione di checkout:
CheckoutSessionRequest params = CheckoutSessionRequest . builder ()
. addProductCart ( ProductItemReq . 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 ());
Gestisci i Clienti
Crea e recupera informazioni sui clienti:
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 () + ")" );
Gestisci Abbonamenti
Crea e gestisci abbonamenti ricorrenti:
import com.dodopayments.api.models.payments.AttachExistingCustomer;
import com.dodopayments.api.models.payments.BillingAddress;
import com.dodopayments.api.models.payments.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 è espresso nella denominazione più bassa della valuta (ad esempio, centesimi per USD, paise per INR). Per addebitare $25,00, passare 2500.
La fatturazione tramite subscriptions().charge(...) è destinata a abbonamenti su richiesta . Gli abbonamenti programmati standard vengono addebitati automaticamente in base al programma di prezzi del prodotto.
Fatturazione basata sull’uso
Configurazione dei contatori
Crea e gestisci i contatori per tracciare l’uso:
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 ()));
Ingestione di eventi di uso
Traccia eventi personalizzati:
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 ());
Ingestione a blocchi di eventi
Ingerire più eventi in modo efficiente (massimo 1000 per richiesta):
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" );
Gestione degli errori
Gestione comprensiva degli errori per diversi scenari:
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 ());
}
L’SDK ritenta automaticamente le richieste in caso di errori di connessione, 408, 409, 429 e errori 5xx con backoff esponenziale.
Operazioni asincrone
Usa CompletableFuture per operazioni asincrone:
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 ;
});
Integrazione Spring Boot
Classe di configurazione
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 ();
}
}
Layer di servizio
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);
}
}
Risorse
GitHub Repository Visualizza il codice sorgente e contribuisci
API Reference Documentazione completa dell’API
Discord Community Ottieni supporto e connettiti con sviluppatori
Report Issues Segnala bug o richiedi funzionalità
Supporto
Hai bisogno di assistenza con il Java SDK?
Contributi
Accogliamo con favore i contributi! Consulta le linee guida per i contributi per iniziare.