Zum Hauptinhalt springen
Das Kotlin SDK bietet bequemen Zugriff auf die Dodo Payments REST API aus in Kotlin geschriebenen Anwendungen. Es bietet nullable Werte, Sequence, suspend-Funktionen und andere Kotlin-spezifische Funktionen für eine ergonomische Nutzung.

Installation

Gradle (Kotlin DSL)

Fügen Sie die Abhängigkeit zu Ihrem build.gradle.kts hinzu:
build.gradle.kts
implementation("com.dodopayments.api:dodo-payments-kotlin:1.61.5")

Maven

Fügen Sie die Abhängigkeit zu Ihrem pom.xml hinzu:
pom.xml
<dependency>
  <groupId>com.dodopayments.api</groupId>
  <artifactId>dodo-payments-kotlin</artifactId>
  <version>1.61.5</version>
</dependency>
Verwenden Sie immer die neueste SDK-Version, um auf die neuesten Dodo Payments-Funktionen zuzugreifen. Überprüfen Sie Maven Central auf die neueste Version.
Das SDK erfordert Kotlin 1.6 oder höher und ist mit sowohl JVM- als auch Android-Plattformen kompatibel.

Schnellstart

Initialisieren Sie den Client und erstellen Sie eine Checkout-Sitzung:
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)
val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()

val params: CheckoutSessionRequest = CheckoutSessionRequest.builder()
    .addProductCart(CheckoutSessionRequest.ProductCart.builder()
        .productId("product_id")
        .quantity(1)
        .build())
    .build()
    
val checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params)
println(checkoutSessionResponse.sessionId())
Bewahren Sie Ihre API-Schlüssel immer sicher auf, indem Sie Umgebungsvariablen oder verschlüsselte Konfigurationen verwenden. Fügen Sie sie niemals der Versionskontrolle hinzu.

Kernfunktionen

Coroutinen

Vollständige Unterstützung für Kotlin-Coroutinen für asynchrone Operationen

Null-Sicherheit

Nutzen Sie die Null-Sicherheit von Kotlin für robuste Fehlerbehandlung

Erweiterungsfunktionen

Idiomatische Kotlin-Erweiterungen für erweiterte Funktionalität

Datenklassen

Typsichere Datenklassen mit Kopier- und Destrukturierungsunterstützung

Konfiguration

Aus Umgebungsvariablen

Initialisieren Sie aus Umgebungsvariablen oder Systemeigenschaften:
val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()

Manuelle Konfiguration

Konfigurieren Sie manuell mit allen Optionen:
import java.time.Duration

val client = DodoPaymentsOkHttpClient.builder()
    .bearerToken("your_api_key_here")
    .baseUrl("https://live.dodopayments.com")
    .maxRetries(3)
    .timeout(Duration.ofSeconds(30))
    .build()

Testmodus

Konfigurieren Sie für die Test-/Sandbox-Umgebung:
val testClient = DodoPaymentsOkHttpClient.builder()
    .fromEnv()
    .testMode()
    .build()

Timeouts und Wiederholungen

Global oder pro Anfrage konfigurieren:
import com.dodopayments.api.core.RequestOptions

// Global configuration
val client = DodoPaymentsOkHttpClient.builder()
    .fromEnv()
    .timeout(Duration.ofSeconds(45))
    .maxRetries(3)
    .build()

// Per-request timeout override
val product = client.products().retrieve(
    "prod_123",
    RequestOptions.builder()
        .timeout(Duration.ofSeconds(10))
        .build()
)

Häufige Operationen

Erstellen einer Checkout-Sitzung

Generieren Sie eine Checkout-Sitzung:
val params = CheckoutSessionRequest.builder()
    .addProductCart(CheckoutSessionRequest.ProductCart.builder()
        .productId("prod_123")
        .quantity(1)
        .build())
    .returnUrl("https://yourdomain.com/return")
    .build()

val session = client.checkoutSessions().create(params)
println("Checkout URL: ${session.url()}")

Erstellen eines Produkts

Erstellen Sie Produkte mit detaillierter Konfiguration:
import com.dodopayments.api.models.products.Product
import com.dodopayments.api.models.products.ProductCreateParams
import com.dodopayments.api.models.misc.Currency
import com.dodopayments.api.models.misc.TaxCategory

val createParams = ProductCreateParams.builder()
    .name("Premium Subscription")
    .description("Monthly subscription with all features")
    .price(
        ProductCreateParams.RecurringPrice.builder()
            .currency(Currency.USD)
            .preTaxAmount(2999) // $29.99 in cents
            .paymentFrequencyInterval(ProductCreateParams.RecurringPrice.TimeInterval.MONTH)
            .paymentFrequencyCount(1)
            .build()
    )
    .taxCategory(TaxCategory.DIGITAL_GOODS)
    .build()

val product: Product = client.products().create(createParams)
println("Created product ID: ${product.productId()}")

Lizenzschlüssel aktivieren

Aktivieren Sie Lizenzschlüssel für Kunden:
import com.dodopayments.api.models.licenses.LicenseActivateParams
import com.dodopayments.api.models.licenses.LicenseActivateResponse

val activateParams = LicenseActivateParams.builder()
    .licenseKey("XXXX-XXXX-XXXX-XXXX")
    .instanceName("user-laptop-01")
    .build()

try {
    val activationResult: LicenseActivateResponse = client.licenses()
        .activate(activateParams)

    println("License activated successfully")
    println("Instance ID: ${activationResult.instanceId()}")
    println("Expires at: ${activationResult.expiresAt()}")
} catch (e: UnprocessableEntityException) {
    println("License activation failed: ${e.message}")
}

Nutzungsbasierte Abrechnung

Nutzungsereignisse aufzeichnen

Verfolgen Sie die Nutzung für Zähler:
import com.dodopayments.api.models.usageevents.UsageEventCreateParams
import java.time.OffsetDateTime

val usageParams = UsageEventCreateParams.builder()
    .meterId("meter_123")
    .customerId("cust_456")
    .value(150)
    .timestamp(OffsetDateTime.now())
    .build()

client.usageEvents().create(usageParams)
println("Usage event recorded")

Asynchrone Operationen

Asynchroner Client

Verwenden Sie den asynchronen Client für auf Coroutinen basierende Operationen:
import com.dodopayments.api.client.DodoPaymentsClientAsync
import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync
import kotlinx.coroutines.runBlocking

val asyncClient: DodoPaymentsClientAsync = DodoPaymentsOkHttpClientAsync.fromEnv()

runBlocking {
    val customer = asyncClient.customers().retrieve("cust_123")
    println("Customer email: ${customer.email()}")
}

Fehlerbehandlung

Behandeln Sie Fehler mit der Fehlerbehandlung von Kotlin:
import com.dodopayments.api.errors.*

try {
    val payment = client.payments().create(params)
    println("Success: ${payment.id()}")
} catch (e: AuthenticationException) {
    println("Authentication failed: ${e.message}")
} catch (e: InvalidRequestException) {
    println("Invalid request: ${e.message}")
    e.parameter?.let { println("Parameter: $it") }
} catch (e: RateLimitException) {
    println("Rate limit exceeded, retry after: ${e.retryAfter}")
} catch (e: DodoPaymentsServiceException) {
    println("API error: ${e.statusCode()} - ${e.message}")
}

Funktionale Fehlerbehandlung

Verwenden Sie Result für funktionale Fehlerbehandlung:
fun safeCreatePayment(client: DodoPaymentsClient): Result<Payment> = runCatching {
    client.payments().create(params)
}

// Usage
safe CreatePayment(client)
    .onSuccess { payment -> println("Created: ${payment.id()}") }
    .onFailure { error -> println("Error: ${error.message}") }
Verwenden Sie Kottlins runCatching für einen funktionaleren Ansatz zur Fehlerbehandlung mit Resultattypen.

Android-Integration

Verwenden Sie es mit Android-Anwendungen:
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dodopayments.api.client.DodoPaymentsClient
import kotlinx.coroutines.launch

class PaymentViewModel(application: Application) : ViewModel() {
    private val client = DodoPaymentsOkHttpClient.builder()
        .bearerToken(BuildConfig.DODO_API_KEY)
        .build()
    
    fun createCheckout(productId: String) {
        viewModelScope.launch {
            try {
                val session = client.async().checkoutSessions().create(params)
                // Open checkout URL in browser or WebView
                openUrl(session.url())
            } catch (e: Exception) {
                handleError(e)
            }
        }
    }
}

Antwortvalidierung

Aktivieren Sie die Antwortvalidierung:
import com.dodopayments.api.core.RequestOptions

// Per-request validation
val product = client.products().retrieve(
    "prod_123",
    RequestOptions.builder()
        .responseValidation(true)
        .build()
)

// Or validate explicitly
val validatedProduct = product.validate()

Erweiterte Funktionen

Proxy-Konfiguration

Konfigurieren Sie die Proxy-Einstellungen:
import java.net.InetSocketAddress
import java.net.Proxy

val client = DodoPaymentsOkHttpClient.builder()
    .fromEnv()
    .proxy(
        Proxy(
            Proxy.Type.HTTP,
            InetSocketAddress("proxy.example.com", 8080)
        )
    )
    .build()

Temporäre Konfiguration

Ändern Sie die Clientkonfiguration vorübergehend:
val customClient = client.withOptions {
    it.baseUrl("https://example.com")
    it.maxRetries(5)
}

Ktor-Integration

Integrieren Sie mit Ktor-Serveranwendungen:
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun Application.configureRouting() {
    val client = DodoPaymentsOkHttpClient.builder()
        .bearerToken(environment.config.property("dodo.apiKey").getString())
        .build()
    
    routing {
        post("/create-checkout") {
            try {
                val request = call.receive<CheckoutRequest>()
                val session = client.checkoutSessions().create(params)
                call.respond(mapOf("checkout_url" to session.url()))
            } catch (e: DodoPaymentsServiceException) {
                call.respond(HttpStatusCode.BadRequest, mapOf("error" to e.message))
            }
        }
    }
}

Ressourcen

Unterstützung

Brauchen Sie Hilfe mit dem Kotlin SDK?

Mitwirken

Wir freuen uns über Beiträge! Überprüfen Sie die Mitwirkungsrichtlinien, um loszulegen.