# Java SDK

## Introduction

The Deposits Java SDK (Software Development Kit) is a software package you can download and add to your existing code facilitating the integration by having pre-defined classes and functions you can call to integrate the [Deposits Endpoints](/api-documentation/deposits-api/endpoints.md).

Review and download the source code from GitHub by clicking on the button below[![Open in GitHub](https://www.kindpng.com/picc/m/141-1419051_github-icon-png-transparent-png.png)](https://github.com/directa24/cashin-java-sdk/)

## Installation

### Requirements

* Java 1.8 or later

### Gradle Users

Add this dependency to your project's build file:

{% code title="Java Gradle Dependency" %}

```java
implementation "com.directa24:cashin-java-sdk:1.0.13"
```

{% endcode %}

### Maven Users

Add this dependency to your project's POM:

{% code title="Java Maven dependency" %}

```markup
<dependency>
  <groupId>com.directa24</groupId>
  <artifactId>cashin-java-sdk</artifactId>
  <version>1.0.13</version>
</dependency>
```

{% endcode %}

####

### Dependencies

The library uses [Project Lombok](https://projectlombok.org/). While it is not a requirement, you might want to install a [plugin](https://projectlombok.org/setup/overview) for your favorite IDE to facilitate development.

[JUnit 4](https://junit.org/junit4/) and [Wiremock](http://wiremock.org/) library are needed to run the bundled tests.

## Usage

Begin by initializing your credentials

### **Deposit Credentials**

```java
String depositKeySbx = "fUEhPEKrUt";
String secretKeySbx = "wSHTfsMMdNskTppilncuZPEklgLmdUAOg";

Directa24 directa24Sandbox = new Directa24.Sandbox(depositKeySbx, secretKeySbx);
```

### **Read-Only Credentials**

```java
String readOnlyKeySbx = "EKiFOWiHnI";

Directa24 directa24Sandbox = new Directa24.Sandbox(readOnlyKeySbx);
```

{% hint style="success" %}
Make sure you have whitelisted your servers IPs on our Merchant Panel by going to Settings -> API Access.
{% endhint %}

[Click here](/api-documentation/deposits-api/technical-and-security-aspects.md#api-keys) for more information about the API Keys.

Once the credentials and the IPs have been properly set-up, you are ready to start using the classes the SDK provides. Each Class can be used to execute the functionalities of its respective [Deposit Endpoint.](/api-documentation/deposits-api/endpoints.md)

Make sure you take a look at the [Deposit Endpoints here](/api-documentation/deposits-api/endpoints.md) to review how the integration of each of them works, the validations and the responses formats.

{% hint style="success" %}
As soon as you are ready with the integration and you have the production credentials, replace the credentials for the production ones.
{% endhint %}

## Classes

{% hint style="success" %}
heck the respective [Endpoint Page ](/api-documentation/deposits-api/endpoints.md)to see the format of the responses, fields requirements and validations.
{% endhint %}

### Create Deposit

Every time you need to create a deposit, you will need to invoke the `CreateDepositRequest` Class with all the objects containing the information required to be sent. The amount of information required depends on the flow you have chosen, either the [Hosted Checkout Experience](/api-documentation/deposits-api.md#hosted-checkout-experience) or the [ONE SHOT Experience.](/api-documentation/deposits-api.md#oneshot-experience)

```java
public class CreateDepositExample {

   public static void main(String[] args) {

      Address address = Address.builder()
                               .street("Rua Dr. Franco Ribeiro, 52")
                               .city("Rio Branco")
                               .state("AC")
                               .zipCode("11600-234")
                               .build();

      Payer payer = Payer
            .builder()
            .id("4-9934519")
            .address(address)
            .document("21329039050")
            .documentType("CPF")
            .email("juanCarlos@hotmail.com")
            .firstName("Ricardo")
            .lastName("Carlos")
            .phone("+59899000878")
            .build();

      BankAccount bankAccount = BankAccount
            .builder()
            .bankCode("01")
            .accountNumber("3242342")
            .accountType("SAVING")
            .beneficiary("Ricardo Carlos")
            .branch("12")
            .build();

      CreateDepositRequest createDepositRequest = CreateDepositRequest
            .builder()
            .invoiceId("108")
            .amount(new BigDecimal(100))
            .country("BR")
            .currency("BRL")
            .payer(payer)
            .paymentMethod("BB")
            .paymentType("BANK_TRANSFER")
            .bankAccount(bankAccount)
            .earlyRelease(false)
            .feeOnPayer(false)
            .surchargeOnPayer(false)
            .bonusAmount(BigDecimal.ONE)
            .bonusRelative(false)
            .strikethroughPrice(BigDecimal.ONE)
            .description("Test")
            .clientIp("186.51.171.84")
            .language("es")
            .deviceId("00000000-00000000-01234567-89ABCDEF")
            .backUrl("https://yoursite.com/deposit/108/cancel")
            .successUrl("https://yoursite.com/deposit/108/confirm")
            .errorUrl("https://yoursite.com/deposit/108/error")
            .notificationUrl("https://yoursite.com/ipn")
            .logo("https://yoursite.com/logo.png")
            .test(true)
            .mobile(false)
            .idempotency("")
            .build();

      try {
         CreateDepositResponse createDepositResponse = directa24Sandbox.client.createDeposit(createDepositRequest);
         
         // Handle response

      } catch (Directa24Exception e) {
         // Handle errors
      }
   }
}
```

{% hint style="info" %}
CreateDepositRequest.amount and CreateDepositRequest.country are the only mandatory fields for a successful request. The rest of the fields needs to be sent depending on the flow you have chosen as those will be collected by us if not sent.
{% endhint %}

###

### Deposit Status

As soon as the deposit is created and you have received the notification in your `notification_url`, you will want to invoke the `DepositStatusRequest` Class to retrieve the [status](/api-documentation/deposits-api/api-codes.md#deposits-status-codes) of the deposit.

Click here to see the [deposits status flow.](/api-documentation/deposits-api/endpoints/refund-status-endpoint.md#status-flow)

```java
public class DepositStatusExample {

   public static void main(String[] args) {
      DepositStatusRequest depositStatusRequest = DepositStatusRequest
                                                  .builder()
                                                  .id(300000001)
                                                  .build();
      try {
         DepositStatusResponse depositStatusResponse = directa24Sandbox.client.depositStatus(depositStatusRequest);
      
         // Handle response

      } catch (Directa24Exception e) {
         // Handle errors
      }
   }
}
```

{% hint style="success" %}
Make sure you are adding the deposit\_id received on your notification\_url in the field DepositStatusRequest.id.
{% endhint %}

### Payment Methods

For the best user experience, we recommend integrating our [Payment Methods Endpoint](/api-documentation/deposits-api/endpoints/payment-methods-endpoint.md) to automatically retrieve the [list](/api-documentation/deposits-api/payment-methods.md) of payment methods name, logos, types and more that your account has available.

In order to do that, invoke the `PaymentMethodRequest` Class containing the [Country's ISO code](/knowledge-base/countries-specifications.md#countries-and-currencies) of the country you need the payment methods from in the field `PaymentMethodRequest.country`

```java
public class PaymentMethodsExample {

   public static void main(String[] args) {
      PaymentMethodRequest paymentMethodRequest = PaymentMethodRequest
                                                  .builder()
                                                  .country("BR")
                                                  .build();
      try {
         List<PaymentMethodResponse> paymentMethodResponse = directa24Sandbox.client.paymentMethods(paymentMethodRequest);
      
         // Handle response

      } catch (Directa24Exception e) {
         // Handle errors
      }
   }
}
```

### Exchange Rates

If you need to know the Exchange Rate of a given currency, you can do so by invoking `ExchangeRateRequest` with the [Country's ISO code](/knowledge-base/countries-specifications.md#countries-and-currencies) of the origin and the amount you want to convert to USD.

```java
public class ExchangeRateExample {

   public static void main(String[] args) {
      ExchangeRateRequest exchangeRatesRequest = ExchangeRateRequest
                                                 .builder()
                                                 .country("BR")
                                                 .amount(BigDecimal.TEN)
                                                 .build();
      try {
         ExchangeRateResponse exchangeRateResponse = directa24Test.client.exchangeRates(exchangeRateRequest);
         
         // Handle response

      } catch (Directa24Exception e) {
         // Handle errors
      }
   }
}
```

### Create Refund

In order to create a refund, you need to send the deposit\_id, merchant\_invoice\_id, and the bank\_account object (only for non-cc payments, otherwise, it is optional).

```java
public class CreateRefundTest extends AbstractDirecta24Test {

   @Before
   public void createMocks() {

      stubFor(post(urlMatching("/v3/refunds"))
            .withHeader("X-Login", equalTo(DEPOSIT_KEY))
            .withHeader("Content-Type", equalTo("application/json"))
            .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("{\"refund_id\": 1000043\n}")));

   }

   @Test
   public void createRefundTest() throws Directa24Exception {

      Directa24 directa24Test = new Directa24.Test(DEPOSIT_KEY, SECRET_KEY);

      BankAccount bankAccount = BankAccount
            .builder()
            .bankCode("01")
            .accountNumber("3242342")
            .accountType("SAVING")
            .beneficiary("Ricardo Carlos")
            .branch("12")
            .build();

      CreateRefundRequest createRefundRequest = CreateRefundRequest
            .builder()
            .depositId(9999)
            .invoiceId("1234")
            .amount(new BigDecimal(100))
            .bankAccount(bankAccount)
            .comments("Test")
            .notificationUrl("https://yoursite.com/ipn")
            .idempotency("")
            .build();

      CreateRefundResponse createRefundResponse = directa24Test.client.createRefund(createRefundRequest);

      assertTrue(createRefundResponse != null && createRefundResponse.getRefundId() != null);

      verify(postRequestedFor(urlEqualTo("/v3/refunds")).withHeader("Content-Type", equalTo("application/json")));
   }

}

```

### Refund Status

```java
public class RefundStatusTest extends AbstractDirecta24Test {

   @Before
   public void createMocks() {

      stubFor(get(urlMatching("/v3/refunds/123456"))
            .withHeader("X-Login", equalTo(DEPOSIT_KEY))
            .withHeader("Content-Type", equalTo("application/json"))
            .willReturn(aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody(
                        "{\"deposit_id\": 300537729,\"merchant_invoice_id\": \"postmanTest971574817\",\"status\": \"PENDING\",\"amount\": 1000.00}")));

      stubFor(get(urlMatching("/v3/refunds/999999"))
            .withHeader("X-Login", equalTo(DEPOSIT_KEY))
            .withHeader("Content-Type", equalTo("application/json"))
            .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "application/json")));
   }

   @Test
   public void refundStatusTest() throws Directa24Exception {

      Directa24 directa24Test = new Directa24.Test(DEPOSIT_KEY, SECRET_KEY);

      RefundStatusRequest refundStatusRequest = RefundStatusRequest.builder() //
                                                                   .id(123456) //
                                                                   .build();

      RefundStatusResponse refundStatusResponse = directa24Test.client.refundStatus(refundStatusRequest);

      assertTrue(refundStatusResponse != null);
      assertEquals(refundStatusResponse.getStatus(), "PENDING");

      verify(getRequestedFor(urlEqualTo("/v3/refunds/" + 123456)).withHeader("Content-Type", equalTo("application/json")));
   }

   @Test
   public void refundNotFoundTest() {

      Directa24 directa24Test = new Directa24.Test(DEPOSIT_KEY, SECRET_KEY);

      RefundStatusRequest refundStatusRequest = RefundStatusRequest.builder() //
                                                                   .id(999999) //
                                                                   .build();

      RefundStatusResponse refundStatusResponse = null;
      try {
         refundStatusResponse = directa24Test.client.refundStatus(refundStatusRequest);
         fail("Refund doesn't exists");
      } catch (Directa24Exception e) {
      }

      assertTrue(refundStatusResponse == null);
   }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://apidocs.onekeypayments.com/deposits-tools/java-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
