Plaid Integration

Nwosu Rosemary
4 min readMay 16, 2024

--

Building Ledgerbrew to have account integration, I decided to use Plaid. I went through their documentation, followed through and got series of errors. I started looking for fixes — Stackoverflow, Reddit, Twitter etc. My code became a series of conjoined codes in a bid to fix the issue, I was getting so aggravated that I had to tell myself to go outside and touch grass.

Fixing the Issue

When I came back from my little trip of touching grass, I reached out to my network and was able to get someone available and we started a Google Meet call to get it done.

Step 1: Grab Credentials

After account creation, create a .env file in your code and grab your client ID and secret. For the secret, there is development and sandbox, grab the sandbox and work with it until you are sure everything is working the way you want before switching to development.

Image source: Daspire.

Step 2: Install dependency

Next step is to install Plaid. I installed plaid using npm i plaid@19.0.0, you can also do npm install plaid.

Step 3: Create configuration

Open a new file and name it whatever you want — I named mine plaid.ts. My file structure looks like this:

services/plaid.ts

Next is to import some libraries from Plaid

import { Configuration, PlaidApi, PlaidEnvironments } from 'plaid';

Then create a new constant with the Plaid configurations

export const plaidClient = new PlaidApi(

new Configuration({

basePath: PlaidEnvironments.sandbox,

baseOptions: {

headers: {

'PLAID-CLIENT-ID': process.env.PLAID_CLIENT_ID,

'PLAID-SECRET': process.env.PLAID_SECRET,

'Plaid-Version': '2020-09-14',

},

},

})

);

  • basePath is the environment you are to use
  • PLAID-CLIENT-ID is your client ID in your .env
  • PLAID-SECRET is your secret — since environment is sandbox, your secret should be sandbox
  • Plaid-Version is the latest Plaid version

Step 4: Create APIs

Create a folder named API with two subfolders — one for link creation and the other for token exchange. In my case, my file structure looks like this:

src/app/api/create-plaid-link

Inside the create-plaid-link folder, create a route.ts file. import every dependency needed

import { plaidClient } from '@/services/plaid';

import { CountryCode, Products } from 'plaid';

import { v4 as uuidv4 } from 'uuid';

The plaidClient was imported from my services file

The CountryCode and Products as I learnt the hard way is the new way to select country and plaid products you want to integrate into your application.

For the uuid, I had to install and use it as plaid expects a unique id for each user. If you already have those implemented, you can ignore this. But if you don’t you can use uuid to generate unique users for each test.

npm install uuid

Next step is to integrate the API. I am using NextJS and didn’t want to use Axios or Express, I modified my code to work this way:

export async function GET() {

try {

// Generate a unique client_user_id

const client_user_id = uuidv4();

// Log the unique identifier

console.log("Unique Identifier:", client_user_id);

const tokenResponse = await plaidClient.linkTokenCreate({

client_id: process.env.PLAID_CLIENT_ID,

secret: process.env.PLAID_SECRET,

user: { client_user_id: client_user_id ?? '' },

client_name: "your-app-name",

language: 'en',

products: [Products.Auth, Products.Transactions],

country_codes: [CountryCode.Us, CountryCode.Ca],

});

return Response.json(tokenResponse.data);

} catch (error) {

console.error(error)

return Response.json({message: error})

}

}

For user, replace with your unique user ID or create a const with uuid which will generate a user for you to test with.

For token exchange, my file structure looks like this:

src/app/api/exchange-plaid-token

Create a route.ts file, then import needed dependencies:

import { plaidClient } from '@/services/plaid';

Then create a POST function to continue the exchange process

export async function POST(req: Request, res: Response) {

let public_token = (await req.json()).public_token

try {

const exchangeResponse = await plaidClient.itemPublicTokenExchange({

public_token,

client_id: process.env.PLAID_CLIENT_ID,

secret: process.env.PLAID_SECRET,

});

const accessToken = exchangeResponse.data.access_token;

// Perform any additional processing here

return Response.json({ access_token: accessToken });

} catch (error) {

console.error(error)

return Response.json({message: error})

}

}

After these are setup, you can move to the next step.

Step 5: Create interface

This is the final step where you call the APIs you have setup to work on the client-side. I had to create a new folder to test it out => app/test-plaid/page.tsx. First import needed dependencies:

'use client'

import React from 'react'

import Router from 'next/router';

import { useState, useEffect, useCallback } from 'react';

import { usePlaidLink } from 'react-plaid-link';

The usePlaidLink was installed using npm install --save react-plaid-link

I had to add the ‘use client’ at the top because Next was assuming it was server and kept throwing errors.

export default function PlaidLink() {

const [token, setToken] = useState(null);

useEffect(() => {

const createLinkToken = async () => {

const response = await fetch('/api/create-plaid-link', {

method: 'GET',

});

const { link_token} = await response.json();

console.log('Link token response:', link_token);

setToken(link_token);

console.log('Link token response:', link_token);

};createLinkToken();

}, []);

const onSuccess = useCallback(async (publicToken: string) => {

await fetch('/api/exchange-plaid-link', {

method: 'POST',

headers: {

'Content-Type': 'application/json',

},

body: JSON.stringify({ public_token: publicToken }),

});

Router.push('/setup');

}, []);

const { open, ready } = usePlaidLink({

token,

onSuccess,

});

return (

<button onClick={() => open()} disabled={!ready} type="submit">

<strong>Link account</strong>

</button>

);

}

Make sure to look at your link and confirm it corresponds with what you have in your API. When you refresh your server, you should see a button with Link account with which you can test it out.

Thank you for reading. You can check out Ledgerbrew, a tool I am building for startups and small businesses.

--

--

Nwosu Rosemary
Nwosu Rosemary

Written by Nwosu Rosemary

Data Scientist || Machine Learning enthusiast and hobbyist

No responses yet