Three questions have plagued mankind since the dawn of philosophy why are we put here on this Earth do we actually have free will and where did all my money go well plaid can't really help you with the first one for the second one turns out the answer is no oh no uh but for the third well we can tackle that on today's episode of plaid Academy [Music] so transactions as the name suggests is Plaid's product for retrieving transaction data both from depository accounts things like checking and savings accounts as well as credit accounts credit cards
and some types of loans all data that's very useful if you're looking to build any kind of personal finance app or help a user better understand their spending or plan out their budgets I should note that if you're looking to fetch transactions for like brokerage and 401K accounts you'll Probably want to look at Investments which is a whole other product now one important thing to understand before we get started with transactions is that they're not set in stone a bank can modify a transaction after it's been added sometimes this is to refine the description name
but it also might be to make corrections to the amount or the date or to other fields transactions can also be removed and this happens more often than you'd think sometimes you'll See this when like a hotel removes an authorization hold on your credit card but you'll also see this when say a transaction goes from pending to posted which includes cases where a restaurant adds a tip to a bill in those situations typically the old transaction is removed and a brand new transaction is added and yeah you might think this would be a case of
an existing transaction being modified I certainly did but it's not it's more of a remove and add kind of Situation and the reason I bring this up is that if you were to look at the API you'd see we have two ways of fetching transactions the first way using transactions get looks very straightforward and it is you specify a date range of transactions to fetch and we give you back all the transactions we have in that range the problem here is that once you get this data you'll have to do a fair chunk of work
to reconcile it with whatever Data you already have for this user how are you going to know if one of these transactions is a modified version of what you already have stored are you going to compare your entire set of data against what's been retrieved so you can find out if something's been removed what happens if the date on a transaction changes and it's set to a date earlier than what you grabbed you're going to miss it right so how far back do you need to go and while these Aren't unsolvable problems it generally means
fetching more data than you intended and doing more work than you probably feel like doing that's why for most applications getting started with a plaid API we recommend using transaction sync Instead This endpoint will give you a list of everything that's changed whether it's a transaction being added removed or modified since you last called it the API might look a little more complicated at first glance but it Generally makes your life easier in the long run when you're using it in a real application so that's what we're going to be covering in this video tutorial
so to get started we're going to build our own where did my money go Application that uses the transaction Sync API to fetch data from our users credit card and savings accounts and we'll display our most recent transactions on screen and I highly recommend you code along with me Throughout this video you'll learn a lot more that way and at the end you'll have some nice working sample code you can copy and paste into your own application our sample app will be running node.js on the back end and plain old JavaScript on the front end
don't worry if you're not super experienced in either of these Technologies as long as you have a solid engineering background and a reasonably up-to-date version of node running on your machine I'm using node 18 but this Should work at least with 16 you should be okay also we're going to be doing a fair amount of work with the sqlite database so I recommend you have some way to view it vs code has a number of different sqlite viewer extensions pick the one that looks best to you and give it a try now before I get
going I'm going to assume you know the basics of how to work with plaid like you have an account at the Plaid dashboard you know how to Get a link token and open link how to exchange a public token for an access token and like the difference between the sandbox and the production environments now if you don't I would recommend watching the getting started video first it's up there like in a little corner of the window and in the description below try and ignore my haircut I was trying something new at the time it didn't
really work but the content is still good So to get started we're going to head on over to the tutorial resources repo on our GitHub page you can find the link in the description below and I'm just going to copy this line here to grab the URL next let's open up a command line window head over to your favorite folder for downloading GitHub projects and git clone this repository we'll jump into our tutorial resources repo get into the transactions directory and then start to get into our starting app run npm Install to install all the
proper packages it looks like you got a couple packages I should probably update well I'll take care of that the next thing I'm going to do is configure our app with all the proper values it needs to talk to Plaid so I'm going to copy.envtemplate.emv then I'll open up this directory in vs code but you know feel free to use whatever ID you like even emacs is okay weirdo Now let's edit our EnV file I'm going to copy over our client ID and secret from The Plaid dashboard I am sticking with the sandbox environment and
you should probably do the same at least for now and then let's talk about this webhook URL now the next part is optional for this tutorial but there are a couple of times here where application will be making use of plaid web Hooks and in order to expose these web hook endpoints to the world without publishing the rest Of my application our backend has a separate server just for receiving web hooks running on Port 8001 because I have ngrok installed I can go back to my terminal window and run ngrok hdp 8001 that's going to
set things up so that any request to this you know crazy looking domain here gets forwarded to my local host on Port 8001 so I can copy and paste this domain name into here now if you have no idea what I just did you know one don't worry you can get Through most of the tutorial without it um but two you probably will want to support web hooks eventually so I would recommend checking out our tutorial on plaid web hooks where I explain to you what web hooks are how to interpret them and how you
can use ngrok like I'm doing here so that you can sort of test them while still running on localhost and with that I think our setup work is done let's get our application up and running by opening up another terminal I'll do this in vs code and running npm run watch if all has gone well you should see a message that your application is up and running on localhost 8000 and that our web hook receiver is running on Port 8001. so let's open up localhost 8000 and here is my test application that does some of
the basics around creating a new user signing them in and fetching a link token in fact let's go through that now I'll ask it to create a new user and Then I'll go ahead and ask to connect to a bank my application creates a link token on the back end opens up link on the client and then once I'm done signing into my bank it sends the public token back down to my server where my server then exchanges it for an access token you'll notice along the way it's created a little database for me if
we open it up and again I'm using a vs code extension to help me see the contents of This database we can see that my application has a users table or I have my username and user ID in items table remember an item is plaid's name for a connection to a bank this table contains the item id the user ID belongs to the access token which we can use to access data for these items the bank name and this mysterious transaction cursor column which we'll get to in a bit I have an accounts table where
we keep a list of all the accounts Associated with an item remember an item typically has one or more accounts associated with it an item representing my bank for instance has two different accounts one for checking and one for savings finally we have a transactions table which is nice and empty and we'll get back to this in a bit meanwhile we can see on the back end that when I was all done my server just made a call to Identity get and spit out these results This is really just so we can be sure that
our application is actually talking to Plaid and getting back data if you did run into trouble at this point uh double check your dot EnV file since that's the most common reason for errors now if you've used any of our sample tutorial applications in the past this application should look pretty familiar to you the biggest difference is that yes I broke down and actually used a real database to store all of our user Data instead of just using a flat file and you'll see why in a bit you'll also notice that I split up our
server code into several different files to make it more manageable and to help you focus on just the code relevant to this tutorial so if you're able to scan this code and you know you feel pretty comfortable that you know what's going on feel free to jump to the next chapter of this video if you want a little more explanation of what's going on we can go Through each of these folders in our code real quick so like I said the database folder here is where I store our sqlite database the public directory is where
we serve up the web pages for our web browser index.html is the HTML page nothing too unusual here you can see I'm using bootstrap CSS to create all these classes just to help my page look nice you know fairly quickly in our JS directory client JS is where We'll be implementing most of our client-facing code for this tutorial I've got this function up here which shows our user what banks they're connected to honestly most of this is just trying to deal with proper punctuation and we got a few empty functions waiting to be filled out
and this bit of code down here that hooks up the appropriate event listeners to the proper buttons oh and this code up here is the code we use to start link the Client-side widget that connects us to a bank you can see that all we're doing is calling this other function start link and passing in this refresh connected Banks code as our completion Handler that's a pretty good segue to our next file link.js it should look pretty standard what I do up here is request a link token from our server then create a link Handler
and the on success callback I call this function down here which exchanges our public token for link Token and then calls our custom success Handler that we passed into this call originally sign-in contains a bunch of methods to sign in our user sign out our user create users and so on utils contains a few utility functions we'll get to some of these in a bit but probably the most interesting one for now is this one here call my server which is basically a nice wrapper function to call our server handle any errors and spit out
the results we get To the JavaScript console I notice that if our second argument is true that makes this a post call and we'll be doing that fairly often over on the server side of things the server file itself just starts up Express the server we're using then reads in all of our endpoints from all these different files so uh why don't we go through those we've got Banks which gets the list of banks that your users connected to from the database and you know returns them Debug which contains a couple special debug calls which
we'll be using later tokens which deals with plaid tokens here's the code to generate a link token here's the code to exchange our public token for an access token and store it under database you'll notice that once we connect to a bank I run some code here to fetch the name of our bank from The Plaid API and also some code to fetch the names and IDs of the accounts associated with the API and then all That gets stored in our database transactions hold some placeholder code for now we'll be using these endpoints to fetch
transactions from plaid and retrieve a list of our users transactions and users contains the code to create a new user sign in a user fetch a list of all our users and so on we're not using any kind of passwords with our sign-in system or anything all I'm doing is setting a cookie with the value equal to our user ID then we Determine the logged in ID of our user by looking for this cookie I'm no security expert but I suspect in a real app adding some kind of password would you know probably be a
good idea looking at the rest of our server code DB is where I run all of our database level scripts I tried to abstract this out into a separate file so we could swap out databases if you know we ever needed to plaid.js configures and creates the Plaid server side client this is where We grab the client ID and secret for our environment variables utils has one function we use get logged in user ID which like I mentioned earlier just looks at the value of a cookie to determine our signed in user ID and I'm
using air quotes when I say signed in simple transaction object contains a class that represents the simplified transaction data that we'll want to use in our app this is what we'll be passing into our database methods and you'll Notice we have a factory method to create one of these from the larger plaid transaction object and we'll be implementing this later today finally we have webhook server this creates an additional server that runs on Port 8001 that we can use for our web hook receiver you can see that when I receive an item web hook I
print out some messages around things our application might want to do and when I receive a transactions web hook I pass It along to this function that well doesn't really do much of anything and that's about it like I said none of this should seem too unusual or surprising if you've done any work with plaid before or gone through a quick starts and if this does all look kind of strange to you I'll once again remind you to check out the getting started video first before continuing with this one okay now that we have a
good idea of how Our application works let's look into adding transactions you'll notice when we first created our link token for our signed in user we initialized our product with identity but not transactions that's actually an interesting use case that I'll get to at the end of this video but for now let's jump into our tokens file where we generate our link token and we can go ahead and replace identity with transactions and then down here in our Exchange public token endpoint let's remove this placeholder code that called identity get we won't be needing that
we can saver file which should automatically restart our server if we're running npm watch so let's go back to our app let's sign out and create a new user I'll call them you know transactions one because I'm super original like that all right so with our new user let's connect to a bank um let's pick this one Because you know Denver is a fun city and then I'll select our checking and savings accounts and when I'm all done I'm back here to my main screen now that I've connected a bank with transactions listed in my
list of products plaid is going to go out and contact this bank and gradually start pulling all of my transactions starting with the most recent but typically going back up to two years normally this takes some amount of time you know typically not More than a minute but you know it depends on the institution but in our case because I'm in sandbox which is kind of fake data this happens almost right away in fact because I do have web hooks working you can see that I'm getting back two different web hooks initial update which tells
me that it's finished pulling the last 30 days of content and historical update which tells me that it's finished pulling all the historical Data that it could now that I've got our connection working let's go ahead and actually perform our first fetch using the Sync API I'm going to go ahead and remove this d none style here from this div over on Line 39 so that we can actually see the rest of our interface wow look at that look at that programmer art it's beautiful so this gives us a table that will eventually contain transaction
data and a few buttons below I'm going to Implement this first one the server refresh button which will tell our server to fetch more transactions from plaid using the Sync API so in the client the code for this is This Server refresh function let's uncomment the code and you can see it simply makes a call to transaction sync on my server and this call currently returns a to-do telling us that we got to implement it fair enough so let's jump into our transactions JS File on the server so we can handle this first things first
I'll need to grab our user ID by calling get logged in user ID passing in our request next we need to call transaction sync against the items our user is connected to you might notice that I have a function down here sync transactions that expects an item ID so here's what I'm going to do I'll say const items equals await DB get item IDs For user with our user ID now this function returns an array of objects that contain a single key value pair that contains the ID of this item the thing that represents our
connection to a bank then well for now I'm just going to say items for each item let's call sync transactions with item.id we'll get back to this in a bit to make this more refined but for now I just want to start calling transaction sync to see what we get So down in my sync transactions function I'm going to need to grab the access token associated with this item remember that to talk to any Bank on behalf of our user we need to send plaid the access token associated with this item or login and if
you're like why don't you pass it into this function earlier you'll see why in a bit so I could say const item info equals await you know DB dot get item info and we'll pass in our item id then I can say that const access Token equals item info dot access token but with a little JavaScript destructuring I can simplify it to this this basically says hey go grab the access token value from the object that gets returned from this call and then rename it to access token because you know I still like camel case
and then I can say results equals await plaidclient.transactionsync with the access token equal to the access token we received from our database And then let's just consult our results data and see what we got so if I were to save this and click this button again you can see we get a lot of data probably more than actually fits in my console buffer but you know let's take a closer look at some of this so our sync call returns an object that contains a few important arrays added removed and modified which contain objects that represent
the individual transactions All these objects that you're seeing right now are part of the added array and you know that kind of makes sense because plaid has gone ahead and fetched several months worth of historical data I'm going to be getting back a lot of added transactions so let's take a look at one so we can understand a little more about the details of these transactions I won't cover every single one of these fields we have documentation for that but we'll hit Most of the popular ones account ID is plaid's internal ID for the specific
account that this transaction belongs to remember that when I connected this item to my bank I retrieved two different accounts checking and savings and so the transactions API will be fetching transactions that it finds in both of these accounts this ID is useful to let me know which account it belongs to it matches up with the same IDs that I fetched from accounts get and already Have stored in my database amount is the amount of the transaction the currency code is down here in ISO currency code one important thing to note about transactions is that
the value is always positive for money going out of the account that is money I'm spending and negative for money going into the account maybe for like accounts like credit cards this might feel intuitive like I always think of this account as contributing to the balance Of my credit card that I eventually need to pay but for accounts like checkings or savings accounts this kind of feels backwards positive values are taking money away from your balance and negative numbers are contributing to it but I suppose it's better to keep this Behavior consistent from account to
account than like switching it back and forth just keep that in mind you have two sets of dates here uh the date field will always exist when your transaction Is in the posted State this represents the date that the bank actually cleared the transaction and moved money out of your account if a transaction is in the pending state that is the transaction hasn't yet been cleared by the bank it usually but not always represents the date that the user initiated the transaction the authorized date will represent the date where the bank or credit card said
yeah we approve this transaction most of the time this will Be the same day that the user initiated the transaction but unlike the date field this is sometimes null which state to use depends on your situation but I actually prefer using the authorized date when it's available because it's more user-centric it's more likely to be the date that my user thinks they made a purchase and then you know if it's not available I can always fall back to the date date but that's just my strategy you do what makes sense for your app You'll notice
these both have corresponding date time fields which can be more precise but is also more likely to be null I think in the US you'll only get this data like a quarter at a time so don't depend on it we have two Fields related to names here name is a slightly cleaned up version of the raw description of the transaction that we receive from the bank and then Merchant name is an attempt to extract just the merchant name sometimes like when the Name already consists of the merchant name they are very similar like this other
times it's a little more distinct like this and sometimes like when you're working with checks or account transfers where you know there is no real Merchant this field can be null just my personal preference but I like using the merchant name if it exists but then falling back to the name field otherwise we also have two Fields up here related to the Category that the transaction fits into this here is a three level hierarchy of a transaction category which corresponds to this ID here but I'm not going to go into any details about these because
I'll be honest there is a better set of categories you should probably be using at the time of this recording they're still opt-in so I'm going to go back up here to my request code and add in a new options object in there I will set include personal finance category to True and if I were to rerun this request you can see that I now have this new personal finance category every entry in here has a primary category and a detailed category at the time of this recording There are 16 primary categories and a total
of 104 secondary ones which one you want to use probably depends on your use case these new categories are simpler to work with and much more accurate than the old Ones so I would recommend them to any developer getting started today with transactions one very important field that you shouldn't miss out on is this pending transaction ID I'll talk more about this later but when a transaction goes from pending to posted that's represented as the old transaction being removed and a new one being added so this field will essentially tell you which transaction this one
is replacing and that can be helpful if you've done Any processing on this transaction already like the user supplied a description or there's other data that you want to copy over from the old transaction that's going away to this new transaction and if you're wondering if a transaction is pending or not well we have a field for that other fields that I use less often but I'll call out here payment channel will let you know if this payment happened Online or in the store location can represent the physical location of the store but I found
this is often null you will typically see these results more often for large chain stores that have multiple locations like this real life Costco example here there's also payment meta which is null except for ACH transfers and transaction code which is only populated in Europe so until my manager approves that trip to Copenhagen I generally don't do much With these uh unofficial currency code will show up when you're working with crypto transactions and then down here is the transaction ID now this you're going to want to hold on to this represents plaid's internal ID for
this transaction and this will be globally unique so you know if you want to make this the primary key in your own database you totally could and the reason I bring this up is because the next section of data you'll Receive are modified transactions like I mentioned earlier these are transactions that are modified afterwards by the financial institution one of the most common reasons this happens is that a bank will like refine the description of the transaction but sometimes they could make corrections to a date or to the amount now in our sandbox data there's
some weird conditions that will sometimes produce modified transactions but I'll Be honest it's kind of difficult to reproduce but this is typically what they look like here's a copy from an application where I'm using real production data and you might notice two things one coffee in San Francisco is delicious but kind of pricey and two these look exactly the same as the added transaction objects and you'd be right on both counts basically plaid just gives you a fully hydrated object with all the fields included whether they Were modified or not so typically you can just
take these transactions and just replace the corresponding Row in your database with all the values that you get in this object finally let's talk about remove transactions like I mentioned earlier you'll see remove transactions more often than you might think like in situations where a transaction goes from pending to posted including when say a restaurant adds a tip to a bill again These are not represented as modifications typically these are represented by a bank as the old pending transaction getting removed and the new posted version of the transaction being added now plaid performs some pretty
sophisticated logic to figure out if any of these added poster transactions correspond to a removed pending transaction in the same batch it's not perfect but it does a pretty good job and if you're interested there is a very Interesting blog post about how we do all this at least I found it interesting but maybe I'm just weird if it finds one it will let you know by adding that pending transaction ID field I mentioned earlier to the added transaction again our sandbox doesn't typically include remove transactions but they basically look like this an array of
objects that have a single transaction ID field finally let's talk about two very Important Fields the hasmore field and the next cursor field when you call transaction sync pad will send you back a bunch of transactions up to a limit by default this is 100 transactions at a time but you know particularly the first time you call sync after we've retrieved several months worth of historical data there might be more than 100 transactions that Platinum needs to tell you about so in those situations we will set the hasmore flag to true and you'll Receive a
next cursor value if you then call transaction sync again and pass along this next cursor value plaid will return the next chunk of transactions and so on and so forth until we've sent you all the data that we have so far so let's modify our code so we can see what this would look like first for reasons that will make sense later in this video I promise I'm going to create a new function called Fetch new sync data where we can just pass in our Access token then let's create a keep going variable initially set
to false and some kind of aggregate all data object which will contain our added modified and removed calls along with a next cursor value which is initially set to null and then we'll set up a do while loop which we'll do while keep going equals true and let's make this strict equality just to be safe then I'll move my actual transaction Sync call for my function down below back up into this do Loop so I'll say that new data equals our results.data and then we'll concatenate our all data added array onto whatever we get back
from New data.added we can then do the same thing for our modified and our removed arrays we'll set our cursor value equal to newdata dot has cursor and we'll set keep going to new data. has more and then back here in our transaction Sync call I'll pass in our cursor value which you know will be null initially but on subsequent fetches it'll be set to the value of our next cursor you know down here so if there is more data we'll be able to retrieve the next page with this next cursor value and uh you
know maybe just to avoid filling up my console log with data for the moment I won't console log the whole thing but up here I'll just report about the batches I received And let's just make a note that we're all done and then we can return the Consolidated all data object from here and then in my original sync transactions call we'll say that all data equals await fetch new sync data with this access token so if I were to run this now I can see that I'm getting 100 new transactions in the first batch and
then my API makes another call where I'm getting 90 odd transactions in the second batch and Then because has more is false it doesn't fetch anymore and it returns that big aggregate object so just like that we know how to make a call to the sync endpoint and what that data means let's take the next step now and start adding those transactions to our database um but before we do let's take a moment to talk about that cursor value a little more you'll might notice that as I'm making the sync call it's giving me all
The transactions data that it has that's fine for first pass but on subsequent calls I don't want all my users transaction data since the beginning of time we just want a list of what's changed since the last call but we don't want that to happen automatically right like what happens if I make a call and it fails or I need to retry a call well cursors can help here too generally speaking you can kind of think of cursors like a timestamp or a Bookmark or as I tend to think of them bookmarks along a timeline
as plaid sends you data it'll send you one of these bookmarks as a way to communicate this is where we last left off in our data transfer when you make another request to the Sync API you can then send this cursor across and plaid will send you the data it has since this bookmark you've obviously seen this already when we retrieved paginated data but this is the Same mechanism you could use to retrieve incremental data in the future in 24 hours when you want to retrieve just the batch of data that plaid is collected between
now and then you could do so by passing along this bookmark in fact let me show you I'm going to ask to print out our final cursor value here and then we will run this call again and so now what I'm going to do is I'm going to take that string and we're going to set that as the next cursor Value of my initial all data object which means this is the cursor that's going to be passed in when I first call transaction sync again and now if I were to run this call you can
see the plot is returning no data and you know that's because there are no transactions that have been updated since it last sent me this data a few seconds ago four other quick notes about these cursors First is that as you already saw if you set the cursor to null or preferably the empty string plaid will try to send you all the data it has starting from the beginning second is that these bookmarks don't go away if something happens to your app and you need refetch a set of changes using an old cursor you can
totally do that third is that these cursors are set per item which makes sense if you think About it since you're always calling transaction sync against items you know not accounts or users fourth is that plaid is pretty aggressive about condensing all the changes you would have seen since the last cursor in a way that would make sense if a transaction is say added modified and modified again and then you fetch it it'll only show up as one added transaction on the other hand if you would happen to make a call to Transaction sync like
at this point here you would have gotten the initial transaction with the first modification again expressed as a single ad and then if you made another call here you would have received the modified transaction I guess you can kind of think of these like a git squash commit if that analogy helps and I have my git analogies right the main point here is that like you never need to worry about multiple modifications to the same transaction in A single fetch or like an object being added and removed at the same time plaid does the right
thing here to make your job easier so with all that under our belt let's go ahead and mimic what we might do if we were a real finance app first we'll want to retrieve any existing cursor for this item from our database it'll be null the first time we call it you know and that's fine next we'll fetch all of our transaction data Since this last cursor we've basically done that work already next we'll want to take any added transactions and add them to our database then we'll want to take any modified transactions and update
those in our database then we want to take any remove transactions and decide how we want to deal with them and then finally we'll want to take that most recent cursor and save it to the database so let's tackle these steps So uh first as you remember our items table has this transaction cursor entry and as it turns out if you look at my get item info call here in our you know database script you can see I'm already grabbing this field so here in transactions JS we can tackle step one we can simply grab
our transaction cursor the same way I'm fetching the access token and I'll rename it the same way I'm also going to do the same thing for our user ID since we'll need that in A moment too then let's have our fetch new sync data function except a new argument initial cursor we'll make sure to set next cursor equal to initial cursor when we first fetch our data and then we just got to make sure we pass our transaction cursor to this function when we first call it and uh Step One is done that was kind
of easy okay next up we're going to want to save our new transactions to the database so we'll want to look at all the objects in Our added array I'm going to make this a map instead of a for each for reasons you'll see shortly and just to make sure we're doing the right thing let's console log this for a moment and yeah sure enough I can see all the transactions I want to add so next up let's convert this transaction object into like my internal simpler version so that we can add it to our
table I'll do that by saying const simple Transaction equals and then we'll call this static simple transaction from plaid transaction method passing in the transaction object from plaid and our user ID now let's jump into the simple transaction file and implement this method so we can say return new simple transaction and let's tackle these fields one by one so for our IDE we'll use the transaction ID we passed in our user ID earlier so we set that like so account ID we can get right from the transaction object category I'm going to get from the
personal finance category field you could use the detailed or the primary one or keep both I'm just going to keep the primary one for now we'll store both the date and the authorized date these are strings by the way that just display the date in like you know ymd format for the name let's grab the merchant name if It exists remember that's plaid's attempt to create a more readable version of The Merchant name and if it doesn't exist we'll default to the plain old name field you might want to keep both in case it turns
out you don't like how plaid extracted the merchant name it's up to you we'll grab the amount and the iso currency code again directly from our transaction object and finally we'll get the pending transaction ID all right going back to Our transaction.js code let's remove that older logging and we can console log this newer object to make sure it looks okay and if I were to run this again you can see that it does then let's call await DB add new transaction with this object vs code is complaining but we'll get back to that let's
handle this database function first now at this point we're just dealing with basic SQL code and since the point Of this tutorial isn't really to write SQL and a lot of you are probably using your own orm anyway I've written some code that we can just uncomment note that I'm not actually storing that pending transaction ID value in fact in this app I'm not going to do anything with it but if you were building an app where a user could write their own description or category or something like that to an existing transaction this would
probably be a good time for You to copy over that data from the other transaction into this one especially since this probably means that other transaction is getting removed in the next step so we can return our result and keep going so uh let's fix up a couple of things here first is that vs code is complaining about this awake call so we're going to mark this function as async and then I believe what we want to do here is wrap all this up into a await promise.all if I have this right this map function
is giving us an array of promises and our program will proceed in the next line only once all these promises have properly resolved second we should probably ask ourselves what happens if we try to insert a transaction that's already been added that shouldn't normally happen very often in practice but it could happen like if you end up rerunning this call on a previous cursor heck maybe you're running into this Already if you're jumping ahead of me and like running this code multiple times so uh I could have made this an insert or ignore particularly if
you think there are cases where you might legitimately rerun a cursor but I decided to put this in a try catch block and just log the fact that we're trying to insert a duplicate entry that might help alert us to instances where we're not saving our cursor correctly or you Know something else funny is going on but it'll let us continue with the rest of our transaction sync finally you might have noticed that I have this summary object up at the beginning of our function so if I were to go ahead and capture and log
the result of these Edition calls you can see that it consists of an object that tells me how many rows were changed so I can do something like this just to update that value in our summary Object now because in that last step I went ahead and made this call for real that means I've actually added 190 odd transactions to my table and if I were to take a look there they are and if I were to run this again I'd get about 193 error messages because I'm just using null as my cursor every time
and it's trying to re-insert transactions that already exist so don't worry we'll get to this soon and let's just take a look at our database to make sure these Transactions look like they've been added okay and looks pretty good admittedly this is a little crude if you wanted to either make some batch insert logic to be more efficient or add in some you know commit rollback logic that's certainly something you could consider just remember you might have a mix of transactions that already exist and ones that don't if you happen to be reusing an earlier
cursor so make sure you handle that case properly now when It comes to our modified transactions plaid gives us a fully hydrated transaction object they basically look exactly the same as the ones in our added array so updating our modified transactions will involve a lot of code that's very similar to what we have before in fact uh let me just copy and paste this section but instead of added we will look at modified we'll call our modify existing transaction function instead and we'll make sure to update Summary.modified down here and then and let's go ahead
and uncomment this database method this really is just a pretty straightforward update call with a lot of different fields maybe the only interesting thing to point out here is that I don't update the user ID since that should never change you might ask yourself is it okay to like overwrite my data like this should I like Mark that old transaction as deprecated and add in a new row instead I would say it probably depends a little on your application's logic but also remember that plaid tends to condense these changes so you're not seeing most of
them anyway so I would say it's generally safe just to overwrite these rows maybe if you're doing some aggressive caching on your client you'll want to add a last modified column so you can make sure you grab the updated info and of course be careful about overriding any Fields your user might Have modified and of course I'm also putting this in a try catch block although I suppose there's fewer expected situations where you'll run into errors here now testing this is actually pretty tough in sandbox it's a rare to see modified transactions I have seen
them often after grabbing data for the first time but it is hard to reproduce so if you really want to test this you know one wave is just run it in development I Did just go ahead and create a test data.js file that contains some code that you can copy and paste if you want to simulate one of these modified entries I'm just going to go ahead and trim some of these unused Fields so you can actually see all my code on screen I'll replace the account ID and the transaction ID with real values from
a database and then I can try this code and there is my modified entry in the Database and I'm going to remove this now okay let's talk about removing transactions with remove transactions you'll see them represented as an array of objects that contain a single key value pair that of transaction ID now how you want to deal with them is up to you a little bit you could just go ahead and delete the row from the database that's totally reasonable but if say you've done any other processing On this deleted transaction and want to leave
it around you know at least for a little while you can do that too so like in our other sections we're going to await promise all alldata.remove.map and async and then for our little mini transaction object I have two functions to find in our database that we could implement we could either call a weight DB delete existing transaction passing in our transaction ID or marked transaction as Removed and both of these are pretty simple let's uncomment this code too and delete existing transaction we simply delete the row from our database and in marked transaction as
removed we'll set the value of our is removed field to True sqlite doesn't have true Boolean so we'll just use the number one now you might ask yourself wait why are we also renaming the ID of their transaction well it turns out in some rare instances a bank will Mark a transaction as Removed and then add it again later with the same transaction ID and this could be a problem for me if I already had an existing but removed transaction with the same primary key in my database and so that's basically why I'm renaming that
primary key so we don't get into any collisions and when it comes time to retrieve these transactions later we'll just make sure not to fetch any of our is removed ones so those are two different ways you Could handle removing transactions I think for my app I'll go with the marked transactions as removed approach you know at least while I'm in development that'll probably make it easier to recover in case you know something goes terribly wrong in my code I haven't actually deleted any rows also you know I think it's kind of interesting to see
what transactions are marked as deleted but again either option is fine let's increment our summary value and we're Good again testing remove transactions is hard on Sandbox without adding your own fake data which you can do like so again I just added some code to that test data file just make sure to copy over your actual transaction ID from your database since they are unique every time and if I were to run this now we can see that this transaction is now marked as removed and then for our final step saving the Cursor let's call
one more database function save cursor for item we'll pass in our next cursor which is also in our all data object and then we can pass in our Item ID and we can uncomment this code now where we're basically just updating the appropriate Row in our items table it's pretty straightforward there and I think we're good and if we were to run this now you can see that it's processing all you know 193 rows of data Or what have you but then if I were to run it again this time it's using my saved cursor
so plaid is only giving me the transactions that have changed in my last cursor in this case it's you know nothing my database is up to date and there's nothing more to sync I think the last thing we need to do here is maybe just clean up this call in my endpoint Handler and make sure we return something so we can say that full results equals await Promise.all then we'll make this in items.map make this in async await call for sync transactions and then we can return those full results which will be an array of
those summary objects one for each bank and uh just like that we've done like 85 percent of the heavy lifting for getting our personal finance app to connect to our banks and you know you can go ahead and try this like create a new user to try connecting to more than one bank and See what happens when you call sync multiple times it should all work okay at this point we have a few more steps to tackle um first let's show something to our user I think that'll just make our application a lot more fun
to work with um after that let's see what we can do to update that data automatically so we don't have to keep clicking This Server refresh button and finally let's talk about what happens if a user decides to Delete their account or they want to remove one of their Banks so let's start showing some transaction information to our users maybe we can retrieve like the 50 most recent transactions from our database this will be using our list endpoint so let's go there so we'll want to grab our user ID which we can get from our
request and then we'll also look for a Max count parameter which we can default to 50. Then we can have transactions equal a weight DB get transactions per user where we'll pass in our user ID and Max count and let's just return that object as a big Json object again our database code is already written for us we just have to uncomment it back in you can see this fetches all our transactions where the user ID equals the variable we passed in and is removed is false order by date and limiting our rows to Max
count then we do a little bit of joining To grab the account associated with each transaction and the item associated with each transaction so we can return both the bank name and the account name and then just to make this call from our client we'll just uncomment this code which hits this endpoint with the URL argument of Max count equal to 50. and if I run this what I get back is a big old array of Json objects so we can display this on screen again since this is a plaid transactions Tutorial and not a
JavaScript tutorial and you're probably using some kind of framework we already have a basic show transaction data method set up here all commented out and ready to go so we'll uncomment that you can see that it just takes some of our data and displays it as a table which is nice but without any proper sanitizing of our data which isn't nice so don't do that in real life so if I were to reload this I get some data and It looks like a good start let's talk about how to clean it up though first uh
this category is a little ugly luckily we've got a human readable category helper function to sort this out what it does is it takes our category replaces underscores with spaces it makes the whole thing lowercase and then capitalizes the first letter of every word except for and in or so we can call human readable category of our transaction category here and That'll start to look nicer next moving on to our amount JavaScript has some nice currency conversion options using international number formatter objects and we've got a function here that uses the objects or you know
creates one if you need it for a specific currency and returns it for you so let's go back to our client here and return currency amount with our transaction objects amount and our currency code okay so I'll reload and this looks much Nicer and you can start to see how I could turn this into a nice little budgeting app okay good progress but let's talk about our strategy for calling sync because it would be nice if this data were already loaded for us when we opened our App instead of having to click that little button
and I'll be honest one option would simply be to call synca on the back end when a user logs in and returns to your App it's a reasonable enough solution uh the biggest drawback of course is that you're going to have to wait for this sync call to complete before we can show our user their latest batch of data also if you want to do any back-end processing like you know alerting your user when their expenses in a certain category exceeds their budget then you'll probably want to fetch data more often than just you know
whenever they log in So another option would be to have some kind of background process running on your server that calls sync once or twice a day for each of your users and honestly that's probably frequently enough now just to be clear when you're calling Sync here you're simply having your server synced with the latest batch of data that plaid's been collecting in the background from these various Banks now how often plaid fetches data from these Banks depends on the institution But if you were to just call sync like every 12 hours or so that
would keep you pretty current with the data that plaid has but the recommended way and the way I'm going to show you how to do this is to respond to a web hook as plaid fetch's new data from these institutions if it sees that it has new information available since the last time you called sync it will send you a sync updates available web Hook when you Receive this web hook then you know it's a good time to call sync and that'll make sure you always have the most current information available without doing more fetching
than necessary so before we start to handle this web hook there are two little quirks that you should know about um first is that planet won't send you this web hook unless you first call transaction sync I guess maybe you know that's your signal to Plaid that this is A web hook you're interested in receiving in the first place so uh that's generally pretty easy to address what I would recommend is as soon as you receive an access token just start making a call to transaction sync so uh let's do that now I should note
that this part of the tutorial does depend on your being able to use a tool like ngrok to actually receive web hooks on Port 8001 of your local machine like I showed you at the beginning of this Video and again if you want more instructions on how to do that or just need a refresher on web hooks or how they work you can check out our web hooks tutorial so here in my tokens.js file right after I've gotten my access token and grabbed my account and Bank names I'll make another call to sync transactions passing
in the item ID that I just received and inserted into my database in a production environment this will Probably return nothing since plaid hasn't had a chance to fetch any data yet but it'll let plaid know to start sending you web hooks as soon as it starts getting any data in sandbox this actually might get you a bunch of data right away because sandbox is kind of fake anyway but uh you know that's fine the call still works speaking of sandbox the second issue is that plaid doesn't actually send this web hook in the sandbox
environment again this is Because while sandbox is close to replicating a real life environment it's not exact it kind of considers this data static luckily there is a set of endpoints we can call that will fire a web hook for us in sandbox so open up our debug JS file and in this generate web hooks endpoint we can replace this code with const result equals await plaid client sandbox item fire web hook and then we need to pass In two arguments the first one is the web hook code to Fire and in our case that
is sandbox item fireweb hook request webhook code enum dot sync updates available and if your IDE isn't Auto completing this for you then the string sync updates available will work too but then the second argument is the access token for the item that we want to simulate the web hook call for so I'll need to get that by grabbing an Access token that's associated with one of the items that belongs to our user so up here we'll fetch our user ID and then we can say that items and tokens equals await DB get items and
access token for user and this is an array of objects that contains our item IDs and our access tokens then I could just pick this first one although if you're feeling fancy we could pick one at random and say that you know random item equals items and Tokens and then we'll get math.floor or math.random times items and tokens dot length and then finally our access token will be the access token property in this random item object so now we can set our access token in the Plaid API equal to this access token and this will
fire off a web hook for this specific item and we'll just return the results we get back from this call so that our client knows the call is done and again we're only doing all this Work so that we can simulate a web hook in the sandbox environment finally we'll hook up our Sunday web hook button to call this endpoint over in client.js just uncomment this code here in the generate webhook function and if we were to reload our client and make this call Now by clicking this button and if I look at my terminal
here it looks like I received a sync updates available web hook for this item which is exactly what I want this field here Is telling me the web Hook is for the sandbox environment these two values here are telling me if the initial update is complete that is the transactions grab the first 30 days of data and if the historical update is complete that is has transactions grabbed the up to two years worth of data that might be available from my Institution you can use this information to you know like update your UI maybe use
the Initial update to let your user know you have some data they can start working with and you know the historical update to let them know their full records are available and in case you're thinking wait don't we already have these separate initial update and historical update web hooks for that uh yes yes we do but you also get this information in the sync update web hook which maybe is a little more convenient depending on your code But the most important element here is this item id which tells us what item this web Hook is
actually for and also seeing a message that our code can't handle this web hook but we can do that easily enough let's open up our webhook server file and down here in my handle transaction web hook code let's add in a case for sync updates available and as you'll recall our sync transactions code is already set up to sync new transactions For a given Item ID so I can just call this we'll call sync transactions for this request body dot Item ID and uh that's it we're done our sync transactions code will ask for any
new data since the last time we called sync by fetching the cursor we have stored and it'll process that data just like before and save it in our database and I should probably note that this will be the most common way by which you'll call transactions out in the real World that whole click to refresh my server button that we have in our app is really only there for development purposes and to reflect the fact that web hooks function a little differently in sandbox mode in a real app maybe you'd have that button buried in
a settings page somewhere just in case web hooks aren't working but you know you wouldn't need it most of the time so let's try this one more time I'll generate another web hook and you can See here that it's been retrieved and I've gone ahead and synced transactions for this specific item now in my case I'm not actually getting any new data but if through the magic of video editing I were to you know jump a few days into the future you'll see that I do have new transactions coming in from calling sync and again
in a production or development environment you'll get this data only when plaid really does have new data so This call should pretty much always fetch something you might also wonder hey what about these other web hooks I'm seeing like transactions removed or default update well if you read the docs you'll see that most of these are really only needed if you're using transactions yet if you're using sync honestly the sync updates available webhook is the only one you really need to worry about okay let's finish up by dealing with a Couple of other important topics
first off because plaid is constantly fetching new transaction data for every item that you've connected with transactions it means that we are regularly charging you for this transaction product so if you have a user who chooses to disconnect a bank or stop using your application entirely you probably want to tell plaid to stop fetching transaction data that you no longer need typically the way you do this is to Remove the item so let's look at this remove this Bank drop down you can see that our drop down is populated by our list of banks with
the ID of each item as the value so if we were to jump into our deactivate Bank call in the client we can uncomment this code too here we're saying that if our Item ID isn't null and it's not the empty string we'll hit the endpoint server Banks deactivate passing in this item ID so let's Implement this on the server open up banks.js and let's find our deactivate endpoint now telling plaid to remove an item is fairly easy I just need the access token of the item to remove and then it's a simple call to
the Plaid client so first I'll say that our Item ID is the request body dot item id I'll also grab our user ID then I'll have access token renamed to access token as await DB get item info for user item ID and user ID this searches our database For the record belonging to this item ID and gives me the access token but it also performs the extra step of confirming that this item id really belongs to our user you know no having malicious users deactivate other people's item IDs that I can say await plaid client
item remove and I will pass in our access token and that's actually all we need to do From plaid's perspective we've essentially invalidated the item and its Associated Access token and plaid will no longer retrieve transaction data for this item so the Plaid part's mostly done but we've got one issue because I've removed this item any calls I make with this old access token will start throwing errors I mean that's what it should do right because the access token is no longer valid but I should probably make sure we don't make these calls in the
first place now so I have a method already set up to Handle that too I'll call away DB deactivate item ID and let's go ahead and look at the code here again there's some code we can uncomment to make our lives easier but I should note that what we want to do here probably depends a bit on your user's intent when they ask to remove this Bank are they removing it because you know maybe they're not using it anymore but they still want to keep their old data or do they really want to remove all
Traces of this Bank including all of their old transactions probably in a real app you'd want to give them the opportunity to sort of Select both with like uh also delete all my data checkbox in our case though we'll just cover that first case we'll keep our data but marked that this bank is no longer active and so that's what our code is doing we're moving our access token and we are noting that this item is no longer Active if we really did want to delete all of our Associated data our strategy would probably look
something like this first we want to delete all transactions belonging to all accounts associated with this bank then we want to delete those accounts from the accounts table and then finally we want to delete the item itself so let's go back to our deactivate endpoint here and make sure we return something and we could run this if we wanted Let me refresh my Client I'll ask to remove this bank and sure enough if I refresh my database table I can see that its item is no longer active but uh we're not done here you can
still see that this bank is showing up in our list of Banks and if I try to call sync on our server I'll get an error because it's trying to make a call to sync with an access token of revoked so we can fix this this is really just adjusting bits And pieces in our client and server logic probably the simplest way is just make sure our database methods don't include any inactive items so okay sorry you are going to have to write three lines of SQL here up here at get item IDs for user
this is the call we make in our sync Call to determine which items to refresh let's add in a and is active equals one line that'll make sure we only retrieve our active items then we'll copy and paste That line here in our get items and access tokens for user call this is kind of that debug call that we make in order to call that fake web hook and we'll also do it here at get Bank names for user which shows our user what banks they're connected to note that at least for now I'm not
going to do this here at get transactions for user since we might want to retrieve transactions even for banks that our user is no longer using so now we're Basically done back in our client you'll notice that we have a call to await refresh connected Banks to update our drop down list once we're done disconnecting a bank and that should do it so you can test this out now go ahead and add a bank or two remove a bank or two and you'll see that this list stays up to date but we'll continue to show
you transaction data that we've grabbed from banks in the past okay moving on to our final part of the Lesson here and that's dealing with one Edge case that occasionally pops up as you know if you make a call to transaction sync and transactions has more than one page of data you'll get back a new cursor value and a has more value of true now at this point plaid essentially makes an assumption that you're going to continue fetching the rest of this data and it basically considers this data Frozen until you finish fetching the rest
of it if some New data were to come in while you're in the middle of fetching a multi-page sync request because the way we process data plaid can't guarantee that we'll give you the correct set of data here so instead we say hey you know what why don't you just refetch this call from the beginning this is otherwise known as a transaction sync mutation during pagination error if you get one of these errors simply retry the entire fetch from your original cursor now again this Shouldn't happen often but it can happen so let's show you
how to handle this error when it does show up so uh going back to my fetch new sync data function here's what I'm going to do I'm going to throw this into a try catch block and in my error catching block down here below let's log the error if you want to check specifically for the transaction sync mutation during pagination error code you can check for that by looking At error.response.data.errorcode although to keep things simple for now I'm just going to retry on any error so I'm going to wait a second literally and then we'll
return the results of fetch new sync data with our access token and our initial cursor again I'm basically asking our code to retry or fetch from the beginning and that should be enough to handle these sync mutation errors but of course I'm retrying on any error and Just to avoid the possibility of an infinite Loop here we should probably add a maximum number of retries here I'll add retries left equals three to our function we can then say if retries left is less than or equal to zero we'll quit out and just return like an
empty data string and you know this will work just fine we still have our original cursor saved in the database and we can always retry it another time once we fix whatever's giving us errors and then Down here when we rerun our function let's decrement retries left so that should avoid any infinite Loop problems and by the way this is why I chose to fetch all of my data first and then handle the database calls instead of like adding the database records in several batches it just makes everything a lot less messy if I ever
need to restart the sync call from the beginning again testing this is quite difficult it's hard to make one of these sync Mutation errors happen intentionally but you can kind of simulate it just by like occasionally throwing errors in your code if I had something like this and you know maybe set my page size smaller I could see that when I create a new account and try to fetch a batch of data I'll occasionally get an error and my code will try from the beginning uh just you know make sure you remove this code before
you start putting your app on product hunt or something Okay one last thing I promise to cover remember how at the beginning of the tutorial we created that new user and only listed identity in the products array well it turns out I can still request transactions for this user here's the thing when you add your list of products in your link token creation object you're basically telling plaid hey I want you to only list financial institutions that you know support these products but in some cases transactions Being one of them you can still try to
use the product even if you didn't List It originally so if we log out and log back in again as this very first user and hit our server refresh button it will still call transaction sync and transaction sync will run and because I'm in sandbox things get a little weird I've activated our web hook which gets fired right away because all of our information is available but in a real app we'd get back no data initially and That's because we didn't list transactions as one of our products therefore plaid wouldn't know that it needs to
retrieve transaction data from my bank so while this works fine it'll take longer than usual to get data out in the real world so for a better user experience you should still list transactions in the products array if you know you're going to need it also I should probably give you a heads up that At some point in the future we might require you to list products that you think you might call at some point in a list of additional consented products so uh this part of the video might not be quite up to date
you should check the docs to make sure and there you have it just about everything you need to know about transactions to figure out where your money's gone as for me it looks like I could probably cut down on the coffee But on the other hand my kids really need to go to college you know it's it's a toss up there anyway make sure to subscribe to our YouTube channel for more exciting content like this one check out the docs for any details that I might have missed and I will see you soon on another
episode of plaid Academy [Music]