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.
SDK Kotlin cung cấp quyền truy cập thuận tiện vào API REST Dodo Payments từ các ứng dụng viết bằng Kotlin. Nó có các giá trị có thể null, Sequence, các hàm suspend và các tính năng đặc trưng khác của Kotlin để sử dụng một cách dễ dàng.
Cài đặt
Gradle (Kotlin DSL)
Thêm phụ thuộc vào build.gradle.kts:
implementation ( "com.dodopayments.api:dodo-payments-kotlin:1.97.1" )
Maven
Thêm phụ thuộc vào pom.xml:
< dependency >
< groupId > com.dodopayments.api </ groupId >
< artifactId > dodo-payments-kotlin </ artifactId >
< version > 1.97.1 </ version >
</ dependency >
Luôn sử dụng phiên bản SDK mới nhất để truy cập các tính năng mới nhất của Dodo Payments. Kiểm tra Maven Central để biết phiên bản mới nhất.
SDK yêu cầu Java 8 trở lên và tương thích với cả nền tảng JVM và Android.
Bắt đầu nhanh
Khởi tạo client và tạo một phiên giao dịch thanh toán:
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 ())
Luôn lưu trữ khóa API một cách an toàn bằng cách sử dụng biến môi trường hoặc cấu hình được mã hóa. Tuyệt đối không cam kết chúng vào hệ thống kiểm soát phiên bản.
Tính năng chính
Coroutines Hỗ trợ đầy đủ cho coroutine Kotlin cho các tác vụ bất đồng bộ
Null Safety Tận dụng tính an toàn null của Kotlin để xử lý lỗi mạnh mẽ
Extension Functions Các phần mở rộng Kotlin đúng chuẩn để tăng cường tính năng
Data Classes Các lớp dữ liệu kiểu an toàn với hỗ trợ sao chép và giải cấu trúc
Cấu hình
Từ biến môi trường
Khởi tạo từ biến môi trường hoặc thuộc tính hệ thống:
val client: DodoPaymentsClient = DodoPaymentsOkHttpClient. fromEnv ()
Cấu hình thủ công
Cấu hình thủ công với tất cả các tùy chọn:
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 ()
Chế độ thử nghiệm
Cấu hình cho môi trường thử nghiệm/sandbox:
val testClient = DodoPaymentsOkHttpClient. builder ()
. fromEnv ()
. testMode ()
. build ()
Thời gian chờ và thử lại
Cấu hình toàn cục hoặc theo yêu cầu:
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 ()
)
Các hoạt động thông thường
Tạo một phiên giao dịch thanh toán
Tạo một phiên giao dịch thanh toán:
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. url () } " )
Tạo một sản phẩm
Tạo sản phẩm với cấu hình chi tiết:
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 () } " )
Kích hoạt khóa bản quyền
Kích hoạt các khóa bản quyền cho khách hàng:
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 } " )
}
Xử Lý Đăng Ký
Tạo và quản lý đăng ký định kỳ:
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.SubscriptionCreateParams
// Create a subscription
val 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 )
. build ()
val subscription = client. subscriptions (). create (subscriptionParams)
println ( "Subscription ID: ${ subscription. subscriptionId () } " )
// Charge an on-demand subscription
// productPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
val chargeParams = SubscriptionChargeParams. builder ()
. subscriptionId (subscription. subscriptionId ())
. productPrice ( 2500 )
. build ()
val chargeResponse = client. subscriptions (). charge (chargeParams)
println ( "Payment ID: ${ chargeResponse. paymentId () } " )
billing yêu cầu ít nhất mã ISO hai chữ cái country. Dùng AttachExistingCustomer để đính kèm khách hàng hiện có, hoặc NewCustomer để tạo một khách hàng mới. productPrice thể hiện ở đơn vị nhỏ nhất của tiền tệ.
Thanh Toán Dựa Trên Sử Dụng
Ghi Lại Sự Kiện Sử Dụng
Theo dõi sử dụng cho meters:
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" )
Hoạt Động Bất Đồng Bộ
Async Client
Sử dụng async client cho các hoạt động dựa trên coroutine:
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 () } " )
}
Xử Lý Lỗi
Xử lý lỗi với quản lý ngoại lệ của 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 } " )
}
Xử Lý Lỗi Chức Năng
Sử dụng Result để xử lý lỗi chức năng:
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 } " ) }
Sử dụng Kotlin’s runCatching cho cách tiếp cận chức năng hơn đến xử lý lỗi với các kiểu Result.
Tích Hợp Android
Sử dụng với ứng dụng Android:
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)
}
}
}
}
Xác Thực Phản Hồi
Kích hoạt xác thực phản hồi:
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 ()
Tính Năng Nâng Cao
Cấu Hình Proxy
Cấu hình cài đặt proxy:
import java.net.InetSocketAddress
import java.net.Proxy
val client = DodoPaymentsOkHttpClient. builder ()
. fromEnv ()
. proxy (
Proxy (
Proxy.Type.HTTP,
InetSocketAddress ( "proxy.example.com" , 8080 )
)
)
. build ()
Cấu Hình Tạm Thời
Thay đổi cấu hình client tạm thời:
val customClient = client. withOptions {
it. baseUrl ( "https://example.com" )
it. maxRetries ( 5 )
}
Tích Hợp Ktor
Tích hợp với ứng dụng server Ktor:
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))
}
}
}
}
Tài Nguyên
GitHub Repository Xem mã nguồn và đóng góp
API Reference Hoàn thành tài liệu API
Discord Community Nhận trợ giúp và kết nối với nhà phát triển
Report Issues Báo cáo lỗi hoặc yêu cầu tính năng
Hỗ Trợ
Cần trợ giúp với Kotlin SDK?
Đóng Góp
Chúng tôi hoan nghênh đóng góp! Kiểm tra hướng dẫn đóng góp để bắt đầu.