### List Resources Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Demonstrates how to list customer resources, which are returned in a paginated ListResponse. ```java // List resources (paginated) ListResponse page = client.customers().list().execute(); ``` -------------------------------- ### Using ApiResponse Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Example demonstrating how to execute a wrapped GET request and access the status code, headers, and the customer resource from the ApiResponse. ```java ApiResponse response = client.customers() .get("CU123") .executeWrapped(); int statusCode = response.getStatusCode(); // 200 Multimap headers = response.getHeaders(); String contentType = headers.get("content-type").iterator().next(); Customer customer = response.getResource(); ``` -------------------------------- ### Webhook Controller Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/webhook.md This example demonstrates how to set up a Spring Boot REST controller to receive and process GoCardless webhooks. It includes signature verification and event parsing. ```APIDOC ## POST /webhooks/gocardless ### Description Receives and processes incoming GoCardless webhook notifications. It verifies the signature, parses the events, and dispatches them for handling based on resource type. ### Method POST ### Endpoint /webhooks/gocardless ### Parameters #### Request Headers - **Webhook-Signature** (string) - Required - The signature of the webhook payload for verification. #### Request Body - **requestBody** (string) - Required - The raw JSON payload of the webhook notification. ### Request Example ```json { "example": "Webhook payload JSON" } ``` ### Response #### Success Response (200 OK) Returns OK if the webhook is successfully processed. #### Error Responses - **401 Unauthorized**: Returned if the webhook signature is invalid. - **500 Internal Server Error**: Returned if the webhook secret is not configured or if any other error occurs during processing. ### Event Structure Events parsed from the webhook have the following methods: ```java public class Event { public String getId(); // Unique event ID public String getAction(); // Action: created, updated, etc. public String getResourceType(); // Resource type: customer, payment, etc. public Map getMetadata(); // Custom metadata public String getCreatedAt(); // ISO 8601 timestamp public T getResource(Class type); // Get the resource object } ``` **Event Types (resourceType):** - `balance` - `creditor` - `customer` - `customer_bank_account` - `event` - `mandate` - `payment` - `payout` - `refund` - `subscription` **Action Types:** - `created` - `updated` - `completed` - `cancelled` - `failed` - `submitted` - `reinstated` ``` -------------------------------- ### Create Resource Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Illustrates how to create a new creditor resource with specified name and country code. ```java // Create a resource Creditor creditor = client.creditors().create() .withName("My Creditor") .withCountryCode("GB") .execute(); ``` -------------------------------- ### Build GoCardless Client with Full Configuration Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Example of building a GoCardless client with access token, environment, retries, and optional proxy settings. ```java import com.gocardless.GoCardlessClient; import java.net.InetSocketAddress; import java.net.Proxy; public class GoCardlessConfig { public static GoCardlessClient buildClient() { String accessToken = System.getenv("GOCARDLESS_ACCESS_TOKEN"); if (accessToken == null || accessToken.isEmpty()) { throw new IllegalStateException("GOCARDLESS_ACCESS_TOKEN not set"); } // Determine environment String env = System.getenv("APP_ENV"); GoCardlessClient.Environment environment = "production".equals(env) ? GoCardlessClient.Environment.LIVE : GoCardlessClient.Environment.SANDBOX; // Build proxy if configured Proxy proxy = null; String proxyHost = System.getenv("HTTP_PROXY_HOST"); if (proxyHost != null) { int proxyPort = Integer.parseInt( System.getenv("HTTP_PROXY_PORT") ); proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort) ); } // Build client GoCardlessClient.Builder builder = GoCardlessClient .newBuilder(accessToken) .withEnvironment(environment) .withMaxNoOfRetries(3) .withWaitBetweenRetriesInMilliSeconds(100); if (proxy != null) { builder.withProxy(proxy); } return builder.build(); } } ``` -------------------------------- ### Fetch Single Resource Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Shows how to retrieve a single customer resource by its ID. ```java // Fetch a single resource Customer customer = client.customers().get("CU123").execute(); ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/errors.md An example demonstrating how to catch and handle various GoCardless exceptions in a Java application. ```APIDOC ## Comprehensive Error Handling Example This example demonstrates how to implement robust error handling for GoCardless API requests using a `try-catch` block to manage various GoCardless-specific exceptions. ```java try { // Make API request Creditor creditor = client.creditors().create() .withName("My Company") .withCountryCode("GB") .execute(); } catch (ValidationFailedException e) { // Validation errors - missing/invalid fields for (ApiError error : e.getErrors()) { String field = error.getField(); String message = error.getMessage(); logger.warn("Validation error on {}: {}", field, message); } // Inform user to fix their input } catch (InvalidStateException e) { // Operation invalid for current resource state logger.warn("Invalid state: {}", e.getErrorMessage()); // Retry operation later or inform user } catch (AuthenticationException e) { // Invalid credentials logger.error("Authentication failed"); // Re-authenticate user } catch (PermissionException e) { // User lacks permission logger.error("Permission denied"); // Inform user they don't have permission } catch (RateLimitException e) { // Rate limited String retryAfter = e.getHeaders().get("Retry-After").iterator().next(); logger.warn("Rate limited, retry after {} seconds", retryAfter); // Implement exponential backoff } catch (GoCardlessInternalException e) { // Server error logger.error("Server error, request ID: {}", e.getRequestId()); // Contact support with request ID } catch (InvalidSignatureException e) { // Webhook signature invalid logger.warn("Invalid webhook signature"); // Reject webhook } catch (MalformedResponseException e) { // Invalid response format logger.error("Malformed response (HTTP {})", e.getStatusCode()); // Likely temporary issue, retry } catch (GoCardlessNetworkException e) { // Network error logger.error("Network error", e); // Implement circuit breaker and retry logic } catch (GoCardlessException e) { // Catch-all for any other GoCardless errors logger.error("Unexpected error", e); } ``` ``` -------------------------------- ### ListResponse Example Usage Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Demonstrates how to retrieve a list of payments, iterate through the items, check for subsequent pages, and access linked resources. ```java ListResponse page = client.payments().list().execute(); // Get items for (Payment payment : page.getItems()) { System.out.println(payment.getId()); } // Check for next page if (page.getAfter() != null) { ListResponse nextPage = client.payments() .list() .withAfter(page.getAfter()) .execute(); } // Access linked resources List linkedMandates = page.getLinkedMandates(); ``` -------------------------------- ### Example: Custom Certificate Configuration Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Demonstrates how to configure the GoCardless client with a custom SSL certificate. This involves creating a custom KeyStore, TrustManagerFactory, SSLContext, and then initializing the client with the custom SSLSocketFactory and TrustManager. ```java import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import java.security.KeyStore; KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // Load custom certificates into keyStore TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(keyStore); X509TrustManager tm = (X509TrustManager) tmf.getTrustManagers()[0]; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new X509TrustManager[] { tm }, null); SSLSocketFactory ssf = sslContext.getSocketFactory(); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withSslSocketFactoryAndTrustManager(ssf, tm) .build(); ``` -------------------------------- ### Update Resource Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Shows how to update an existing subscription resource by its ID, changing its name. ```java // Update a resource Subscription updated = client.subscriptions().update("SU123") .withName("New Name") .execute(); ``` -------------------------------- ### Get Customer with Response Metadata Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md An example of using executeWrapped() to fetch a customer and access its status code, resource object, and headers. ```java ApiResponse response = client.customers() .get("CU123") .executeWrapped(); int statusCode = response.getStatusCode(); Customer customer = response.getResource(); Map> headers = response.getHeaders(); ``` -------------------------------- ### Error Handling Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Demonstrates how to catch and handle various exceptions thrown by the GoCardless API client. ```APIDOC ## Error Handling ### Description Demonstrates how to catch and handle various exceptions thrown by the GoCardless API client. ### Code Example ```java try { Customer customer = client.customers().get("CU123").execute(); } catch (ValidationFailedException e) { // Invalid parameters - HTTP 422 for (ApiError error : e.getErrors()) { System.out.println(error.getField() + ": " + error.getMessage()); } } catch (InvalidStateException e) { // Resource state doesn't allow operation - HTTP 422 } catch (AuthenticationException e) { // Invalid credentials - HTTP 401 } catch (PermissionException e) { // Insufficient permissions - HTTP 403 } catch (GoCardlessApiException e) { // Other API errors String requestId = e.getRequestId(); } catch (GoCardlessException e) { // Network or client errors } ``` ``` -------------------------------- ### List Customers with Pagination Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Fetches a paginated list of customers. The example iterates through the items in the current page and prints their given names. ```java ListResponse page = client.customers().list().execute(); for (Customer customer : page.getItems()) { System.out.println(customer.getGivenName()); } ``` -------------------------------- ### LoggingInterceptor Configuration Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Example Logback configuration to enable DEBUG level logging for the LoggingInterceptor, which logs HTTP requests and responses. ```xml ``` -------------------------------- ### Example: Set Wait Time Between Retries Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configures the GoCardless client to wait for 500 milliseconds between each retry attempt. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withWaitBetweenRetriesInMilliSeconds(500) .build(); ``` -------------------------------- ### Example: Idempotency Conflict Behavior Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Shows how to configure the GoCardless client to either return an existing resource or raise an error when an idempotency key conflict is encountered. ```java // Default: return existing resource on conflict GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withErrorOnIdempotencyConflict(false) .build(); // Raise error on conflict GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withErrorOnIdempotencyConflict(true) .build(); ``` -------------------------------- ### Get Customer Details Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/types.md Retrieves a customer by their ID and accesses their email and name. Also shows how to get associated metadata. ```java Customer customer = client.customers().get("CU123").execute(); String email = customer.getEmail(); String name = customer.getGivenName() + " " + customer.getFamilyName(); Map meta = customer.getMetadata(); ``` -------------------------------- ### GetRequest Constructor Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Base class for HTTP GET requests. Use this constructor to initialize a GET request. ```java public GetRequest(HttpClient httpClient, String path) ``` -------------------------------- ### Handle Wrapped Response Example Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Demonstrates how to handle a wrapped API response, accessing the status code and the resource data separately. ```java // Handle wrapped response with metadata ApiResponse response = client.customers() .get("CU123") .executeWrapped(); int statusCode = response.getStatusCode(); Customer data = response.getResource(); ``` -------------------------------- ### Example: Set Maximum Retries Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configures the GoCardless client to attempt a maximum of 2 retries for failed requests. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withMaxNoOfRetries(2) .build(); ``` -------------------------------- ### WebhookParseResult Example Usage Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Shows how to parse a webhook request body and signature header to obtain a list of events and the webhook ID. ```java WebhookParseResult result = Webhook.parseWithMeta( requestBody, signatureHeader, webhookSecret ); List events = result.getEvents(); String webhookId = result.getWebhookId(); // For debugging ``` -------------------------------- ### Comprehensive GoCardless Java Error Handling Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/errors.md A comprehensive example demonstrating how to handle various GoCardless exceptions. This snippet covers specific exceptions like ValidationFailedException, InvalidStateException, AuthenticationException, and more, providing tailored responses for each. ```java try { // Make API request Creditor creditor = client.creditors().create() .withName("My Company") .withCountryCode("GB") .execute(); } catch (ValidationFailedException e) { // Validation errors - missing/invalid fields for (ApiError error : e.getErrors()) { String field = error.getField(); String message = error.getMessage(); logger.warn("Validation error on {}: {}", field, message); } // Inform user to fix their input } catch (InvalidStateException e) { // Operation invalid for current resource state logger.warn("Invalid state: {}", e.getErrorMessage()); // Retry operation later or inform user } catch (AuthenticationException e) { // Invalid credentials logger.error("Authentication failed"); // Re-authenticate user } catch (PermissionException e) { // User lacks permission logger.error("Permission denied"); // Inform user they don't have permission } catch (RateLimitException e) { // Rate limited String retryAfter = e.getHeaders().get("Retry-After").iterator().next(); logger.warn("Rate limited, retry after {} seconds", retryAfter); // Implement exponential backoff } catch (GoCardlessInternalException e) { // Server error logger.error("Server error, request ID: {}", e.getRequestId()); // Contact support with request ID } catch (InvalidSignatureException e) { // Webhook signature invalid logger.warn("Invalid webhook signature"); // Reject webhook } catch (MalformedResponseException e) { // Invalid response format logger.error("Malformed response (HTTP {})", e.getStatusCode()); // Likely temporary issue, retry } catch (GoCardlessNetworkException e) { // Network error logger.error("Network error", e); // Implement circuit breaker and retry logic } catch (GoCardlessException e) { // Catch-all for any other GoCardless errors logger.error("Unexpected error", e); } ``` -------------------------------- ### Spring Boot Webhook Handler Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/webhook.md A complete example for handling GoCardless webhooks in a Spring Boot application. It includes signature verification, event parsing, and routing to specific event handlers. ```java import com.gocardless.Webhook; import com.gocardless.errors.InvalidSignatureException; import com.gocardless.resources.Event; import com.gocardless.resources.Payment; import org.springframework.web.bind.annotation.*; import org.springframework.http.ResponseEntity; import org.springframework.http.HttpStatus; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RestController @RequestMapping("/webhooks") public class WebhookController { private static final Logger logger = LoggerFactory.getLogger(WebhookController.class); @PostMapping("/gocardless") public ResponseEntity handleGoCardlessWebhook( @RequestHeader("Webhook-Signature") String signatureHeader, @RequestBody String requestBody) { String webhookSecret = System.getenv("GOCARDLESS_WEBHOOK_SECRET"); if (webhookSecret == null) { logger.error("Webhook secret not configured"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } try { List events = Webhook.parse(requestBody, signatureHeader, webhookSecret); for (Event event : events) { logger.info("Processing event: {} ({})", event.getId(), event.getResourceType()); switch (event.getResourceType()) { case "payment": handlePaymentEvent(event); break; case "mandate": handleMandateEvent(event); break; case "customer": handleCustomerEvent(event); break; default: logger.debug("Unhandled event type: {}", event.getResourceType()); } } return ResponseEntity.ok().build(); } catch (InvalidSignatureException e) { logger.warn("Invalid webhook signature"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } catch (Exception e) { logger.error("Error processing webhook", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } private void handlePaymentEvent(Event event) { Payment payment = event.getResource(Payment.class); String action = event.getAction(); switch (action) { case "completed": logger.info("Payment completed: {}", payment.getId()); // Update payment status in database break; case "failed": logger.info("Payment failed: {}", payment.getId()); // Notify customer of failed payment break; } } private void handleMandateEvent(Event event) { // Handle mandate events } private void handleCustomerEvent(Event event) { // Handle customer events } } ``` -------------------------------- ### Handling GoCardlessNetworkException Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/errors.md Example of catching a GoCardlessNetworkException. This snippet shows how to log the underlying cause of the network error and suggests implementing retry logic or fallback mechanisms. ```java try { List customers = client.customers().all().execute(); } catch (GoCardlessNetworkException e) { logger.error("Network error", e.getCause()); // Implement retry logic or fallback } ``` -------------------------------- ### Configure Client from Environment Variables Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Demonstrates how to configure the GoCardless client using environment variables for the access token, environment (sandbox/live), base URL, and webhook secret. ```java // Access token String accessToken = System.getenv("GOCARDLESS_ACCESS_TOKEN"); // Environment String envString = System.getenv("GOCARDLESS_ENVIRONMENT"); GoCardlessClient.Environment environment = "sandbox".equalsIgnoreCase(envString) ? GoCardlessClient.Environment.SANDBOX : GoCardlessClient.Environment.LIVE; // Base URL String baseUrl = System.getenv("GOCARDLESS_BASE_URL"); // Webhook secret (for webhook processing) String webhookSecret = System.getenv("GOCARDLESS_WEBHOOK_SECRET"); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(environment) .build(); ``` -------------------------------- ### Initialize GoCardless Client with Access Token Source: https://github.com/gocardless/gocardless-pro-java/blob/master/README.md Instantiate the GoCardlessClient using an access token. This client defaults to the GoCardless live environment. ```java import com.gocardless.GoCardlessClient; String accessToken = "AO00000123"; GoCardlessClient client = GoCardlessClient.newBuilder(accessToken).build(); ``` -------------------------------- ### Build GoCardlessClient with Access Token Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Shows how to build a GoCardlessClient instance using an access token obtained from an environment variable. Ensures the access token is set before proceeding. ```java String accessToken = System.getenv("GOCARDLESS_ACCESS_TOKEN"); if (accessToken == null) { throw new IllegalArgumentException("GOCARDLESS_ACCESS_TOKEN not set"); } GoCardlessClient client = GoCardlessClient.newBuilder(accessToken).build(); ``` -------------------------------- ### GetRequest Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Base class for HTTP GET requests. It is idempotent and safe for retries. Provides methods to execute the request, get wrapped responses with metadata, and add custom headers. ```APIDOC ## GetRequest ### Description Base class for HTTP GET requests. This class is designed for idempotent operations and is safe to retry. It allows for executing the request to retrieve a resource, executing it to get the resource along with metadata, and adding custom HTTP headers. ### Methods - `execute()`: Executes the request and returns the resource of type T. - `executeWrapped()`: Executes the request and returns an `ApiResponse` which includes the resource and metadata. - `withHeader(String name, String value)`: Adds a custom HTTP header to the request. Custom headers override library-generated headers. ``` -------------------------------- ### Configure GoCardlessClient with Builder Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Demonstrates the fluent configuration of the GoCardlessClient instance using the Builder. All options are optional except for the access token. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(Environment.SANDBOX) .withMaxNoOfRetries(2) .withWaitBetweenRetriesInMilliSeconds(200) .withProxy(proxy) .build(); ``` -------------------------------- ### Configure GoCardless Client for Sandbox Environment Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Initializes the GoCardless client and configures it to use the SANDBOX environment. This is useful for testing without affecting live data. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .build(); ``` -------------------------------- ### GoCardlessClient Construction Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Demonstrates how to create a GoCardlessClient instance using a static factory method and an OAuth access token. ```APIDOC ## GoCardlessClient Construction ### Description Initializes the GoCardlessClient using a static factory method. Requires an OAuth access token for authentication. ### Method Signature `public static Builder newBuilder(String accessToken)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.gocardless.GoCardlessClient; String accessToken = "AO00000123"; GoCardlessClient client = GoCardlessClient.newBuilder(accessToken).build(); ``` ### Response #### Success Response Returns a `GoCardlessClient.Builder` instance. #### Response Example `GoCardlessClient.Builder` ``` -------------------------------- ### Initialize GoCardless Client with Custom Options Source: https://github.com/gocardless/gocardless-pro-java/blob/master/README.md Configure the GoCardlessClient with custom settings such as environment, proxy, retry count, and wait time. The maximum number of retries allowed is 3. ```java import com.gocardless.GoCardlessClient; import java.net.InetSocketAddress; import java.net.Proxy; String accessToken = "AO00000123"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .withMaxNoOfRetries(2) .withWaitBetweenRetriesInMilliSeconds(200) .withProxy(proxy) .build(); ``` -------------------------------- ### Configure GoCardlessClient with SOCKS Proxy Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Demonstrates setting up a SOCKS proxy for GoCardless client requests. ```java Proxy socksProxy = new Proxy( Proxy.Type.SOCKS, new InetSocketAddress("socks.company.com", 1080) ); ``` -------------------------------- ### Execute Request and Get Resource Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Executes a request and returns the resource object. Automatic retry is applied for safe requests. ```java T execute() ``` -------------------------------- ### Client Initialization Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Initializes the GoCardlessClient with an access token. Supports configuration for different environments like SANDBOX. ```APIDOC ## Client Initialization ### Description Initializes the GoCardlessClient with an access token. Supports configuration for different environments like SANDBOX. ### Code Example ```java import com.gocardless.GoCardlessClient; // Basic initialization String accessToken = "AO00000123"; GoCardlessClient client = GoCardlessClient.newBuilder(accessToken).build(); // Initialization with Sandbox environment GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .build(); ``` ``` -------------------------------- ### Get Payment by ID Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/types.md Retrieves a Payment resource using its unique identifier. Extracts the amount and currency if the payment status is confirmed. ```java Payment payment = client.payments().get("PM123").execute(); if (payment.getStatus() == Payment.Status.CONFIRMED) { int amount = payment.getAmount(); // In lowest denomination String currency = payment.getCurrency().toString(); } ``` -------------------------------- ### Build Client for Development Environment Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configure the client to use the sandbox environment for development purposes. ```java // Use sandbox, more verbose logging GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .build(); ``` -------------------------------- ### Build Client for Production Environment Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configure the client for the production environment with a specified number of retries and wait time. ```java // Use live environment, stable configuration GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.LIVE) .withMaxNoOfRetries(3) .withWaitBetweenRetriesInMilliSeconds(100) .build(); ``` -------------------------------- ### Configure Logback XML Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Set up the logback.xml file to define logging levels and appenders for the GoCardless client and HTTP requests. ```xml %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n ``` -------------------------------- ### Handling MalformedResponseException Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/errors.md Example of how to catch and handle a MalformedResponseException. This snippet demonstrates accessing the status code and response body from the exception to log the error. ```java try { Customer customer = client.customers().get("CU123").execute(); } catch (MalformedResponseException e) { int statusCode = e.getStatusCode(); String preview = e.getResponseBody(); logger.error("Malformed response (HTTP {}): {}", statusCode, preview); } ``` -------------------------------- ### Configure GoCardlessClient for Live Environment Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configures the GoCardlessClient to connect to the LIVE environment for production use. This is the default behavior if no environment is specified. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.LIVE) .build(); ``` -------------------------------- ### Get Mandate by ID Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/types.md Retrieves a Mandate resource using its unique identifier. Checks if the mandate is active and retrieves the next possible charge date. ```java Mandate mandate = client.mandates().get("MD123").execute(); if (mandate.getStatus() == Mandate.Status.ACTIVE) { String nextChargeDate = mandate.getNextPossibleChargeDate(); // Can create payments } ``` -------------------------------- ### Fetch a Single Mandate Source: https://github.com/gocardless/gocardless-pro-java/blob/master/README.md Retrieve a specific mandate using its ID with the `get` method. The result can be processed to access mandate details like the reference. ```java Mandate mandate = client.mandates().get("MD123").execute(); System.out.println(mandate.getReference()); ``` -------------------------------- ### Create Creditor with Address Details Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Demonstrates creating a new creditor resource by chaining multiple 'with' methods to set name and address fields before execution. ```java Creditor creditor = client.creditors().create() .withName("My Company") .withAddressLine1("123 Main St") .withCity("London") .withPostalCode("N1 1AA") .withCountryCode("GB") .execute(); ``` -------------------------------- ### Configure GoCardlessClient with Custom Proxy Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Set up an HTTP proxy for all client requests. This is necessary when operating behind a corporate proxy or for specific network configurations. ```java import java.net.InetSocketAddress; import java.net.Proxy; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withProxy(proxy) .build(); ``` -------------------------------- ### Request Parameter Setting Methods Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Explains how to set resource fields for create and update requests using fluent `with*` methods. ```APIDOC ## Request Parameter Methods Create and update requests support setting resource fields via `with*` methods. Each method: - Sets the corresponding field - Returns the request for chaining - Does not validate immediately (validation occurs on execute) **Example:** ```java Creditor creditor = client.creditors().create() .withName("My Company") .withAddressLine1("123 Main St") .withCity("London") .withPostalCode("N1 1AA") .withCountryCode("GB") .execute(); ``` ``` -------------------------------- ### MalformedResponseException Definition Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/errors.md Defines the MalformedResponseException class, which is triggered when the API returns invalid JSON or an unexpected format. It provides methods to get the HTTP status code and the raw response body. ```java public class MalformedResponseException extends GoCardlessException { public int getStatusCode(); public String getResponseBody(); } ``` -------------------------------- ### Create a Customer Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Creates a new customer with the provided details. ```APIDOC ## Create a Customer ### Description Creates a new customer with the provided details. ### Method `client.customers().create()` ### Parameters #### Request Body - **givenName** (string) - Required - The customer's first name. - **familyName** (string) - Required - The customer's last name. - **email** (string) - Required - The customer's email address. ### Request Example ```java Customer customer = client.customers().create() .withGivenName("John") .withFamilyName("Doe") .withEmail("john@example.com") .execute(); ``` ### Response #### Success Response Returns the created `Customer` object. ``` -------------------------------- ### Configure Maximum Number of Retries Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Sets the maximum number of retry attempts for failed requests. This applies to idempotent GET requests, POST requests with idempotency keys, 5xx server errors, 429 rate limit errors, and network timeouts. The maximum effective value is always 3. ```java Builder withMaxNoOfRetries(int maxNoOfRetries) ``` -------------------------------- ### List Customers - Fetch First Page Source: https://github.com/gocardless/gocardless-pro-java/blob/master/README.md Obtain the first page of customer resources. The response contains a list of customers and a cursor for fetching subsequent pages. ```java ListResponse firstPage = client.customers().list().execute(); for (Customer customer : firstPage.getItems()) { System.out.println(customer.getGivenName()); } String cursor = firstPage.getAfter(); ListResponse nextPage = client.customers().list().withAfter(cursor).execute(); ``` -------------------------------- ### Create and Check Customer Bank Account Status Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/types.md Demonstrates how to create a customer bank account and check its status. The status must be ENABLED to create mandates. ```java CustomerBankAccount bankAccount = client.customerBankAccounts() .create() .withAccountHolderName("John Doe") .withIban("DE89370400440532013000") .execute(); if (bankAccount.getStatus() == CustomerBankAccount.Status.ENABLED) { // Can create mandates } ``` -------------------------------- ### Build Client for Corporate Network with Proxy Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configure the client to route requests through a corporate proxy server. ```java // Route through proxy Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.corp.com", 8080) ); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withProxy(proxy) .build(); ``` -------------------------------- ### Create a Customer Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Creates a new customer with the provided details. Requires customer's name and email. ```java Customer customer = client.customers().create() .withGivenName("John") .withFamilyName("Doe") .withEmail("john@example.com") .execute(); ``` -------------------------------- ### GoCardlessClient Builder Configuration Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Details the various configuration options available for the GoCardlessClient.Builder, including environment, proxy, retries, and more. ```APIDOC ## GoCardlessClient Builder Configuration ### Description Configures the GoCardlessClient with optional parameters using a fluent interface. All `with*` methods return the Builder for chaining. ### Methods #### `withEnvironment(Environment environment)` Configures the GoCardless environment for the client. - **Parameters**: - `environment` (Environment): `LIVE` or `SANDBOX` - **Default**: `LIVE` (base URL: `https://api.gocardless.com`) - **Returns**: `Builder` (fluent) - **Example**: ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .build(); ``` #### `withBaseUrl(String baseUrl)` Configures a custom base URL for the client. Overrides environment setting. - **Parameters**: - `baseUrl` (String): Full base URL for API (e.g., `https://custom.gocardless.com`) - **Returns**: `Builder` (fluent) #### `withProxy(Proxy proxy)` Configures an HTTP proxy for all requests made by the client. - **Parameters**: - `proxy` (java.net.Proxy): HTTP proxy configuration - **Returns**: `Builder` (fluent) - **Example**: ```java import java.net.InetSocketAddress; import java.net.Proxy; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withProxy(proxy) .build(); ``` #### `withSslSocketFactoryAndTrustManager(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)` Configures custom SSL/TLS certificate handling. - **Parameters**: - `sslSocketFactory` (javax.net.ssl.SSLSocketFactory): Custom SSL socket factory - `trustManager` (javax.net.ssl.X509TrustManager): Custom trust manager - **Returns**: `Builder` (fluent) #### `withMaxNoOfRetries(int maxNoOfRetries)` Configures the maximum number of automatic retries for failed requests. - **Parameters**: - `maxNoOfRetries` (int): Maximum retry count (default: 3, maximum: 3) - **Returns**: `Builder` (fluent) - **Note**: GET requests are retried automatically. POST requests with idempotency keys are also retried. #### `withWaitBetweenRetriesInMilliSeconds(long waitBetweenRetriesInMilliSeconds)` Configures the fixed wait time between retry attempts. - **Parameters**: - `waitBetweenRetriesInMilliSeconds` (long): Wait time in milliseconds (default: 100ms) - **Returns**: `Builder` (fluent) #### `withErrorOnIdempotencyConflict(boolean errorOnIdempotencyConflict)` Configures behavior when an idempotency key conflict occurs. - **Parameters**: - `errorOnIdempotencyConflict` (boolean): If true, raises error; if false, fetches the existing resource (default: false) - **Returns**: `Builder` (fluent) #### `build()` Constructs the final `GoCardlessClient` instance with configured settings. - **Returns**: `GoCardlessClient` - **Throws**: None (runtime validation only) - **Example**: ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .withMaxNoOfRetries(2) .withWaitBetweenRetriesInMilliSeconds(200) .build(); ``` ``` -------------------------------- ### Configure GoCardlessClient with HTTP Proxy Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Sets up an HTTP proxy for all client requests, enabling routing through corporate proxies or custom gateways. ```java import java.net.InetSocketAddress; import java.net.Proxy; Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.company.com", 8080) ); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withProxy(proxy) .build(); ``` -------------------------------- ### Add Custom Metadata to Customer Creation Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Shows how to include custom key-value metadata when creating a new customer resource. ```java Customer customer = client.customers().create() .withGivenName("John") .withFamilyName("Doe") .withMetadata(Map.of("user_id", "12345", "source", "web")) .execute(); ``` -------------------------------- ### Build GoCardlessClient with Custom Retry Settings Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/client.md Construct a GoCardlessClient instance with custom retry settings, including the maximum number of retries and the wait time between retries. This allows fine-tuning of the client's resilience to transient network issues. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withEnvironment(GoCardlessClient.Environment.SANDBOX) .withMaxNoOfRetries(2) .withWaitBetweenRetriesInMilliSeconds(200) .build(); ``` -------------------------------- ### Singleton GoCardlessClient Instance Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Implement a singleton pattern to ensure a single, thread-safe instance of GoCardlessClient is shared across the application. ```java public class GoCardlessClientHolder { private static final GoCardlessClient client = GoCardlessClient.newBuilder(accessToken).build(); public static GoCardlessClient get() { return client; } } ``` -------------------------------- ### List All Customers (Iteration) Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Iterates through all customer resources using the all() method, executing the request to fetch each customer. ```java for (Customer customer : client.customers().all().execute()) { // Process each customer } ``` -------------------------------- ### Create Subscription Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/types.md Creates a new subscription with specified details. Use this to set up recurring payments. ```java Subscription sub = client.subscriptions().create() .withName("Monthly Plan") .withAmount(2999) .withCurrency("GBP") .withIntervalUnit("monthly") .execute(); if (sub.getStatus() == Subscription.Status.ACTIVE) { String nextDate = sub.getNextChargeDate(); } ``` -------------------------------- ### List Customers with Pagination Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Executes a paginated list request for customers and demonstrates how to process items and retrieve the next page using the cursor. ```java ListResponse page = client.customers().list().execute(); for (Customer customer : page.getItems()) { // Process customer } String nextCursor = page.getAfter(); if (nextCursor != null) { ListResponse nextPage = client.customers() .list() .withAfter(nextCursor) .execute(); } ``` -------------------------------- ### Configure HTTP Proxy Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Set up the GoCardless client to use an HTTP proxy for making requests. Specify the proxy host and port. ```java import java.net.InetSocketAddress; import java.net.Proxy; Proxy proxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080) ); GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withProxy(proxy) .build(); ``` -------------------------------- ### Retrieve Metadata from a Customer Resource Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Demonstrates how to access the metadata associated with an existing customer resource. ```java Map metadata = customer.getMetadata(); ``` -------------------------------- ### Create Refund Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/types.md Initiates a refund for a payment. Use this to return funds to a customer. ```java Refund refund = client.refunds().create() .withAmount(1000) .execute(); if (refund.getStatus() == Refund.Status.COMPLETED) { // Refund processed } ``` -------------------------------- ### Create a Payment Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/README.md Creates a new payment with a specified amount, linked mandate, and charge date. The amount is in the smallest currency unit (e.g., pence for GBP). ```java Payment payment = client.payments().create() .withAmount(1000) // £10.00 .withLinksMandate("MD123") .withChargeDate("2024-12-25") .execute(); ``` -------------------------------- ### Build Client with Custom API Endpoint Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Configure the client to use a custom base URL for the GoCardless API. ```java // Use custom base URL GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withBaseUrl("https://api.custom.endpoint.com") .build(); ``` -------------------------------- ### List Operations Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Demonstrates how to perform paginated listings and iterate through all items using `list()` and `all()` methods, respectively. ```APIDOC ## List with Pagination ### Description Retrieves a paginated list of resources. ### Method ```java ListResponse list() ``` ### Example ```java ListResponse page = client.customers().list().execute(); for (Customer customer : page.getItems()) { // Process customer } String nextCursor = page.getAfter(); if (nextCursor != null) { ListResponse nextPage = client.customers() .list() .withAfter(nextCursor) .execute(); } ``` ## List All Items (Iteration) ### Description Iterates through all available items of a resource. ### Method ```java ListResponse all() ``` ### Example ```java for (Customer customer : client.customers().all().execute()) { // Process each customer } ``` ``` -------------------------------- ### Configure GoCardlessClient with Custom Base URL Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Allows setting a custom base URL for the GoCardless API, overriding the default environment setting. This is useful for custom or proxied API endpoints. ```java GoCardlessClient client = GoCardlessClient.newBuilder(accessToken) .withBaseUrl("https://api-proxy.mycompany.com") .build(); ``` -------------------------------- ### Idempotency Handling Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Explains how POST requests for resource creation use automatic idempotency keys for safe retries and how to override them. ```APIDOC ## Idempotency POST requests for resource creation use automatic idempotency keys to allow safe retries. If a request fails and is retried, the library detects if the resource was already created and returns the existing resource (if `withErrorOnIdempotencyConflict(false)` in client config, which is the default). To override the idempotency key: ```java Customer customer = client.customers().create() .withGivenName("John") .withFamilyName("Doe") .withHeader("Idempotency-Key", "my-custom-key-123") .execute(); ``` ``` -------------------------------- ### List All Customers Source: https://github.com/gocardless/gocardless-pro-java/blob/master/README.md Iterate through all customer resources in a collection, handling pagination automatically. This is useful for processing large datasets. ```java for (Customer customer : client.customers().all().execute()) { System.out.println(customer.getGivenName()); } ``` -------------------------------- ### Custom Headers Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/services.md Demonstrates how to add custom HTTP headers to any request using the `withHeader()` method. ```APIDOC ## Custom Headers Add custom HTTP headers to any request using `withHeader()`: ```java MandatePdf pdf = client.mandatePdfs().create() .withIban("DE89370400440532013000") .withHeader("Accept-Language", "de-DE") .execute(); ``` Custom headers take precedence over library-generated headers (Authorization, Idempotency-Key, etc.). ``` -------------------------------- ### Add Custom Header to Request Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Demonstrates how to add a custom header, such as 'Accept-Language', to a customer creation request. Custom headers override built-in ones. ```java Customer customer = client.customers().create() .withGivenName("John") .withFamilyName("Doe") .withHeader("Accept-Language", "de-DE") .execute(); ``` -------------------------------- ### Advanced Usage: Custom Retry and Headers Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/api-reference/http.md Demonstrates implementing custom retry logic using `executeWrapped()` and adding custom headers like `X-Request-ID` for tracing. ```java import com.gocardless.GoCardlessClient; import com.gocardless.http.ApiResponse; import com.gocardless.resources.Customer; GoCardlessClient client = GoCardlessClient.newBuilder(accessToken).build(); // Custom retry logic for (int attempt = 0; attempt < 3; attempt++) { try { // Use executeWrapped to bypass automatic retry ApiResponse response = client.customers() .get("CU123") .executeWrapped(); if (response.getStatusCode() == 200) { Customer customer = response.getResource(); break; } else if (response.getStatusCode() >= 500) { // Retry on server error if (attempt < 2) { Thread.sleep(1000 * (attempt + 1)); continue; } } } catch (GoCardlessNetworkException e) { if (attempt < 2) { Thread.sleep(1000); continue; } throw e; } } // Add custom header for request tracing String traceId = UUID.randomUUID().toString(); Customer customer = client.customers().create() .withGivenName("Jane") .withFamilyName("Smith") .withHeader("X-Request-ID", traceId) .withHeader("Accept-Language", "fr-FR") .execute(); ``` -------------------------------- ### Add Logback Classic Dependency Source: https://github.com/gocardless/gocardless-pro-java/blob/master/_autodocs/configuration.md Add the Logback Classic dependency to your project's build file to enable SLF4J logging. ```gradle implementation 'ch.qos.logback:logback-classic:1.2.11' ```