> ## 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.

# Kotlin

> Integrieren Sie Dodo Payments in Ihre Kotlin-Anwendungen mit modernen Coroutinen und Null-Sicherheit

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:

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

### Maven

Fügen Sie die Abhängigkeit zu Ihrem `pom.xml` hinzu:

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

<Tip>
  Verwenden Sie immer die neueste SDK-Version, um auf die aktuellsten Dodo Payments-Funktionen zuzugreifen. Prüfen Sie [Maven Central](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-kotlin) auf die neueste Version.
</Tip>

<Info>
  Das SDK benötigt Java 8 oder höher und ist sowohl mit der JVM als auch mit Android-Plattformen kompatibel.
</Info>

## Schnellstart

Initialisieren Sie den Client und erstellen Sie eine Checkout-Sitzung:

```kotlin theme={null}
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)
val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()

val params: CheckoutSessionRequest = CheckoutSessionRequest.builder()
    .addProductCart(ProductItemReq.builder()
        .productId("product_id")
        .quantity(1)
        .build())
    .build()
    
val checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params)
println(checkoutSessionResponse.sessionId())
```

<Warning>
  Speichern Sie Ihre API-Schlüssel stets sicher, z. B. über Umgebungsvariablen oder verschlüsselte Konfigurationen. Committen Sie sie niemals in Versionskontrollsysteme.
</Warning>

## Kernfunktionen

<CardGroup cols={2}>
  <Card title="Coroutines" icon="bolt">
    Vollständige Unterstützung für Kotlin-Coroutinen für asynchrone Vorgänge
  </Card>

  <Card title="Null Safety" icon="shield-check">
    Nutzen Sie Kotlins Nullsicherheit für eine robuste Fehlerbehandlung
  </Card>

  <Card title="Extension Functions" icon="code">
    Idiomatische Kotlin-Erweiterungen für erweiterte Funktionalität
  </Card>

  <Card title="Data Classes" icon="layer-group">
    Typensichere Datenklassen mit Unterstützung für Kopieren und Destrukturierung
  </Card>
</CardGroup>

## Konfiguration

### Aus Umgebungsvariablen

Initialisieren Sie aus Umgebungsvariablen oder Systemeigenschaften:

```kotlin theme={null}
val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()
```

### Manuelle Konfiguration

Konfigurieren Sie manuell mit allen Optionen:

```kotlin theme={null}
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:

```kotlin theme={null}
val testClient = DodoPaymentsOkHttpClient.builder()
    .fromEnv()
    .testMode()
    .build()
```

### Timeouts und Wiederholungen

Global oder pro Anfrage konfigurieren:

```kotlin theme={null}
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:

```kotlin theme={null}
val params = CheckoutSessionRequest.builder()
    .addProductCart(ProductItemReq.builder()
        .productId("prod_123")
        .quantity(1)
        .build())
    .returnUrl("https://yourdomain.com/return")
    .build()

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

### Erstellen eines Produkts

Erstellen Sie Produkte mit detaillierter Konfiguration:

```kotlin theme={null}
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_PRODUCTS)
    .build()

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

### Lizenzschlüssel aktivieren

Aktivieren Sie Lizenzschlüssel für Kunden:

```kotlin theme={null}
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:

```kotlin theme={null}
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:

```kotlin theme={null}
import com.dodopayments.api.models.usageevents.EventInput
import com.dodopayments.api.models.usageevents.UsageEventIngestParams

val usageParams = UsageEventIngestParams.builder()
    .addEvent(EventInput.builder()
        .customerId("cust_456")
        .eventId("event_123")
        .eventName("api_call")
        .build())
    .build()

client.usageEvents().ingest(usageParams)
println("Usage event recorded")
```

## Fehlerbehandlung

Behandeln Sie Fehler mit der Fehlerbehandlung von Kotlin:

```kotlin theme={null}
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:

```kotlin theme={null}
fun safeCreatePayment(client: DodoPaymentsClient): Result<Payment> = runCatching {
    client.payments().create(params)
}

// Usage
safeCreatePayment(client)
    .onSuccess { payment -> println("Created: ${payment.id()}") }
    .onFailure { error -> println("Error: ${error.message}") }
```

<Tip>
  Verwenden Sie Kotlins `runCatching` für einen funktionaleren Ansatz bei der Fehlerbehandlung mit Result-Typen.
</Tip>

## Android-Integration

Verwenden Sie es mit Android-Anwendungen:

```kotlin theme={null}
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:

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

```kotlin theme={null}
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.checkoutUrl())
            } catch (e: Exception) {
                handleError(e)
            }
        }
    }
}
```

### Proxy-Konfiguration

Konfigurieren Sie die Proxy-Einstellungen:

```kotlin theme={null}
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:

```kotlin theme={null}
val customClient = client.withOptions {
    it.baseUrl("https://example.com")
    it.maxRetries(5)
}
```

## Ktor-Integration

Integrieren Sie mit Ktor-Serveranwendungen:

```kotlin theme={null}
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

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-kotlin">
    Quellcode anzeigen und mitwirken
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Vollständige API-Dokumentation
  </Card>

  ```kotlin theme={null}
  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.checkoutUrl()))
              } catch (e: DodoPaymentsServiceException) {
                  call.respond(HttpStatusCode.BadRequest, mapOf("error" to e.message))
              }
          }
      }
  }
  ```

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-kotlin/issues">
    Fehler melden oder Funktionen anfordern
  </Card>
</CardGroup>

## Unterstützung

Brauchen Sie Hilfe mit dem Kotlin SDK?

* **Discord**: Treten Sie unserem [Community-Server](https://discord.gg/bYqAp4ayYh) für Echtzeit-Support bei
* **E-Mail**: Kontaktieren Sie uns unter [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Öffnen Sie ein Problem im [Repository](https://github.com/dodopayments/dodopayments-kotlin)

## Mitwirken

Wir freuen uns über Beiträge! Überprüfen Sie die [Mitwirkungsrichtlinien](https://github.com/dodopayments/dodopayments-kotlin/blob/main/CONTRIBUTING.md), um loszulegen.

Benötigen Sie Hilfe mit dem Kotlin SDK?

* **Discord**: Treten Sie unserem [Community-Server](https://discord.gg/bYqAp4ayYh) für Echtzeitunterstützung bei
* **Email**: Kontaktieren Sie uns unter [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Eröffnen Sie ein Issue im [Repository](https://github.com/dodopayments/dodopayments-kotlin)

## Beitrag leisten

Wir begrüßen Beiträge! Lesen Sie die [Richtlinien für Beiträge](https://github.com/dodopayments/dodopayments-kotlin/blob/main/CONTRIBUTING.md), um loszulegen.
