### Create a Product (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Creates a new product with details such as name, description, pricing (recurring with currency and frequency), and tax category. The example shows how to build the `ProductCreateParams` object and handle potential `UnauthorizedException` and other `DodoPaymentsException` types. ```kotlin 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) .licenseKeyEnabled(false) .build() try { val product: Product = client.products().create(createParams) println("Created product ID: ${product.productId()}") println("Product name: ${product.name()}") println("Is recurring: ${product.isRecurring()}") } catch (e: UnauthorizedException) { println("Authentication failed: ${e.message}") } ``` -------------------------------- ### Configure Dodo Payments Client Manually (Kotlin) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md This example demonstrates manual configuration of the Dodo Payments client using a builder pattern. You can set the bearer token and build the client instance. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .bearerToken("My Bearer Token") .build() ``` -------------------------------- ### Install Dodo Payments Kotlin SDK with Maven Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md This snippet demonstrates how to include the Dodo Payments Kotlin SDK in your Maven project. Ensure you use the correct version. ```xml com.dodopayments.api dodo-payments-kotlin 1.53.4 ``` -------------------------------- ### Create Checkout Session with Dodo Payments Kotlin SDK Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md This example illustrates how to initialize the Dodo Payments client from environment variables or system properties and then use it to create a checkout session. It requires importing necessary classes and constructing a `CheckoutSessionRequest`. ```kotlin 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.CheckoutSessionResponse // Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties // Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() val params: CheckoutSessionRequest = CheckoutSessionRequest.builder() .addProductCart(CheckoutSessionRequest.ProductCart.builder() .productId("product_id") .quantity(0) .build()) .build() val checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params) ``` -------------------------------- ### Initialize Async DodoPaymentsClient from Environment Variables (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Initializes an asynchronous DodoPaymentsClient using environment variables. This client is designed for non-blocking, coroutine-based API interactions. The example demonstrates fetching customer data asynchronously. ```kotlin 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()}") } ``` -------------------------------- ### Install Dodo Payments Kotlin SDK with Gradle Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md This snippet shows how to add the Dodo Payments Kotlin SDK to your project using Gradle. It requires a specific version number. ```kotlin implementation("com.dodopayments.api:dodo-payments-kotlin:1.53.4") ``` -------------------------------- ### Initialize and Use Asynchronous Dodo Payments Client in Kotlin Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Illustrates the initialization and usage of an asynchronous DodoPayments client from the start in Kotlin. It details how to configure the client using environment variables or system properties and then perform asynchronous operations like creating checkout sessions. This method is suitable when the entire client interaction is intended to be asynchronous. ```kotlin import com.dodopayments.api.client.DodoPaymentsClientAsync import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync import com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse // Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties // Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables val client: DodoPaymentsClientAsync = DodoPaymentsOkHttpClientAsync.fromEnv() val params: CheckoutSessionRequest = CheckoutSessionRequest.builder() .addProductCart(CheckoutSessionRequest.ProductCart.builder() .productId("product_id") .quantity(0) .build()) .build() val checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params) ``` -------------------------------- ### Handling Binary Responses Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Retrieve API responses as binary data, suitable for non-JSON content. Includes examples for saving to a file or transferring to an OutputStream. ```APIDOC ## Binary Responses The SDK provides methods to return binary responses for APIs that do not return JSON. ### Method ```kotlin client.invoices().payments().retrieve("payment_id") ``` ### Description This method retrieves a payment by its ID and returns an `HttpResponse` object, which can be used to access the raw binary response body. ### Response #### Success Response (200) - **body** (HttpResponse) - The raw binary response body. ### Request Example ```kotlin import com.dodopayments.api.core.http.HttpResponse import com.dodopayments.api.models.invoices.payments.PaymentRetrieveParams val payment: HttpResponse = client.invoices().payments().retrieve("payment_id") ``` ### Saving Binary Response to File #### Method ```kotlin client.invoices().payments().retrieve(params).use { ... } ``` #### Description Saves the binary response content directly to a file on the local filesystem. #### Request Example ```kotlin import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption client.invoices().payments().retrieve(params).use { Files.copy( it.body(), Paths.get(path), StandardCopyOption.REPLACE_EXISTING ) } ``` ### Transferring Binary Response to OutputStream #### Method ```kotlin client.invoices().payments().retrieve(params).use { ... } ``` #### Description Transfers the binary response content to a specified `OutputStream`. #### Request Example ```kotlin import java.nio.file.Files import java.nio.file.Paths client.invoices().payments().retrieve(params).use { it.body().transferTo(Files.newOutputStream(Paths.get(path))) } ``` ``` -------------------------------- ### Create a Checkout Session (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Creates a new checkout session by defining a request with product cart details. This example demonstrates constructing the `CheckoutSessionRequest` and `CheckoutSessionCreateParams` objects, then making the API call. It includes specific error handling for `BadRequestException` and general `DodoPaymentsException`. ```kotlin import com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse val sessionRequest = CheckoutSessionRequest.builder() .addProductCart( CheckoutSessionRequest.ProductCart.builder() .productId("prod_abc123") .quantity(2) .build() ) .addProductCart( CheckoutSessionRequest.ProductCart.builder() .productId("prod_xyz789") .quantity(1) .build() ) .build() val params = CheckoutSessionCreateParams.builder() .checkoutSessionRequest(sessionRequest) .build() try { val session: CheckoutSessionResponse = client.checkoutSessions().create(params) println("Checkout URL: ${session.url()}") println("Session ID: ${session.id()}") } catch (e: BadRequestException) { println("Invalid request: ${e.message}") } catch (e: DodoPaymentsException) { println("Payment error: ${e.message}") } ``` -------------------------------- ### Client Initialization Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to initialize the DodoPaymentsClient using environment variables or explicit credentials. ```APIDOC ## Client Initialization ### Initialize from environment variables ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient // Reads from DODO_PAYMENTS_API_KEY and DODO_PAYMENTS_BASE_URL env vars // Or from dodopayments.apiKey and dodopayments.baseUrl system properties val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() // Use the client val payments = client.payments().list() ``` ### Initialize with explicit credentials ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .bearerToken("your_api_token_here") .baseUrl("https://live.dodopayments.com") .maxRetries(3) .build() try { val products = client.products().list() println("Retrieved ${products.items().size} products") } catch (e: Exception) { println("Error: ${e.message}") } ``` ### Async client initialization ```kotlin 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()}") } ``` ``` -------------------------------- ### POST /products Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Creates a new product with specified details including name, description, pricing, and tax information. ```APIDOC ## POST /products ### Description Creates a new product with specified details including name, description, pricing, and tax information. ### Method POST ### Endpoint `/products` ### Parameters #### Request Body - **name** (string) - Required - The name of the product. - **description** (string) - Optional - A description of the product. - **price** (ProductCreateParams.RecurringPrice or ProductCreateParams.OneTimePrice) - Required - Pricing information for the product. - **currency** (Currency) - Required - The currency of the price (e.g., USD). - **preTaxAmount** (integer) - Required - The price before tax, in cents. - **paymentFrequencyInterval** (ProductCreateParams.RecurringPrice.TimeInterval) - Required for recurring prices - The interval for recurring payments (e.g., MONTH). - **paymentFrequencyCount** (integer) - Required for recurring prices - The number of intervals for recurring payments. - **taxCategory** (TaxCategory) - Optional - The tax category for the product (e.g., DIGITAL_GOODS). - **licenseKeyEnabled** (boolean) - Optional - Indicates if license keys are enabled for the product. ### Request Example ```json { "name": "Premium Subscription", "description": "Monthly subscription with all features", "price": { "currency": "USD", "preTaxAmount": 2999, "paymentFrequencyInterval": "MONTH", "paymentFrequencyCount": 1 }, "taxCategory": "DIGITAL_GOODS", "licenseKeyEnabled": false } ``` ### Response #### Success Response (200) - **productId** (string) - The unique identifier for the created product. - **name** (string) - The name of the product. - **isRecurring** (boolean) - Indicates if the product is a recurring subscription. #### Response Example ```json { "productId": "prod_new123", "name": "Premium Subscription", "isRecurring": true } ``` #### Error Handling - **UnauthorizedException**: Thrown if authentication fails. ``` -------------------------------- ### List and Paginate Products using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to list products with manual pagination and auto-pagination using sequences. It shows how to iterate through products and filter them. This requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.products.ProductListParams import com.dodopayments.api.models.products.ProductListPage // Manual pagination var page: ProductListPage = client.products().list() while (true) { for (product in page.items()) { println("${product.productId()}: ${product.name()} - ${product.price()}") } if (!page.hasNextPage()) { break } page = page.nextPage() } // Auto-pagination with sequence val allProducts = client.products().list() .autoPager() .take(100) .filter { it.isRecurring() } .forEach { product -> println("Recurring product: ${product.name()}") } ``` -------------------------------- ### Initialize DodoPaymentsClient from Environment Variables (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Initializes the DodoPaymentsClient using environment variables DODO_PAYMENTS_API_KEY and DODO_PAYMENTS_BASE_URL, or system properties. This client is used for synchronous API interactions. It leverages the OkHttp integration for efficient communication. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient // Reads from DODO_PAYMENTS_API_KEY and DODO_PAYMENTS_BASE_URL env vars // Or from dodopayments.apiKey and dodopayments.baseUrl system properties val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() // Use the client val payments = client.payments().list() ``` -------------------------------- ### Create a Customer using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to create a new customer using the Dodo Payments Kotlin SDK. It involves building `CustomerCreateParams` with customer details like email, name, and phone number. Requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.customers.Customer import com.dodopayments.api.models.customers.CustomerCreateParams val customerParams = CustomerCreateParams.builder() .email("customer@example.com") .name("John Doe") .phoneNumber("+1234567890") .build() val customer: Customer = client.customers().create(customerParams) println("Customer ID: ${customer.customerId()}") println("Email: ${customer.email()}") ``` -------------------------------- ### Configure Dodo Payments Client from Environment/System Properties (Kotlin) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md This code snippet shows how to configure the Dodo Payments client using `DodoPaymentsOkHttpClient.fromEnv()`. This method automatically reads API keys and base URLs from environment variables or system properties. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient // Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties // Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() ``` -------------------------------- ### Configure Dodo Payments Client with Mixed Approaches (Kotlin) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md This snippet shows how to configure the Dodo Payments client by combining environment/system property settings with manual overrides, such as setting a bearer token. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() // Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties // Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables .fromEnv() .bearerToken("My Bearer Token") .build() ``` -------------------------------- ### Manual Pagination with Synchronous Client (Kotlin) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Illustrates manual pagination using `items()`, `hasNextPage()`, and `nextPage()` methods. This approach allows for explicit control over fetching pages and iterating through items. ```kotlin import com.dodopayments.api.models.payments.PaymentListPage import com.dodopayments.api.models.payments.PaymentListResponse val page: PaymentListPage = client.payments().list() while (true) { for (payment in page.items()) { println(payment) } if (!page.hasNextPage()) { break } page = page.nextPage() } ``` -------------------------------- ### Checkout Session API - Parameter Handling Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Demonstrates how to set undocumented parameters (headers, query params, body properties) and documented parameters with special values using the CheckoutSessionCreateParams builder. ```APIDOC ## POST /checkout/sessions (Example) ### Description This endpoint allows for the creation of checkout sessions. It supports setting both documented and undocumented parameters, headers, query parameters, and body properties. Special handling is provided for undocumented fields and for setting documented fields to unsupported values using `JsonValue`. ### Method POST ### Endpoint `/checkout/sessions` ### Parameters #### Path Parameters None #### Query Parameters - **secret_query_param** (string) - Optional - An example of an undocumented query parameter. #### Request Body - **checkoutSessionRequest** (object) - Required - Details of the checkout session request. - **productCart** (object) - Required - Information about the products in the cart. - **productId** (string) - Required - The ID of the product. - **quantity** (number) - Required - The quantity of the product. - **secretProperty** (any) - Optional - An example of an undocumented body property. ### Request Example ```kotlin import com.dodopayments.api.core.JsonValue import com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest val params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder() .putAdditionalHeader("Secret-Header", "42") .putAdditionalQueryParam("secret_query_param", "42") .putAdditionalBodyProperty("secretProperty", JsonValue.from("42")) .checkoutSessionRequest(CheckoutSessionRequest.builder() .addProductCart(CheckoutSessionRequest.ProductCart.builder() .productId("product_id") .quantity(0) .build()) .build()) .build() // To omit a required parameter/property, use JsonMissing.of() // val paramsWithMissing: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder() // .productCart(JsonMissing.of()) // .build() val response = client.checkoutSessions().create(params) ``` ### Response #### Success Response (200) - **_additionalProperties** (map) - A map containing any undocumented properties returned in the response. #### Response Example ```json { "id": "cs_test_12345", "status": "open", "secretProperty": "42", "_additionalProperties": { "extra_info": "some value" } } ``` ### Error Handling - **IllegalStateException**: Thrown if a required parameter or property is unset (unless `JsonMissing.of()` is used). ``` -------------------------------- ### Enabling Logging with Environment Variable (Shell) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Demonstrates how to enable logging for the DodoPayments SDK by setting the `DODO_PAYMENTS_LOG` environment variable. This uses standard shell commands to set the variable to 'info' or 'debug' levels. ```sh $ export DODO_PAYMENTS_LOG=info ``` ```sh $ export DODO_PAYMENTS_LOG=debug ``` -------------------------------- ### POST /checkout-sessions Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Creates a new checkout session with specified product details. ```APIDOC ## POST /checkout-sessions ### Description Creates a new checkout session with specified product details. ### Method POST ### Endpoint `/checkout-sessions` ### Parameters #### Request Body - **checkoutSessionRequest** (CheckoutSessionRequest) - Required - The request object for creating a checkout session. - **productCarts** (List) - Required - A list of product carts for the session. - **productId** (string) - Required - The ID of the product. - **quantity** (integer) - Required - The quantity of the product. ### Request Example ```json { "checkoutSessionRequest": { "productCarts": [ { "productId": "prod_abc123", "quantity": 2 }, { "productId": "prod_xyz789", "quantity": 1 } ] } } ``` ### Response #### Success Response (200) - **url** (string) - The URL for the checkout session. - **id** (string) - The unique identifier for the checkout session. #### Response Example ```json { "url": "https://checkout.dodopayments.com/session_abc123", "id": "session_abc123" } ``` #### Error Handling - **BadRequestException**: Thrown for invalid requests. - **DodoPaymentsException**: Thrown for general payment errors. ``` -------------------------------- ### Initialize DodoPaymentsClient with Explicit Credentials (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Initializes the DodoPaymentsClient with explicit API token, base URL, and retry count. This allows for customized client configuration for synchronous API calls. Error handling for potential exceptions is demonstrated. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .bearerToken("your_api_token_here") .baseUrl("https://live.dodopayments.com") .maxRetries(3) .build() try { val products = client.products().list() println("Retrieved ${products.items().size} products") } catch (e: Exception) { println("Error: ${e.message}") } ``` -------------------------------- ### Configure DodoPayments Client for Test Environment Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Switches the DodoPayments client to send requests to a testing environment instead of the live production environment. This is crucial for development and integration testing without affecting live data. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .fromEnv() .testMode() .build() ``` -------------------------------- ### Generate Customer Portal Session using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Illustrates how to create a customer portal session. This involves using `CustomerPortalCreateParams` to specify the customer ID and then obtaining a session URL. Requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.customers.customerportal.CustomerPortalCreateParams import com.dodopayments.api.models.customers.CustomerPortalSession val portalParams = CustomerPortalCreateParams.builder() .customerId("cust_123") .build() val portalSession: CustomerPortalSession = client.customers() .customerPortal() .create(portalParams) println("Customer portal URL: ${portalSession.url()}") ``` -------------------------------- ### Update Product Files for Digital Delivery using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Shows how to update files associated with a product for digital delivery. This involves building `ProductUpdateFilesParams` and handling potential `NotFoundException`. Requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.products.ProductUpdateFilesParams import com.dodopayments.api.models.products.ProductUpdateFilesResponse val updateFilesParams = ProductUpdateFilesParams.builder() .id("prod_abc123") .addFileId("file_12345") .addFileId("file_67890") .build() try { val response: ProductUpdateFilesResponse = client.products() .updateFiles("prod_abc123", updateFilesParams) println("Updated files for product") } catch (e: NotFoundException) { println("Product not found") } ``` -------------------------------- ### Retrieve Invoice Payment as Binary (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Retrieves an invoice payment as a binary file (e.g., PDF) and saves it to a local path. It requires the DodoPayments client and handles 'NotFoundException' for missing invoices or payments. The response body is streamed directly to a file. ```kotlin import com.dodopayments.api.core.http.HttpResponse import com.dodopayments.api.models.invoices.payments.PaymentRetrieveParams import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption val retrieveParams = PaymentRetrieveParams.builder() .invoiceId("inv_123") .paymentId("pay_456") .build() try { client.invoices().payments().retrieve("pay_456", retrieveParams).use { response: HttpResponse -> Files.copy( response.body(), Paths.get("/tmp/invoice_payment.pdf"), StandardCopyOption.REPLACE_EXISTING ) println("Invoice saved successfully") } } catch (e: NotFoundException) { println("Invoice or payment not found") } ``` -------------------------------- ### Create Dodo Payments Checkout Session Asynchronously with Kotlin Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Shows how to create a checkout session asynchronously using the Dodo Payments Kotlin SDK. It covers initializing an asynchronous client from environment variables or system properties, constructing the request parameters, and handling the asynchronous response. This is ideal for non-blocking API calls. ```kotlin 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.CheckoutSessionResponse // Configures using the `dodopayments.apiKey` and `dodopayments.baseUrl` system properties // Or configures using the `DODO_PAYMENTS_API_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() val params: CheckoutSessionRequest = CheckoutSessionRequest.builder() .addProductCart(CheckoutSessionRequest.ProductCart.builder() .productId("product_id") .quantity(0) .build()) .build() val checkoutSessionResponse: CheckoutSessionResponse = client.async().checkoutSessions().create(params) ``` -------------------------------- ### Configure Proxy Settings in Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Illustrates how to configure the Dodo Payments client to use an HTTP proxy. This is done by providing a `java.net.Proxy` object to the `DodoPaymentsOkHttpClient.builder()`. ```kotlin import java.net.InetSocketAddress import java.net.Proxy val client = DodoPaymentsOkHttpClient.builder() .fromEnv() .proxy( Proxy( Proxy.Type.HTTP, InetSocketAddress("proxy.example.com", 8080) ) ) .build() ``` -------------------------------- ### Configure Proxy for DodoPayments Client Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Routes all SDK requests through a specified proxy server. This is essential for network environments that require traffic to be funneled through a proxy, such as corporate networks. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient import java.net.InetSocketAddress import java.net.Proxy val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .fromEnv() .proxy(Proxy( Proxy.Type.HTTP, InetSocketAddress( "https://example.com", 8080 ) )) .build() ``` -------------------------------- ### Auto-pagination with Synchronous Client (Kotlin) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Demonstrates how to iterate through all results across multiple pages using the `autoPager()` method with the synchronous client. This method returns a Sequence for easy processing of paginated data. ```kotlin import com.dodopayments.api.models.payments.PaymentListPage val page: PaymentListPage = client.payments().list() page.autoPager() .take(50) .forEach { payment -> println(payment) } ``` -------------------------------- ### List Payments with Filtering using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to list payments with filtering options, such as by customer ID and limit. It uses `PaymentListParams` to specify criteria and iterates through the results, displaying payment details. Requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.payments.PaymentListParams import com.dodopayments.api.models.payments.PaymentListPage import com.dodopayments.api.models.payments.PaymentListResponse val paymentParams = PaymentListParams.builder() .customerId("cust_123") .limit(25) .build() val paymentsPage: PaymentListPage = client.payments().list(paymentParams) for (payment: PaymentListResponse in paymentsPage.items()) { println("Payment ID: ${payment.paymentId()}") println("Amount: ${payment.totalAmount()} ${payment.currency()}") println("Status: ${payment.status()}") println("Customer: ${payment.customer().email()}") println("Created: ${payment.createdAt()}") payment.subscriptionId()?.let { println("Linked to subscription: $it") } } ``` -------------------------------- ### Create Discount (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Creates a new discount with a specified code, type, amount, and duration. It returns the created discount object, including its ID. This function requires the DodoPayments client. ```kotlin import com.dodopayments.api.models.discounts.Discount import com.dodopayments.api.models.discounts.DiscountCreateParams import com.dodopayments.api.models.discounts.DiscountType val discountParams = DiscountCreateParams.builder() .code("SUMMER2024") .type(DiscountType.PERCENTAGE) .amount(2500) // 25% .durationInMonths(3) .build() val discount: Discount = client.discounts().create(discountParams) println("Created discount code: ${discount.code()}") println("Discount ID: ${discount.discountId()}") ``` -------------------------------- ### Enable Test Mode in Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to configure the Dodo Payments client for test mode using the `.testMode()` builder method. This is useful for making API calls against test environments without affecting live data. ```kotlin val testClient = DodoPaymentsOkHttpClient.builder() .bearerToken("test_api_key") .testMode() .build() // All operations now use test mode endpoint val testProduct = testClient.products().create(createParams) ``` -------------------------------- ### Modify Client Configuration Temporarily with Kotlin Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Demonstrates how to temporarily modify a DodoPayments client's configuration using the `withOptions` method. This approach reuses existing connection and thread pools without altering the original client instance. It's useful for making isolated, temporary configuration changes for specific operations. ```kotlin import com.dodopayments.api.client.DodoPaymentsClient val clientWithOptions: DodoPaymentsClient = client.withOptions { it.baseUrl("https://example.com") it.maxRetries(42) } ``` -------------------------------- ### Save Binary Response Content to File using Java NIO Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Shows how to save the content of an `HttpResponse` body to a file using Java's NIO `Files.copy()` method. This requires the `java.nio.file.Files` and `java.nio.file.Paths` classes. The response body is provided as an `InputStream`. The `StandardCopyOption.REPLACE_EXISTING` option is used to overwrite the file if it already exists. ```kotlin import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption client.invoices().payments().retrieve(params).use { Files.copy( it.body(), Paths.get(path), StandardCopyOption.REPLACE_EXISTING ) } ``` -------------------------------- ### Retrieve Customer with Pagination using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Shows how to retrieve a list of customers with pagination and filtering. It utilizes `CustomerListParams` and the `autoPager()` for efficient iteration. Requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.customers.CustomerListParams import com.dodopayments.api.models.customers.CustomerListPage val listParams = CustomerListParams.builder() .limit(50) .build() val customersPage: CustomerListPage = client.customers().list(listParams) customersPage.autoPager() .filter { it.email() != null } .forEach { customer -> println("${customer.customerId()}: ${customer.email()}") } ``` -------------------------------- ### Access Response Headers and Status Codes in Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to retrieve raw HTTP responses to access status codes and headers. This is useful for inspecting response metadata, such as rate limiting information, directly from the `HttpResponseFor` object. ```kotlin import com.dodopayments.api.core.http.HttpResponseFor import com.dodopayments.api.core.http.Headers val rawResponse: HttpResponseFor = client.products() .withRawResponse() .retrieve("prod_123") val statusCode: Int = rawResponse.statusCode() val headers: Headers = rawResponse.headers() val rateLimit = headers["X-RateLimit-Remaining"] println("Status: $statusCode") println("Rate limit remaining: $rateLimit") val product: Product = rawResponse.parse() println("Product: ${product.name()}") ``` -------------------------------- ### Activate License Key (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Activates a license key for a specific instance name. It returns details about the activation, including the instance ID and expiration date. This function requires the DodoPayments client and handles 'UnprocessableEntityException' for activation failures. ```kotlin 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}") } ``` -------------------------------- ### List Subscriptions with Filtering using Kotlin Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to list subscriptions, optionally filtering by customer ID. It uses `SubscriptionListParams` and `autoPager()` for iterating through subscriptions and displays key details. Requires the Dodo Payments API client. ```kotlin import com.dodopayments.api.models.subscriptions.Subscription import com.dodopayments.api.models.subscriptions.SubscriptionListParams val subscriptionParams = SubscriptionListParams.builder() .customerId("cust_123") .build() val subscriptions = client.subscriptions().list(subscriptionParams) subscriptions.autoPager().forEach { subscription: Subscription -> println("Subscription ${subscription.subscriptionId()}") println("Status: ${subscription.status()}") println("Next billing: ${subscription.nextBillingDate()}") println("Amount: ${subscription.recurringPreTaxAmount()} ${subscription.currency()}") if (subscription.cancelAtNextBillingDate()) { println("Will cancel at: ${subscription.nextBillingDate()}") } } ``` -------------------------------- ### Auto-pagination with Asynchronous Client (Kotlin) Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Shows how to use the `autoPager()` method with the asynchronous client to process paginated results. This method returns a Flow, suitable for non-blocking operations. ```kotlin import com.dodopayments.api.models.payments.PaymentListPageAsync val page: PaymentListPageAsync = client.async().payments().list() page.autoPager() .take(50) .forEach { payment -> println(payment) } ``` -------------------------------- ### List Active Discounts (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Retrieves a list of all currently active discounts. It allows iterating through the discounts and printing their details. This function requires the DodoPayments client. ```kotlin import com.dodopayments.api.models.discounts.DiscountListParams val discounts = client.discounts().list() discounts.autoPager().forEach { discount -> println("Code: ${discount.code()}") println("Type: ${discount.type()}") println("Amount: ${discount.amount()}") } ``` -------------------------------- ### DodoPayments Kotlin Core - JsonValue Handling Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Illustrates the creation and usage of `JsonValue` objects for representing primitive, array, and object JSON types within the DodoPayments Kotlin SDK. ```APIDOC ## JsonValue Creation and Usage ### Description The `JsonValue` class in the DodoPayments Kotlin SDK allows for the programmatic creation of JSON values, including primitives, arrays, objects, and nested structures. This is essential for passing complex or non-standard data to API parameters. ### Method N/A (Utility Class) ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin import com.dodopayments.api.core.JsonValue // Create primitive JSON values val nullValue: JsonValue = JsonValue.from(null) val booleanValue: JsonValue = JsonValue.from(true) val numberValue: JsonValue = JsonValue.from(42) val stringValue: JsonValue = JsonValue.from("Hello World!") // Create a JSON array value equivalent to `["Hello", "World"]` val arrayValue: JsonValue = JsonValue.from(listOf( "Hello", "World" )) // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` val objectValue: JsonValue = JsonValue.from(mapOf( "a" to 1, "b" to 2 )) // Create an arbitrarily nested JSON equivalent to: // { // "a": [1, 2], // "b": [3, 4] // } val complexValue: JsonValue = JsonValue.from(mapOf( "a" to listOf( 1, 2 ), "b" to listOf( 3, 4 ) )) // These JsonValue objects can be used when setting parameters, e.g.: // val params = CheckoutSessionCreateParams.builder() // .putAdditionalBodyProperty("complexData", complexValue) // .build() ``` ### Response N/A ``` -------------------------------- ### Create Meter (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Creates a new meter for tracking usage-based billing. It requires a name, aggregation type, and measurement unit. The function returns the created meter object, including its ID. This requires the DodoPayments client. ```kotlin import com.dodopayments.api.models.meters.Meter import com.dodopayments.api.models.meters.MeterCreateParams import com.dodopayments.api.models.meters.MeterAggregation val meterParams = MeterCreateParams.builder() .name("API Requests") .aggregation(MeterAggregation.COUNT) .measurementUnit("requests") .build() val meter: Meter = client.meters().create(meterParams) println("Created meter: ${meter.meterId()}") ``` -------------------------------- ### Handle Specific Error Types (Kotlin) Source: https://context7.com/dodopayments/dodopayments-kotlin/llms.txt Demonstrates how to handle various DodoPayments exceptions, including 'NotFoundException', 'UnauthorizedException', 'RateLimitException', 'InternalServerException', 'DodoPaymentsIoException', and the general 'DodoPaymentsException'. This helps in gracefully managing API errors. ```kotlin import com.dodopayments.api.errors.* try { val product = client.products().retrieve("invalid_id") } catch (e: NotFoundException) { println("Product not found (404): ${e.message}") } catch (e: UnauthorizedException) { println("Authentication failed (401): ${e.message}") } catch (e: RateLimitException) { println("Rate limit exceeded (429): ${e.message}") println("Retry after: ${e.headers()["Retry-After"]}") } catch (e: InternalServerException) { println("Server error (5xx): ${e.statusCode()}") } catch (e: DodoPaymentsIoException) { println("Network error: ${e.message}") } catch (e: DodoPaymentsException) { println("General error: ${e.message}") } ``` -------------------------------- ### Transfer Binary Response Content to OutputStream Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Illustrates how to transfer the content of an `HttpResponse` body directly to an `OutputStream` using `Files.newOutputStream()`. This method is efficient for streaming data without necessarily loading the entire content into memory. It utilizes the `transferTo` method on the `InputStream` obtained from `it.body()`. ```kotlin import java.nio.file.Files import java.nio.file.Paths client.invoices().payments().retrieve(params).use { it.body().transferTo(Files.newOutputStream(Paths.get(path))) } ``` -------------------------------- ### DodoPayments Kotlin Core - Response Property Access Source: https://github.com/dodopayments/dodopayments-kotlin/blob/main/README.md Explains how to access both documented and undocumented properties from API responses using `_additionalProperties()` and `_` prefixed methods for raw JSON field access. ```APIDOC ## Accessing Response Properties ### Description This documentation covers how to access data from API responses, including retrieving undocumented properties via `_additionalProperties()` and accessing raw JSON field values using `_` prefixed methods, which offer methods like `asString()`, `asNumber()`, `asUnknown()`, and `isMissing()`. ### Method N/A (Client Method Return Value) ### Endpoint N/A (Applies to responses from any endpoint) ### Parameters N/A ### Request Example ```kotlin import com.dodopayments.api.core.JsonBoolean import com.dodopayments.api.core.JsonField import com.dodopayments.api.core.JsonNull import com.dodopayments.api.core.JsonNumber import com.dodopayments.api.core.JsonValue // Assuming 'client' is an initialized DodoPayments client instance // val params = CheckoutSessionCreateParams.builder()...build() // val response = client.checkoutSessions().create(params) // Accessing undocumented properties // val additionalProperties: Map = response._additionalProperties() // val secretPropertyValue: JsonValue? = additionalProperties.get("secretProperty") // Example of type checking for a JsonValue // val result = when (secretPropertyValue) { // is JsonNull -> "It's null!" // is JsonBoolean -> "It's a boolean!" // is JsonNumber -> "It's a number!" // // Other types include `JsonMissing`, `JsonString`, `JsonArray`, and `JsonObject` // else -> "It's something else!" // } // Accessing a property's raw JSON value // val field: JsonField = response._field() // Replace _field() with the actual field name prefixed by underscore // if (field.isMissing()) { // // The property is absent from the JSON response // } else if (field.isNull()) { // // The property was set to literal null // } else { // // Check if value was provided as a string // val jsonString: String? = field.asString(); // // Try to deserialize into a custom type (if applicable) // // val myObject: MyClass = field.asUnknown()!!.convert(MyClass::class.java) // } ``` ### Response #### Success Response - **_additionalProperties** (Map) - A map containing key-value pairs of any undocumented properties returned in the response. - **_field** (JsonField) - Represents a specific field from the response, allowing access to its raw value and type information. #### Response Example ```json { "someField": "someValue", "anotherField": 123, "_additionalProperties": { "undocumentedField1": "abc", "undocumentedField2": true } } ``` ```