Kotlin SDK ger bekväm åtkomst till Dodo Payments REST API från applikationer skrivna i Kotlin. Den har nullable-värden, Sequence, suspend-funktioner och andra Kotlin-specifika funktioner för ergonomisk användning.
Installation
Gradle (Kotlin DSL)
Lägg till beroendet i din build.gradle.kts:
implementation ( "com.dodopayments.api:dodo-payments-kotlin:1.61.5" )
Maven
Lägg till beroendet i din pom.xml:
< dependency >
< groupId > com.dodopayments.api </ groupId >
< artifactId > dodo-payments-kotlin </ artifactId >
< version > 1.61.5 </ version >
</ dependency >
Använd alltid den senaste SDK-versionen för att få tillgång till de senaste Dodo Payments-funktionerna. Kontrollera Maven Central för den senaste versionen.
SDK:n kräver Kotlin 1.6 eller högre och är kompatibel med både JVM och Android-plattformar.
Snabbstart
Initiera klienten och skapa en checkout-session:
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 ())
Lagra alltid dina API-nycklar säkert med hjälp av miljövariabler eller krypterad konfiguration. Kom aldrig ihåg dem i versionskontroll.
Kärnfunktioner
Coroutines Fullt stöd för Kotlin coroutines för asynkrona operationer
Null Safety Utnyttja Kottins null-säkerhet för robust felhantering
Extension Functions Idiomatiska Kotlin-extensions för förbättrad funktionalitet
Data Classes Typ-säkra dataklasser med kopierings- och destruktureringsstöd
Konfiguration
Från miljövariabler
Initiera från miljövariabler eller systemegenskaper:
val client: DodoPaymentsClient = DodoPaymentsOkHttpClient. fromEnv ()
Manuell konfiguration
Konfigurera manuellt med alla alternativ:
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 ()
Testläge
Konfigurera för test/sandbox-miljö:
val testClient = DodoPaymentsOkHttpClient. builder ()
. fromEnv ()
. testMode ()
. build ()
Tidsgränser och omförsök
Konfigurera globalt eller per begäran:
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 ()
)
Vanliga operationer
Skapa en checkout-session
Generera en checkout-session:
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 () } " )
Skapa en produkt
Skapa produkter med detaljerad 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 () } " )
Aktivera licensnyckel
Aktivera licensnycklar för kunder:
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 } " )
}
Användningsbaserad fakturering
Registrera användningsevenemang
Spåra användning för mätare:
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" )
Asynkrona operationer
Asynkron klient
Använd den asynkrona klienten för coroutine-baserade operationer:
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 () } " )
}
Felhantering
Hantera fel med Kotlins undantagshantering:
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 } " )
}
Funktionell felhantering
Använd Result för funktionell felhantering:
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 } " ) }
Använd Kottins runCatching för en mer funktionell metod för felhantering med Result-typer.
Android-integration
Använd med Android-applikationer:
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)
}
}
}
}
Svarsvalidering
Aktivera svarsvalidering:
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 ()
Avancerade funktioner
Proxykonfiguration
Konfigurera proxyinställningar:
import java.net.InetSocketAddress
import java.net.Proxy
val client = DodoPaymentsOkHttpClient. builder ()
. fromEnv ()
. proxy (
Proxy (
Proxy.Type.HTTP,
InetSocketAddress ( "proxy.example.com" , 8080 )
)
)
. build ()
Tillfällig konfiguration
Ändra klientkonfiguration tillfälligt:
val customClient = client. withOptions {
it. baseUrl ( "https://example.com" )
it. maxRetries ( 5 )
}
Ktor-integration
Integrera med Ktor-serverapplikationer:
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))
}
}
}
}
Resurser
Support
Behöver du hjälp med Kotlin SDK?
Bidra
Vi välkomnar bidrag! Kontrollera bidragsriktlinjerna för att komma igång.