diff --git a/.github/workflows/sonar_scanner.yml b/.github/workflows/sonar_scanner.yml new file mode 100644 index 0000000..ead990e --- /dev/null +++ b/.github/workflows/sonar_scanner.yml @@ -0,0 +1,39 @@ +name: Run SonarCloud Scan + +on: + workflow_call: + workflow_dispatch: + +jobs: + sonar-scan: + runs-on: ubuntu-20.04 + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + # Shallow clones should be disabled for a better relevancy of analysis + fetch-depth: 0 + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'adopt' + - name: Cache Gradle packages + uses: actions/cache@v4 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*') }} + restore-keys: ${{ runner.os }}-gradle + - name: Cache SonarCloud packages + uses: actions/cache@v4 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + - name: Build and analyze + run: ./gradlew build jacocoTestReport sonarqube --info + env: + # Needed to get some information about the pull request, if any + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # SonarCloud access token should be generated from https://sonarcloud.io/account/security/ + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 14b837c..e69e644 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,10 +26,10 @@ jobs: with: java-version: ${{ matrix.java }} distribution: 'adopt' - - name: Setup Gradle 8.8 + - name: Setup Gradle 8.9 uses: gradle/actions/setup-gradle@v3 with: - gradle-version: 8.8 + gradle-version: 8.9 - name: Test run: | ./gradlew :lib:test diff --git a/.github/workflows/test_and_build.yml b/.github/workflows/test_and_build.yml index b23022d..7295452 100644 --- a/.github/workflows/test_and_build.yml +++ b/.github/workflows/test_and_build.yml @@ -10,8 +10,12 @@ jobs: test: uses: ./.github/workflows/test.yml - build-and-publish: + sonar-scan: needs: [test] + uses: ./.github/workflows/sonar_scanner.yml + + build-and-publish: + needs: [test, sonar-scan] runs-on: ubuntu-20.04 steps: - name: Checkout code @@ -21,10 +25,10 @@ jobs: with: java-version: '17' distribution: 'adopt' - - name: Setup Gradle 8.8 + - name: Setup Gradle 8.9 uses: gradle/actions/setup-gradle@v3 with: - gradle-version: 8.8 + gradle-version: 8.9 - name: Build Lib run: ./gradlew :lib:build - name: Publish package diff --git a/README.md b/README.md index bf3e835..b3e3b80 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ class App { This repo contains a demo app that showcases how to implement common use cases, like a [Step-by-Step Checkout](https://docs.payone.com/pcp/checkout-flows/step-by-step-checkout) and an [One-Stop-Checkout](https://docs.payone.com/pcp/checkout-flows/one-step-checkout). For each use case the demo app contains a private method in the top level class `App`. You can run the app to execute the code within in the sandbox API. This is a good way to test, if your setup is correct. -If you're using grald can run it within the demo app directory via: +If you're using gradle can run it within the demo app directory via: ```sh API_KEY=api_key API_SECRET=api_secret MERCHANT_ID=123 COMMERCE_CASE_ID=234 CHECKOUT_ID=345 ./gradlew :app:run diff --git a/app/src/main/java/com/payone/commerce/platform/app/App.java b/app/src/main/java/com/payone/commerce/platform/app/App.java index e9990f4..0f2cf01 100644 --- a/app/src/main/java/com/payone/commerce/platform/app/App.java +++ b/app/src/main/java/com/payone/commerce/platform/app/App.java @@ -52,321 +52,343 @@ import com.payone.commerce.platform.lib.models.ShoppingCartInput; public class App { - private final String MERCHANT_ID; - private final CommunicatorConfiguration config; - private final CommerceCaseApiClient commerceCaseClient; - private final CheckoutApiClient checkoutClient; - private final OrderManagementCheckoutActionsApiClient orderManagementCheckoutClient; - private final PaymentExecutionApiClient paymentExecutionClient; + private final String MERCHANT_ID; + private final CommunicatorConfiguration config; + private final CommerceCaseApiClient commerceCaseClient; + private final CheckoutApiClient checkoutClient; + private final OrderManagementCheckoutActionsApiClient orderManagementCheckoutClient; + private final PaymentExecutionApiClient paymentExecutionClient; - public App(String API_KEY, String API_SECRET, String MERCHANT_ID) { - this.MERCHANT_ID = MERCHANT_ID; - this.config = new CommunicatorConfiguration(API_KEY, API_SECRET, "preprod.commerce-api.payone.com"); - try { - this.commerceCaseClient = new CommerceCaseApiClient(config); - this.checkoutClient = new CheckoutApiClient(config); - this.orderManagementCheckoutClient = new OrderManagementCheckoutActionsApiClient(config); - this.paymentExecutionClient = new PaymentExecutionApiClient(config); - } catch (InvalidKeyException e) { - throw new RuntimeException("Expected key to be valid", e); + public App(String API_KEY, String API_SECRET, String MERCHANT_ID) { + this.MERCHANT_ID = MERCHANT_ID; + this.config = new CommunicatorConfiguration(API_KEY, API_SECRET, "preprod.commerce-api.payone.com", + "YOUR_SHOP_NAME"); + try { + this.commerceCaseClient = new CommerceCaseApiClient(config); + this.checkoutClient = new CheckoutApiClient(config); + this.orderManagementCheckoutClient = new OrderManagementCheckoutActionsApiClient(config); + this.paymentExecutionClient = new PaymentExecutionApiClient(config); + } catch (InvalidKeyException e) { + throw new RuntimeException("Expected key to be valid", e); + } } - } - private static App initFromEnv() { - String apiKey = System.getenv("API_KEY"); - String apiSecret = System.getenv("API_SECRET"); - String merchantId = System.getenv("MERCHANT_ID"); + private static App initFromEnv() { + String apiKey = System.getenv("API_KEY"); + String apiSecret = System.getenv("API_SECRET"); + String merchantId = System.getenv("MERCHANT_ID"); - if (apiKey == null) { - throw new RuntimeException("required environment variable API_KEY is not set"); - } - if (apiSecret == null) { - throw new RuntimeException("required environment variable API_SECRET is not set"); - } - if (merchantId == null) { - throw new RuntimeException("required environment variable MERCHANT_ID is not set"); - } - - return new App(apiKey, apiSecret, merchantId); - } - - private void runCheckoutWithPaymentExecution(String commerceCaseMerchantReference) - throws IOException, ApiException { - // Create a commerce case, add customer data, put something into the shopping - // cart - CreateCommerceCaseRequest createCommerceCaseRequest = new CreateCommerceCaseRequest(); - - Customer customer = new Customer(); - PersonalInformation personalInformation = new PersonalInformation() - .dateOfBirth("19991112") - .name(new PersonalName().firstName("Ryan").surname("Carniato")); - ContactDetails contactDetails = new ContactDetails().emailAddress("mail@mail.com"); - Address address = new Address() - .countryCode("DE") - .zip("24937") - .city("Flensburg") - .street("Rathausplatz") - .houseNumber("1"); - customer.setPersonalInformation(personalInformation); - customer.setContactDetails(contactDetails); - customer.billingAddress(address); - - CreateCheckoutRequest checkoutRequest = new CreateCheckoutRequest(); - AmountOfMoney amountOfMoney = new AmountOfMoney() - .amount(3599L) - .currencyCode("EUR"); - Shipping shipping = new Shipping() - .address(new AddressPersonal() - .countryCode("DE") - .zip("24937") - .city("Flensburg") - .street("Rathausplatz").houseNumber("1")); - ShoppingCartInput shoppingCart = new ShoppingCartInput(); - CartItemInput cartItem = new CartItemInput() - .invoiceData(new CartItemInvoiceData() - .description("T-Shirt - Scaleshape Logo - S")) - .orderLineDetails(new OrderLineDetailsInput() - .productPrice(3599L) - .quantity(1L) - .productType(ProductType.GOODS)); - shoppingCart.addItemsItem(cartItem); + if (apiKey == null) { + throw new RuntimeException("required environment variable API_KEY is not set"); + } + if (apiSecret == null) { + throw new RuntimeException("required environment variable API_SECRET is not set"); + } + if (merchantId == null) { + throw new RuntimeException("required environment variable MERCHANT_ID is not set"); + } - checkoutRequest.amountOfMoney(amountOfMoney) - .shoppingCart(shoppingCart) - .shipping(shipping); + return new App(apiKey, apiSecret, merchantId); + } - createCommerceCaseRequest - .merchantReference(commerceCaseMerchantReference) - .customer(customer) - .checkout(checkoutRequest); + private void runCheckoutWithPaymentExecution(String commerceCaseMerchantReference) + throws IOException, ApiException { + // Create a commerce case, add customer data, put something into the shopping + // cart + CreateCommerceCaseRequest createCommerceCaseRequest = new CreateCommerceCaseRequest(); - CreateCommerceCaseResponse commerceCase = commerceCaseClient.createCommerceCaseRequest( - MERCHANT_ID, - createCommerceCaseRequest); + Customer customer = new Customer(); + PersonalInformation personalInformation = new PersonalInformation() + .dateOfBirth("19991112") + .name(new PersonalName().firstName("Ryan").surname("Carniato")); + ContactDetails contactDetails = new ContactDetails().emailAddress("mail@mail.com"); + Address address = new Address() + .countryCode("DE") + .zip("24937") + .city("Flensburg") + .street("Rathausplatz") + .houseNumber("1"); + customer.setPersonalInformation(personalInformation); + customer.setContactDetails(contactDetails); + customer.billingAddress(address); - PaymentExecutionRequest paymentExecutionRequest = new PaymentExecutionRequest() - .paymentExecutionSpecificInput(new PaymentExecutionSpecificInput() - .paymentReferences(new References().merchantReference("p-" + commerceCaseMerchantReference)) - .amountOfMoney(new AmountOfMoney() + CreateCheckoutRequest checkoutRequest = new CreateCheckoutRequest(); + AmountOfMoney amountOfMoney = new AmountOfMoney() .amount(3599L) - .currencyCode("EUR"))) - .paymentMethodSpecificInput(new PaymentMethodSpecificInput() - .sepaDirectDebitPaymentMethodSpecificInput(new SepaDirectDebitPaymentMethodSpecificInput() - .paymentProductId(771) - .paymentProduct771SpecificInput(new SepaDirectDebitPaymentProduct771SpecificInput() - .mandate(new ProcessingMandateInformation() - .bankAccountIban(new BankAccountInformation() - .iban("DE75512108001245126199") - .accountHolder("Ryan Carniato")) - .dateOfSignature("20240730") - .recurrenceType(MandateRecurrenceType.UNIQUE) - .uniqueMandateReference("m-" + commerceCaseMerchantReference) - .creditorId("DE98ZZZ09999999999"))))); - CreatePaymentResponse paymentResponse = this.paymentExecutionClient.createPayment(MERCHANT_ID, - commerceCase.getCommerceCaseId().toString(), - commerceCase.getCheckout().getCheckoutId().toString(), paymentExecutionRequest); - System.out.println(paymentResponse); - - CheckoutResponse finalCheckout = this.checkoutClient.getCheckoutRequest( - MERCHANT_ID, - commerceCase.getCommerceCaseId().toString(), - commerceCase.getCheckout().getCheckoutId().toString()); - System.out.println(finalCheckout); - } - - private void runSingleStepCheckout(String commerceCaseMerchantReference) - throws IOException, ApiException { - CreateCommerceCaseRequest payload = new CreateCommerceCaseRequest(); - - Customer customer = new Customer(); - PersonalInformation personalInformation = new PersonalInformation() - .dateOfBirth("19840505") - .name(new PersonalName().firstName("Rich").surname("Harris")); - ContactDetails contactDetails = new ContactDetails().emailAddress("mail@mail.com"); - Address address = new Address() - .countryCode("DE") - .zip("40474") - .city("Düsseldorf") - .street("Cecilienallee") - .houseNumber("2"); - customer.setPersonalInformation(personalInformation); - customer.setContactDetails(contactDetails); - customer.billingAddress(address); + .currencyCode("EUR"); + Shipping shipping = new Shipping() + .address(new AddressPersonal() + .countryCode("DE") + .zip("24937") + .city("Flensburg") + .street("Rathausplatz").houseNumber("1")); + ShoppingCartInput shoppingCart = new ShoppingCartInput(); + CartItemInput cartItem = new CartItemInput() + .invoiceData(new CartItemInvoiceData() + .description("T-Shirt - Scaleshape Logo - S")) + .orderLineDetails(new OrderLineDetailsInput() + .productPrice(3599L) + .quantity(1L) + .productType(ProductType.GOODS)); + shoppingCart.addItemsItem(cartItem); - CreateCheckoutRequest checkout = new CreateCheckoutRequest(); + checkoutRequest.amountOfMoney(amountOfMoney) + .shoppingCart(shoppingCart) + .shipping(shipping); - CheckoutReferences checkoutReferences = new CheckoutReferences() - .merchantReference("c-" + commerceCaseMerchantReference); - AmountOfMoney amountOfMoney = new AmountOfMoney() - .amount(5199L) - .currencyCode("EUR"); - Shipping shipping = new Shipping() - .address(new AddressPersonal() - .countryCode("DE") - .zip("40474") - .city("Düsseldorf") - .street("Cecilienallee").houseNumber("2")); - ShoppingCartInput shoppingCart = new ShoppingCartInput(); - CartItemInput cartItem = new CartItemInput() - .invoiceData(new CartItemInvoiceData() - .description("Hoodie - Scaleshape Logo - L")) - .orderLineDetails(new OrderLineDetailsInput() - .productPrice(5199L) - .quantity(1L) - .productType(ProductType.GOODS)); - shoppingCart.addItemsItem(cartItem); + createCommerceCaseRequest + .merchantReference(commerceCaseMerchantReference) + .customer(customer) + .checkout(checkoutRequest); - OrderRequest orderRequest = new OrderRequest() - .orderReferences(new References().merchantReference("o-" + commerceCaseMerchantReference)) - .paymentMethodSpecificInput(new PaymentMethodSpecificInput() - .sepaDirectDebitPaymentMethodSpecificInput(new SepaDirectDebitPaymentMethodSpecificInput() - .paymentProductId(771) - .paymentProduct771SpecificInput(new SepaDirectDebitPaymentProduct771SpecificInput() - .mandate(new ProcessingMandateInformation() - .bankAccountIban(new BankAccountInformation() - .iban("DE75512108001245126199") - .accountHolder("Rich Harris")) - .dateOfSignature("20240730") - .recurrenceType(MandateRecurrenceType.UNIQUE) - .uniqueMandateReference("m-" + commerceCaseMerchantReference) - .creditorId("DE98ZZZ09999999999"))))); + CreateCommerceCaseResponse commerceCase = commerceCaseClient.createCommerceCaseRequest( + MERCHANT_ID, + createCommerceCaseRequest); - checkout - .references(checkoutReferences) - .amountOfMoney(amountOfMoney) - .shipping(shipping) - .shoppingCart(shoppingCart) - .orderRequest(orderRequest); + PaymentExecutionRequest paymentExecutionRequest = new PaymentExecutionRequest() + .paymentExecutionSpecificInput(new PaymentExecutionSpecificInput() + .paymentReferences(new References().merchantReference( + "p-" + commerceCaseMerchantReference)) + .amountOfMoney(new AmountOfMoney() + .amount(3599L) + .currencyCode("EUR"))) + .paymentMethodSpecificInput(new PaymentMethodSpecificInput() + .sepaDirectDebitPaymentMethodSpecificInput( + new SepaDirectDebitPaymentMethodSpecificInput() + .paymentProductId(771) + .paymentProduct771SpecificInput( + new SepaDirectDebitPaymentProduct771SpecificInput() + .mandate(new ProcessingMandateInformation() + .bankAccountIban( + new BankAccountInformation() + .iban("DE75512108001245126199") + .accountHolder("Ryan Carniato")) + .dateOfSignature( + "20240730") + .recurrenceType(MandateRecurrenceType.UNIQUE) + .uniqueMandateReference( + "m-" + commerceCaseMerchantReference) + .creditorId("DE98ZZZ09999999999"))))); + CreatePaymentResponse paymentResponse = this.paymentExecutionClient.createPayment(MERCHANT_ID, + commerceCase.getCommerceCaseId().toString(), + commerceCase.getCheckout().getCheckoutId().toString(), paymentExecutionRequest); + System.out.println(paymentResponse); - payload.setMerchantReference(commerceCaseMerchantReference); - payload.checkout(checkout); - payload.customer(customer); + CheckoutResponse finalCheckout = this.checkoutClient.getCheckoutRequest( + MERCHANT_ID, + commerceCase.getCommerceCaseId().toString(), + commerceCase.getCheckout().getCheckoutId().toString()); + System.out.println(finalCheckout); + } - CreateCommerceCaseResponse commerceCase = commerceCaseClient.createCommerceCaseRequest(MERCHANT_ID, - payload); - System.out.println(commerceCase); - } + private void runSingleStepCheckout(String commerceCaseMerchantReference) + throws IOException, ApiException { + CreateCommerceCaseRequest payload = new CreateCommerceCaseRequest(); - private void runMultiStepCheckout(String commerceCaseMerchantReference) - throws IOException, ApiException { - // create the commercase - CreateCommerceCaseRequest createCommerceCaseRequest = new CreateCommerceCaseRequest() - .customer(new Customer() - .businessRelation("B2C") - .locale("de") - .personalInformation(new PersonalInformation().dateOfBirth("19840604") - .name(new PersonalName().firstName("Rich").surname("Harris"))) - .contactDetails(new ContactDetails().emailAddress("mail@mail.com")) - .billingAddress(new Address() + Customer customer = new Customer(); + PersonalInformation personalInformation = new PersonalInformation() + .dateOfBirth("19840505") + .name(new PersonalName().firstName("Rich").surname("Harris")); + ContactDetails contactDetails = new ContactDetails().emailAddress("mail@mail.com"); + Address address = new Address() .countryCode("DE") .zip("40474") .city("Düsseldorf") .street("Cecilienallee") - .houseNumber("2"))) - .checkout(new CreateCheckoutRequest() - .shoppingCart(new ShoppingCartInput() - .items(Arrays.asList(new CartItemInput() - .invoiceData(new CartItemInvoiceData() - .description("Frankenstein - Mary Shelley - Hardcover")) - .orderLineDetails(new OrderLineDetailsInput() - .productCode("shelley-42") - .productPrice(1999L) - .quantity(1L) - .productType(ProductType.GOODS) - .taxAmount(19L)))))); - CreateCommerceCaseResponse initialCommerceCase = this.commerceCaseClient.createCommerceCaseRequest(MERCHANT_ID, - createCommerceCaseRequest); - // add shipping information - PatchCheckoutRequest patchCheckoutRequest = new PatchCheckoutRequest() - .shipping(new Shipping() - .address(new AddressPersonal() - .countryCode("DE") - .zip("40474") - .city("Düsseldorf") - .street("Cecilienallee") - .houseNumber("2"))); - this.checkoutClient.updateCheckoutRequest( - MERCHANT_ID, - initialCommerceCase.getCommerceCaseId().toString(), - initialCommerceCase.getCheckout().getCheckoutId().toString(), - patchCheckoutRequest); + .houseNumber("2"); + customer.setPersonalInformation(personalInformation); + customer.setContactDetails(contactDetails); + customer.billingAddress(address); + + CreateCheckoutRequest checkout = new CreateCheckoutRequest(); - // confirm the order - OrderRequest orderRequest = new OrderRequest() - .orderType(OrderType.FULL) - .orderReferences(new References().merchantReference("o-" + commerceCaseMerchantReference)) - .paymentMethodSpecificInput(new PaymentMethodSpecificInput() - .paymentChannel(PaymentChannel.ECOMMERCE) - .sepaDirectDebitPaymentMethodSpecificInput(new SepaDirectDebitPaymentMethodSpecificInput() - .paymentProductId(771) - .paymentProduct771SpecificInput(new SepaDirectDebitPaymentProduct771SpecificInput() - .mandate(new ProcessingMandateInformation() - .bankAccountIban(new BankAccountInformation() - .iban("DE75512108001245126199") - .accountHolder("Rich Harris")) - .dateOfSignature("20240730") - .recurrenceType(MandateRecurrenceType.UNIQUE) - .uniqueMandateReference("m-" + commerceCaseMerchantReference) - .creditorId("DE98ZZZ09999999999"))))); - this.orderManagementCheckoutClient.createOrder( - MERCHANT_ID, - initialCommerceCase.getCommerceCaseId().toString(), - initialCommerceCase.getCheckout().getCheckoutId().toString(), - orderRequest); + CheckoutReferences checkoutReferences = new CheckoutReferences() + .merchantReference("c-" + commerceCaseMerchantReference); + AmountOfMoney amountOfMoney = new AmountOfMoney() + .amount(5199L) + .currencyCode("EUR"); + Shipping shipping = new Shipping() + .address(new AddressPersonal() + .countryCode("DE") + .zip("40474") + .city("Düsseldorf") + .street("Cecilienallee").houseNumber("2")); + ShoppingCartInput shoppingCart = new ShoppingCartInput(); + CartItemInput cartItem = new CartItemInput() + .invoiceData(new CartItemInvoiceData() + .description("Hoodie - Scaleshape Logo - L")) + .orderLineDetails(new OrderLineDetailsInput() + .productPrice(5199L) + .quantity(1L) + .productType(ProductType.GOODS)); + shoppingCart.addItemsItem(cartItem); - CheckoutResponse finalCheckout = this.checkoutClient.getCheckoutRequest( - MERCHANT_ID, - initialCommerceCase.getCommerceCaseId().toString(), - initialCommerceCase.getCheckout().getCheckoutId().toString()); - System.out.println(finalCheckout); + OrderRequest orderRequest = new OrderRequest() + .orderReferences(new References() + .merchantReference("o-" + commerceCaseMerchantReference)) + .paymentMethodSpecificInput(new PaymentMethodSpecificInput() + .sepaDirectDebitPaymentMethodSpecificInput( + new SepaDirectDebitPaymentMethodSpecificInput() + .paymentProductId(771) + .paymentProduct771SpecificInput( + new SepaDirectDebitPaymentProduct771SpecificInput() + .mandate(new ProcessingMandateInformation() + .bankAccountIban( + new BankAccountInformation() + .iban("DE75512108001245126199") + .accountHolder("Rich Harris")) + .dateOfSignature( + "20240730") + .recurrenceType(MandateRecurrenceType.UNIQUE) + .uniqueMandateReference( + "m-" + commerceCaseMerchantReference) + .creditorId("DE98ZZZ09999999999"))))); - // items are ready for shipment, the delivery can be performed to capture the - // money from the reservation - DeliverResponse delivery = this.orderManagementCheckoutClient.deliverOrder( - MERCHANT_ID, - initialCommerceCase.getCommerceCaseId().toString(), - initialCommerceCase.getCheckout().getCheckoutId().toString(), - new DeliverRequest().deliverType(DeliverType.FULL).isFinal(true)); - System.out.println(delivery); - } + checkout + .references(checkoutReferences) + .amountOfMoney(amountOfMoney) + .shipping(shipping) + .shoppingCart(shoppingCart) + .orderRequest(orderRequest); - public static void main(String[] args) { - App app = initFromEnv(); + payload.setMerchantReference(commerceCaseMerchantReference); + payload.checkout(checkout); + payload.customer(customer); - // creates a checkout and executes the payment in one go - try { - app.runCheckoutWithPaymentExecution("comc1a5"); - } catch (ApiErrorResponseException e) { - for (APIError error : e.getErrors()) { - System.err.println(error.getMessage()); - } - System.exit(1); - } catch (Exception e) { - throw new RuntimeException(e); + CreateCommerceCaseResponse commerceCase = commerceCaseClient.createCommerceCaseRequest(MERCHANT_ID, + payload); + System.out.println(commerceCase); } - // see: https://docs.payone.com/pcp/checkout-flows/step-by-step-checkout - // not that the given reference must be unique and has to renewed after each run - try { - app.runMultiStepCheckout("comc1a1"); - } catch (ApiErrorResponseException e) { - for (APIError error : e.getErrors()) { - System.err.println(error.getMessage()); - } - } catch (Exception e) { - throw new RuntimeException(e); + private void runMultiStepCheckout(String commerceCaseMerchantReference) + throws IOException, ApiException { + // create the commercase + CreateCommerceCaseRequest createCommerceCaseRequest = new CreateCommerceCaseRequest() + .customer(new Customer() + .businessRelation("B2C") + .locale("de") + .personalInformation(new PersonalInformation().dateOfBirth("19840604") + .name(new PersonalName().firstName("Rich") + .surname("Harris"))) + .contactDetails(new ContactDetails().emailAddress("mail@mail.com")) + .billingAddress(new Address() + .countryCode("DE") + .zip("40474") + .city("Düsseldorf") + .street("Cecilienallee") + .houseNumber("2"))) + .checkout(new CreateCheckoutRequest() + .shoppingCart(new ShoppingCartInput() + .items(Arrays.asList(new CartItemInput() + .invoiceData(new CartItemInvoiceData() + .description("Frankenstein - Mary Shelley - Hardcover")) + .orderLineDetails( + new OrderLineDetailsInput() + .productCode("shelley-42") + .productPrice(1999L) + .quantity(1L) + .productType(ProductType.GOODS) + .taxAmount(19L)))))); + CreateCommerceCaseResponse initialCommerceCase = this.commerceCaseClient.createCommerceCaseRequest( + MERCHANT_ID, + createCommerceCaseRequest); + // add shipping information + PatchCheckoutRequest patchCheckoutRequest = new PatchCheckoutRequest() + .shipping(new Shipping() + .address(new AddressPersonal() + .countryCode("DE") + .zip("40474") + .city("Düsseldorf") + .street("Cecilienallee") + .houseNumber("2"))); + this.checkoutClient.updateCheckoutRequest( + MERCHANT_ID, + initialCommerceCase.getCommerceCaseId().toString(), + initialCommerceCase.getCheckout().getCheckoutId().toString(), + patchCheckoutRequest); + + // confirm the order + OrderRequest orderRequest = new OrderRequest() + .orderType(OrderType.FULL) + .orderReferences(new References() + .merchantReference("o-" + commerceCaseMerchantReference)) + .paymentMethodSpecificInput(new PaymentMethodSpecificInput() + .paymentChannel(PaymentChannel.ECOMMERCE) + .sepaDirectDebitPaymentMethodSpecificInput( + new SepaDirectDebitPaymentMethodSpecificInput() + .paymentProductId(771) + .paymentProduct771SpecificInput( + new SepaDirectDebitPaymentProduct771SpecificInput() + .mandate(new ProcessingMandateInformation() + .bankAccountIban( + new BankAccountInformation() + .iban("DE75512108001245126199") + .accountHolder("Rich Harris")) + .dateOfSignature( + "20240730") + .recurrenceType(MandateRecurrenceType.UNIQUE) + .uniqueMandateReference( + "m-" + commerceCaseMerchantReference) + .creditorId("DE98ZZZ09999999999"))))); + this.orderManagementCheckoutClient.createOrder( + MERCHANT_ID, + initialCommerceCase.getCommerceCaseId().toString(), + initialCommerceCase.getCheckout().getCheckoutId().toString(), + orderRequest); + + CheckoutResponse finalCheckout = this.checkoutClient.getCheckoutRequest( + MERCHANT_ID, + initialCommerceCase.getCommerceCaseId().toString(), + initialCommerceCase.getCheckout().getCheckoutId().toString()); + System.out.println(finalCheckout); + + // items are ready for shipment, the delivery can be performed to capture the + // money from the reservation + DeliverResponse delivery = this.orderManagementCheckoutClient.deliverOrder( + MERCHANT_ID, + initialCommerceCase.getCommerceCaseId().toString(), + initialCommerceCase.getCheckout().getCheckoutId().toString(), + new DeliverRequest().deliverType(DeliverType.FULL).isFinal(true)); + System.out.println(delivery); } - // see: https://docs.payone.com/pcp/checkout-flows/one-step-checkout - // not that the given reference must be unique and has to renewed after each run - try { - app.runSingleStepCheckout("comc1a1"); - } catch (ApiErrorResponseException e) { - for (APIError error : e.getErrors()) { - System.err.println(error.getMessage()); - } - } catch (Exception e) { - throw new RuntimeException(e); + public static void main(String[] args) { + App app = initFromEnv(); + + // creates a checkout and executes the payment in one go + try { + app.runCheckoutWithPaymentExecution("comc1a5"); + } catch (ApiErrorResponseException e) { + for (APIError error : e.getErrors()) { + System.err.println(error.getMessage()); + } + System.exit(1); + } catch (Exception e) { + throw new RuntimeException(e); + } + + // see: https://docs.payone.com/pcp/checkout-flows/step-by-step-checkout + // not that the given reference must be unique and has to renewed after each run + try { + app.runMultiStepCheckout("comc1a1"); + } catch (ApiErrorResponseException e) { + for (APIError error : e.getErrors()) { + System.err.println(error.getMessage()); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + + // see: https://docs.payone.com/pcp/checkout-flows/one-step-checkout + // not that the given reference must be unique and has to renewed after each run + try { + app.runSingleStepCheckout("comc1a1"); + } catch (ApiErrorResponseException e) { + for (APIError error : e.getErrors()) { + System.err.println(error.getMessage()); + } + } catch (Exception e) { + throw new RuntimeException(e); + } } - } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e644113..2c35211 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a441313..09523c0 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index b740cf1..f5feea6 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -84,7 +86,8 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum diff --git a/gradlew.bat b/gradlew.bat index 25da30d..9d21a21 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## diff --git a/lib/build.gradle b/lib/build.gradle index 75c874d..c974975 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -4,8 +4,9 @@ buildscript { gradlePluginPortal() } dependencies { - if (JavaVersion.current().majorVersion != "8") { + if (JavaVersion.current().majorVersion != '8') { classpath 'com.vanniktech:gradle-maven-publish-plugin:0.29.0' + classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:5.1.0.4882' } } } @@ -14,14 +15,14 @@ plugins { id 'java-library' id 'jacoco' id 'checkstyle' - id "io.github.kmbisset89.changelog.plugin" version "1.0.4" + id 'io.github.kmbisset89.changelog.plugin' version '1.0.4' } -if (JavaVersion.current().majorVersion != "8") { +if (JavaVersion.current().majorVersion != '8') { apply plugin: 'com.vanniktech.maven.publish' + apply plugin: 'org.sonarqube' } - version = '0.0.2' repositories { @@ -39,7 +40,7 @@ dependencies { } jacoco { - toolVersion = "0.8.8" // Specify the version of JaCoCo you want to use + toolVersion = '0.8.8' // Specify the version of JaCoCo you want to use } tasks.test { @@ -56,42 +57,58 @@ tasks.jacocoTestReport { afterEvaluate { classDirectories.setFrom(files(classDirectories.files.collect { fileTree(dir: it, exclude: [ - "com/payone/**/models/*" + 'com/payone/**/models/*' ]) })) } } -if (JavaVersion.current().majorVersion != "8") { + +if (JavaVersion.current().majorVersion != '8') { mavenPublishing { - publishToMavenCentral("CENTRAL_PORTAL") + publishToMavenCentral('CENTRAL_PORTAL') signAllPublications() - coordinates("io.github.payone-gmbh", "pcp-serversdk-java", version) + coordinates('io.github.payone-gmbh', 'pcp-serversdk-java', version) pom { - name = "PCP-SERVERSDK-JAVA" - description = "The PayOne PCP Java SDK." - inceptionYear = "2024" - url = "https://github.com/PAYONE-GmbH/PCP-ServerSDK-java" + name = 'PCP-SERVERSDK-JAVA' + description = 'The PayOne PCP Java SDK.' + inceptionYear = '2024' + url = 'https://github.com/PAYONE-GmbH/PCP-ServerSDK-java' licenses { license { - name = "MIT" + name = 'MIT' } } developers { developer { - id = "username" - name = "PayOne-GmbH" - url = "https://github.com/PAYONE-GmbH" + id = 'username' + name = 'PayOne-GmbH' + url = 'https://github.com/PAYONE-GmbH' } } scm { - url = "https://github.com/PAYONE-GmbH/PCP-ServerSDK-java" - connection = "scm:git:git://github.com/PAYONE-GmbH/PCP-ServerSDK-java.git" - developerConnection = "scm:git:ssh://git@github.com/PAYONE-GmbH/PCP-ServerSDK-java.git" + url = 'https://github.com/PAYONE-GmbH/PCP-ServerSDK-java' + connection = 'scm:git:git://github.com/PAYONE-GmbH/PCP-ServerSDK-java.git' + developerConnection = 'scm:git:ssh://git@github.com/PAYONE-GmbH/PCP-ServerSDK-java.git' } } } + + tasks['sonar'].dependsOn 'jacocoTestReport' + + sonar { + properties { + property 'sonar.projectKey', 'PAYONE-GmbH_PCP-ServerSDK-java' + property 'sonar.projectName', 'PCP-ServerSDK-java' + property 'sonar.organization', 'payone-gmbh' + property 'sonar.host.url', 'https://sonarcloud.io' + property 'sonar.sources', 'src/main' + property 'sonar.tests', 'src/test' + property 'sonar.coverage.exclusions', '**/models/*' + property 'sonar.exclusions', '**/models/*' + } + } } \ No newline at end of file diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/CommunicatorConfiguration.java b/lib/src/main/java/com/payone/commerce/platform/lib/CommunicatorConfiguration.java index 9bbcfed..a6fb90d 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/CommunicatorConfiguration.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/CommunicatorConfiguration.java @@ -4,11 +4,13 @@ public class CommunicatorConfiguration { private final String apiKey; private final String apiSecret; private final String host; + private final String integrator; - public CommunicatorConfiguration(String apiKey, String apiSecret, String host) { + public CommunicatorConfiguration(String apiKey, String apiSecret, String host, String integrator) { this.apiKey = apiKey; this.apiSecret = apiSecret; this.host = host; + this.integrator = integrator; } public String getApiKey() { @@ -22,4 +24,8 @@ public String getApiSecret() { public String getHost() { return host; } + + public String getIntegrator() { + return integrator; + } } diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/RequestHeaderGenerator.java b/lib/src/main/java/com/payone/commerce/platform/lib/RequestHeaderGenerator.java index b8bdf90..873a070 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/RequestHeaderGenerator.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/RequestHeaderGenerator.java @@ -17,14 +17,14 @@ import okhttp3.Request; public class RequestHeaderGenerator { - - public static final String SERVER_META_INFO_HEADER_NAME = "X-GCS-ServerMetaInfo"; + private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; + private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; + private static final String DATE_HEADER_NAME = "Date"; public static final String CLIENT_META_INFO_HEADER_NAME = "X-GCS-ClientMetaInfo"; + public static final String SERVER_META_INFO_HEADER_NAME = "X-GCS-ServerMetaInfo"; private static final String ALGORITHM = "HmacSHA256"; private static final String WHITESPACE_REGEX = "\\r?\\n[\\h]*"; - private final String DATE_HEADER_NAME = "Date"; - private final String AUTHORIZATION_HEADER_NAME = "Authorization"; private final CommunicatorConfiguration config; private final Mac mac; @@ -38,7 +38,7 @@ public RequestHeaderGenerator(CommunicatorConfiguration config) throws InvalidKe ALGORITHM); this.mac.init(secretKeySpec); } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("HmacSHA256 must be available to use the PCP Java SDK", e); + throw new AssertionError("HmacSHA256 must be available to use the PCP Java SDK", e); } } @@ -69,8 +69,8 @@ private String getAuthHeader(Request request, Builder headersBuilder) { StringBuilder stringToSign = new StringBuilder(request.method()); stringToSign.append("\n"); // 2. Content-Type - if (headersBuilder.get("Content-Type") != null) { - stringToSign.append(headersBuilder.get("Content-Type")); + if (headersBuilder.get(CONTENT_TYPE_HEADER_NAME) != null) { + stringToSign.append(headersBuilder.get(CONTENT_TYPE_HEADER_NAME)); } stringToSign.append("\n"); // 3. Date @@ -90,7 +90,7 @@ private String getAuthHeader(Request request, Builder headersBuilder) { .append("\n"); } // 5. Canonicalized Resource (has to include query parameters) - stringToSign.append(request.url().encodedPath().toString()); + stringToSign.append(request.url().encodedPath()); if (request.url().encodedQuery() != null) { stringToSign.append("?") .append(request.url().encodedQuery()); @@ -106,14 +106,14 @@ private String sign(String target) { } private String getServerMetaInfo() { - ServerMetaInfo meta = new ServerMetaInfo(); + ServerMetaInfo meta = new ServerMetaInfo(this.config.getIntegrator()); String jsonString; try { jsonString = JsonSerializer.serializeToJson(meta); return Base64.getEncoder().encodeToString(jsonString.getBytes(StandardCharsets.UTF_8)); } catch (JsonProcessingException e) { - throw new RuntimeException( + throw new AssertionError( "Server Meta Info must be encodable as JSON, this is likely an internal bug of the java PCP SDK", e); } diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/BaseApiClient.java b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/BaseApiClient.java index 9f94df5..f7f3928 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/BaseApiClient.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/BaseApiClient.java @@ -19,9 +19,15 @@ import okhttp3.Response; public class BaseApiClient { + private static final String JSON_PARSE_ERROR = "Excepted valid JSON response, but failed to parse"; + protected static final String MERCHANT_ID_REQUIRED_ERROR = "Merchant ID is required"; + protected static final String COMMERCE_CASE_ID_REQUIRED_ERROR = "Commerce Case ID is required"; + protected static final String CHECKOUT_ID_REQUIRED_ERROR = "Checkout ID is required"; + protected static final String PAYLOAD_REQUIRED_ERROR = "Payload is required"; + protected static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + protected static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; + private final OkHttpClient client = new OkHttpClient(); - private final String JSON_PARSE_ERROR = "Excepted valid JSON response, but failed to parse"; - protected final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private final RequestHeaderGenerator requestHeaderGenerator; private final CommunicatorConfiguration config; @@ -86,7 +92,7 @@ private void handleError(Response response) } String responseBody = response.body().string(); - if (responseBody == null || responseBody.isEmpty()) { + if (responseBody.isEmpty()) { throw new ApiResponseRetrievalException(response.code(), responseBody); } try { diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClient.java b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClient.java index 26d5d10..ce51e95 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClient.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClient.java @@ -32,13 +32,13 @@ public CreateCheckoutResponse createCheckoutRequest(String merchantId, String co CreateCheckoutRequest payload) throws ApiErrorResponseException, ApiResponseRetrievalException, IOException { if (merchantId == null) { - throw new IllegalArgumentException("Merchant ID is required"); + throw new IllegalArgumentException(MERCHANT_ID_REQUIRED_ERROR); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -58,7 +58,7 @@ public CreateCheckoutResponse createCheckoutRequest(String merchantId, String co Request request = new Request.Builder() .url(url) .post(RequestBody.create(jsonString, JSON)) - .header("Content-Type", JSON.toString()) + .header(CONTENT_TYPE_HEADER_NAME, JSON.toString()) .build(); return this.makeApiCall(request, CreateCheckoutResponse.class); @@ -68,13 +68,13 @@ public CreateCheckoutResponse createCheckoutRequest(String merchantId, String co public CheckoutResponse getCheckoutRequest(String merchantId, String commerceCaseId, String checkoutId) throws ApiErrorResponseException, ApiResponseRetrievalException, IOException { if (merchantId == null) { - throw new IllegalArgumentException("Merchant ID is required"); + throw new IllegalArgumentException(MERCHANT_ID_REQUIRED_ERROR); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -105,7 +105,7 @@ public CheckoutsResponse getCheckoutsRequest(String merchantID) public CheckoutsResponse getCheckoutsRequest(String merchantId, GetCheckoutsQuery queryParams) throws ApiErrorResponseException, ApiResponseRetrievalException, IOException { if (merchantId == null) { - throw new IllegalArgumentException("Merchant ID is required"); + throw new IllegalArgumentException(MERCHANT_ID_REQUIRED_ERROR); } HttpUrl.Builder urlBuilder = new HttpUrl.Builder() @@ -134,16 +134,16 @@ public void updateCheckoutRequest(String merchantId, String commerceCaseId, Stri PatchCheckoutRequest payload) throws ApiErrorResponseException, ApiResponseRetrievalException, IOException { if (merchantId == null) { - throw new IllegalArgumentException("Merchant ID is required"); + throw new IllegalArgumentException(MERCHANT_ID_REQUIRED_ERROR); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -157,14 +157,12 @@ public void updateCheckoutRequest(String merchantId, String commerceCaseId, Stri .addPathSegment(checkoutId) .build(); - String jsonString = null; - - jsonString = JsonSerializer.serializeToJson(payload); + String jsonString = JsonSerializer.serializeToJson(payload); Request request = new Request.Builder() .url(url) .patch(RequestBody.create(jsonString, JSON)) - .header("Content-Type", JSON.toString()) + .header(CONTENT_TYPE_HEADER_NAME, JSON.toString()) .build(); this.makeApiCall(request); @@ -174,13 +172,13 @@ public void updateCheckoutRequest(String merchantId, String commerceCaseId, Stri public void removeCheckoutRequest(String merchantId, String commerceCaseId, String checkoutId) throws ApiErrorResponseException, ApiResponseRetrievalException, IOException { if (merchantId == null) { - throw new IllegalArgumentException("Merchant ID is required"); + throw new IllegalArgumentException(MERCHANT_ID_REQUIRED_ERROR); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CommerceCaseApiClient.java b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CommerceCaseApiClient.java index 81be14a..9e8b096 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CommerceCaseApiClient.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/CommerceCaseApiClient.java @@ -35,7 +35,7 @@ public CreateCommerceCaseResponse createCommerceCaseRequest(String merchantId, C throw new IllegalArgumentException("Merchant ID is required"); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -53,7 +53,7 @@ public CreateCommerceCaseResponse createCommerceCaseRequest(String merchantId, C Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, CreateCommerceCaseResponse.class); @@ -66,7 +66,7 @@ public CommerceCaseResponse getCommerceCaseRequest(String merchantId, throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } HttpUrl.Builder urlBuilder = new HttpUrl.Builder() @@ -130,10 +130,10 @@ public void updateCommerceCaseRequest(String merchantId, String commerceCaseId, throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -145,16 +145,14 @@ public void updateCommerceCaseRequest(String merchantId, String commerceCaseId, .addPathSegment(commerceCaseId) .build(); - String jsonString = null; - - jsonString = JsonSerializer.serializeToJson(payload); + String jsonString = JsonSerializer.serializeToJson(payload); RequestBody formBody = RequestBody.create("{\"customer\":" + jsonString + "}", JSON); Request request = new Request.Builder() .url(url) .patch(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); this.makeApiCall(request); diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/OrderManagementCheckoutActionsApiClient.java b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/OrderManagementCheckoutActionsApiClient.java index ba38dfd..deab21b 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/OrderManagementCheckoutActionsApiClient.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/OrderManagementCheckoutActionsApiClient.java @@ -36,13 +36,13 @@ public OrderResponse createOrder(String merchantId, String commerceCaseId, throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -64,7 +64,7 @@ public OrderResponse createOrder(String merchantId, String commerceCaseId, Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, OrderResponse.class); @@ -78,13 +78,13 @@ public DeliverResponse deliverOrder(String merchantId, String commerceCaseId, throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -106,7 +106,7 @@ public DeliverResponse deliverOrder(String merchantId, String commerceCaseId, Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, DeliverResponse.class); @@ -120,13 +120,13 @@ public ReturnResponse returnOrder(String merchantId, String commerceCaseId, throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -148,7 +148,7 @@ public ReturnResponse returnOrder(String merchantId, String commerceCaseId, Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, ReturnResponse.class); @@ -162,13 +162,13 @@ public CancelResponse cancelOrder(String merchantId, String commerceCaseId, throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -190,7 +190,7 @@ public CancelResponse cancelOrder(String merchantId, String commerceCaseId, Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, CancelResponse.class); diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClient.java b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClient.java index 4dfbf98..4440e8d 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClient.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClient.java @@ -35,13 +35,13 @@ public CreatePaymentResponse createPayment(String merchantId, String commerceCas throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -63,7 +63,7 @@ public CreatePaymentResponse createPayment(String merchantId, String commerceCas Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, CreatePaymentResponse.class); @@ -77,16 +77,16 @@ public CapturePaymentResponse capturePayment(String merchantId, String commerceC throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (paymentExecutionId == null) { throw new IllegalArgumentException("Payment Execution ID is required"); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -110,7 +110,7 @@ public CapturePaymentResponse capturePayment(String merchantId, String commerceC Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, CapturePaymentResponse.class); @@ -124,16 +124,16 @@ public CancelPaymentResponse cancelPayment(String merchantId, String commerceCas throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (paymentExecutionId == null) { throw new IllegalArgumentException("Payment Execution ID is required"); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -157,7 +157,7 @@ public CancelPaymentResponse cancelPayment(String merchantId, String commerceCas Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, CancelPaymentResponse.class); @@ -171,16 +171,16 @@ public RefundPaymentResponse refundPayment(String merchantId, String commerceCas throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (paymentExecutionId == null) { throw new IllegalArgumentException("Payment Execution ID is required"); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -204,7 +204,7 @@ public RefundPaymentResponse refundPayment(String merchantId, String commerceCas Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, RefundPaymentResponse.class); @@ -218,16 +218,16 @@ public CompletePaymentResponse completePayment(String merchantId, String commerc throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (paymentExecutionId == null) { throw new IllegalArgumentException("Payment Execution ID is required"); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -251,7 +251,7 @@ public CompletePaymentResponse completePayment(String merchantId, String commerc Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, CompletePaymentResponse.class); diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentInformationApiClient.java b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentInformationApiClient.java index 0c3d511..a4dc715 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentInformationApiClient.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/endpoints/PaymentInformationApiClient.java @@ -26,13 +26,13 @@ public PaymentInformationResponse createPaymentInformation(String merchantId, St throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (payload == null) { - throw new IllegalArgumentException("Payload is required"); + throw new IllegalArgumentException(PAYLOAD_REQUIRED_ERROR); } HttpUrl url = new HttpUrl.Builder() @@ -54,7 +54,7 @@ public PaymentInformationResponse createPaymentInformation(String merchantId, St Request request = new Request.Builder() .url(url) .post(formBody) - .header("Content-Type", formBody.contentType().toString()) + .header(CONTENT_TYPE_HEADER_NAME, formBody.contentType().toString()) .build(); return this.makeApiCall(request, PaymentInformationResponse.class); @@ -68,10 +68,10 @@ public PaymentInformationResponse getPaymentInformation(String merchantId, Strin throw new IllegalArgumentException("Merchant ID is required"); } if (commerceCaseId == null) { - throw new IllegalArgumentException("Commerce Case ID is required"); + throw new IllegalArgumentException(COMMERCE_CASE_ID_REQUIRED_ERROR); } if (checkoutId == null) { - throw new IllegalArgumentException("Checkout ID is required"); + throw new IllegalArgumentException(CHECKOUT_ID_REQUIRED_ERROR); } if (paymentInformationId == null) { throw new IllegalArgumentException("Payment Information ID is required"); diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/serializer/JsonSerializer.java b/lib/src/main/java/com/payone/commerce/platform/lib/serializer/JsonSerializer.java index f78b6e7..e6705bc 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/serializer/JsonSerializer.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/serializer/JsonSerializer.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @@ -18,17 +17,20 @@ public class JsonSerializer { JSON_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } + private JsonSerializer() { + } + public static String serializeToJson(Object object) throws JsonProcessingException { return JSON_MAPPER.writeValueAsString(object); } public static T deserializeFromJson(String json, Class clazz) - throws JsonMappingException, JsonProcessingException { + throws JsonProcessingException { return JSON_MAPPER.readValue(json, clazz); } public static T deserializeFromJson(String json, TypeReference valueTypeRef) - throws JsonMappingException, JsonProcessingException { + throws JsonProcessingException { return JSON_MAPPER.readValue(json, valueTypeRef); } } diff --git a/lib/src/main/java/com/payone/commerce/platform/lib/utils/ServerMetaInfo.java b/lib/src/main/java/com/payone/commerce/platform/lib/utils/ServerMetaInfo.java index 82687b8..f7683b8 100644 --- a/lib/src/main/java/com/payone/commerce/platform/lib/utils/ServerMetaInfo.java +++ b/lib/src/main/java/com/payone/commerce/platform/lib/utils/ServerMetaInfo.java @@ -6,6 +6,7 @@ public class ServerMetaInfo { public String platformIdentifier; public String sdkIdentifier; public String sdkCreator; + public String integrator; public ServerMetaInfo() { this.platformIdentifier = String.format("%s, java version is: %s", System.getProperty("os.name"), @@ -13,8 +14,16 @@ public ServerMetaInfo() { // version gets updated with the prepare-release.sh script this.sdkIdentifier = "JavaServerSDK/v0.0.2"; this.sdkCreator = "PAYONE GmbH"; + this.integrator = null; + } - // TODO: what about integrator? + public ServerMetaInfo(String integrator) { + this.platformIdentifier = String.format("%s, java version is: %s", System.getProperty("os.name"), + System.getProperty("java.version")); + // version gets updated with the prepare-release.sh script + this.sdkIdentifier = "JavaServerSDK/v0.0.2"; + this.sdkCreator = "PAYONE GmbH"; + this.integrator = integrator; } @Override diff --git a/lib/src/test/java/com/payone/commerce/platform/lib/RequestHeaderGeneratorTest.java b/lib/src/test/java/com/payone/commerce/platform/lib/RequestHeaderGeneratorTest.java index 812bc7c..a9cbe2f 100644 --- a/lib/src/test/java/com/payone/commerce/platform/lib/RequestHeaderGeneratorTest.java +++ b/lib/src/test/java/com/payone/commerce/platform/lib/RequestHeaderGeneratorTest.java @@ -21,11 +21,11 @@ import java.util.Base64; import java.util.Date; -public class RequestHeaderGeneratorTest { +class RequestHeaderGeneratorTest { private static final String TEST_KEY = "KEY"; private static final String TEST_SECRET = "Super duper Ethan Hunt level secret"; private static final CommunicatorConfiguration CONFIG = new CommunicatorConfiguration(TEST_KEY, TEST_SECRET, - "awesome-api.com"); + "awesome-api.com", null); private static final RequestHeaderGenerator HEADER_GENERATOR; static { try { @@ -51,8 +51,9 @@ void testSignatureGenerationForGet() { try { Request updatedRequest = HEADER_GENERATOR.generateAdditionalRequestHeaders(request); - assertEquals(updatedRequest.header("Authorization"), - "GCS v1HMAC:KEY:ZSq7H19dyhyNGSPY5UgyPwITc5n4QG+zHnNDExIa6A8="); + assertEquals( + "GCS v1HMAC:KEY:ZSq7H19dyhyNGSPY5UgyPwITc5n4QG+zHnNDExIa6A8=", + updatedRequest.header("Authorization")); } catch (Exception e) { fail(e); } @@ -78,8 +79,8 @@ void testSignatureGenerationWithContentType() { try { Request updatedRequest = HEADER_GENERATOR.generateAdditionalRequestHeaders(request); - assertEquals(updatedRequest.header("Authorization"), - "GCS v1HMAC:KEY:c5aNDw4AUxRChugRyN0OmTCs38YLA9E/tR+k0bOQzyk="); + assertEquals("GCS v1HMAC:KEY:c5aNDw4AUxRChugRyN0OmTCs38YLA9E/tR+k0bOQzyk=", + updatedRequest.header("Authorization")); } catch (Exception e) { fail(e); } @@ -96,7 +97,7 @@ void addADateHeaderIfMissingTest() { Request updatedRequest = HEADER_GENERATOR.generateAdditionalRequestHeaders(request); assertNotNull(updatedRequest.headers().get("Date")); - assertNotEquals(updatedRequest.headers().get("Date"), ""); + assertNotEquals("", updatedRequest.headers().get("Date")); } catch (Exception e) { fail(e); } @@ -119,7 +120,7 @@ void addServerMetaInfoIfMissingTest() { serverMetaInfoAsJson = new String(Base64.getDecoder().decode(serverMetaInfoBase64), StandardCharsets.UTF_8); ServerMetaInfo serverMetaInfo = objectMapper.readValue(serverMetaInfoAsJson, ServerMetaInfo.class); - assertEquals(serverMetaInfo, new ServerMetaInfo()); + assertEquals(serverMetaInfo, new ServerMetaInfo(null)); } catch (JsonProcessingException e) { fail(String.format("Decoded meta info '%s', should have been valid json", serverMetaInfoAsJson), e); } catch (Exception e) { @@ -140,7 +141,7 @@ void addServerClientInfoIfMissingTest() { assertNotNull(clientMetaInfo); String metaInfoAsJson = new String(Base64.getDecoder().decode(clientMetaInfo), StandardCharsets.UTF_8); - assertEquals(metaInfoAsJson, "\"[]\""); + assertEquals("\"[]\"", metaInfoAsJson); } catch (Exception e) { fail(e); } diff --git a/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClientTest.java b/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClientTest.java index c37396b..d3db66e 100644 --- a/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClientTest.java +++ b/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/CheckoutApiClientTest.java @@ -35,7 +35,7 @@ public class CheckoutApiClientTest { class CreateCheckoutRequestTests { @Test @DisplayName("given request was successful, then return response") - void createCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, IOException { + void createCheckoutRequestSuccessful() throws InvalidKeyException, IOException, ApiException { CheckoutApiClient checkoutApiClient = spy( new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -54,7 +54,7 @@ void createCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, @Test @DisplayName("given request was unsuccessful (400), then throw exception") - void createCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiException, IOException { + void createCheckoutRequestUnsuccessful() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); @@ -70,7 +70,7 @@ void createCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiExceptio @Test @DisplayName("given request was unsuccessful (500) with an empty body, then throw exception") - void createCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { + void createCheckoutRequestUnsuccessful500() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); @@ -86,7 +86,7 @@ void createCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiExcep @Test @DisplayName("given some params are null, then throw exception") - void createCheckoutRequestNullParams() throws InvalidKeyException, ApiException, IOException { + void createCheckoutRequestNullParams() throws InvalidKeyException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CreateCheckoutRequest payload = new CreateCheckoutRequest(); @@ -114,7 +114,7 @@ void createCheckoutRequestNullParams() throws InvalidKeyException, ApiException, class GetCheckoutRequestTests { @Test @DisplayName("given request was successful, then return response") - void getCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, IOException { + void getCheckoutRequestSuccessful() throws InvalidKeyException, IOException, ApiException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CheckoutResponse expected = new CheckoutResponse(); @@ -131,7 +131,7 @@ void getCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, IO @Test @DisplayName("given request was unsuccessful (400), then throw exception") - void getCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiException, IOException { + void getCheckoutRequestUnsuccessful() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); @@ -146,7 +146,7 @@ void getCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiException, @Test @DisplayName("given request was unsuccessful (500), then throw exception") - void getCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { + void getCheckoutRequestUnsuccessful500() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); @@ -162,7 +162,7 @@ void getCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiExceptio @Test @DisplayName("given some params are null, then throw exception") - void getCheckoutRequestNullParams() throws InvalidKeyException, ApiException, IOException { + void getCheckoutRequestNullParams() throws InvalidKeyException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -191,7 +191,7 @@ void getCheckoutRequestNullParams() throws InvalidKeyException, ApiException, IO class getCheckoutsRequestTests { @Test @DisplayName("given request was successful, then return response") - void getCheckoutsRequestSuccessful() throws InvalidKeyException, ApiException, IOException { + void getCheckoutsRequestSuccessful() throws InvalidKeyException, IOException, ApiException { CheckoutApiClient checkoutApiClient = spy( new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -209,7 +209,7 @@ void getCheckoutsRequestSuccessful() throws InvalidKeyException, ApiException, I @Test @DisplayName("given request was unsuccessful (400), then throw exception") - void getCheckoutsRequestUnsuccessful() throws InvalidKeyException, ApiException, IOException { + void getCheckoutsRequestUnsuccessful() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy( new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -227,7 +227,7 @@ void getCheckoutsRequestUnsuccessful() throws InvalidKeyException, ApiException, @Test @DisplayName("given request was unsuccessful (500) with empty body, then throw exception") - void getCommerceCaseRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { + void getCommerceCaseRequestUnsuccessful500() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy( new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -244,7 +244,7 @@ void getCommerceCaseRequestUnsuccessful500() throws InvalidKeyException, ApiExce @Test @DisplayName("given some params are null, then throw exception") - void getCheckoutsRequestNullParams() throws InvalidKeyException, ApiException, IOException { + void getCheckoutsRequestNullParams() throws InvalidKeyException { CheckoutApiClient checkoutApiClient = spy( new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -263,7 +263,7 @@ void getCheckoutsRequestNullParams() throws InvalidKeyException, ApiException, I class UpdateCheckoutRequestTests { @Test @DisplayName("given request was successful, then throw no exception") - void updateCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, IOException { + void updateCheckoutRequestSuccessful() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createResponse(200); @@ -279,7 +279,7 @@ void updateCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, @Test @DisplayName("given request was unsuccessful (400), then throw exception") - void updateCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiException, IOException { + void updateCheckoutRequestUnsuccessful() throws InvalidKeyException, IOException { Response response = ApiResponseMocks.createErrorResponse(400); CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); doReturn(response).when(checkoutApiClient).getResponse(any()); @@ -293,7 +293,7 @@ void updateCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiExceptio @Test @DisplayName("given request was unsuccessful (500), then throw exception") - void updateCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { + void updateCheckoutRequestUnsuccessful500() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(500); @@ -310,7 +310,7 @@ void updateCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiExcep @Test @DisplayName("given some params are null, then throw exception") - void updateCheckoutRequestNullParams() throws InvalidKeyException, ApiException, IOException { + void updateCheckoutRequestNullParams() throws InvalidKeyException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); @@ -351,7 +351,7 @@ void updateCheckoutRequestNullParams() throws InvalidKeyException, ApiException, class RemoveCheckoutRequestTests { @Test @DisplayName("given request was successful, then throw no exception") - void removeCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, IOException { + void removeCheckoutRequestSuccessful() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createResponse(200); @@ -365,7 +365,7 @@ void removeCheckoutRequestSuccessful() throws InvalidKeyException, ApiException, @Test @DisplayName("given request was unsuccessful (400), then throw exception") - void removeCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiException, IOException { + void removeCheckoutRequestUnsuccessful() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); @@ -381,7 +381,7 @@ void removeCheckoutRequestUnsuccessful() throws InvalidKeyException, ApiExceptio @Test @DisplayName("given request was unsuccessful (500), then throw exception") - void removeCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { + void removeCheckoutRequestUnsuccessful500() throws InvalidKeyException, IOException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); @@ -397,7 +397,7 @@ void removeCheckoutRequestUnsuccessful500() throws InvalidKeyException, ApiExcep @Test @DisplayName("given some params are null, then throw exception") - void removeCheckoutRequestNullParams() throws InvalidKeyException, ApiException, IOException { + void removeCheckoutRequestNullParams() throws InvalidKeyException { CheckoutApiClient checkoutApiClient = spy(new CheckoutApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); diff --git a/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClientTest.java b/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClientTest.java index 922c2dc..197f0a7 100644 --- a/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClientTest.java +++ b/lib/src/test/java/com/payone/commerce/platform/lib/endpoints/PaymentExecutionApiClientTest.java @@ -17,7 +17,6 @@ import com.payone.commerce.platform.lib.errors.ApiErrorResponseException; import com.payone.commerce.platform.lib.errors.ApiException; import com.payone.commerce.platform.lib.errors.ApiResponseRetrievalException; -import com.payone.commerce.platform.lib.CommunicatorConfiguration; import com.payone.commerce.platform.lib.models.PaymentExecutionRequest; import com.payone.commerce.platform.lib.models.RefundPaymentResponse; import com.payone.commerce.platform.lib.models.RefundRequest; @@ -29,15 +28,11 @@ import com.payone.commerce.platform.lib.models.CompletePaymentResponse; import com.payone.commerce.platform.lib.models.CreatePaymentResponse; import com.payone.commerce.platform.lib.testutils.ApiResponseMocks; +import com.payone.commerce.platform.lib.testutils.TestConfig; import okhttp3.Response; public class PaymentExecutionApiClientTest { - private final String TEST_KEY = "KEY"; - private final String TEST_SECRET = "Super duper Ethan Hunt level secret"; - private final CommunicatorConfiguration CONFIG = new CommunicatorConfiguration(TEST_KEY, TEST_SECRET, - "awesome-api.com"); - @Nested @DisplayName("createPaymentRequest") class createPayment { @@ -45,7 +40,8 @@ class createPayment { @DisplayName("given request was successful, then return response") void createPaymentRequestSuccessful() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CreatePaymentResponse expected = new CreatePaymentResponse(); Response response = ApiResponseMocks.createResponse(200, new CreatePaymentResponse()); @@ -62,7 +58,8 @@ void createPaymentRequestSuccessful() throws InvalidKeyException, ApiException, @DisplayName("given request was unsuccessful (400), then throw exception") void createPaymentRequestUnsuccessful() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -80,7 +77,8 @@ void createPaymentRequestUnsuccessful() throws InvalidKeyException, ApiException @DisplayName("given request was unsuccessful (500) with empty body, then throw exception") void createPaymentRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -98,7 +96,8 @@ void createPaymentRequestUnsuccessful500() throws InvalidKeyException, ApiExcept @DisplayName("Given required params are null, then throw exception") void createPaymentRequestNullParams() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); PaymentExecutionRequest payload = new PaymentExecutionRequest(); IllegalArgumentException e; @@ -137,7 +136,8 @@ class CapturePayment { @DisplayName("given request was successful, then return response") void capturePaymentRequestSuccessful() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CapturePaymentResponse expected = new CapturePaymentResponse(); Response response = ApiResponseMocks.createResponse(200, new CapturePaymentResponse()); @@ -154,7 +154,8 @@ void capturePaymentRequestSuccessful() throws InvalidKeyException, ApiException, @DisplayName("given request unsuccessful (400), then throw exception") void capturePaymentRequestUnsuccessful400() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -172,7 +173,8 @@ void capturePaymentRequestUnsuccessful400() throws InvalidKeyException, ApiExcep @DisplayName("given request unsuccessful (500) with empty body, then throw exception") void capturePaymentRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -190,7 +192,8 @@ void capturePaymentRequestUnsuccessful500() throws InvalidKeyException, ApiExcep @DisplayName("Given required params are null, then throw exception") void capturePaymentRequestParamsNull() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CapturePaymentRequest payload = new CapturePaymentRequest(); IllegalArgumentException e; @@ -235,7 +238,8 @@ class CancelPayment { @DisplayName("given request was successful, then return response") void cancelPaymentRequestSuccessful() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CancelPaymentResponse expected = new CancelPaymentResponse(); Response response = ApiResponseMocks.createResponse(200, new CancelPayment()); @@ -252,7 +256,8 @@ void cancelPaymentRequestSuccessful() throws InvalidKeyException, ApiException, @DisplayName("given request unsuccessful (400), then throw exception") void cancelPaymentRequestUnsuccessful400() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -270,7 +275,8 @@ void cancelPaymentRequestUnsuccessful400() throws InvalidKeyException, ApiExcept @DisplayName("given request unsuccessful (500) with empty body, then throw exception") void cancelPaymentRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -288,7 +294,8 @@ void cancelPaymentRequestUnsuccessful500() throws InvalidKeyException, ApiExcept @DisplayName("Given required params are null, then throw exception") void cancelPaymentRequestParamsNull() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CancelPaymentRequest payload = new CancelPaymentRequest(); IllegalArgumentException e; @@ -333,7 +340,8 @@ class CompletePayment { @DisplayName("given request was successful, then return response") void completePaymentRequestSuccessful() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CompletePaymentResponse expected = new CompletePaymentResponse(); Response response = ApiResponseMocks.createResponse(200, new CompletePaymentResponse()); @@ -350,7 +358,8 @@ void completePaymentRequestSuccessful() throws InvalidKeyException, ApiException @DisplayName("given request unsuccessful (400), then throw exception") void completePaymentRequestUnsuccessful400() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -368,7 +377,8 @@ void completePaymentRequestUnsuccessful400() throws InvalidKeyException, ApiExce @DisplayName("given request unsuccessful (500) with empty body, then throw exception") void completePaymentRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -386,7 +396,8 @@ void completePaymentRequestUnsuccessful500() throws InvalidKeyException, ApiExce @DisplayName("Given required params are null, then throw exception") void completePaymentRequestParamsNull() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); CompletePaymentRequest payload = new CompletePaymentRequest(); IllegalArgumentException e; @@ -431,7 +442,8 @@ class PaymentRefund { @DisplayName("given request was successful, then return response") void refundPaymentRequestSuccessful() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); RefundPaymentResponse expected = new RefundPaymentResponse(); Response response = ApiResponseMocks.createResponse(200, new RefundPaymentResponse()); @@ -448,7 +460,8 @@ void refundPaymentRequestSuccessful() throws InvalidKeyException, ApiException, @DisplayName("given request unsuccessful (400), then throw exception") void refundPaymentRequestUnsuccessful400() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createErrorResponse(400); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -466,7 +479,8 @@ void refundPaymentRequestUnsuccessful400() throws InvalidKeyException, ApiExcept @DisplayName("given request unsuccessful (500) with empty body, then throw exception") void refundPaymentRequestUnsuccessful500() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); Response response = ApiResponseMocks.createEmptyErrorResponse(500); doReturn(response).when(paymentExecutionApiClient).getResponse(any()); @@ -484,7 +498,8 @@ void refundPaymentRequestUnsuccessful500() throws InvalidKeyException, ApiExcept @DisplayName("Given required params are null, then throw exception") void refundPaymentRequestParamsNull() throws InvalidKeyException, ApiException, IOException { - PaymentExecutionApiClient paymentExecutionApiClient = spy(new PaymentExecutionApiClient(CONFIG)); + PaymentExecutionApiClient paymentExecutionApiClient = spy( + new PaymentExecutionApiClient(TestConfig.COMMUNICATOR_CONFIGURATION)); RefundRequest payload = new RefundRequest(); IllegalArgumentException e; diff --git a/lib/src/test/java/com/payone/commerce/platform/lib/testutils/TestConfig.java b/lib/src/test/java/com/payone/commerce/platform/lib/testutils/TestConfig.java index c903ced..5ac6c6e 100644 --- a/lib/src/test/java/com/payone/commerce/platform/lib/testutils/TestConfig.java +++ b/lib/src/test/java/com/payone/commerce/platform/lib/testutils/TestConfig.java @@ -6,5 +6,5 @@ public abstract class TestConfig { public static final CommunicatorConfiguration COMMUNICATOR_CONFIGURATION = new CommunicatorConfiguration("KEY", "Super duper Ethan Hunt level secret", - "awesome-api.com"); + "awesome-api.com", null); }