### Basic Setup with Test API Key Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Initializes the Adyen client for the test environment using an API key. This is a common starting point for development and testing. ```java import com.adyen.Client; import com.adyen.Config; import com.adyen.enums.Environment; import com.adyen.service.checkout.PaymentsApi; Config config = new Config() .environment(Environment.TEST) .apiKey("YOUR_TEST_API_KEY"); Client client = new Client(config); PaymentsApi paymentsApi = new PaymentsApi(client); ``` -------------------------------- ### Complete RequestOptions Example with API Call Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/REQUEST_OPTIONS_AND_ERROR_HANDLING.md Demonstrates the complete setup of RequestOptions with an idempotency key and additional headers, followed by making a payments API call. ```java import com.adyen.model.RequestOptions; import com.adyen.service.checkout.PaymentsApi; import java.util.HashMap; import java.util.UUID; HashMap additionalHeaders = new HashMap<>(); additionalHeaders.put("X-Custom-Header", "custom-value"); RequestOptions requestOptions = new RequestOptions() .idempotencyKey(UUID.randomUUID().toString()) .additionalServiceHeaders(additionalHeaders); PaymentsApi paymentsApi = new PaymentsApi(client); PaymentResponse paymentResponse = paymentsApi.payments(paymentRequest, requestOptions); ``` -------------------------------- ### Client and Config Setup Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/MANIFEST.txt Demonstrates how to initialize the Adyen Client with API key authentication and configure various settings like environment and timeouts. This is a common starting point for most API interactions. ```java import com.adyen.Client; import com.adyen.Config; // ... // Set your API key and environment Config config = new Config(); config.setApiKey("YOUR_API_KEY"); config.setEnvironment(Environment.TEST); config.setExternalPlatform("YOUR_PLATFORM_NAME", "YOUR_PLATFORM_VERSION"); config.setMerchantAccount("YOUR_MERCHANT_ACCOUNT"); // Set connection and read timeouts config.setConnectionTimeout(5000); config.setReadTimeout(5000); // Initialize the client Client client = new Client(config); ``` -------------------------------- ### Client Certificate Authentication Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Shows how to configure the client for authentication using a client certificate. ```java import com.adyen.Client; public class ClientCertAuth { public static void main(String[] args) { // Replace with your certificate details String certificatePath = "path/to/your/certificate.p12"; String certificatePassword = "YOUR_CERTIFICATE_PASSWORD"; String environment = "TEST"; // Or "LIVE" Client client = new Client(certificatePath, certificatePassword, environment); // Further configuration can be done here if needed System.out.println("Client configured with client certificate authentication."); } } ``` -------------------------------- ### Setup Client for Payments Links API with Basic Auth Source: https://github.com/adyen/adyen-java-api-library/blob/main/README.md Configure the Adyen client using username and password for basic authentication. This example shows setup for the PaymentLinksApi. ```java // Import the required classes import com.adyen.Client; import com.adyen.enums.Environment; import com.adyen.service.checkout.PaymentLinksApi // Setup Client and Service passing prefix Client client = new Client("YOUR_USERNAME", "YOUR_PASSWORD", Environment.LIVE, "mycompany123"); // Or setup Client and Service passing prefix and application name //Client client = new Client("YOUR_USERNAME", "YOUR_PASSWORD", Environment.LIVE, "mycompany123", "YOUR_APPLICATION_NAME"); PaymentLinksApi paymentLinksApi = new PaymentLinksApi(client); ... ``` -------------------------------- ### HTTP Basic Authentication Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Illustrates how to set up HTTP Basic authentication for API requests. ```java import com.adyen.Client; public class BasicAuth { public static void main(String[] args) { // Replace with your username and password String username = "YOUR_USERNAME"; String password = "YOUR_PASSWORD"; String environment = "TEST"; // Or "LIVE" Client client = new Client(username, password, environment); // Further configuration can be done here if needed System.out.println("Client configured with HTTP Basic authentication."); } } ``` -------------------------------- ### Create Order Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/ADDITIONAL_APIS.md Example of creating a new order for payment processing using the Orders API. Ensure you provide the currency and value for the amount, along with a reference. ```java CreateOrderRequest request = new CreateOrderRequest() .amount(new Amount().currency("EUR").value(10000L)) .reference("ORDER-123"); CreateOrderResponse response = ordersApi.createOrder(request); String orderData = response.getOrderData(); ``` -------------------------------- ### Initialize CloudDeviceApi Client on TEST Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/CloudDeviceApi.md Setup the Adyen Client for the TEST environment. Ensure you have the necessary imports. ```java import com.adyen.Client; import com.adyen.enums.Environment; import com.adyen.service.clouddevice.CloudDeviceApi; import com.adyen.model.clouddevice.*; import com.adyen.model.tapi.*; import java.math.BigDecimal; import java.time.OffsetDateTime; import java.time.ZoneOffset; // Setup Client on TEST Client client = new Client(new Config().apiKey("test").environment(Environment.TEST)); CloudDeviceApi cloudDeviceApi = new CloudDeviceApi(client); ``` -------------------------------- ### Handling Webhook Notifications (Spring Boot Example) Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/MANIFEST.txt Provides an example of setting up a webhook endpoint using Spring Boot to receive and process notifications from Adyen. It includes signature validation and basic notification handling. ```java import com.adyen.model.notification.NotificationRequest; import com.adyen.model.notification.NotificationResponse; import com.adyen.model.notification.NotificationResponse.StatusEnum; import com.adyen.util.HMACValidator; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/webhooks") public class WebhookController { private final String hmacKey = "YOUR_HMAC_KEY"; // Get this from your Adyen Customer Area @PostMapping("/...") // Use the same endpoint path as configured in Adyen public ResponseEntity handleNotification( @RequestBody String requestBody, @RequestHeader("notification-signature") String signature) { // 1. Validate the signature if (!HMACValidator.validate(requestBody, signature, hmacKey)) { return ResponseEntity.status(401).build(); // Unauthorized } // 2. Parse the notification request // Use Adyen's Jackson deserializer for NotificationRequest // Example: NotificationRequest notificationRequest = objectMapper.readValue(requestBody, NotificationRequest.class); NotificationRequest notificationRequest = new NotificationRequest(); // Placeholder for actual deserialization // Populate notificationRequest from requestBody for demonstration // In a real app, use Jackson or similar to parse requestBody into NotificationRequest // 3. Process the notifications NotificationResponse notificationResponse = new NotificationResponse(); notificationResponse.setNotificationResponseItems(List.of()); // Placeholder for (var notificationItem : notificationRequest.getNotificationItems()) { // Process each notification item based on eventCode, success, etc. // Example: if ("AUTHORISATION".equals(notificationItem.getEventCode()) && notificationItem.getSuccess()) { // // Update order status, send confirmation email, etc. // } // Add a response item for each processed notification // notificationResponse.addNotificationResponseItem(new NotificationResponseItem().notificationResponse(StatusEnum.RECEIVED)); } // 4. Return a success response return ResponseEntity.ok(notificationResponse); } } ``` -------------------------------- ### Timeout Configuration Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Demonstrates how to configure various timeout settings for API requests. This covers one of three scenarios. ```java import com.adyen.Client; import com.adyen.model.RequestOptions; public class TimeoutConfig { public static void main(String[] args) { // Assume client is already initialized // Client client = new Client("YOUR_API_KEY", "TEST"); Client client = null; // Placeholder for initialized client // Configure request options with specific timeouts RequestOptions requestOptions = new RequestOptions(); requestOptions.setConnectionTimeout(5000); // 5 seconds requestOptions.setReadTimeout(10000); // 10 seconds requestOptions.setWriteTimeout(10000); // 10 seconds // You would then pass these requestOptions to your service calls // Example: paymentService.submit(request, requestOptions); System.out.println("Request options configured with custom timeouts."); } } ``` -------------------------------- ### Configure API with Test Environment Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/types.md Example of setting the API configuration to use the TEST environment. ```java Config config = new Config() .environment(Environment.TEST); ``` -------------------------------- ### Setup Adyen Client Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/README.md Configure and initialize the Adyen client with your API key and environment settings. Ensure the read timeout is set appropriately. ```java import com.adyen.Client; import com.adyen.Config; import com.adyen.enums.Environment; Config config = new Config() .environment(Environment.TEST) .apiKey("YOUR_API_KEY") .readTimeoutMillis(15000); Client client = new Client(config); ``` -------------------------------- ### Start a Payment Transaction with Request Options Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CHECKOUT_PAYMENTS_API.md Starts a payment transaction and allows for additional request headers, such as an idempotency key, to be included. This is useful for ensuring requests are processed exactly once. ```java RequestOptions options = new RequestOptions() .idempotencyKey(UUID.randomUUID().toString()); PaymentResponse response = paymentsApi.payments(paymentRequest, options); ``` -------------------------------- ### Payment Method Listing Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Shows how to retrieve a list of available payment methods for a given merchant account and country. ```java import com.adyen.Client; import com.adyen.model.Amount; import com.adyen.model.PaymentMethod; import com.adyen.model.PaymentMethodsRequest; import com.adyen.model.PaymentMethodsResponse; import com.adyen.service.Payment; // Assuming Payment service handles this import java.util.List; public class PaymentMethodList { public static void main(String[] args) { // Assume client is initialized Client client = null; // Placeholder Payment paymentService = null; // Placeholder PaymentMethodsRequest request = new PaymentMethodsRequest(); request.setMerchantAccount("YOUR_MERCHANT_ACCOUNT"); request.setCountryCode("NL"); // Example country code Amount amount = new Amount(); amount.setCurrency("EUR"); amount.setValue(1000L); // Example amount in cents request.setAmount(amount); try { // PaymentMethodsResponse response = paymentService.getPaymentMethods(request); PaymentMethodsResponse response = null; // Placeholder List paymentMethods = response.getPaymentMethods(); if (paymentMethods != null) { System.out.println("Available payment methods:"); for (PaymentMethod method : paymentMethods) { System.out.println("- " + method.getName() + " (" + method.getType() + ")"); } } } catch (Exception e) { System.err.println("Error fetching payment methods: " + e.getMessage()); } } } ``` -------------------------------- ### Initialize CloudDeviceApi Client on LIVE Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/CloudDeviceApi.md Setup the Adyen Client for the LIVE environment, specifying the closest terminal API region. Ensure you have the necessary imports. ```java import com.adyen.Client; import com.adyen.enums.Environment; import com.adyen.service.clouddevice.CloudDeviceApi; import com.adyen.model.clouddevice.*; import com.adyen.model.tapi.*; import java.math.BigDecimal; import java.time.OffsetDateTime; import java.time.ZoneOffset; // Setup Client on LIVE (Region is required) Client client = new Client(new Config().apiKey("test").environment(Environment.LIVE).terminalApiRegion(Region.US)); CloudDeviceApi cloudDeviceApi = new CloudDeviceApi(client); ``` -------------------------------- ### Complete Payment Flow Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/README.md Demonstrates the complete payment flow, from setting up the client and API to creating a payment request and handling the response. Use this for direct payment processing. ```java // 1. Setup Config config = new Config() .environment(Environment.TEST) .apiKey("YOUR_API_KEY"); Client client = new Client(config); PaymentsApi paymentsApi = new PaymentsApi(client); // 2. Create payment PaymentRequest request = new PaymentRequest() .merchantAccount("YOUR_MERCHANT_ACCOUNT") .amount(new Amount().currency("EUR").value(10000L)) .reference("ORDER-123") .paymentMethod(cardDetails) .returnUrl("https://your-domain.com/return"); RequestOptions options = new RequestOptions() .idempotencyKey(UUID.randomUUID().toString()); try { PaymentResponse response = paymentsApi.payments(request, options); System.out.println("Result: " + response.getResultCode()); } catch (ApiException e) { System.err.println("Error: " + e.getError().getErrorCode()); } ``` -------------------------------- ### Create an Amount Object Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/types.md Example of creating an Amount object with a specified currency and value. ```java Amount amount = new Amount() .currency("EUR") .value(10000L); // €100.00 ``` -------------------------------- ### Complete Webhook Handling Example in Java Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/WEBHOOKS_AND_UTILITIES.md This example demonstrates the full process of handling an Adyen webhook. It includes validating the HMAC signature, parsing the JSON payload, iterating through notification items, and processing different event codes. Ensure you replace 'YOUR_HMAC_KEY_FROM_CA' with your actual HMAC key. ```java import com.adyen.util.HMACValidator; import com.adyen.notification.WebhookHandler; import com.adyen.model.notification.NotificationRequest; import com.adyen.model.notification.NotificationRequestItem; @PostMapping("/webhooks/payments") public ResponseEntity handleWebhook(@RequestBody String payload, @RequestHeader("hmacsignature") String signature) { try { // 1. Validate HMAC signature HMACValidator hmacValidator = new HMACValidator(); String hmacKey = "YOUR_HMAC_KEY_FROM_CA"; if (!hmacValidator.validateHMAC(signature, hmacKey, payload)) { System.err.println("Invalid HMAC signature"); return ResponseEntity.status(401).body("[invalid hmac]"); } // 2. Parse webhook WebhookHandler webhookHandler = new WebhookHandler(); NotificationRequest notification = webhookHandler.handleNotificationJson(payload); // 3. Process each notification item for (NotificationRequestItem item : notification.getNotificationItems()) { String eventCode = item.getEventCode(); String pspReference = item.getPspReference(); String merchantReference = item.getMerchantReference(); String success = item.getSuccess(); System.out.printf("Event: %s | PSP: %s | Merchant Ref: %s | Success: %s%n", eventCode, pspReference, merchantReference, success); // Handle specific event codes switch (eventCode) { case "AUTHORISATION": if ("true".equals(success)) { System.out.println("Payment authorized"); // Update order status to paid } else { System.out.println("Payment declined"); // Update order status to failed } break; case "CAPTURE": System.out.println("Payment captured"); // Update order status to captured break; case "REFUND": System.out.println("Payment refunded"); // Update order status to refunded break; case "CANCEL_OR_REFUND": System.out.println("Payment cancelled/refunded"); break; default: System.out.println("Unhandled event: " + eventCode); } } // 4. Return success response to Adyen return ResponseEntity.ok("[accepted]"); } catch (Exception e) { System.err.println("Webhook processing error: " + e.getMessage()); return ResponseEntity.status(500).body("[error]"); } } ``` -------------------------------- ### Idempotency Key Usage Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Shows how to use an idempotency key to ensure that a request is processed only once. ```java import com.adyen.Client; import com.adyen.model.RequestOptions; import com.adyen.model.payments.PaymentRequest; import com.adyen.service.Payment; import java.util.UUID; public class IdempotencyKey { public static void main(String[] args) { // Assume client and paymentService are initialized Client client = null; // Placeholder Payment paymentService = null; // Placeholder PaymentRequest request = new PaymentRequest(); // ... populate payment request details ... RequestOptions requestOptions = new RequestOptions(); // Generate a unique idempotency key for each request String idempotencyKey = UUID.randomUUID().toString(); requestOptions.setIdempotencyKey(idempotencyKey); try { // paymentService.submit(request, requestOptions); System.out.println("Payment request submitted with idempotency key: " + idempotencyKey); } catch (Exception e) { // Handle exceptions e.printStackTrace(); } } } ``` -------------------------------- ### HTTP Basic Authentication Setup Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Initializes the Adyen client using HTTP Basic Authentication with a username and password for the test environment. Ensure your credentials are kept secure. ```java Client client = new Client( "username", "password", Environment.TEST, null ); ``` -------------------------------- ### Card Details Lookup Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Demonstrates how to perform a card details lookup, often used for pre-authorization checks or retrieving card information. ```java import com.adyen.Client; import com.adyen.model.CardDetailsLookupRequest; import com.adyen.model.CardDetailsLookupResponse; import com.adyen.service.Card; public class CardLookup { public static void main(String[] args) { // Assume client is initialized Client client = null; // Placeholder Card cardService = null; // Placeholder CardDetailsLookupRequest request = new CardDetailsLookupRequest(); request.setMerchantAccount("YOUR_MERCHANT_ACCOUNT"); // Populate card details (e.g., last 4 digits, expiry month/year, card brand) // request.setCard(...); try { // CardDetailsLookupResponse response = cardService.cardDetailsLookup(request); CardDetailsLookupResponse response = null; // Placeholder // Process the response to determine card details or validity System.out.println("Card details lookup performed."); } catch (Exception e) { System.err.println("Error performing card details lookup: " + e.getMessage()); } } } ``` -------------------------------- ### Error Code Checking Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Demonstrates how to check for specific error codes returned by the API. ```java import com.adyen.model.errors.ErrorDetail; import com.adyen.service.exception.ApiException; public class ErrorCodeCheck { public static void main(String[] args) { try { // Assume a service call that might throw an ApiException // paymentService.submit(request); } catch (ApiException e) { System.err.println("API Exception occurred: " + e.getMessage()); if (e.getError() != null && "12345".equals(e.getError().getErrorCode())) { System.out.println("Specific error code '12345' detected."); // Handle specific error code } // Handle other errors } catch (Exception e) { System.err.println("An unexpected error occurred: " + e.getMessage()); } } } ``` -------------------------------- ### RequestOptions Usage Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/types.md Demonstrates creating a RequestOptions object and setting an idempotency key and an additional custom service header. Use UUID for idempotency keys. ```java RequestOptions options = new RequestOptions() .idempotencyKey(UUID.randomUUID().toString()) .addAdditionalServiceHeader("X-Custom-Header", "value"); ``` -------------------------------- ### Session-Based Payment Flow Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/README.md Illustrates how to create a checkout session and later retrieve the payment result. This is suitable for scenarios where the session ID needs to be passed to the frontend. ```java // Create session CreateCheckoutSessionRequest request = new CreateCheckoutSessionRequest() .merchantAccount("YOUR_MERCHANT_ACCOUNT") .amount(new Amount().currency("EUR").value(10000L)) .reference("ORDER-456") .returnUrl("https://your-domain.com/return"); CreateCheckoutSessionResponse sessionResponse = paymentsApi.sessions(request); // Pass sessionId and sessionData to frontend String sessionId = sessionResponse.getId(); // Later: Get result SessionResultResponse result = paymentsApi.getResultOfPaymentSession( sessionId, sessionResultFromFrontend ); ``` -------------------------------- ### Configure API with Live Environment and US Region Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/types.md Example of setting the API configuration to use the LIVE environment and a specific terminal API region (US). ```java Config config = new Config() .environment(Environment.LIVE) .terminalApiRegion(Region.US); ``` -------------------------------- ### API Key Authentication Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Demonstrates how to authenticate API requests using an API key. This is one of five variants for API key authentication. ```java import com.adyen.Client; import com.adyen.service.Payment; // Example import, actual service may vary public class ApiKeyAuth { public static void main(String[] args) { // Replace with your actual API key and client key String apiKey = "YOUR_API_KEY"; String clientKey = "YOUR_CLIENT_KEY"; // If applicable String environment = "TEST"; // Or "LIVE" Client client = new Client(apiKey, clientKey, environment); // Further configuration can be done here if needed // Example: Initialize a service // Payment paymentService = new Payment(client); System.out.println("Client configured with API Key authentication."); } } ``` -------------------------------- ### Payment Flow with Modifications Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/ADDITIONAL_APIS.md This example illustrates a complete payment flow including authorization, capture, and partial refund using the Adyen Java API. ```APIDOC ## Payment Flow with Modifications ### Description This example demonstrates a complete payment flow including authorization, capture, and partial refund using the Adyen Java API. ### Methods - `paymentsApi.payments()`: Initiates a payment authorization. - `modificationsApi.captureAuthorisedPayment()`: Captures an authorized payment. - `modificationsApi.refundCapturedPayment()`: Refunds a captured payment. ### Request Body Examples #### Payment Request ```json { "merchantAccount": "YOUR_MERCHANT_ACCOUNT", "amount": { "currency": "EUR", "value": 10000 }, "reference": "ORDER-123", "paymentMethod": { ... } } ``` #### Capture Request ```json { "merchantAccount": "YOUR_MERCHANT_ACCOUNT", "amount": { "currency": "EUR", "value": 10000 }, "reference": "CAPTURE-123" } ``` #### Refund Request ```json { "merchantAccount": "YOUR_MERCHANT_ACCOUNT", "amount": { "currency": "EUR", "value": 2000 }, "reference": "REFUND-123" } ``` ### Response Examples #### Payment Response ```json { "pspReference": "YOUR_PSP_REFERENCE", ... } ``` #### Capture Response ```json { "pspReference": "YOUR_PSP_REFERENCE", ... } ``` #### Refund Response ```json { "pspReference": "YOUR_PSP_REFERENCE", ... } ``` ``` -------------------------------- ### Get Configuration Properties Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/configuration.md Demonstrates how to retrieve individual configuration properties using getter methods. These methods allow access to settings like API key, username, environment, and timeouts. ```java String apiKey = config.getApiKey(); String username = config.getUsername(); Environment env = config.getEnvironment(); String livePrefix = config.getLiveEndpointUrlPrefix(); int readTimeout = config.getReadTimeoutMillis(); Region region = config.getTerminalApiRegion(); SSLContext sslContext = config.getSSLContext(); ``` -------------------------------- ### Get Connected Devices Status Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/CloudDeviceApi.md Retrieve a list of connected payment terminals or SDK mobile installation IDs for a given merchant account. Use this to get a list of unique device identifiers. ```java ConnectedDevicesResponse connectedDevices = cloudDeviceApi.getConnectedDevices("myMerchant"); System.out.println(connectedDevices.getUniqueDeviceIds()); // [P400Plus-123456789, AMS1-000168242800763] ``` -------------------------------- ### Set up Adyen Client and Process Payment Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/00_START_HERE.txt This example demonstrates how to set up the Adyen client, create a PaymentsApi instance, and process a payment. It includes basic error handling for API exceptions. Ensure you replace placeholder values with your actual credentials and details. ```java Config config = new Config() .environment(Environment.TEST) .apiKey("YOUR_API_KEY"); Client client = new Client(config); PaymentsApi paymentsApi = new PaymentsApi(client); PaymentRequest request = new PaymentRequest() .merchantAccount("YOUR_MERCHANT_ACCOUNT") .amount(new Amount().currency("EUR").value(10000L)) .reference("ORDER-123") .paymentMethod(cardDetails) .returnUrl("https://your-domain.com/return"); try { PaymentResponse response = paymentsApi.payments(request); System.out.println("Status: " + response.getResultCode()); } catch (ApiException e) { System.err.println("Error: " + e.getError().getErrorCode()); } ``` -------------------------------- ### Get Device Status Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/CloudDeviceApi.md Check the status of a specific payment terminal or SDK mobile installation ID. ```APIDOC ## Get Device Status ### Description Checks and returns the current status of a specific payment terminal or SDK mobile installation ID for a given merchant. ### Method ```java cloudDeviceApi.getDeviceStatus(String merchantAccount, String deviceId) ``` ### Parameters #### Path Parameters - **merchantAccount** (String) - Required - The merchant account identifier. - **deviceId** (String) - Required - The unique identifier of the device (terminal or mobile installation). ### Response #### Success Response (200) - **DeviceStatusResponse** - An object containing the status of the device. - **status** (String) - The current status of the device (e.g., ONLINE, OFFLINE). ### Response Example ```json { "status": "ONLINE" } ``` ``` -------------------------------- ### Get Connected Devices Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/CloudDeviceApi.md Retrieve a list of connected payment terminals or SDK mobile installation IDs for a given merchant. ```APIDOC ## Get Connected Devices ### Description Retrieves a list of unique device identifiers for connected payment terminals or SDK mobile installations associated with a merchant. ### Method ```java cloudDeviceApi.getConnectedDevices(String merchantAccount) ``` ### Parameters #### Path Parameters - **merchantAccount** (String) - Required - The merchant account identifier. ### Response #### Success Response (200) - **ConnectedDevicesResponse** - An object containing a list of unique device identifiers. - **uniqueDeviceIds** (List) - A list of unique identifiers for the connected devices. ### Response Example ```json { "uniqueDeviceIds": [ "P400Plus-123456789", "AMS1-000168242800763" ] } ``` ``` -------------------------------- ### Create Client with API Key for TEST or LIVE Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Initializes a Client with an API Key, supporting both TEST and LIVE environments. For the LIVE environment, a specific live URL prefix must be provided. ```java Client client = new Client("YOUR_API_KEY", Environment.LIVE, "myCompany"); ``` -------------------------------- ### Get Specific Device Status Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/CloudDeviceApi.md Check the status of a specific payment terminal or SDK mobile installation ID for a given merchant account. This returns the current status, such as ONLINE. ```java DeviceStatusResponse deviceStatus = cloudDeviceApi.getDeviceStatus("myMerchant", "AMS1-000168242800763"); System.out.println(deviceStatus.getStatus()); // ONLINE ``` -------------------------------- ### Client() Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Creates a Client instance with empty configuration. Configuration properties must be set before using the client. ```APIDOC ## Client() ### Description Creates a Client instance with empty configuration. You must set configuration properties before using the client. ### Method Constructor ### Parameters None ### Request Example ```java Client client = new Client(); Config config = new Config() .apiKey("YOUR_API_KEY") .environment(Environment.TEST); client.setConfig(config); ``` ``` -------------------------------- ### Terminal Cloud API Request Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/doc/MigratingToCloudDeviceApi.md This snippet demonstrates how to construct and send a payment request using the Terminal Cloud API. It requires manual setup of most message header and transaction details. ```java import com.adyen.Client; import com.adyen.enums.Environment; import com.adyen.service.TerminalCloudAPI; import com.adyen.model.terminal.TerminalAPIRequest; import com.adyen.model.terminal.TerminalAPIResponse; import com.adyen.model.nexo.*; Client client = new Client("Your X-API-KEY", Environment.TEST); TerminalCloudAPI terminalCloudAPI = new TerminalCloudAPI(client); SaleToPOIRequest saleToPOIRequest = new SaleToPOIRequest(); MessageHeader messageHeader = new MessageHeader(); messageHeader.setProtocolVersion("3.0"); messageHeader.setMessageClass(MessageClassType.SERVICE); messageHeader.setMessageCategory(MessageCategoryType.PAYMENT); messageHeader.setMessageType(MessageType.REQUEST); messageHeader.setSaleID("001"); messageHeader.setServiceID("001"); messageHeader.setPOIID("P400Plus-123456789"); saleToPOIRequest.setMessageHeader(messageHeader); PaymentRequest paymentRequest = new PaymentRequest(); SaleData saleData = new SaleData(); TransactionIdentification transactionIdentification = new TransactionIdentification(); transactionIdentification.setTransactionID("001"); // Using XMLGregorianCalendar XMLGregorianCalendar timestamp = DatatypeFactory.newInstance() .newXMLGregorianCalendar(new GregorianCalendar()); transactionIdentification.setTimeStamp(timestamp); saleData.setSaleTransactionID(transactionIdentification); PaymentTransaction paymentTransaction = new PaymentTransaction(); AmountsReq amountsReq = new AmountsReq(); amountsReq.setCurrency("EUR"); amountsReq.setRequestedAmount(BigDecimal.ONE); paymentTransaction.setAmountsReq(amountsReq); paymentRequest.setSaleData(saleData); paymentRequest.setPaymentTransaction(paymentTransaction); saleToPOIRequest.setPaymentRequest(paymentRequest); TerminalAPIRequest terminalAPIRequest = new TerminalAPIRequest(); terminalAPIRequest.setSaleToPOIRequest(saleToPOIRequest); TerminalAPIResponse response = terminalCloudAPI.sync(terminalAPIRequest); ``` -------------------------------- ### Client(String, Environment, String) Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Creates a Client with API Key authentication for TEST or LIVE environments. ```APIDOC ## Client(String apiKey, Environment environment, String liveEndpointUrlPrefix) ### Description Creates a Client with API Key authentication for TEST or LIVE environments. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **apiKey** (String) - Required - Adyen API Key - **environment** (Environment) - Required - Environment (TEST or LIVE) - **liveEndpointUrlPrefix** (String) - Required (for LIVE) - Live URL prefix required for live integrations ### Request Example ```java Client client = new Client("YOUR_API_KEY", Environment.LIVE, "myCompany"); ``` ``` -------------------------------- ### Server Error Retry Handling Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Provides an example of how to implement retry logic for server-side errors. ```java import com.adyen.service.exception.ApiException; public class ServerRetryHandling { private static final int MAX_RETRIES = 3; private static final int INITIAL_BACKOFF_MILLIS = 1000; public void makeApiCallWithRetry(String requestData) { int retryCount = 0; long backoff = INITIAL_BACKOFF_MILLIS; while (retryCount < MAX_RETRIES) { try { // Assume this is the API call // performApiRequest(requestData); System.out.println("API call successful."); return; // Success } catch (ApiException e) { if (isRetryable(e)) { System.err.println("Retryable API error: " + e.getMessage() + ". Retrying in " + backoff + "ms..."); try { Thread.sleep(backoff); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); break; } backoff *= 2; // Exponential backoff retryCount++; } else { System.err.println("Non-retryable API error: " + e.getMessage()); break; // Non-retryable error } } catch (Exception e) { System.err.println("Unexpected error: " + e.getMessage()); break; } } System.err.println("API call failed after " + MAX_RETRIES + " retries."); } private boolean isRetryable(ApiException e) { // Implement logic to determine if the error is retryable // e.g., check for 5xx status codes or specific error codes return e.getHttpStatus() >= 500; } // Placeholder for the actual API request method // private void performApiRequest(String data) throws ApiException { // // Simulate an API call // if (Math.random() < 0.7) { // Simulate failure 70% of the time // throw new ApiException("Simulated server error", 503); // } // } } ``` -------------------------------- ### Client(String, String, Environment, String) Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Creates a Client with HTTP Basic authentication. ```APIDOC ## Client(String username, String password, Environment environment, String liveEndpointUrlPrefix) ### Description Creates a Client with HTTP Basic authentication. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **username** (String) - Required - HTTP basic username - **password** (String) - Required - HTTP basic password - **environment** (Environment) - Required - Environment (TEST or LIVE) - **liveEndpointUrlPrefix** (String) - Required (for LIVE) - Unique prefix for live environment endpoints ### Request Example ```java Client client = new Client("username", "password", Environment.LIVE, "myCompany"); ``` ``` -------------------------------- ### Comprehensive API Error Handling Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/REQUEST_OPTIONS_AND_ERROR_HANDLING.md A complete error handling example that covers `ApiException` for API-specific errors and `IOException` for network issues. It demonstrates extracting detailed information from `ApiError`, including validation errors and additional data, and handling common HTTP status codes. ```java import com.adyen.service.exception.ApiException; import java.io.IOException; try { PaymentResponse response = paymentsApi.payments(paymentRequest, requestOptions); String pspReference = response.getPspReference(); System.out.println("Payment processed: " + pspReference); } catch (ApiException e) { int statusCode = e.getStatusCode(); ApiError error = e.getError(); System.out.println("API Error - Status: " + statusCode); System.out.println("Message: " + e.getMessage()); if (error != null) { System.out.println("Error Code: " + error.getErrorCode()); System.out.println("Error Type: " + error.getErrorType()); System.out.println("Details: " + error.getMessage()); if (error.getInvalidFields() != null) { System.out.println("Validation Errors:"); for (InvalidField field : error.getInvalidFields()) { System.out.println(" - " + field.getName() + ": " + field.getMessage()); } } if (error.getAdditionalData() != null) { System.out.println("Additional Data: " + error.getAdditionalData()); } } if (statusCode == 401 || statusCode == 403) { // Handle authentication/authorization error System.out.println("Please check your credentials"); } } catch (IOException e) { // Handle network errors System.out.println("Network error: " + e.getMessage()); } ``` -------------------------------- ### Create Client with Config Object Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Initializes a Client instance using a pre-configured Config object. This is useful when you have all necessary settings like environment, live endpoint prefix, and API key ready. ```java Config config = new Config() .environment(Environment.LIVE) .liveEndpointUrlPrefix("myCompany") .apiKey("YOUR_API_KEY"); Client client = new Client(config); ``` -------------------------------- ### Accessing HttpMethod Enum Value Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/types.md Example of how to reference an HttpMethod constant. ```java ApiConstants.HttpMethod.POST ``` -------------------------------- ### Create Client with Empty Configuration Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Instantiates a Client with default empty configuration. You must explicitly set configuration properties like API key and environment before using the client. ```java Client client = new Client(); Config config = new Config() .apiKey("YOUR_API_KEY") .environment(Environment.TEST); client.setConfig(config); ``` -------------------------------- ### Initialize Balance Platform API Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/API_SERVICES_OVERVIEW.md Instantiate the Balance Platform API client for test environments. Ensure you replace 'YOUR_API_KEY' with your actual API key. ```java Config config = new Config() .environment(Environment.TEST) .apiKey("YOUR_API_KEY"); Client client = new Client(config); AccountHoldersApi accountHoldersApi = new AccountHoldersApi(client); ``` -------------------------------- ### Get available payment methods Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CHECKOUT_PAYMENTS_API.md Retrieves a list of payment methods available for the shopper. ```APIDOC ## POST /paymentMethods ### Description Get available payment methods. ### Method POST ### Endpoint /paymentMethods ### Request Body - **paymentMethodsRequest** (PaymentMethodsRequest) - Required - Request for available payment methods. ### Response #### Success Response (200) - **paymentMethodsResponse** (PaymentMethodsResponse) - A list of available payment methods. ``` -------------------------------- ### Create Client with API Key for TEST Environment Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Constructs a Client instance for the TEST environment using an API Key. This is a straightforward way to initialize the client for testing purposes. ```java Client client = new Client("YOUR_API_KEY", Environment.TEST); ``` -------------------------------- ### Get Result of Payment Session Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CHECKOUT_PAYMENTS_API.md Retrieves the result of a payment initiated through a checkout session. ```APIDOC ## GET /results/{sessionId} ### Description Retrieves the final status and details of a payment that was processed via a checkout session. ### Method GET ### Endpoint /results/{sessionId} ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the checkout session. #### Query Parameters - **sessionResult** (string) - Required - The result token obtained from the frontend after the user completes the payment. ### Response #### Success Response (200) - **status** (string) - The status of the payment (e.g., "Authorised"). - **pspReference** (string) - The Adyen payment reference. #### Response Example ```json { "status": "Authorised", "pspReference": "YOUR_PSP_REFERENCE" } ``` ``` -------------------------------- ### Client(String, Environment) Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Creates a Client with API Key authentication for the TEST environment. ```APIDOC ## Client(String apiKey, Environment environment) ### Description Creates a Client with API Key authentication for TEST environment. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **apiKey** (String) - Required - Adyen API Key - **environment** (Environment) - Required - Environment (TEST or LIVE) ### Request Example ```java Client client = new Client("YOUR_API_KEY", Environment.TEST); ``` ``` -------------------------------- ### Configure Adyen API Client with Live Environment Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Sets up the Adyen API client configuration for the live environment using a fluent builder pattern. This example demonstrates setting the environment, live endpoint URL prefix, API key, and custom connection/read timeouts. ```java Config config = new Config() .environment(Environment.LIVE) .liveEndpointUrlPrefix("myCompany") .apiKey("YOUR_API_KEY") .connectionTimeoutMillis(10000) .readTimeoutMillis(15000); ``` -------------------------------- ### Validation Error Handling Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Illustrates how to handle validation errors that occur during request processing. ```java import com.adyen.model.errors.ErrorDetail; import com.adyen.service.exception.ApiException; public class ValidationErrorHandling { public static void main(String[] args) { try { // Assume a service call that might throw an ApiException due to validation issues // paymentService.submit(request); } catch (ApiException e) { System.err.println("API Exception during validation: " + e.getMessage()); if (e.getError() != null && "validationErrors".equals(e.getError().getReason())) { System.out.println("Validation errors found:"); for (ErrorDetail errorDetail : e.getError().getErrorDetails()) { System.out.println("- Field: " + errorDetail.getField() + ", Message: " + errorDetail.getMessage()); } // Handle validation errors, e.g., prompt user to correct input } } } } ``` -------------------------------- ### Setup Client and Make Payments API Call with API Key Source: https://github.com/adyen/adyen-java-api-library/blob/main/README.md Configure the Adyen client using an API key and environment settings, then make a payment request. For live environments, ensure the Live URL Prefix is set. ```java // Import the required classes import com.adyen.Client; import com.adyen.enums.Environment; import com.adyen.service.checkout.PaymentsApi; import com.adyen.model.checkout.*; // Setup Client using Config object Config config = new Config() .environment(Environment.LIVE) .liveEndpointUrlPrefix("myCompany") .apiKey(apiKey); Client client = new Client(config); PaymentsApi paymentsApi = new PaymentsApi(client); // Create PaymentRequest CardDetails cardDetails = new CardDetails() .type(CardDetails.TypeEnum.SCHEME) .encryptedCardNumber("ENCRYPTED_CARD_NUMBER") .holderName("John Doe") .cvc("737") .encryptedExpiryMonth("08") .encryptedExpiryYear("2018"); PaymentRequest paymentRequest = new PaymentRequest() .merchantAccount("YOUR_MERCHANT_ACCOUNT") .reference("YOUR_REFERENCE") .amount(new Amount() .currency("EUR") .value(1000L)) .returnUrl("https://your-company.example.org/checkout?shopperOrder=12xy..") .paymentMethod(new CheckoutPaymentMethod(cardDetails)); // Make a call to the /payments endpoint PaymentResponse paymentResponse = paymentsApi.payments(paymentRequest); ``` -------------------------------- ### Initialize Management API Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/API_SERVICES_OVERVIEW.md Instantiate the Management API client for live environments. Configure the live endpoint URL prefix and replace 'YOUR_API_KEY' with your actual API key. ```java Config config = new Config() .environment(Environment.LIVE) .liveEndpointUrlPrefix("myCompany") .apiKey("YOUR_API_KEY"); Client client = new Client(config); ManagementApi managementApi = new ManagementApi(client); ``` -------------------------------- ### Webhook HMAC Validation Example Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/INDEX.md Demonstrates how to validate incoming webhook requests using HMAC signatures. ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class WebhookValidation { private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; public boolean isValidSignature(String requestBody, String adyenSignatureHeader, String hmacKey) { try { Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); SecretKeySpec secretKey = new SecretKeySpec(hmacKey.getBytes(StandardCharsets.UTF_8), HMAC_SHA256_ALGORITHM); mac.init(secretKey); byte[] hmacBytes = mac.doFinal(requestBody.getBytes(StandardCharsets.UTF_8)); String calculatedSignature = Base64.getEncoder().encodeToString(hmacBytes); // Compare the calculated signature with the one provided in the header // Use a constant-time comparison to prevent timing attacks return constantTimeEquals(calculatedSignature, adyenSignatureHeader); } catch (Exception e) { System.err.println("Error validating signature: " + e.getMessage()); return false; } } // Constant-time string comparison to prevent timing attacks private boolean constantTimeEquals(String a, String b) { if (a.length() != b.length()) { return false; } int result = 0; for (int i = 0; i < a.length(); i++) { result |= a.charAt(i) ^ b.charAt(i); } return result == 0; } // Example usage: // public void handleWebhook(HttpServletRequest request) throws IOException { // String requestBody = ... // Read request body // String adyenSignatureHeader = request.getHeader("Adyen-Signature"); // String hmacKey = "YOUR_HMAC_KEY"; // Get from Adyen Customer Area // // if (isValidSignature(requestBody, adyenSignatureHeader, hmacKey)) { // System.out.println("Webhook signature is valid."); // // Process the webhook // } else { // System.err.println("Invalid webhook signature."); // // Reject the webhook // } // } } ``` -------------------------------- ### Configure Client Certificate Authentication Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/configuration.md Set up the client for live production using client certificate authentication. This involves initializing an SSL context with a keystore and password. ```java // Setup SSL context with client certificate KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(loadClientKeystore(), clientKeyPassword); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(keyManagerFactory.getKeyManagers(), null, null); Config config = new Config() .environment(Environment.LIVE) .liveEndpointUrlPrefix("myCompany") .apiKey("YOUR_API_KEY") .sslContext(sslContext) .connectionTimeoutMillis(10000) .readTimeoutMillis(15000); Client client = new Client(config); ``` -------------------------------- ### Client(String, String, Environment, String, String) Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CLIENT_AND_CONFIG.md Creates a Client with HTTP Basic authentication and an application name tag. ```APIDOC ## Client(String username, String password, Environment environment, String liveEndpointUrlPrefix, String applicationName) ### Description Creates a Client with HTTP Basic authentication and an application name tag. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **username** (String) - Required - HTTP basic username - **password** (String) - Required - HTTP basic password - **environment** (Environment) - Required - Environment (TEST or LIVE) - **liveEndpointUrlPrefix** (String) - Required (for LIVE) - Unique prefix for live endpoints - **applicationName** (String) - Optional - Application identifier in User-Agent header ### Request Example ```java Client client = new Client("username", "password", Environment.LIVE, "myCompany", "myApplication"); ``` ``` -------------------------------- ### Get card brand details Source: https://github.com/adyen/adyen-java-api-library/blob/main/_autodocs/api-reference/CHECKOUT_PAYMENTS_API.md Retrieves details about a card brand based on the provided card number. ```APIDOC ## POST /cardDetails ### Description Get card brand details. ### Method POST ### Endpoint /cardDetails ### Request Body - **cardDetailsRequest** (CardDetailsRequest) - Required - Request for card brand details. ### Response #### Success Response (200) - **cardDetailsResponse** (CardDetailsResponse) - The card brand and associated details. ```