# Java API Client
source: https://developer.mastercard.com/mastercard-send-disbursements/documentation/tutorials-and-guides/api-tutorial/index.md

## Overview {#overview}

This tutorial generates a Java API client library using the OpenAPI Generator and the API specification and then builds a simple Java program that makes API calls to the Sandbox environment. You can also adapt this tutorial to [make API Calls to MTF](https://developer.mastercard.com/mastercard-send-disbursements/documentation/tutorials-and-guides/api-tutorial/index.md#make-api-calls-to-mtf).

Note that the sample code in this tutorial does not prescribe the design and coding of your funds transfer service; those aspects are for you to define.

![Sample Java class](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/java-api-tutorial-overview-rntz.png)

## Prerequisites {#prerequisites}

To complete this tutorial, you need:

* [Java 11+](https://www.java.com/en/download/manual.jsp). Ensure that your `JAVA_HOME` environment variable is pointing to your JDK installation or have the Java executable on your `PATH` environment variable.
* [Maven 3.6.0+](https://maven.apache.org/download.cgi)
* The latest [OpenAPI Generator CLI](https://openapi-generator.tech/docs/installation/#jar) JAR directly from Maven.org.
* Integrated Development Environment (IDE) of your choice. The tutorials use the IntelliJ IDEA IDE.
* If your organization uses internal artifact repositories for obtaining dependencies, refer to this [documentation](https://maven.apache.org/guides/mini/guide-multiple-repositories.html) to ensure that your dependencies are set up.
* A Mastercard Developers [project](https://developer.mastercard.com/dashboard) created with the **Mastercard Send** API service. This generated the Sandbox signing key (.p12 file) and credentials you will use to access the Sandbox environment. For guidance on creating a project, see [Getting Started with the APIs](https://developer.mastercard.com/mastercard-send/documentation/implementation/getting-started/).
* The API specification: [send-disbursement-api-swagger.yaml](https://static.developer.mastercard.com/content/mastercard-send-disbursements/swagger/send-disbursement-api-swagger.yaml) (166KB)

## Generate a Client Application {#generate-a-client-application}

Note: This tutorial was developed using a Windows machine. You can follow the same steps in other Operating Systems (OS) as well.

In File Explorer, create a folder in your desired location. In that folder:

1. Add the API specification YAML file and OpenAPI Generator CLI JAR file.

2. Create a `config.json` file and add the following configurations to the file:

```json
{
   "groupId":"com.acme.app",
   "artifactId":"mastercard-api-client",
   "artifactVersion":"1.0.0",
   "invokerPackage":"com.acme.app.mastercard",
   "apiPackage":"com.acme.app.mastercard.api",
   "modelPackage":"com.acme.app.mastercard.model"
}  
```

Your current folder should look as follows:

![Folder view with client generation files](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/api-tutorial-1-disb.png)

3. Open the Command Prompt, navigate to that folder, and run this command to generate the client application:

    openapi-generator-cli-7.8.0.jar generate -g java --library okhttp-gson -i send-disbursement-api-swagger.yaml -c config.json -o MyTestClient

In the above command, alter these parts as necessary:

* JAR version number, for example, "7.8.0"
* Name of the swagger file, for example, "send-disbursement-api-swagger.yaml"
* Name of the desired client application, for example, "MyTestClient"

After you run the command, a client application folder is generated within your folder:

![Folder with generated client folder](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/api-tutorial-2-disb.png)

## Set up a Maven Project {#set-up-a-maven-project}

After generating the client application, complete the below Maven project setup to download the dependencies and generate the Java client library.

1. In the IntelliJ IDE, open the client application as a **Maven** project. Your IntelliJ IDE should look as follows:

![IntelliJ project window](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/api-tutorial-3-disb.png)

2. Edit the **pom.xml** file to add the following OAuth Client Authentication Library as one of the dependencies:

```xml
    <dependency>
        <groupId>com.mastercard.developer</groupId>
        <artifactId>oauth1-signer</artifactId>
        <version>1.5.2</version>
    </dependency>
```

For example:

![Where to add the dependency in the POM file](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/api-tutorial-4.png)

3. In the IntelliJ IDE, navigate to the Terminal window and run this command:

    mvn clean install

When you have successfully run the command, a new folder named **target** is generated within your root directory, which contains classes generated for the schemas and API calls defined within the API specification. The generated classes can be found in `target/classes/com/acme/app/mastercard`:

![IntelliJ project target folder contents](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/api-tutorial-5.png)

4. In `./src/main/`, create a **resources** folder and copy the Sandbox signing key (.p12) file to that folder:

![Project key file](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/api-tutorial-6.png)

## Make API Calls to Sandbox {#make-api-calls-to-sandbox}

These steps build a simple Java program that makes calls to the Sandbox API using the generated client library. You can either:

* Download and use the Java class file [DisbursementSampleClass.java](https://static.developer.mastercard.com/content/mastercard-send-disbursements/uploads/DisbursementSampleClass.java) (8KB), then locate and adjust its code snippets as directed below.
* Create a new Java class file, then add and adjust the code snippets as directed below.

<br />

In your IntelliJ IDE project, add or create the Java class file in `./src/main/java`:

![Folder structure](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/java-api-tutorial-1-disb.png)

Open the Java class file and modify or add the following parts accordingly:

1. Add or adjust the code to import the required classes:

```java
import com.acme.app.mastercard.ApiClient;
import com.acme.app.mastercard.ApiException;
import com.acme.app.mastercard.api.DisbursementApi;
import com.acme.app.mastercard.model.*;
import com.mastercard.developer.interceptors.OkHttpOAuth1Interceptor;
import com.mastercard.developer.utils.AuthenticationUtils;
import java.security.PrivateKey;
import java.util.Random;
import java.util.concurrent.TimeUnit;
```

If any external class libraries do not import automatically, you may need to click the **Reload All Maven Projects** button in the Maven project window (**View \> Tool Windows \> Maven**):

![Reload Maven projects button](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/java-api-tutorial-2.png)

2. Update the consumer key and signing key values to match your .p12 file and the Sandbox Credentials from your Mastercard Developers project. These will be used by the `AuthenticationUtils.loadSigningKey()` method to generate a private signing key object.

```java
        // Update these values to match your OAuth credentials
        String consumerKey = "your_consumer_key_WdnUc_-2345tF245A-_DE7f71c_-75!b10-_23451b440ab_-e210b12-_58f650000000000000000";
        String signingKeyAlias = "your_key_alias";
        String signingKeyFilePath = "./src/main/resources/Send_API_Testing-sandbox.p12";
        String signingKeyPassword = "your_key_password";

        // This method generates the signing key which can be used to sign your API requests
        PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword);

        // Set request header values
        String partnerId = "ptnr_BEeCrYJHh2BXTXPy_PEtp-8DBOo";
        Boolean declineDetailsQuery = false;
```

3. The base path is set to the Sandbox environment by default. You instantiate a client that can sign requests with your authentication credentials.

```java
        ApiClient apiClient = new ApiClient();

        apiClient.setBasePath("https://sandbox.api.move.mastercard.com/send/static");
        apiClient.setHttpClient(
                apiClient.getHttpClient()
                        .newBuilder()
                        .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
                        .build()
        );
```

4. You create a new `disbursementApi` request object to make the POST API call to the `/v1/partners/{partnerId}/disbursements/payment` endpoint.

```java
        DisbursementApi disbursementApi = new DisbursementApi(apiClient);
```

5. The `paymentDisbursementParent` object sets the values to the Request Body fields that are required to make a successful API call to the endpoint. You can modify the values as required.

```java
        PaymentDisbursementParent paymentDisbursementParent = new PaymentDisbursementParent();

        // This builder builds a unique Disbursement Reference for the disbursement
        StringBuilder builder = new StringBuilder();
        builder.append("ref_");
        for (int i = 0; i < 10; i++) {
            builder.append(new Random().nextInt(10));
        }
        String disbursementRefGenerated = builder.toString();

        // Set the values for the sender object
        Sender sender = new Sender();
        SenderAddress senderAddress = new SenderAddress();
        senderAddress.setLine1("101 Main St");
        senderAddress.setLine2("Unit 5");
        senderAddress.setCity("Chicago");
        senderAddress.setCountrySubdivision("IL");
        senderAddress.setPostalCode("60618");
        senderAddress.setCountry("USA");
        sender.setFirstName("XYZ");
        sender.setLastName("Record Store");
        sender.setAccountType("03");
        sender.setAddress(senderAddress);

        // Set the values for the recipient object
        Recipient recipient = new Recipient();
        RecipientAddress recipientAddress = new RecipientAddress();
        recipientAddress.setLine1("234 Spiral Drive");
        recipientAddress.setLine2("Unit B");
        recipientAddress.setCity("St. Louis");
        recipientAddress.setCountrySubdivision("MO");
        recipientAddress.setPostalCode("63368");
        recipientAddress.setCountry("USA");
        recipient.setFirstName("Vinyl");
        recipient.setLastName("Importers");
        recipient.setAccountType("03");
        recipient.setAddress(recipientAddress);
        recipient.setNameOnAccount("Lucy Lawrence");

        // Set the values for the participant object
        Participant participant = new Participant();
        TransferAcceptorAddress transferAcceptorAddress = new TransferAcceptorAddress();
        transferAcceptorAddress.setLine1("123 Elm St");
        transferAcceptorAddress.setLine2("Apartment 9");
        transferAcceptorAddress.setCity("Chicago");
        transferAcceptorAddress.setCountrySubdivision("IL");
        transferAcceptorAddress.setPostalCode("60618");
        transferAcceptorAddress.setCountry("USA");
        participant.setMerchantCategoryCode("6536");
        participant.setTransferAcceptorAddress(transferAcceptorAddress);

        // Set the values for the paymentDisbursement object
        PaymentDisbursement paymentDisbursement = new PaymentDisbursement();
        paymentDisbursement.setDisbursementReference(disbursementRefGenerated);
        paymentDisbursement.setPaymentType("BDB");
        paymentDisbursement.setAmount("5300");
        paymentDisbursement.setCurrency("USD");
        paymentDisbursement.setSenderAccountUri("pan:5102589999999921;exp=2077-02;cvc=123");
        paymentDisbursement.setSender(sender);
        paymentDisbursement.setRecipientAccountUri("pan:5102589999999913;exp=2077-08;cvc=123");
        paymentDisbursement.setRecipient(recipient);
        paymentDisbursement.setParticipant(participant);
        paymentDisbursement.setFundingSource("DEBIT");
        paymentDisbursement.setTransactionPurpose("00");

        // Wrap paymentDisbursement object into the main parent object
        paymentDisbursementParent.setPaymentDisbursement(paymentDisbursement);
```

6. You call the `sendDisbursement` function to make the POST API call to the `/v1/partners/{partnerId}/disbursements/payment` endpoint and store the response in a `disbursementResponse` object.

```java
        // Make the POST call to create the disbursement
        DisbursementParent disbursementResponse = null;
        try {
            disbursementResponse = disbursementApi.sendDisbursement(partnerId, paymentDisbursementParent, declineDetailsQuery, false);
            System.out.println("Request:");
            System.out.println(paymentDisbursementParent);
            System.out.println();
            System.out.println("Response:");
            System.out.println(disbursementResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling disbursementApi.sendDisbursement");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

7. You can access the individual response values using the `disbursementResponse.get()` method. For example, this code gets the disbursement status and reference IDs:

```java
        // Show the disbursement status and reference IDs
        String disbursementStatus = disbursementResponse.getDisbursement().getStatus();
        String disbursementRef = disbursementResponse.getDisbursement().getDisbursementReference();
        String disbursementId = disbursementResponse.getDisbursement().getId();
        System.out.println();
        System.out.println("Disbursement is " + disbursementStatus);
        System.out.println("Disbursement Reference = " + disbursementRef);
        System.out.println("Disbursement ID = " + disbursementId);
```

8. You can retrieve details of the disbursement using a GET by ID call with the Disbursement ID obtained from the POST response.

You call the `retrieveDisbursement` function to make the GET API call to the `/v1/partners/{partnerId}/disbursements/{disbursementId}` endpoint and store the response in a `disbursementByIdResponse` object.

```java
        // Make a GET by ID call to retrieve information on the disbursement
        System.out.println();
        System.out.println("Wait five seconds before trying GET by ID call...");
        TimeUnit.SECONDS.sleep(5);

        DisbursementParentGetId disbursementByIdResponse = null;
        try {
            disbursementByIdResponse = disbursementApi.retrieveDisbursement(partnerId, disbursementId);
            System.out.println();
            System.out.println("Response:");
            System.out.println(disbursementByIdResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling disbursementApi.retrieveDisbursement");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

9. You can retrieve details of the disbursement using a GET by Reference call with the Disbursement Reference obtained from the POST response.

You call the `retrieveDisbursementByRef` function to make the GET API call to the `/v1/partners/{partnerId}/disbursements` endpoint and store the response in a `disbursementByRefResponse` object.

```java
        // Make a GET by Reference call to retrieve information on the disbursement
        System.out.println();
        System.out.println("Wait five seconds before trying GET by Reference call...");
        TimeUnit.SECONDS.sleep(5);

        DisbursementsParent disbursementByRefResponse = null;
        try {
            disbursementByRefResponse = disbursementApi.retrieveDisbursementByRef(partnerId, disbursementRef);
            System.out.println();
            System.out.println("Response:");
            System.out.println(disbursementByRefResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling disbursementApi.retrieveDisbursementByRef");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

10. Build and run the Java class file. You can do this using the **Build Project** and **Run** buttons:

![Build and run Java class file](https://static.developer.mastercard.com/content/mastercard-send-disbursements/documentation/img/java-api-tutorial-3.png)

#### Expected result {#expected-result}

When run successfully, the Java code should print the following in the IntelliJ IDE Run window:

1. POST request and response objects, for example (truncated):

```plain
Request:
class PaymentDisbursementParent {
    paymentDisbursement: class PaymentDisbursement {
        disbursementReference: ref_5481669240
        paymentType: BDB
        amount: 5300
        currency: USD
        senderAccountUri: pan:5102589999999921;exp=2077-02;cvc=123
        sender: class Sender {
            firstName: XYZ
...
```

2. Disbursement status and reference IDs obtained from the POST response, for example:

```plain
Disbursement is APPROVED
Disbursement Reference = ref_5481669240
Disbursement ID = 4e249d5742e24158b460377fc9a13751
```

3. GET by ID response objects, for example (truncated):

```plain
Response:
class DisbursementParentGetId {
    disbursement: class DisbursementGetId {
        id: 4e249d5742e24158b460377fc9a13751
        resourceType: disbursement
        disbursementReference: ref_5481669240
        paymentType: BDB
        senderAccountUri: pan:************9921
        sender: class SenderRetrieved {
            firstName: XYZ
...
```

4. GET by Reference response objects, for example (truncated):

```plain
Response:
class DisbursementsParent {
    disbursements: class Disbursements {
        resourceType: list
        itemCount: 1
        data: class DisbursementsData {
            disbursement: [class DisbursementRetrieved {
                id: 4e249d5742e24158b460377fc9a13751
                resourceType: disbursement
                disbursementReference: ref_5481669240
...
```

## Make API Calls to MTF {#make-api-calls-to-mtf}

You can make calls to the MTF environment when you have registered for this service and Mastercard has configured that environment for your Sandbox keys. When you have the tutorial working with Sandbox, you can adapt the code easily to call MTF:

* Adjust the base path to "https://sandbox.api.move.mastercard.com/send".
* Change the `partnerId` value to match your onboarded configuration.

You may need to adjust the code to pass request fields and values appropriate to the environment and your configuration, such as valid test account numbers and any required acquiring credentials.
