### Installation and Setup
Source: https://context7.com/plaid/plaid-java/llms.txt
Add the plaid-java dependency to your Maven project to begin using the Plaid API in your Java application.
```APIDOC
## Installation and Setup
Add the plaid-java dependency to your Maven project to begin using the Plaid API in your Java application.
```xml
com.plaid
plaid-java
39.0.0
```
```
--------------------------------
### Client Initialization
Source: https://context7.com/plaid/plaid-java/llms.txt
Initialize the Plaid API client with your credentials and environment configuration. This setup is necessary before making any API calls.
```APIDOC
## Client Initialization
Initialize the Plaid API client with your credentials and environment configuration.
```java
import com.plaid.client.ApiClient;
import com.plaid.client.request.PlaidApi;
import java.util.HashMap;
// Initialize API client with credentials
HashMap apiKeys = new HashMap<>();
apiKeys.put("clientId", "YOUR_CLIENT_ID");
apiKeys.put("secret", "YOUR_SECRET");
apiKeys.put("plaidVersion", "2020-09-14");
ApiClient apiClient = new ApiClient(apiKeys);
// Set environment: ApiClient.Sandbox or ApiClient.Production
apiClient.setPlaidAdapter(ApiClient.Sandbox);
// Optional: Set custom timeout (in seconds)
apiClient.setTimeout(120);
// Create the PlaidApi service
PlaidApi plaidClient = apiClient.createService(PlaidApi.class);
```
```
--------------------------------
### Execute Asynchronous API Calls with Plaid Java SDK
Source: https://context7.com/plaid/plaid-java/llms.txt
Demonstrates how to perform asynchronous API calls using Retrofit's callback mechanism for non-blocking operations. This example shows an asynchronous public token exchange.
```java
import com.plaid.client.model.*;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
// Asynchronous public token exchange
ItemPublicTokenExchangeRequest request = new ItemPublicTokenExchangeRequest()
.publicToken(publicToken);
plaidClient.itemPublicTokenExchange(request).enqueue(new Callback() {
@Override
public void onResponse(Call call,
Response response) {
if (response.isSuccessful()) {
String accessToken = response.body().getAccessToken();
String itemId = response.body().getItemId();
System.out.println("Access Token obtained: " + accessToken);
// Continue with next operations
} else {
try {
System.err.println("Error: " + response.errorBody().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
System.err.println("Request failed: " + t.getMessage());
t.printStackTrace();
}
});
```
--------------------------------
### Link Token Create
Source: https://context7.com/plaid/plaid-java/llms.txt
Create a Link token to initialize Plaid Link in your application for user authentication with financial institutions. This token is used to start the Plaid Link flow.
```APIDOC
## Link Token Create
Create a Link token to initialize Plaid Link in your application for user authentication with financial institutions.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Arrays;
import java.util.Date;
// Create user object with unique client user ID
LinkTokenCreateRequestUser user = new LinkTokenCreateRequestUser()
.clientUserId(Long.toString(new Date().getTime()))
.legalName("John Doe")
.phoneNumber("4155558888")
.emailAddress("john@example.com");
// Configure account filters (optional)
DepositoryFilter depositoryFilter = new DepositoryFilter()
.accountSubtypes(Arrays.asList(DepositoryAccountSubtype.CHECKING, DepositoryAccountSubtype.SAVINGS));
LinkTokenAccountFilters accountFilters = new LinkTokenAccountFilters()
.depository(depositoryFilter);
// Build the Link token request
LinkTokenCreateRequest request = new LinkTokenCreateRequest()
.user(user)
.clientName("My App")
.products(Arrays.asList(Products.AUTH, Products.TRANSACTIONS))
.countryCodes(Arrays.asList(CountryCode.US))
.language("en")
.webhook("https://example.com/webhook")
.accountFilters(accountFilters);
// Execute the request
Response response = plaidClient.linkTokenCreate(request).execute();
if (response.isSuccessful()) {
String linkToken = response.body().getLinkToken();
System.out.println("Link Token: " + linkToken);
System.out.println("Expiration: " + response.body().getExpiration());
} else {
System.err.println("Error: " + response.errorBody().string());
}
```
```
--------------------------------
### Plaid Client Method Call Updates
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Demonstrates the updated method calling conventions for Plaid client endpoints. The `service()` call has been removed, and endpoints starting with `get` are now named `${Model}Get`.
```java
// Old method call
// client().service().accountsBalanceGet(new AccountsBalanceGetRequest(accessToken)).execute();
// New method call
// AccountsBalanceGetRequest request = new AccountsBalanceGetRequest().accessToken(accessToken);
// client().accountsBalanceGet(request).execute();
```
--------------------------------
### Liabilities Get
Source: https://context7.com/plaid/plaid-java/llms.txt
Retrieves liability information for various account types, including credit cards, student loans, and mortgages. Provides details on balances, payments, and interest rates.
```APIDOC
## GET /liabilities/get
### Description
Retrieve liability information for credit cards, student loans, and mortgages.
### Method
GET
### Endpoint
/liabilities/get
### Parameters
#### Query Parameters
- **access_token** (string) - Required - The access token associated with the Item data is being requested for.
### Request Example
```json
{
"access_token": "your_access_token"
}
```
### Response
#### Success Response (200)
- **liabilities** (object) - An object containing liability details.
- **credit** (array of objects) - Credit card liabilities.
- **account_id** (string) - The Plaid `account_id`.
- **is_overdue** (boolean) - Whether the liability is currently overdue.
- **last_payment_amount** (number) - The amount of the last payment.
- **last_payment_date** (string) - The date of the last payment (YYYY-MM-DD).
- **minimum_payment_amount** (number) - The minimum payment due for the current billing cycle.
- **next_payment_due_date** (string) - The date on which the next payment is due (YYYY-MM-DD).
- **aprs** (array of objects) - Details about the Annual Percentage Rates (APRs).
- **apr_percentage** (number) - The APR percentage.
- **apr_type** (string) - The type of APR (e.g., 'regular', 'promotional').
- **balance_subject_to_apr** (number) - The balance subject to this APR.
- **student** (array of objects) - Student loan liabilities.
- **loan_name** (string) - The name of the loan.
- **account_number** (string) - The loan account number.
- **interest_rate_percentage** (number) - The interest rate as a percentage.
- **origination_principal_amount** (number) - The original principal amount of the loan.
- **outstanding_interest_amount** (number) - The outstanding interest amount.
- **minimum_payment_amount** (number) - The minimum payment due for the current billing cycle.
- **next_payment_due_date** (string) - The date on which the next payment is due (YYYY-MM-DD).
- **expected_payoff_date** (string) - The expected date of loan payoff (YYYY-MM-DD).
- **loan_status** (object) - The status of the loan.
- **type** (string) - The type of loan status (e.g., 'active', 'paid off').
#### Response Example
```json
{
"liabilities": {
"credit": [
{
"account_id": "acc_credit123",
"is_overdue": false,
"last_payment_amount": 50.00,
"last_payment_date": "2023-10-01",
"minimum_payment_amount": 25.00,
"next_payment_due_date": "2023-11-01",
"aprs": [
{
"apr_percentage": 19.99,
"apr_type": "regular",
"balance_subject_to_apr": 1200.50
}
]
}
],
"student": [
{
"loan_name": "Federal Student Loan",
"account_number": "SL123456789",
"interest_rate_percentage": 4.5,
"origination_principal_amount": 30000.00,
"outstanding_interest_amount": 500.75,
"minimum_payment_amount": 150.00,
"next_payment_due_date": "2023-11-15",
"expected_payoff_date": "2030-05-01",
"loan_status": {
"type": "active"
}
}
]
}
}
```
```
--------------------------------
### Retrieve Liabilities Information with Plaid Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Fetches liability information for various accounts like credit cards, student loans, and mortgages using the Plaid Java client. This example demonstrates how to process credit card and student loan liabilities, including details like payment amounts, due dates, and interest rates. It requires the Plaid client and an access token.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
LiabilitiesGetRequest request = new LiabilitiesGetRequest()
.accessToken(accessToken);
Response response = plaidClient.liabilitiesGet(request).execute();
if (response.isSuccessful()) {
LiabilitiesObject liabilities = response.body().getLiabilities();
// Credit card liabilities
System.out.println("Credit Cards:");
for (CreditCardLiability creditCard : liabilities.getCredit()) {
System.out.println(" Account ID: " + creditCard.getAccountId());
System.out.println(" Is Overdue: " + creditCard.getIsOverdue());
System.out.println(" Last Payment: $" + creditCard.getLastPaymentAmount());
System.out.println(" Last Payment Date: " + creditCard.getLastPaymentDate());
System.out.println(" Minimum Payment: $" + creditCard.getMinimumPaymentAmount());
System.out.println(" Next Payment Due: " + creditCard.getNextPaymentDueDate());
// APR details
for (APR apr : creditCard.getAprs()) {
System.out.println(" APR: " + apr.getAprPercentage() + "% (" + apr.getAprType() + ")");
System.out.println(" Balance Subject to APR: $" + apr.getBalanceSubjectToApr());
}
}
// Student loan liabilities
System.out.println("\nStudent Loans:");
for (StudentLoan loan : liabilities.getStudent()) {
System.out.println(" Loan Name: " + loan.getLoanName());
System.out.println(" Account Number: " + loan.getAccountNumber());
System.out.println(" Interest Rate: " + loan.getInterestRatePercentage() + "% ");
System.out.println(" Original Principal: $" + loan.getOriginationPrincipalAmount());
System.out.println(" Outstanding Interest: $" + loan.getOutstandingInterestAmount());
System.out.println(" Minimum Payment: $" + loan.getMinimumPaymentAmount());
System.out.println(" Next Payment Due: " + loan.getNextPaymentDueDate());
System.out.println(" Expected Payoff: " + loan.getExpectedPayoffDate());
System.out.println(" Loan Status: " + loan.getLoanStatus().getType());
}
}
```
--------------------------------
### Get Account Balances - Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Retrieves real-time balance information for all accounts associated with an Item. This includes available, current, and currency details. It supports filtering by specific account IDs.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Arrays;
// Basic balance request
AccountsBalanceGetRequest request = new AccountsBalanceGetRequest()
.accessToken(accessToken);
Response response = plaidClient.accountsBalanceGet(request).execute();
if (response.isSuccessful()) {
for (AccountBase account : response.body().getAccounts()) {
System.out.println("Account: " + account.getName());
System.out.println(" Type: " + account.getType());
System.out.println(" Subtype: " + account.getSubtype());
System.out.println(" Available Balance: " + account.getBalances().getAvailable());
System.out.println(" Current Balance: " + account.getBalances().getCurrent());
System.out.println(" Currency: " + account.getBalances().getIsoCurrencyCode());
}
}
// Balance request with specific account filtering
AccountsBalanceGetRequestOptions options = new AccountsBalanceGetRequestOptions()
.accountIds(Arrays.asList("account_id_1", "account_id_2"));
AccountsBalanceGetRequest filteredRequest = new AccountsBalanceGetRequest()
.accessToken(accessToken)
.options(options);
Response filteredResponse = plaidClient.accountsBalanceGet(filteredRequest).execute();
```
--------------------------------
### Investments Holdings Get
Source: https://context7.com/plaid/plaid-java/llms.txt
Retrieves investment holdings, including details about securities, quantities, and current values. It also supports filtering by specific investment account IDs.
```APIDOC
## GET /investments/holdings/get
### Description
Retrieve investment holdings including securities, quantities, and current values.
### Method
GET
### Endpoint
/investments/holdings/get
### Parameters
#### Query Parameters
- **access_token** (string) - Required - The access token associated with the Item data is being requested for.
- **options** (object) - Optional - An object containing options for the request.
- **account_ids** (array of strings) - Optional - Specify an array of `account_id`s to retrieve holdings for.
### Request Example
```json
{
"access_token": "your_access_token",
"options": {
"account_ids": ["investment_account_id"]
}
}
```
### Response
#### Success Response (200)
- **securities** (array of objects) - Information about the securities held.
- **name** (string) - Name of the security.
- **security_id** (string) - Plaid's unique identifier for the security.
- **type** (string) - The type of security (e.g., 'equity', 'mutual fund').
- **ticker_symbol** (string) - The security's ticker symbol or exchange-traded fund symbol.
- **close_price** (number) - The closing price of the security.
- **iso_currency_code** (string) - The ISO-4217 currency code for the security.
- **holdings** (array of objects) - Information about the investment holdings.
- **security_id** (string) - The `security_id` of the holding.
- **account_id** (string) - The `account_id` associated with the holding.
- **quantity** (number) - The number of units of the security held.
- **institution_value** (number) - The total value of the holding in the `institution_currency_code`.
- **cost_basis** (number) - The cost basis of the holding.
#### Response Example
```json
{
"securities": [
{
"name": "Apple Inc.",
"security_id": "ABC12345",
"type": "equity",
"ticker_symbol": "AAPL",
"close_price": 170.50,
"iso_currency_code": "USD"
}
],
"holdings": [
{
"security_id": "ABC12345",
"account_id": "acc_abc123",
"quantity": 10,
"institution_value": 1705.00,
"cost_basis": 1500.00
}
]
}
```
```
--------------------------------
### Install plaid-java Dependency (Maven)
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Add the plaid-java library to your Maven project by including the following dependency in your pom.xml. Ensure you replace '9.0.0' with the latest version available on Maven Central or GitHub tags.
```xml
com.plaid
plaid-java
9.0.0
```
--------------------------------
### Get Transactions with Pagination - Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Retrieves transaction history for an Item, supporting pagination and filtering by date range. It includes options to control the number of transactions per request and whether to include personal finance categories. Retry logic is implemented for potential PRODUCT_NOT_READY errors.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Define date range
LocalDate startDate = LocalDate.now().minusDays(30);
LocalDate endDate = LocalDate.now();
// Configure request options
TransactionsGetRequestOptions options = new TransactionsGetRequestOptions()
.count(100)
.offset(0)
.includePersonalFinanceCategory(true);
// Build transactions request
TransactionsGetRequest request = new TransactionsGetRequest()
.accessToken(accessToken)
.startDate(startDate)
.endDate(endDate)
.options(options);
// Execute with retry logic for PRODUCT_NOT_READY
Response response = null;
for (int i = 0; i < 5; i++) {
response = plaidClient.transactionsGet(request).execute();
if (response.isSuccessful()) {
break;
}
Thread.sleep(3000); // Wait before retry
}
if (response.isSuccessful()) {
TransactionsGetResponse txnResponse = response.body();
System.out.println("Total Transactions: " + txnResponse.getTotalTransactions());
// Paginate through all transactions
List allTransactions = new ArrayList<>(txnResponse.getTransactions());
while (allTransactions.size() < txnResponse.getTotalTransactions()) {
options = new TransactionsGetRequestOptions()
.offset(allTransactions.size())
.count(100)
.includePersonalFinanceCategory(true);
request = new TransactionsGetRequest()
.accessToken(accessToken)
.startDate(startDate)
.endDate(endDate)
.options(options);
response = plaidClient.transactionsGet(request).execute();
if (response.isSuccessful()) {
allTransactions.addAll(response.body().getTransactions());
}
}
// Process transactions
for (Transaction txn : allTransactions) {
System.out.println("Transaction: " + txn.getName());
System.out.println(" Amount: $" + txn.getAmount());
System.out.println(" Date: " + txn.getDate());
System.out.println(" Category: " + txn.getCategory());
System.out.println(" Pending: " + txn.getPending());
}
}
```
--------------------------------
### Fetch Transactions with Date Range (Java)
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Fetches transactions within a specified date range using the Plaid Java SDK. This example shows the older method of date parsing and the newer approach using LocalDate.
```java
SimpleDateFormat simpleDateFormat = new SimpleSimpleDateFormat("yyyy-MM-dd");
Date startDate = simpleDateFormat.parse("2018-01-01");
Date endDate = simpleDateFormat.parse("2018-02-01");
// Pull transactions for a date range
Response response = client().service().transactionsGet(
new TransactionsGetRequest(
accessToken,
startDate,
endDate))
.execute();
LocalDate startDateNew = LocalDate.now().minusDays(30);
LocalDate endDateNew = LocalDate.now();
TransactionsGetRequestOptions options = new TransactionsGetRequestOptions()
.includePersonalFinanceCategory(true)
// Pull transactions for a date range
TransactionsGetRequest request = new TransactionsGetRequest()
.accessToken(accessToken)
.startDate(startDateNew)
.endDate(endDateNew)
.options(options)
Response
response = plaidClient.transactionsGet(request).execute();
```
--------------------------------
### Identity Get: Retrieve Account Holder Information (Java)
Source: https://context7.com/plaid/plaid-java/llms.txt
Retrieves account holder identity information, including names, addresses, emails, and phone numbers, using the Plaid Java client. It iterates through accounts and their associated owners to extract detailed identity data. Requires an access token and the Plaid client object.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
IdentityGetRequest identityRequest = new IdentityGetRequest()
.accessToken(accessToken);
Response response = plaidClient.identityGet(identityRequest).execute();
if (response.isSuccessful()) {
for (AccountIdentity account : response.body().getAccounts()) {
System.out.println("Account: " + account.getName());
for (Owner owner : account.getOwners()) {
// Names
System.out.println(" Owner Names: " + owner.getNames());
// Email addresses
for (Email email : owner.getEmails()) {
System.out.println(" Email: " + email.getData());
System.out.println(" Type: " + email.getType());
System.out.println(" Primary: " + email.getPrimary());
}
// Addresses
for (Address address : owner.getAddresses()) {
System.out.println(" Address:");
System.out.println(" Street: " + address.getData().getStreet());
System.out.println(" City: " + address.getData().getCity());
System.out.println(" Region: " + address.getData().getRegion());
System.out.println(" Postal Code: " + address.getData().getPostalCode());
System.out.println(" Primary: " + address.getPrimary());
}
// Phone numbers
for (PhoneNumber phone : owner.getPhoneNumbers()) {
System.out.println(" Phone: " + phone.getData());
System.out.println(" Type: " + phone.getType());
System.out.println(" Primary: " + phone.getPrimary());
}
}
}
}
```
--------------------------------
### Auth Get: Retrieve Account and Routing Numbers (Java)
Source: https://context7.com/plaid/plaid-java/llms.txt
Retrieves bank account and routing numbers for ACH transfers using the Plaid Java client. It handles different account types (US ACH, Canadian EFT, UK BACS) and allows filtering by account ID. Requires an access token and the Plaid client object.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Collections;
// Basic auth request
AuthGetRequest authRequest = new AuthGetRequest()
.accessToken(accessToken);
Response response = plaidClient.authGet(authRequest).execute();
if (response.isSuccessful()) {
AuthGetNumbers numbers = response.body().getNumbers();
// ACH numbers (US accounts)
for (NumbersACH ach : numbers.getAch()) {
System.out.println("Account ID: " + ach.getAccountId());
System.out.println(" Account Number: " + ach.getAccount());
System.out.println(" Routing Number: " + ach.getRouting());
System.out.println(" Wire Routing: " + ach.getWireRouting());
}
// EFT numbers (Canadian accounts)
for (NumbersEFT eft : numbers.getEft()) {
System.out.println("Account ID: " + eft.getAccountId());
System.out.println(" Account Number: " + eft.getAccount());
System.out.println(" Branch: " + eft.getBranch());
System.out.println(" Institution: " + eft.getInstitution());
}
// BACS numbers (UK accounts)
for (NumbersBACS bacs : numbers.getBacs()) {
System.out.println("Account ID: " + bacs.getAccountId());
System.out.println(" Account Number: " + bacs.getAccount());
System.out.println(" Sort Code: " + bacs.getSortCode());
}
}
// Filter to specific accounts
AuthGetRequestOptions options = new AuthGetRequestOptions()
.accountIds(Collections.singletonList("specific_account_id"));
AuthGetRequest filteredRequest = new AuthGetRequest()
.accessToken(accessToken)
.options(options);
```
--------------------------------
### Initialize Plaid Client and Make API Call (Java)
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Demonstrates how to initialize the Plaid API client using API keys and set the environment (e.g., Sandbox). It shows both synchronous and asynchronous methods for exchanging a public token for an access token, including basic error handling for unsuccessful responses.
```java
private PlaidApi plaidClient;
HashMap apiKeys = new HashMap();
apiKeys.put("clientId", plaidClientId);
apiKeys.put("secret", plaidSecret);
apiClient = new ApiClient(apiKeys);
apiClient.setPlaidAdapter(ApiClient.Sandbox); // or equivalent, depending on which environment you're calling into
plaidClient = apiClient.createService(PlaidApi.class);
// Synchronously exchange a Link public_token for an API access_token
// Required request parameters are always Request object constructor arguments
ItemPublicTokenExchangeRequest request = new ItemPublicTokenExchangeRequest().publicToken("the_link_public_token");
Response response = plaidClient()
.itemPublicTokenExchange(request).execute();
if (response.isSuccessful()) {
accessToken = response.body().getAccessToken();
}
// Asynchronously do the same thing. Useful for potentially long-lived calls.
ItemPublicTokenExchangeRequest request = new ItemPublicTokenExchangeRequest().publicToken(publicToken);
plaidClient()
.itemPublicTokenExchange(request)
.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
accessToken = response.body.getAccessToken();
}
}
@Override
public void onFailure(Call call, Throwable t) {
// handle the failure as needed
}
});
// Decoding an unsuccessful response
try {
Gson gson = new Gson();
PlaidError error = gson.fromJson(response.errorBody().string(), PlaidError.class);
} catch (Exception e) {
throw new Exception(
String.format(
"Failed converting from API Response Error Body to Error %f",
response.errorBody().string()
)
);
}
```
--------------------------------
### Sandbox Testing with Plaid Java SDK
Source: https://context7.com/plaid/plaid-java/llms.txt
Illustrates how to use Plaid's sandbox environment to create test Items, exchange public tokens for access tokens, simulate login required states, and fire webhooks. This is crucial for development and testing without using real user data. Requires Plaid client libraries.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Arrays;
// Create a sandbox public token for testing
SandboxPublicTokenCreateRequest createRequest = new SandboxPublicTokenCreateRequest()
.institutionId("ins_109508") // First Platypus Bank
.initialProducts(Arrays.asList(Products.AUTH, Products.TRANSACTIONS));
Response createResponse = plaidClient
.sandboxPublicTokenCreate(createRequest)
.execute();
if (createResponse.isSuccessful()) {
String publicToken = createResponse.body().getPublicToken();
System.out.println("Sandbox Public Token: " + publicToken);
// Exchange for access token
ItemPublicTokenExchangeRequest exchangeRequest = new ItemPublicTokenExchangeRequest()
.publicToken(publicToken);
Response exchangeResponse = plaidClient
.itemPublicTokenExchange(exchangeRequest)
.execute();
if (exchangeResponse.isSuccessful()) {
String accessToken = exchangeResponse.body().getAccessToken();
// Simulate login required state
SandboxItemResetLoginRequest resetRequest = new SandboxItemResetLoginRequest()
.accessToken(accessToken);
Response resetResponse = plaidClient
.sandboxItemResetLogin(resetRequest)
.execute();
// Fire a webhook for testing
SandboxItemFireWebhookRequest webhookRequest = new SandboxItemFireWebhookRequest()
.accessToken(accessToken)
.webhookCode(SandboxItemFireWebhookRequestWebhookCodeEnum.DEFAULT_UPDATE);
Response webhookResponse = plaidClient
.sandboxItemFireWebhook(webhookRequest)
.execute();
}
}
```
--------------------------------
### Initialize Plaid API Client in Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Configure and initialize the Plaid API client using your Plaid credentials (clientId, secret) and specify the API version. You can set the environment to Sandbox or Production and optionally configure custom timeouts.
```java
import com.plaid.client.ApiClient;
import com.plaid.client.request.PlaidApi;
import java.util.HashMap;
// Initialize API client with credentials
HashMap apiKeys = new HashMap<>();
apiKeys.put("clientId", "YOUR_CLIENT_ID");
apiKeys.put("secret", "YOUR_SECRET");
apiKeys.put("plaidVersion", "2020-09-14");
ApiClient apiClient = new ApiClient(apiKeys);
// Set environment: ApiClient.Sandbox or ApiClient.Production
apiClient.setPlaidAdapter(ApiClient.Sandbox);
// Optional: Set custom timeout (in seconds)
apiClient.setTimeout(120);
// Create the PlaidApi service
PlaidApi plaidClient = apiClient.createService(PlaidApi.class);
```
--------------------------------
### Request Model Builder Syntax in Plaid Java
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Illustrates the shift from constructor-based option passing to builder syntax for request models in the Plaid Java client library. This provides a more fluent and readable way to construct requests.
```java
// Old syntax
// new AuthGetRequest(accessToken)
// New syntax
// new AuthGetRequest().accessToken(accessToken)
```
--------------------------------
### Payment Initiation Model Renaming in Plaid Java
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Describes the renaming convention for Payment Initiation models in the Plaid Java client library. Imports are now structured as `com.plaid.client.model.PaymentInitiation${Model}`.
```java
// Old import pattern
// import com.plaid.client.model.paymentinitiation.*
// New import pattern
// import com.plaid.client.model.PaymentInitiation${Model}
```
--------------------------------
### Paginate Transactions with Offset and Count (Java)
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Demonstrates how to paginate through transaction data using the count and offset parameters in the Plaid Java SDK. It shows how to retrieve all available transactions by repeatedly fetching data until the total count is met.
```java
// Manipulate the count and offset parameters to paginate
// transactions and retrieve all available data
Response response = client().service().transactionsGet(
new TransactionsGetRequest(
accessToken,
startDate,
endDate)
.withAccountIds(Arrays.asList(someAccountId))
.withCount(numTxns)
.withOffset(1)).execute();
List transactions = new ArrayList ();
transactions.addAll(response.body().getTransactions());
// Manipulate the offset parameter to paginate
// transactions and retrieve all available data
while (transactions.size() < response.body().getTotalTransactions()) {
options = new TransactionsGetRequestOptions()
.offset(transactions.size())
.includePersonalFinanceCategory(true)
TransactionsGetRequest request = new TransactionsGetRequest()
.accessToken(accessToken)
.startDate(startDate)
.endDate(endDate)
.options(options);
Response
response = plaidClient.transactionsGet(request).execute();
transactions.addAll(response.body().getTransactions());
}
```
--------------------------------
### Create Plaid Link Token in Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Generate a Link token required to initialize Plaid Link for user authentication. This involves creating a user object, optionally configuring account filters, and specifying products, country codes, language, and webhook URL.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Arrays;
import java.util.Date;
// Create user object with unique client user ID
LinkTokenCreateRequestUser user = new LinkTokenCreateRequestUser()
.clientUserId(Long.toString(new Date().getTime()))
.legalName("John Doe")
.phoneNumber("4155558888")
.emailAddress("john@example.com");
// Configure account filters (optional)
DepositoryFilter depositoryFilter = new DepositoryFilter()
.accountSubtypes(Arrays.asList(DepositoryAccountSubtype.CHECKING, DepositoryAccountSubtype.SAVINGS));
LinkTokenAccountFilters accountFilters = new LinkTokenAccountFilters()
.depository(depositoryFilter);
// Build the Link token request
LinkTokenCreateRequest request = new LinkTokenCreateRequest()
.user(user)
.clientName("My App")
.products(Arrays.asList(Products.AUTH, Products.TRANSACTIONS))
.countryCodes(Arrays.asList(CountryCode.US))
.language("en")
.webhook("https://example.com/webhook")
.accountFilters(accountFilters);
// Execute the request
Response response = plaidClient.linkTokenCreate(request).execute();
if (response.isSuccessful()) {
String linkToken = response.body().getLinkToken();
System.out.println("Link Token: " + linkToken);
System.out.println("Expiration: " + response.body().getExpiration());
} else {
System.err.println("Error: " + response.errorBody().string());
}
```
--------------------------------
### Search Financial Institutions with Plaid Java SDK
Source: https://context7.com/plaid/plaid-java/llms.txt
Searches for financial institutions supported by Plaid. It allows filtering by query, country codes, products, and optional metadata. The output includes details about each matching institution.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Arrays;
// Search for institutions
InstitutionsSearchRequestOptions options = new InstitutionsSearchRequestOptions()
.includeOptionalMetadata(true)
.oauth(true);
InstitutionsSearchRequest request = new InstitutionsSearchRequest()
.query("Chase")
.countryCodes(Arrays.asList(CountryCode.US))
.products(Arrays.asList(Products.AUTH, Products.TRANSACTIONS))
.options(options);
Response response = plaidClient.institutionsSearch(request).execute();
if (response.isSuccessful()) {
for (Institution institution : response.body().getInstitutions()) {
System.out.println("Institution: " + institution.getName());
System.out.println(" ID: " + institution.getInstitutionId());
System.out.println(" URL: " + institution.getUrl());
System.out.println(" Primary Color: " + institution.getPrimaryColor());
System.out.println(" OAuth: " + institution.getOauth());
System.out.println(" Products: " + institution.getProducts());
System.out.println(" Country Codes: " + institution.getCountryCodes());
}
}
```
--------------------------------
### Manage Items with Plaid Java SDK
Source: https://context7.com/plaid/plaid-java/llms.txt
Provides functionality to manage Items within Plaid, including retrieving item details, updating webhook URLs, and removing items. Requires an access token for operations.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
// Get Item details
ItemGetRequest getRequest = new ItemGetRequest()
.accessToken(accessToken);
Response getResponse = plaidClient.itemGet(getRequest).execute();
if (getResponse.isSuccessful()) {
Item item = getResponse.body().getItem();
System.out.println("Item ID: " + item.getItemId());
System.out.println("Institution ID: " + item.getInstitutionId());
System.out.println("Available Products: " + item.getAvailableProducts());
System.out.println("Billed Products: " + item.getBilledProducts());
System.out.println("Webhook: " + item.getWebhook());
System.out.println("Update Type: " + item.getUpdateType());
}
// Update Item webhook
ItemWebhookUpdateRequest updateRequest = new ItemWebhookUpdateRequest()
.accessToken(accessToken)
.webhook("https://example.com/new-webhook");
Response updateResponse = plaidClient.itemWebhookUpdate(updateRequest).execute();
// Remove an Item
ItemRemoveRequest removeRequest = new ItemRemoveRequest()
.accessToken(accessToken);
Response removeResponse = plaidClient.itemRemove(removeRequest).execute();
if (removeResponse.isSuccessful()) {
System.out.println("Item removed successfully");
}
```
--------------------------------
### Retrieve Investment Holdings with Plaid Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Fetches investment holdings, including details about securities, quantities, and current values, using the Plaid Java client. This snippet shows how to make a basic request and how to filter results by account ID. It requires the Plaid client and an access token.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
import java.util.Arrays;
// Basic investments holdings request
InvestmentsHoldingsGetRequest request = new InvestmentsHoldingsGetRequest()
.accessToken(accessToken);
Response response = plaidClient.investmentsHoldingsGet(request).execute();
if (response.isSuccessful()) {
InvestmentsHoldingsGetResponse holdings = response.body();
// Process securities
System.out.println("Securities:");
for (Security security : holdings.getSecurities()) {
System.out.println(" " + security.getName());
System.out.println(" Security ID: " + security.getSecurityId());
System.out.println(" Type: " + security.getType());
System.out.println(" Ticker: " + security.getTickerSymbol());
System.out.println(" Close Price: " + security.getClosePrice());
System.out.println(" Currency: " + security.getIsoCurrencyCode());
}
// Process holdings
System.out.println("\nHoldings:");
for (Holding holding : holdings.getHoldings()) {
System.out.println(" Security ID: " + holding.getSecurityId());
System.out.println(" Account ID: " + holding.getAccountId());
System.out.println(" Quantity: " + holding.getQuantity());
System.out.println(" Institution Value: " + holding.getInstitutionValue());
System.out.println(" Cost Basis: " + holding.getCostBasis());
}
}
// Filter to specific investment accounts
InvestmentHoldingsGetRequestOptions options = new InvestmentHoldingsGetRequestOptions()
.accountIds(Arrays.asList("investment_account_id"));
InvestmentsHoldingsGetRequest filteredRequest = new InvestmentsHoldingsGetRequest()
.accessToken(accessToken)
.options(options);
```
--------------------------------
### Handle Plaid API Errors in Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Demonstrates how to parse Plaid API error responses into a PlaidError object for detailed error handling. It includes checking for specific error types and codes to implement appropriate recovery or retry mechanisms. Requires Gson and Plaid client libraries.
```java
import com.google.gson.Gson;
import com.plaid.client.model.*;
import retrofit2.Response;
TransactionsGetRequest request = new TransactionsGetRequest()
.accessToken("invalid-access-token")
.startDate(LocalDate.now().minusDays(30))
.endDate(LocalDate.now());
Response response = plaidClient.transactionsGet(request).execute();
if (!response.isSuccessful()) {
try {
Gson gson = new Gson();
PlaidError error = gson.fromJson(response.errorBody().string(), PlaidError.class);
System.err.println("Error Type: " + error.getErrorType());
System.err.println("Error Code: " + error.getErrorCode());
System.err.println("Error Message: " + error.getErrorMessage());
System.err.println("Display Message: " + error.getDisplayMessage());
System.err.println("Request ID: " + error.getRequestId());
// Handle specific error types
if (error.getErrorType() == PlaidErrorType.INVALID_INPUT) {
if ("INVALID_ACCESS_TOKEN".equals(error.getErrorCode())) {
// Re-authenticate the user
System.out.println("User needs to re-authenticate");
}
} else if (error.getErrorType() == PlaidErrorType.ITEM_ERROR) {
if ("PRODUCT_NOT_READY".equals(error.getErrorCode())) {
// Retry after delay
System.out.println("Product not ready, retry later");
}
}
} catch (Exception e) {
System.err.println("Failed to parse error response: " + e.getMessage());
}
}
```
--------------------------------
### Handle Dates with Java 8 LocalDate and OffsetDateTime in Plaid API Requests
Source: https://context7.com/plaid/plaid-java/llms.txt
Demonstrates how to use Java 8's LocalDate for date fields and OffsetDateTime for datetime fields when constructing Plaid API requests. This includes parsing specific dates, using current dates, and calculating relative dates like 'thirty days ago'.
```java
import java.time.LocalDate;
import java.time.OffsetDateTime;
import com.plaid.client.model.*;
// LocalDate for date fields (format: date)
LocalDate startDate = LocalDate.parse("2024-01-01");
LocalDate endDate = LocalDate.now();
TransactionsGetRequest request = new TransactionsGetRequest()
.accessToken(accessToken)
.startDate(startDate)
.endDate(endDate);
// OffsetDateTime for datetime fields (format: date-time)
OffsetDateTime scheduledTime = OffsetDateTime.parse("2024-06-15T10:30:00+00:00");
// Using relative dates
LocalDate thirtyDaysAgo = LocalDate.now().minusDays(30);
LocalDate oneYearAgo = LocalDate.now().minusYears(1);
LocalDate nextWeek = LocalDate.now().plusWeeks(1);
```
--------------------------------
### Handling Dates in Plaid Java Client
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Demonstrates how to represent dates and datetimes in the Plaid Java client library. For date fields, use `LocalDate`; for datetime fields requiring time zone information, use `OffsetDateTime`. Failing to provide time zone info for datetimes will result in an error.
```java
import java.time.LocalDate;
LocalDate myDate = LocalDate.parse("2019-12-06");
```
```java
import java.time.OffsetDateTime;
OffsetDateTime myDateTime = OffsetDateTime.parse("2019-12-06T22:35:49+00:00");
```
--------------------------------
### Model Import Renaming in Plaid Java Client
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Shows the renaming of model imports in the Plaid Java client library. Models previously located in `com.plaid.request` and `com.plaid.response` are now consolidated under `com.plaid.model`.
```java
// Old imports
// import com.plaid.request.ModelName;
// import com.plaid.response.ModelName;
// New import
// import com.plaid.model.ModelName;
```
--------------------------------
### Enum Usage in Plaid Java Client Requests
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Shows the updated way to specify enum values in Plaid Java client requests. Previously, singletons were used; now, enum types are used, aligning with the API's string representation of enums.
```java
// Old enum usage
// Collections.singletonList("auth")
// .withCountryCodes(Collections.singletonList("US"))
// New enum usage
// .products(Arrays.asList(Products.AUTH))
// .countryCodes(Arrays.asList(CountryCode.US))
```
--------------------------------
### Product Enum Renaming in Plaid Java Client
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Details the renaming of the `Product` enum to `Products` in the Plaid Java client library. This affects how products are referenced in requests.
```java
// Old reference
// com.plaid.client.request.common.Product
// New reference
// com.plaid.model.Products
```
--------------------------------
### Optional Parameters Setter Renaming in Plaid Java
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Explains the renaming of chained setters for optional parameters in Plaid Java request models. `with$VARNAME` setters have been converted to `${}options` for better clarity.
```java
// Old setter
// .withEndDate(endDate)
// New setter
// .endDate(endDate)
```
--------------------------------
### Public Token Exchange
Source: https://context7.com/plaid/plaid-java/llms.txt
Exchange a public token received from Plaid Link for an access token. This access token is then used to make authenticated API calls to retrieve financial data.
```APIDOC
## Public Token Exchange
Exchange a public token from Plaid Link for an access token to make authenticated API calls.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
// Exchange public token received from Plaid Link
ItemPublicTokenExchangeRequest exchangeRequest = new ItemPublicTokenExchangeRequest()
.publicToken("public-sandbox-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
Response response = plaidClient
.itemPublicTokenExchange(exchangeRequest)
.execute();
if (response.isSuccessful()) {
String accessToken = response.body().getAccessToken();
String itemId = response.body().getItemId();
System.out.println("Access Token: " + accessToken);
System.out.println("Item ID: " + itemId);
// Store accessToken securely for future API calls
} else {
System.err.println("Exchange failed: " + response.errorBody().string());
}
```
```
--------------------------------
### Filter Transactions by Account ID (Java)
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Shows how to filter transaction results to a specific account using the `withAccountIds` method in the Plaid Java SDK. This is useful when you only need transactions from a particular account.
```java
Response response = client().service().transactionsGet(
new TransactionsGetRequest(
accessToken,
startDate,
endDate)
.withAccountIds(Arrays.asList(someAccountId))
.withCount(numTxns)
.withOffset(1)).execute();
```
--------------------------------
### Account Model Renaming in Plaid Java Client
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Highlights the renaming of the `Account` model to `AccountBase` in the Plaid Java client library. This change affects how account-related data structures are imported and referenced.
```java
// Old import
// import com.plaid.client.model.Account
// New import
// import com.plaid.client.model.AccountBase
```
--------------------------------
### Exchange Plaid Public Token for Access Token in Java
Source: https://context7.com/plaid/plaid-java/llms.txt
Convert a public token received from Plaid Link into an access token and an item ID. This access token is then used for making authenticated calls to the Plaid API on behalf of the user.
```java
import com.plaid.client.model.*;
import retrofit2.Response;
// Exchange public token received from Plaid Link
ItemPublicTokenExchangeRequest exchangeRequest = new ItemPublicTokenExchangeRequest()
.publicToken("public-sandbox-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
Response response = plaidClient
.itemPublicTokenExchange(exchangeRequest)
.execute();
if (response.isSuccessful()) {
String accessToken = response.body().getAccessToken();
String itemId = response.body().getItemId();
System.out.println("Access Token: " + accessToken);
System.out.println("Item ID: " + itemId);
// Store accessToken securely for future API calls
} else {
System.err.println("Exchange failed: " + response.errorBody().string());
}
```
--------------------------------
### CountryCodes Enum Migration in Plaid Java
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Illustrates the change in handling `CountryCodes` from a list of strings to an enum in the Plaid Java client library. This change affects how country codes are specified in requests.
```java
// Old way
// Arrays.asList("US")
// New way
// Arrays.asList(CountryCode.US)
```
--------------------------------
### Error Model Renaming in Plaid Java Client
Source: https://github.com/plaid/plaid-java/blob/master/README.md
Explains the renaming of the `ErrorResponse` model and its nested `ErrorType` to `Error` and `ErrorTypeEnum` respectively in the Plaid Java client library. This change impacts error handling and type references.
```java
// Old model and type
// com.plaid.client.model.ErrorResponse
// ErrorResponse.ErrorType
// New model and type
// com.plaid.client.model.Error
// Error.ErrorTypeEnum
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.