### Request Methods Examples Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Examples of creating different types of requests (GET, POST with form body, POST with JSON body) using `Request.builder()`. ```APIDOC ## Request Methods ```java Request getRequest = Request.builder() .method("GET") .url("https://acme.chargebee.com/api/v2/customers") .build(); Request postRequest = Request.builder() .method("POST") .url("https://acme.chargebee.com/api/v2/customers") .formBody(Map.of("email", "john@example.com")) .build(); Request jsonRequest = Request.builder() .method("POST") .url("https://acme.chargebee.com/api/v2/customers") .jsonBody("{\"email\": \"john@example.com\"}") .build(); ``` ``` -------------------------------- ### Request Method Usage Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/01-client-initialization.md Provides examples of how to use both synchronous and asynchronous HTTP methods on the ChargebeeClient. ```APIDOC ## Usage Example ### Description This section demonstrates how to invoke the synchronous and asynchronous request methods. ### Synchronous Request Example ```java // Synchronous request Response response = client.get("/customers", queryParams); ``` ### Asynchronous Request Example ```java // Asynchronous request CompletableFuture future = client.getAsync("/customers", queryParams); future.thenAccept(response -> { if (response.isSuccessful()) { System.out.println(response.getBodyAsString()); } }); ``` ``` -------------------------------- ### Complex Request Configuration Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/02-request-options.md This example demonstrates setting up a Chargebee client with advanced request options, including idempotency, custom network retries, timeouts, and trace IDs, before creating a customer. ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.client.request.RequestOptions; import com.chargebee.v4.models.customer.params.CustomerCreateParams; import com.chargebee.v4.models.customer.responses.CustomerCreateResponse; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); // Create request options with idempotency and custom retry RequestOptions opts = RequestOptions.builder() .idempotencyKey("cust-" + System.currentTimeMillis()) .maxNetworkRetries(3) .timeout(20000, 60000) // connect: 20s, read: 60s .header("X-Trace-ID", "trace-123") .build(); // Apply options to service and create customer CustomerCreateResponse response = client.customers() .withOptions(opts) .create( CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .build() ); System.out.println("Created customer: " + response.getCustomer().getId()); ``` -------------------------------- ### Create Customer with Request-Response Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/07-request-response-models.md This snippet shows a complete example of creating a customer using the Chargebee Java SDK. It includes building the request parameters with nested objects and custom fields, executing the request, and accessing data from the customer response object. ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.models.customer.params.CustomerCreateParams; import com.chargebee.v4.models.customer.responses.CustomerCreateResponse; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); // Create request parameters CustomerCreateParams params = CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .phone("+1-555-1234") .company("Acme Corp") // Nested address .billingAddress( CustomerCreateParams.BillingAddressParams.builder() .line1("123 Main St") .city("San Francisco") .state("CA") .zip("94105") .country("US") .build() ) // Custom fields .customField("cf_plan_tier", "gold") // Metadata .metaData(Map.of( "source", "integration", "integration_id", "123" )) .build(); // Execute request try { CustomerCreateResponse response = client.customers().create(params); // Access response data Customer customer = response.getCustomer(); System.out.println("Created customer: " + customer.getId()); System.out.println("Email: " + customer.getEmail()); System.out.println("Status: " + customer.getStatus()); // Access nested fields Address address = customer.getBillingAddress(); if (address != null) { System.out.println("Address: " + address.getLine1() + ", " + address.getCity()); } } catch (InvalidRequestException e) { System.err.println("Validation error: " + e.getMessage()); } catch (ChargebeeException e) { System.err.println("Error: " + e.getMessage()); } ``` -------------------------------- ### Create GET and POST Requests Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Demonstrates building `Request` objects for GET and POST methods. The POST requests show how to include form data or a JSON body. ```java Request getRequest = Request.builder() .method("GET") .url("https://acme.chargebee.com/api/v2/customers") .build(); Request postRequest = Request.builder() .method("POST") .url("https://acme.chargebee.com/api/v2/customers") .formBody(Map.of("email", "john@example.com")) .build(); Request jsonRequest = Request.builder() .method("POST") .url("https://acme.chargebee.com/api/v2/customers") .jsonBody("{\"email\": \"john@example.com\"}") .build(); ``` -------------------------------- ### Initialize Chargebee Client Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/10-quick-reference.md Shows how to create an instance of the ChargebeeClient with basic authentication. Includes examples for configuring retries and timeouts. ```java // Create client ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); ``` ```java // With retries ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .retry(RetryConfig.builder() .enabled(true) .maxRetries(3) .baseDelayMs(500) .build()) .build(); ``` ```java // With timeout ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .timeout(30000, 80000) // connect, read in ms .build(); ``` -------------------------------- ### Chargebee API Request Usage Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/01-client-initialization.md Demonstrates how to make both synchronous and asynchronous GET requests to the Chargebee API using the client. Handles successful responses for asynchronous calls. ```java // Synchronous request Response response = client.get("/customers", queryParams); // Asynchronous request CompletableFuture future = client.getAsync("/customers", queryParams); future.thenAccept(response -> { if (response.isSuccessful()) { System.out.println(response.getBodyAsString()); } }); ``` -------------------------------- ### Synchronous HTTP Methods (ChargebeeClient) Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Examples of making synchronous GET and POST requests using the `ChargebeeClient`, including options for query parameters, form data, and JSON bodies. ```APIDOC ## Synchronous Methods ```java // GET with query parameters Map> queryParams = Map.of( "limit", List.of("20"), "email[starts_with]", List.of("john@") ); Response response = client.get("/customers", queryParams); // GET without parameters Response response = client.get("/customers"); // POST with form data Map formData = Map.of( "email", "john@example.com", "first_name", "John" ); Response response = client.post("/customers", formData); // POST with JSON body String jsonBody = "{\"email\": \"john@example.com\"}"; Response response = client.postJson("/customers", jsonBody); ``` ``` -------------------------------- ### Example: Chargebee Client Initialization with Try-with-Resources Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/01-client-initialization.md Demonstrates initializing the Chargebee client using a builder and the try-with-resources statement for automatic resource management. Ensure API key and site name are provided. ```java try (ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build()) { CustomerService customers = client.customers(); // Use the client } // Automatically closed and resources released ``` -------------------------------- ### Create Customer Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/10-quick-reference.md Example of creating a new customer record using the CustomerService. Requires basic customer details. ```java CustomerCreateResponse response = client.customers().create( CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .build() ); String customerId = response.getCustomer().getId(); ``` -------------------------------- ### Complete Async Example: Create Customer and Subscription Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/08-async-operations.md Demonstrates chaining asynchronous operations to create a customer and then a subscription. Includes error handling for async operations and a mechanism to keep the application alive. ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.internal.RetryConfig; import java.util.concurrent.CompletableFuture; public class AsyncExample { public static void main(String[] args) { ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .retry(RetryConfig.builder() .enabled(true) .maxRetries(2) .build()) .build(); // Create customer and then subscription asynchronously CustomerCreateParams customerParams = CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .build(); client.customers() .createAsync(customerParams) .thenCompose(customerResponse -> { String customerId = customerResponse.getCustomer().getId(); System.out.println("Created customer: " + customerId); SubscriptionCreateParams subParams = SubscriptionCreateParams.builder() .customerId(customerId) .planId("plan-monthly") .build(); return client.subscriptions().createAsync(subParams); }) .thenAccept(subResponse -> { System.out.println("Created subscription: " + subResponse.getSubscription().getId()); }) .exceptionally(throwable -> { Throwable cause = throwable instanceof CompletionException ? throwable.getCause() : throwable; System.err.println("Error: " + cause.getMessage()); return null; }); // Keep the application alive for async operations Thread.sleep(5000); } } ``` -------------------------------- ### Asynchronous HTTP Methods (ChargebeeClient) Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Examples of making asynchronous GET and POST requests using the `ChargebeeClient`, returning `CompletableFuture` for non-blocking operations. ```APIDOC ## Asynchronous Methods ```java // GET async CompletableFuture future = client.getAsync("/customers"); future.thenAccept(response -> { System.out.println(response.getStatusCode()); }); // POST async CompletableFuture future = client.postAsync("/customers", formData); future.thenAccept(response -> { System.out.println(response.getStatusCode()); }); // JSON POST async CompletableFuture future = client.postJsonAsync("/customers", jsonBody); future.thenAccept(response -> { System.out.println(response.getStatusCode()); }); ``` ``` -------------------------------- ### ChargebeeClient Initialization Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/01-client-initialization.md Example of how to build and configure a ChargebeeClient instance with various options like API key, site name, timeouts, retry configuration, custom headers, and debug logging. ```APIDOC ## ChargebeeClient Initialization ### Description This section shows a complete example of how to initialize the `ChargebeeClient` with various configuration options. ### Code Example ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.internal.RetryConfig; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_xxxxxxxxxxx") .siteName("acme") // HTTP timeouts .timeout(30000, 80000) // connect: 30s, read: 80s // Retry configuration .retry( RetryConfig.builder() .enabled(true) .maxRetries(3) .baseDelayMs(500) .build() ) // Custom headers .header("X-Custom-Header", "value") // Enable debugging .debugLogging(true) // Build the client .build(); ``` ``` -------------------------------- ### Synchronous Retry Configuration Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/04-retry-configuration.md Configure retry behavior for the Chargebee client, including enabling retries, setting the maximum number of retries, and defining the base delay in milliseconds. This example demonstrates setting up a client with retry logic before making a customer creation call. ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.internal.RetryConfig; import com.chargebee.v4.models.customer.params.CustomerCreateParams; import com.chargebee.v4.models.customer.responses.CustomerCreateResponse; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .retry( RetryConfig.builder() .enabled(true) .maxRetries(3) .baseDelayMs(500) .build() ) .build(); try { CustomerCreateResponse response = client.customers().create( CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .build() ); System.out.println("Customer created: " + response.getCustomer().getId()); } catch (TimeoutException e) { // Retried 3 times with backoff, still failed System.err.println("Timeout after retries: " + e.getMessage()); } catch (NetworkException e) { System.err.println("Network error after retries: " + e.getMessage()); } ``` -------------------------------- ### ConfigurationException Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/03-exception-hierarchy.md Thrown when the SDK is configured incorrectly, such as missing API key or invalid URL. Catch this exception to handle configuration issues. ```java try { ChargebeeClient client = ChargebeeClient.builder() .apiKey("") // Missing! .siteName("acme") .build(); } catch (ConfigurationException e) { System.err.println("Configuration error: " + e.getMessage()); } ``` -------------------------------- ### Quick Reference Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/COMPLETION_SUMMARY.txt A quick reference guide covering initialization, service access, CRUD operations, filters, request options, error handling, and common patterns. ```APIDOC ## Quick Reference ### Description This section serves as a quick reference guide for the Chargebee Java SDK, summarizing key functionalities and common patterns. It includes snippets for client initialization, accessing services, performing CRUD operations, applying various filters, configuring per-request options, and handling errors. It also covers asynchronous operations, common patterns like pagination and retries, and debugging techniques. ### Key Areas Covered - **Initialization Snippets**: Code examples for setting up the `ChargebeeClient`. - **Service Access Quick List**: How to get instances of different services. - **CRUD Operations**: Common patterns for Create, Retrieve, Update, Delete, and List. - **Filters**: Quick reference for String, Number, Boolean, Timestamp, and Custom field filters. - **Per-Request Options**: How to set options like idempotency keys and timeouts for individual requests. - **Error Handling Patterns**: Common approaches to managing exceptions and API errors. - **Type-Safe Error Codes**: Using SDK-provided constants for error codes. - **Async Operations**: Basic usage and `CompletableFuture` patterns. - **Common Patterns**: Pagination, retry logic, bulk operations. - **Retry Configuration**: Summary of retry settings. - **Resource Cleanup**: Best practices for managing SDK resources. - **Accessing Response Data**: How to extract information from API responses. - **Custom Fields**: Working with custom data fields. - **Common Resource Operations**: Quick lookups for operations on core resources. - **Debugging Techniques**: Tips for troubleshooting issues. - **Dependencies**: Information on SDK dependencies. ``` -------------------------------- ### Synchronous GET Request without Parameters Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Executes a simple synchronous GET request to the `/customers` endpoint. Requires `client` to be initialized. ```java Response response = client.get("/customers"); ``` -------------------------------- ### Synchronous GET Request with Query Parameters Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Executes a synchronous GET request to retrieve customers, including query parameters for filtering and limiting results. Requires `client` to be initialized. ```java Map> queryParams = Map.of( "limit", List.of("20"), "email[starts_with]", List.of("john@") ); Response response = client.get("/customers", queryParams); ``` -------------------------------- ### Asynchronous GET Request Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Initiates an asynchronous GET request to the `/customers` endpoint. The response is handled via a `CompletableFuture`. ```java CompletableFuture future = client.getAsync("/customers"); future.thenAccept(response -> { System.out.println(response.getStatusCode()); }); ``` -------------------------------- ### Construct URL with Path and Query Parameters Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Make an API GET request by specifying the path and a map of query parameters. The SDK will construct the full URL. ```java String baseUrl = client.getBaseUrl(); // https://acme.chargebee.com/api/v2 // Method 1: Using path and query parameters Response response = client.get( "/customers", Map.of("limit", List.of("20"), "email[starts_with]", List.of("john@")) ); ``` -------------------------------- ### Implement a Logging Interceptor Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md This example demonstrates a LoggingInterceptor that logs request details and response status codes for both synchronous and asynchronous operations. ```java import com.chargebee.v4.client.request.RequestInterceptor; import com.chargebee.v4.client.request.RequestWrap; import com.chargebee.v4.transport.Response; public class LoggingInterceptor implements RequestInterceptor { @Override public Response handleRequest(RequestWrap wrap) throws ChargebeeException { Request request = wrap.getRequest(); long startTime = System.currentTimeMillis(); System.out.println("-> " + request.getMethod() + " " + request.getUrl()); Response response = wrap.proceed(); long duration = System.currentTimeMillis() - startTime; System.out.println("<- " + response.getStatusCode() + " (" + duration + "ms)"); return response; } @Override public CompletableFuture handleRequestAsync(RequestWrap wrap) { // Async version Request request = wrap.getRequest(); long startTime = System.currentTimeMillis(); System.out.println("-> " + request.getMethod() + " " + request.getUrl()); return wrap.proceedAsync().thenApply(response -> { long duration = System.currentTimeMillis() - startTime; System.out.println("<- " + response.getStatusCode() + " (" + duration + "ms)"); return response; }); } } ``` -------------------------------- ### Chargebee Java SDK Custom Transport Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md An example of a custom transport implementation using a preferred HTTP client. Ensure the response is built correctly from the HTTP client's result. ```java import com.chargebee.v4.transport.Transport; import com.chargebee.v4.transport.Request; import com.chargebee.v4.transport.Response; public class CustomTransport implements Transport { @Override public Response send(Request request) throws TransportException { // Use your preferred HTTP client (HttpUrlConnection, OkHttp, etc.) // Build the response from the HTTP client return response; } @Override public CompletableFuture sendAsync(Request request) { // Async variant return CompletableFuture.supplyAsync(() -> { try { return send(request); } catch (TransportException e) { throw new CompletionException(e); } }); } } ``` -------------------------------- ### Create Customer with Nested Billing Address and Payment Method Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/07-request-response-models.md Construct `CustomerCreateParams` including nested `BillingAddressParams` and `PaymentMethodParams` for detailed customer setup. ```java CustomerCreateParams params = CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") // Nested billing address .billingAddress( CustomerCreateParams.BillingAddressParams.builder() .line1("123 Main St") .line2("Apt 4") .city("San Francisco") .state("CA") .zip("94105") .country("US") .build() ) // Nested payment method .paymentMethod( CustomerCreateParams.PaymentMethodParams.builder() .type("card") .build() ) .build(); ``` -------------------------------- ### Construct Customer List Parameters Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/06-filters-and-list-operations.md Build comprehensive list parameters for customer queries, including pagination, sorting, and type-safe field filters. This example demonstrates filtering by email, first name, creation date, auto-collection status, and custom fields. ```java CustomerListParams params = CustomerListParams.builder() // Pagination .limit(10) .offset("offset-from-previous-response") // Sort .sort(CustomerListParams.SortOrder.ASCENDING) .sortOrder(CustomerListParams.SortOrder.DESCENDING) // Field filters (type-safe) .email().startsWith("john@") .firstName().contains("John") .createdAt().onOrAfter(timestamp) .autoCollection().is(true) .customField("cf_tier").stringFilter().in("gold", "platinum") .build(); CustomerListResponse response = client.customers().list(params); ``` -------------------------------- ### Custom Service Actions Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/05-services-overview.md Examples of custom actions available on services, such as adding promotional credits or pausing/resuming subscriptions. These follow a consistent synchronous and asynchronous pattern. ```java // CustomerService example CustomerAddPromotionalCreditsResponse response = client.customers().addPromotionalCredits(customerId, params); CustomerDeductPromotionalCreditsResponse response = client.customers().deductPromotionalCredits(customerId, params); // SubscriptionService example SubscriptionPauseResponse response = client.subscriptions().pause(subscriptionId, params); SubscriptionResumeResponse response = client.subscriptions().resume(subscriptionId, params); ``` ```java public ActionResponseType actionName(String id, ParamsType params) throws ChargebeeException public CompletableFuture actionNameAsync(String id, ParamsType params) ``` -------------------------------- ### Query Parameters in Java Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Query parameters are appended to the URL. This example demonstrates setting multiple query parameters, including a prefixed one. ```java Map> queryParams = new HashMap<>(); queryParams.put("limit", List.of("20")); queryParams.put("offset", List.of("offset-123")); queryParams.put("email[starts_with]", List.of("john@")); Response response = client.get("/customers", queryParams); // Generates: /customers?limit=20&offset=offset-123&email[starts_with]=john@ ``` -------------------------------- ### Install Chargebee Java SDK v3 Source: https://github.com/chargebee/chargebee-java/wiki/Migration-guide-for-V4 Use this Maven dependency for Chargebee Java SDK version 3.x.x. ```xml com.chargebee chargebee-java 3.0.0 ``` -------------------------------- ### Handling HTTP Responses Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/11-transport-and-http.md Examples demonstrating how to use the Response class methods to check the status of an HTTP request and access response data. ```APIDOC ## Handling HTTP Responses ### Description Illustrates common use cases for checking response status and accessing headers and body. ### Status Code Checks ```java Response response = client.get("/customers"); if (response.isSuccessful()) { // 2xx System.out.println(response.getBodyAsString()); } else if (response.isRedirect()) { // 3xx String location = response.getHeader("Location"); } else if (response.isError()) { // 4xx, 5xx System.err.println("Error: " + response.getStatusCode()); } ``` ### Header Access ```java Response response = client.post("/customers", formData); String contentType = response.getHeader("Content-Type"); String cacheControl = response.getHeader("Cache-Control"); // Get all headers Map headers = response.getHeaders(); headers.forEach((key, value) -> { System.out.println(key + ": " + value); }); ``` ### Response Body ```java Response response = client.get("/customers"); // As string String jsonBody = response.getBodyAsString(); // As bytes byte[] body = response.getBodyAsBytes(); // Parse with Gson // JsonObject obj = JsonUtil.parse(response.getBodyAsString()); ``` ``` -------------------------------- ### Complex Filter and Pagination Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/06-filters-and-list-operations.md Demonstrates advanced filtering with standard and custom fields, including date ranges, string matching, numerical comparisons, and boolean checks. Also shows how to paginate through results and reapply filters for subsequent pages. ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.models.customer.params.CustomerListParams; import com.chargebee.v4.models.customer.responses.CustomerListResponse; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); long oneMonthAgo = System.currentTimeMillis() / 1000 - (30 * 24 * 60 * 60); long sixMonthsAgo = System.currentTimeMillis() / 1000 - (180 * 24 * 60 * 60); // Find premium customers who registered in the last month CustomerListParams params = CustomerListParams.builder() // Standard fields .firstName().isNot("") // Has a name .email().endsWith("@company.com") // Company email .createdAt().between(sixMonthsAgo, oneMonthAgo) // Recent signups .autoCollection().is(true) // Auto-collect enabled // Custom fields .customField("cf_plan_type").stringFilter() .in("premium", "enterprise") .customField("cf_total_mrr").numberFilter() .gte(1000000) // At least $10,000 MRR .customField("cf_vip_status").booleanFilter() .is(true) // Pagination .limit(25) .build(); CustomerListResponse response = client.customers().list(params); for (Customer customer : response.getCustomers()) { System.out.println(customer.getEmail() + " (" + customer.getId() + ")"); } // Load additional pages if available while (response.hasMore()) { response = client.customers().list( CustomerListParams.builder() .limit(25) .offset(response.getNextOffset()) // Reapply the same filters .email().endsWith("@company.com") .createdAt().between(sixMonthsAgo, oneMonthAgo) .build() ); for (Customer customer : response.getCustomers()) { System.out.println(customer.getEmail() + " (" + customer.getId() + ")"); } } ``` -------------------------------- ### Configure Retry Settings in v3 SDK Source: https://github.com/chargebee/chargebee-java/wiki/Migration-guide-for-V4 Update the default retry configuration for the v3 SDK. Note: This example includes an import for RetryConfig from v4, which might be an oversight in the original documentation. ```java import com.chargebee.Environment; import com.chargebee.v4.internal.RetryConfig; Environment.configure("site", "key"); Environment.defaultConfig().updateRetryConfig( new RetryConfig(true, 3, 500, Set.of(500, 502)) ); ``` -------------------------------- ### Chargebee Java SDK Documentation Map Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/INDEX.md This markdown structure outlines the organization of the Chargebee Java SDK documentation, guiding users through various aspects of the SDK's functionality. ```markdown Documentation ├── README.md (START HERE) ├── 01-client-initialization.md │ └── How to create and configure the client ├── 02-request-options.md │ └── Per-request settings and headers ├── 03-exception-hierarchy.md │ └── All exception types and error handling ├── 04-retry-configuration.md │ └── Automatic retry logic and backoff ├── 05-services-overview.md │ └── Service API and CRUD operations ├── 06-filters-and-list-operations.md │ └── Type-safe filtering and pagination ├── 07-request-response-models.md │ └── Request builders and response objects ├── 08-async-operations.md │ └── CompletableFuture and non-blocking calls ├── 09-common-resources.md │ └── Detailed reference for all resources ├── 10-quick-reference.md │ └── Code snippets and patterns └── 11-transport-and-http.md └── Low-level HTTP and custom transport ``` -------------------------------- ### Create and List Customers (Synchronous) Source: https://github.com/chargebee/chargebee-java/blob/v4/README.md Demonstrates how to create a new customer and then list customers using synchronous API calls. Ensure necessary imports are included. ```java import com.chargebee.v4.services.CustomerService; import com.chargebee.v4.models.customer.params.CustomerCreateParams; import com.chargebee.v4.models.customer.params.CustomerListParams; import com.chargebee.v4.models.customer.responses.CustomerCreateResponse; import com.chargebee.v4.models.customer.responses.CustomerListResponse; CustomerService customers = client.customers(); CustomerCreateResponse created = customers.create( CustomerCreateParams.builder() .firstName("Ada") .lastName("Lovelace") .email("ada@example.com") .billingAddress( CustomerCreateParams.BillingAddressParams.builder() .line1("50 Market St") .city("San Francisco") .state("CA") .zip("94105") .country("US") .build() ) .build() ); CustomerListResponse list = customers.list( CustomerListParams.builder() .limit(10) .email().startsWith("ada@") .build() ); ``` -------------------------------- ### Client Initialization Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/10-quick-reference.md Demonstrates how to initialize the ChargebeeClient with basic configuration, retries, and timeouts. ```APIDOC ## Initialization ### Basic Initialization ```java // Create client ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); ``` ### Initialization with Retries ```java // With retries ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .retry(RetryConfig.builder() .enabled(true) .maxRetries(3) .baseDelayMs(500) .build()) .build(); ``` ### Initialization with Timeout ```java // With timeout ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .timeout(30000, 80000) // connect, read in ms .build(); ``` ``` -------------------------------- ### Block on Async Result using get() Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/08-async-operations.md Use `get()` to block until an asynchronous operation completes. It can throw `InterruptedException` or `ExecutionException`. ```java try { CustomerCreateResponse response = client.customers() .createAsync(params) .get(); // Blocks until complete System.out.println("Customer: " + response.getCustomer().getId()); } catch (InterruptedException e) { System.err.println("Operation interrupted: " + e.getMessage()); } catch (ExecutionException e) { // Unwrap to get the original exception Throwable cause = e.getCause(); handleException(cause); } ``` -------------------------------- ### Create a Plan Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/09-common-resources.md Define and create a new subscription plan with specified pricing and interval details. Prices should be in cents. ```java PlanCreateResponse response = client.plans().create( PlanCreateParams.builder() .id("plan-monthly") .name("Monthly Plan") .interval(1) .intervalUnit(PlanCreateParams.IntervalUnit.MONTH) .pricingModel(PlanCreateParams.PricingModel.FLAT_FEE) .price(9999) // Amount in cents ($99.99) .currencyCode("USD") .build() ); Plan plan = response.getPlan(); ``` -------------------------------- ### ClientErrorException Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/03-exception-hierarchy.md Thrown for HTTP 4xx client-side errors. This example shows how to check for common client errors like Unauthorized or Not Found. ```java try { CustomerCreateResponse response = client.customers().create(params); } catch (ClientErrorException e) { if (e.isUnauthorized()) { System.err.println("Invalid API key"); } else if (e.isNotFound()) { System.err.println("Resource not found"); } } ``` -------------------------------- ### TimeoutException Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/03-exception-hierarchy.md Thrown when HTTP requests exceed configured timeouts, either connect or read timeouts. This example shows setting a connect timeout. ```java try { // With 5s connect timeout ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .connectTimeout(5000) .build(); Response response = client.get("/customers"); } catch (TimeoutException e) { System.err.println("Request timed out: " + e.getMessage()); } ``` -------------------------------- ### Initialize Chargebee Client Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/README.md Create a Chargebee client instance with your API key and site name. Access services like customers through the client. ```java ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); CustomerService customers = client.customers(); CustomerCreateResponse response = customers.create( CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .build() ); ``` -------------------------------- ### Configure and Use Chargebee Services Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/05-services-overview.md Demonstrates how to initialize the ChargebeeClient and configure services with custom request options or direct headers. Use scoped services for requests requiring specific headers, idempotency keys, or retry settings. Unscoped services use default client configurations. ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.client.request.RequestOptions; import com.chargebee.v4.services.CustomerService; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); // Option 1: Create a scoped service with custom options RequestOptions opts = RequestOptions.builder() .header("X-Trace-ID", "trace-123") .idempotencyKey("customer-create-" + System.currentTimeMillis()) .maxNetworkRetries(2) .build(); CustomerService scoped = client.customers().withOptions(opts); // All subsequent calls use these options CustomerCreateResponse response = scoped.create(params); CustomerListResponse listResponse = scoped.list(listParams); // Option 2: Chain headers directly CustomerService scoped2 = client.customers() .header("X-Custom-1", "value1") .header("X-Custom-2", "value2"); // Option 3: Use service without options CustomerService unscoped = client.customers(); CustomerRetrieveResponse retrieve = unscoped.retrieve("customer-123"); ``` -------------------------------- ### Block on Async Result with Timeout using get() Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/08-async-operations.md Use `get(timeout, timeUnit)` to block for a specified duration. Throws `TimeoutException` if the operation doesn't complete in time. ```java try { CustomerCreateResponse response = client.customers() .createAsync(params) .get(10, TimeUnit.SECONDS); // Timeout after 10 seconds System.out.println("Customer: " + response.getCustomer().getId()); } catch (TimeoutException e) { System.err.println("Operation timed out"); } catch (ExecutionException e) { handleException(e.getCause()); } ``` -------------------------------- ### Configure Client in v3 SDK Source: https://github.com/chargebee/chargebee-java/wiki/Migration-guide-for-V4 Configure the global environment for the v3 SDK using your site name and API key. ```java import com.chargebee.Environment; Environment.configure("your-site", "your-api-key"); ``` -------------------------------- ### Client Initialization and Configuration Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/COMPLETION_SUMMARY.txt Details on how to initialize and configure the Chargebee Java SDK client, including builder options, custom headers, and retry configurations. ```APIDOC ## Client Initialization and Configuration ### Description This section covers the setup of the Chargebee Java SDK client. It details the various configuration options available, including builder patterns, per-request overrides, custom headers, idempotency keys, retry settings, timeout management, request interception, and custom transport mechanisms. ### Key Features: - 15+ builder options - Per-request overrides - Custom headers - Idempotency keys - Retry configuration - Timeout management - Request interception - Custom transport ``` -------------------------------- ### Complex Filter Example Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/06-filters-and-list-operations.md Provides a comprehensive example of constructing complex filter criteria, including standard and custom fields, for retrieving specific customer data. It also demonstrates how to handle pagination for subsequent pages. ```APIDOC ## Complex Filter Example ```java import com.chargebee.v4.client.ChargebeeClient; import com.chargebee.v4.models.customer.params.CustomerListParams; import com.chargebee.v4.models.customer.responses.CustomerListResponse; ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_...") .siteName("acme") .build(); long oneMonthAgo = System.currentTimeMillis() / 1000 - (30 * 24 * 60 * 60); long sixMonthsAgo = System.currentTimeMillis() / 1000 - (180 * 24 * 60 * 60); // Find premium customers who registered in the last month CustomerListParams params = CustomerListParams.builder() // Standard fields .firstName().isNot("") // Has a name .email().endsWith("@company.com") // Company email .createdAt().between(sixMonthsAgo, oneMonthAgo) // Recent signups .autoCollection().is(true) // Auto-collect enabled // Custom fields .customField("cf_plan_type").stringFilter() .in("premium", "enterprise") .customField("cf_total_mrr").numberFilter() .gte(1000000) // At least $10,000 MRR .customField("cf_vip_status").booleanFilter() .is(true) // Pagination .limit(25) .build(); CustomerListResponse response = client.customers().list(params); for (Customer customer : response.getCustomers()) { System.out.println(customer.getEmail() + " (" + customer.getId() + ")"); } // Load additional pages if available while (response.hasMore()) { response = client.customers().list( CustomerListParams.builder() .limit(25) .offset(response.getNextOffset()) // Reapply the same filters .email().endsWith("@company.com") .createdAt().between(sixMonthsAgo, oneMonthAgo) .build() ); for (Customer customer : response.getCustomers()) { System.out.println(customer.getEmail() + " (" + customer.getId() + ")"); } } ``` ``` -------------------------------- ### Initialize ChargebeeClient with Builder Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/01-client-initialization.md Use the builder pattern to create a ChargebeeClient instance. You can set the API key and site name directly or use the convenience method. ```java ChargebeeClient client = ChargebeeClient.builder() .apiKey("cb_test_xxxxxxxxxxx") .siteName("acme") .build(); ``` ```java ChargebeeClient client = ChargebeeClient.builder("cb_test_xxxxxxxxxxx", "acme") .build(); ``` -------------------------------- ### Delete Customer Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/10-quick-reference.md Example of deleting a customer record using their unique ID. ```java CustomerDeleteResponse response = client.customers() .delete("customer-123"); ``` -------------------------------- ### Access Coupon Service Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/09-common-resources.md Get an instance of the CouponService to interact with coupon-related operations. ```java CouponService coupons = client.coupons(); ``` -------------------------------- ### Access Plan Service Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/09-common-resources.md Get an instance of the PlanService for managing subscription plans. ```java PlanService plans = client.plans(); ``` -------------------------------- ### Create RequestOptions using Factory Methods Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/02-request-options.md Demonstrates creating RequestOptions using the empty() factory method or the builder() pattern. Use builder() for custom configurations. ```java RequestOptions opts = RequestOptions.empty(); RequestOptions opts = RequestOptions.builder() .header("X-Custom", "value") .maxNetworkRetries(2) .build(); ``` -------------------------------- ### Client Initialization Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/COMPLETION_SUMMARY.txt Details on how to initialize the ChargebeeClient, including builder patterns, configuration methods for essential, HTTP, retry, and header settings, as well as accessing services and making requests. ```APIDOC ## Client Initialization ### Description This section covers the initialization of the `ChargebeeClient` class. It details the use of the builder pattern for configuration, including essential settings, HTTP client configuration, retry mechanisms, and header management. It also explains how to access various services and make synchronous or asynchronous requests. ### Key Concepts - **ChargebeeClient**: The main entry point for interacting with the Chargebee API. - **Builder Pattern**: Used for configuring the client with various options. - **Configuration Methods**: Essential, HTTP, retry, header, and transport configurations. - **Service Access**: How to obtain instances of service classes (e.g., `CustomerService`, `SubscriptionService`). - **Request Methods**: Synchronous and asynchronous methods for making API calls. - **Validation and Cleanup**: Procedures for validating configurations and cleaning up resources. ``` -------------------------------- ### Invoice Resource Operations Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/09-common-resources.md Operations for managing invoices, including retrieving, listing, getting PDFs, and sending. ```APIDOC ## Invoice Resource Invoices represent billing documents sent to customers. ### Service Access ```java InvoiceService invoices = client.invoices(); ``` ### Common Operations #### Retrieve an Invoice ```java InvoiceRetrieveResponse response = client.invoices() .retrieve("invoice-123"); Invoice invoice = response.getInvoice(); System.out.println(invoice.getTotal()); System.out.println(invoice.getStatus()); System.out.println(invoice.getInvoiceDate()); ``` #### List Invoices ```java InvoiceListResponse response = client.invoices().list( InvoiceListParams.builder() .limit(20) .status().in("issued", "paid") .customerId().is("customer-123") .invoiceDate().onOrAfter(threeMonthsAgo) .build() ); for (Invoice invoice : response.getInvoices()) { System.out.println(invoice.getId() + ": $" + (invoice.getTotal() / 100.0)); } ``` #### Get Invoice PDF ```java InvoicePdfResponse response = client.invoices().pdf( "invoice-123", InvoicePdfParams.builder() .sppCode("SPP-CODE") // Optional .build() ); byte[] pdfData = response.getPdf(); // Save to file or send to customer ``` #### Send Invoice ```java InvoiceSendResponse response = client.invoices().send( "invoice-123", InvoiceSendParams.builder() .email("john@example.com") .build() ); ``` ``` -------------------------------- ### Create a Customer Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/09-common-resources.md Demonstrates how to create a new customer in Chargebee with various details including billing address and auto-collection settings. ```APIDOC ## Create a Customer ### Description This operation creates a new customer in your Chargebee account. You can specify details like name, email, phone, company, billing address, and auto-collection preferences. ### Method `client.customers().create(...) ### Parameters #### Request Body - **CustomerCreateParams** (object) - Required - Parameters for creating a customer. - **firstName** (string) - Required - The first name of the customer. - **lastName** (string) - Required - The last name of the customer. - **email** (string) - Required - The email address of the customer. - **phone** (string) - Optional - The phone number of the customer. - **company** (string) - Optional - The company name. - **locale** (string) - Optional - The locale for the customer. - **preferredCurrencyCode** (string) - Optional - The preferred currency code for the customer. - **billingAddress** (object) - Optional - Billing address details. - **line1** (string) - Required - Street address line 1. - **city** (string) - Required - City. - **state** (string) - Required - State or province. - **zip** (string) - Required - Zip or postal code. - **country** (string) - Required - Country code (ISO 3166-1 alpha-2). - **autoCollection** (boolean) - Optional - Whether to automatically collect payments. - **netTermDays** (integer) - Optional - Number of days for net terms. ### Response #### Success Response (200) - **customer** (object) - The created customer object. - **id** (string) - The unique identifier for the customer. ### Request Example ```java CustomerCreateResponse response = client.customers().create( CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .phone("+1-555-1234") .company("Acme Corp") .locale("en") .preferredCurrencyCode("USD") .billingAddress( CustomerCreateParams.BillingAddressParams.builder() .line1("123 Main St") .city("San Francisco") .state("CA") .zip("94105") .country("US") .build() ) .autoCollection(true) .netTermDays(30) .build() ); String customerId = response.getCustomer().getId(); ``` ``` -------------------------------- ### Customer CRUD Operations Source: https://github.com/chargebee/chargebee-java/blob/v4/_autodocs/10-quick-reference.md Provides examples for performing Create, Retrieve, Update, Delete, and List operations on customers. ```APIDOC ## CRUD Operations ### Create Customer ```java CustomerCreateResponse response = client.customers().create( CustomerCreateParams.builder() .firstName("John") .lastName("Doe") .email("john@example.com") .build() ); String customerId = response.getCustomer().getId(); ``` ### Retrieve Customer ```java CustomerRetrieveResponse response = client.customers() .retrieve("customer-123"); Customer customer = response.getCustomer(); ``` ### Update Customer ```java CustomerUpdateResponse response = client.customers().update( "customer-123", CustomerUpdateParams.builder() .firstName("Jane") .build() ); ``` ### Delete Customer ```java CustomerDeleteResponse response = client.customers() .delete("customer-123"); ``` ### List Customers ```java CustomerListResponse response = client.customers().list( CustomerListParams.builder() .limit(20) .email().startsWith("john@") .build() ); for (Customer customer : response.getCustomers()) { System.out.println(customer.getEmail()); } ``` ``` -------------------------------- ### Build JAR Files with Maven Source: https://github.com/chargebee/chargebee-java/blob/v4/README.md After checking out the source code, use this Maven command to clean and package the project, generating the necessary JAR files. ```shell mvn clean package ```