# Java Tutorial
source: https://developer.mastercard.com/transaction-notifications/documentation/tutorials/java-tutorial/index.md

## Introduction {#introduction}

This project showcases the use case of sending test notifications for a transaction using the [Transaction Notifications API](https://developer.mastercard.com/transaction-notifications/documentation/api-reference/endpoints/index.md).

Warning: Transaction Notifications API is only available in sandbox at the moment.

<br />

## Prerequisites {#prerequisites}

* [Mastercard Developers Account](https://developer.mastercard.com/account/log-in)
* [Java 8+](https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html)
* [Apache Maven 3.3+](https://maven.apache.org/download.cgi)
* [Mastercard API signing library](https://github.com/Mastercard/oauth1-signer-java)

## Application Configuration {#application-configuration}

1. Create an account at [Mastercard Developers](https://developer.mastercard.com/account/sign-up).
2. Create a new project and add the `Transaction Notifications` API to your project.
   * A zip file will be downloaded automatically with your keys.
3. Take note of the given **consumer key, keyalias, and keystore password** given upon the project creation.
4. Download the reference app from here: [tn-java-ref-app.zip](https://static.developer.mastercard.com/content/transaction-notifications/uploads/tn-java-ref-app.zip) (231KB)
5. Copy the downloaded `.p12` file to `/src/main/resources`.
6. Update the properties found in `src/main/java/com/mastercard/notification/ApiService.java`.

```java
    private static final String API_BASE_PATH = "https://sandbox.api.mastercard.com/openapis";

    //Below properties will be required for authentication of API calls.
    private static final String CONSUMER_KEY = "Your consumer key"; // This refers to your consumer key. Copy it from "Keys" section on your project page in [Mastercard Developers](https://developer.mastercard.com/dashboard)
    private static final String SIGNING_KEY_ALIAS = "your key alias"; // This is the default value of key alias. If it is modified, use the updated one from keys section in [Mastercard Developers](https://developer.mastercard.com/dashboard).
    private static final String SIGNING_KEY_FILE_PATH = "path to your.p12 private key file"; // This refers to .p12 file found in the signing key. Please place .p12 file at ./src/main/resources in the project folder and add classpath for .p12 file.
    private static final String SIGNING_KEY_PASSWORD = "your password"; // This is the default value of key alias. If it is modified, use the updated one from keys section in [Mastercard Developers](https://developer.mastercard.com/dashboard).

```

7. Run `mvn clean compile` from the root of the project directory.
   * When compile is run, the [OpenAPI Generator plugin](https://developer.mastercard.com/transaction-notifications/documentation/tutorials/java-tutorial/index.md#integrating-with-openapi-generator) will generate the sources for connecting to the Transaction Notification API.
8. Run `mvn spring-boot:run` to run the project.

#### Integrating with OpenAPI Generator {#integrating-with-openapi-generator}

[OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) generates API client libraries from [OpenAPI Specs](https://github.com/OAI/OpenAPI-Specification).
It provides generators and library templates for supporting multiple languages and frameworks.

##### OpenAPI Generator Plugin Configuration {#openapi-generator-plugin-configuration}

```xml
<build>
  <plugins>
    <plugin>
      <groupId>org.openapitools</groupId>
      <artifactId>openapi-generator-maven-plugin</artifactId>
      <version>3.3.4</version>
      <executions>
        <execution>
          <id>Transaction Notifications REST Client</id>
          <goals>
            <goal>generate</goal>
          </goals>
          <configuration>
            <inputSpec>${project.basedir}/src/main/resources/inbound.yml</inputSpec>
            <generatorName>java</generatorName>
            <!-- No "library" element here means the plugin will use the default library template ("okhttp-gson") -->
            <configOptions>
              <sourceFolder>src/gen/java/main</sourceFolder>
              <dateLibrary>java8</dateLibrary>
            </configOptions>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
```

#### See also: {#see-also}

* [OpenAPI Generator (maven Plugin)](https://mvnrepository.com/artifact/org.openapitools/openapi-generator-maven-plugin)
* [OpenAPI Generator (executable)](https://mvnrepository.com/artifact/org.openapitools/openapi-generator-cli)
* [CONFIG OPTIONS for java](https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/java.md)

## Mastercard oauth1 Signer Library {#mastercard-oauth1-signer-library}

These dependency are required to properly call the API.

```xml
    <dependency>
        <groupId>com.mastercard.developer</groupId>
        <artifactId>oauth1-signer</artifactId>
        <version>${oauth1-signer-version}</version>
        <!-- See: https://github.com/Mastercard/oauth1-signer-java/releases -->
    </dependency>

```

See the code used in this application to utilize the library.

```Java

    ApiClient client = new ApiClient();
    client.setBasePath(API_BASE_PATH);
    client.setDebugging(true);
    
    PrivateKey signingKey = AuthenticationUtils.loadSigningKey(SIGNING_KEY_FILE_PATH, SIGNING_KEY_ALIAS, SIGNING_KEY_PASSWORD);
    
    List<Interceptor> interceptors = client.getHttpClient().networkInterceptors();
    interceptors.add(new OkHttp2OAuth1Interceptor(CONSUMER_KEY, signingKey));
    interceptors.add(new Main.LogInterceptor());

```

## Test transaction {#test-transaction}

Call `/createTestTransaction` endpoint of the application.

`curl http://localhost:5000/createTestTransaction`

In the application logs, you should see the request and response (200 OK) from the test transaction API call.

To receive the notification at your webhook endpoint:

1. Your webhook endpoint (on which you want to receive the transaction notifications) must have been onboarded on to our system.
2. You must have enrolled the card through consent flow for which you are calling a test transaction notification API.

The following program shows how to trigger a test transaction for a card:

```java

    TestTransaction testTransaction = new TestTransaction();
    testTransaction.setCardholderAmount(BigDecimal.valueOf(9.99));
    testTransaction.setCardholderCurrency("EUR");
    testTransaction.setCardReference("CARD_REF");
    testTransaction.setMerchantName("Centra");
    
    apiService.createTransaction(testTransaction);
    System.out.println("Transaction: "+ testTransaction);
```

## Undelivered Notifications {#undelivered-notifications}

In case you don't have your webhook endpoint setup yet, you can use undelivered API to see the test notification you just created.

`curl http://localhost:5000/undeliveredNotifications`

Sample output:

```json
{
	"nextCursor": 5621260951,
	"data": [
		{
      "notificationSequenceId": "5621260801",
			"cardAcceptorId": "123456",
			"financialNetworkCode": "MCU",
			"recurringTransaction": "false",
			"channel": "ECOM",
			"transactionLocalDate": "2023-09-08",
			"cardReference": "e7917328-983f-410a-9c58-afc83ff5c856",
			"systemDateTime": "2023-09-08T20:46:03+0000",
			"cardLastNumbers": "1066",
      ...
		},
```

