# Affordability assessment - 5 Minutes Tutorial - Java SDK

## Prerequisites

The following information is required to be able to integrate with Authologic:

- Developer portal credentials,
- API Keys.

### Developer Portal Credentials

The developer portal address and credentials were provided during onboarding.

### Passwords And API Keys

During the onboarding you have received the API keys:

- API key allowing communication with Authologic.
- The key used to verify the data sent by Authologic by the callback mechanism.

## Integration Overview

<note>

Authologic provides a simple and effective way to check a user’s affordability assessment. The API process
involves three key steps: initiating the verification through an external system, redirecting
the user to the appropriate page, and receiving the verification results.

</note>

The entire process is called **conversation**. The following diagram represents the process logical flow:

<mermaid-diagram dark="/diagrams/534205ce5e9e-dark.svg" description="Sequence diagram" light="/diagrams/534205ce5e9e-light.svg">



</mermaid-diagram>

1. Start of the affordability assessment verification process. Your server calls the API method called: *POST
/api/conversations*
2. The response returns information about the address to which the user should be redirected
3. Your system redirects the user's browser to the above URL
4. The user verifies himself
5. Authologic redirects the user's browser to a predefined page of your system
6. Your server displays the return page
7. Authologic calls a callback on your server's side with the result of the verification

One API for online affordability assessment verification written in Java.

## Installation

The installation of the library is as simple as including it as one of the projects dependencies.

We encourage to use the newest version of the library as we are constantly expanding our product
offering and the underlying functionalities.

### Maven

Include the following dependency in your `pom.xml` file to use Authologic Java SDK:

```xml
<dependency>
    <groupId>com.authologic.client</groupId>
    <artifactId>authologic-client</artifactId>
    <version>0.2.42</version>
</dependency>
```

### Gradle

Include the following dependency in your `build.gradle` file to use Authologic Java SDK:

```java
implementation("com.authologic.client:authologic-client:0.2.42")
```

## Usage

The following example demonstrate an example on how you can use the Java SDK to interact with the Authologic APIs.

### Creating Conversation

To start a new conversation process, which is the main entry point for the identity checking product the
following example can be used:

```java
import com.authologic.client.api.*;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Client client = ClientBuilder.builder("username", "password").sandbox().build();

        Conversation conversation = client.execute(
                Requests.
                        createConversation().
                        strategy("public:sandbox").
                        callbackUrl("some_callback_url").
                        addProduct(
                                new AffordabilityProductQueryBuilder(
                                        new AffordabilityUser("John", "Doe", "J", "1990-01-01", "44", "00-999", "PL", "johndoe@email.com")
                                ))
        ).get();

        System.out.println(conversation.getUrl());
    }
}
```

#### Creating the Client Instance

We start by creating the Client instance:

```java
Client client = ClientBuilder.builder("username", "password").sandbox().build();
```

API credentials can be generated via OmniPanel.
Because the API is secured you need the provided credentials to be able to interact with it.
Once initialized the `Client` instance may be used to interact with the Authologic API.

#### Creating the Conversation

Next we can create the conversation and request the first and last name of the person we are
requesting the identification for. For that purpose we use the `Requests.createConversation()`
using the following code snippet:

```java
Requests.createConversation().strategy("public:sandbox").callbackUrl("some_callback_url").addProduct(
        new AffordabilityProductQueryBuilder(
                new AffordabilityUser("John", "Doe","J","1990-01-01","44","00-999","PL","johndoe@email.com")
        )
)
```

We set:

- the strategy
- the callback URL
- the product that we want to use

The **strategy** is the information that tells Authologic how to perform the operation.
The field is optional, but you can explicitly provide the information to choose the strategy that
you want to use. In the above example we used the `public:sandbox`, a strategy which doesn't perform a
real verification, but allows to test the whole flow.

The **callback URL** is the URL that Authologic will send the user when the process, in our example case
the identification process, will be completed. You should set it to match return to your application or
use a service like [Webhook Site](https://webhook.site/) if you plan on testing the SDK.

The product that we want to use is the **Affordability assessment** product, which allows us to perform verification.
In our example we provide all information required to perform affordability assessment check.
To do that we use the `AffordabilityProductQueryBuilder` class and provide the person's data:

```java
new AffordabilityProductQueryBuilder(
        new AffordabilityProductUserBuilder(
                new AffordabilityUser("John", "Doe","J","1990-01-01","44","00-999","PL","johndoe@email.com")
        )
                )
```

As the final step we print the URL of the created conversation to the standard output to be able to continue
the process. If you are trying out the SDK head to the returned link to fill out the data that will be
returned as test data for your affordability assessment verification test.

### Working with Callbacks

<note>

**Project dependencies:**
Please remember that when working with callbacks you not only need the
`authologic-client` library, but also `authologic-client-json` and one of the JSON parsing modules, for example
`authologic-client-module-jackson`.

</note>

The Java SDK can also be used to parse the information sent to your callback URL. It is as simple as initializing one
of the JSON parsing engines, deserializing the body of the request received in the callback and using the result data.
For example this is how the code could look like:

```java
JsonEngine jsonEngine = (new JacksonJsonEngineProvider()).createJsonEngine();
Callback callback = jsonEngine.deserialize(callbackBody, Callback.class);

if (callback.isConversationFinished()) {
    Conversation conversation = callback.asConversationFinished().getConversation();
    if (conversation.getResult().getAffordability().getStatus() == ProductResultStatus.FINISHED) {
        // TODO: schedule affordability assessment result fetching
    }
}
```

Let's discuss the above example.

#### Initializing JSON Parser

We start by initializing the JSON parser, so we can easily parse the response.
We do it only once as the parser is thread-safe and can be reused later when needed:

```java
JsonEngine jsonEngine = (new JacksonJsonEngineProvider()).createJsonEngine();
```

#### Deserializing the Results

We assume that we got the callback body and stored i tin the `callbackBody` variable. Once we have it
we can easily deserialize it to the `CallbackResult` class using the initialized JSON parser:

```java
Callback callbackResult = jsonEngine.deserialize(ctx.body(), Callback.class);
```

The abstract Callback class provides two methods to identify the type of the result:

- the `isConversationFinished` returning `true` if the result is of type `Conversation` representing conversation
- the `isUnknownCallback` returning `true` if the result is of type `UnknownCallback` representing unknown callback

In the example code we expect the `FinishedConversationCallback`, so we check for it:

```java
if (callback.isConversationFinished()) {
```

After we verified that we got the class we were expecting we can retrieve the conversation from the
deserialized object and check whether the affordability assessment results are ready and if they are, we can schedule
fetching of the affordability assessment results via the dedicated API:

```java
Conversation conversation = callback.asConversationFinished().getConversation();
if (conversation.getResult().getAffordability().getStatus() == ProductResultStatus.FINISHED) {
    // TODO: schedule affordability assessment results fetching
}
```

#### Collecting affordability product results from API endpoint

The Java SDK can also be used to call API endpoint to retrieve the information about affordability assessment
results.
Simply initialize the client and call `getAffordabilityResults` method and provide `conversationId` parameter.
You should then parse the response and retrieve the result data from individual sections.
For example this is how the code could look like:

```java
Client client = ClientBuilder.builder("your-username", "your-password")
        .sandbox()
        .build();

    String conversationId = "Authologic conversation identifier";

    // Execute GET /conversations/{conversationId}/affordability/info
    AffordabilityResults results = client
        .execute(Requests.getAffordabilityResults(conversationId))
        .getOrThrow(ex -> ex);  // rethrows ApiException

        results.getItems().forEach(item -> {

            //Fetch personal information
            item.getPersonalInformation().getFirstName()
            item.getPersonalInformation().getLastName());

            //Fetch account information
            item.getAccountInformation().getAccount().forEach(...);

            //Fetch source of funds information
            item.getSourceOfFundsInformation().getSource().forEach(...);

            //Fetch financial analysis information
            item.getFinancialAnalysis().getIncome()
            item.getFinancialAnalysis().getExpenditure());
        });
```

## What's Next

<card-group>
<card title="Handling Callbacks" to="/docs/integration/callbacks">

Handling callbacks using Java SDK.

</card>

<card title="Combining Products" to="/docs/integration/combining-products">

Combining multiple products together in a single request.

</card>

<card title="Testing" to="/docs/integration/testing">

Learn how to test your integration.

</card>

<card title="Productionize" to="/docs/integration/going-live">

What to do before going to production.

</card>
</card-group>

## Troubleshooting

<card-group>
<card title="Callbacks" to="/docs/integration/use-cases#not-able-to-receive-callbacks">

Not being able to receive callbacks.

</card>

<card title="Errors" to="/docs/technical/errors">

Verification failure reasons.

</card>

<card title="Statuses" to="/docs/technical/conversation-statuses">

Handling various conversation statuses.

</card>

<card title="FAQ" to="/docs/integration/faq">

Frequently asked questions.

</card>

<card title="Deprecations" to="/docs/integration/deprecations">

Deprecated features and options list.

</card>
</card-group>

<note>

Despite our sincere intentions, it is difficult to create perfect technical documentation.
If you have an idea on how to improve this documentation, or you have trouble understanding any section,
please email us at [tech-support@authologic.com](mailto:tech-support@authologic.com)

</note>
