How To Setup Payments With Node.js And Stripe

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody kyle here from webdev simplified in this video i'm going to go through all the steps that you need to take in order to set up a shopping cart using stripe to accept payments I'm going to go through all of the different security concerns that you need to take into account as well as how to set up your back-end server and how to set up your front end so that it's integrated properly with your back-end so let's get started now the first thing we need to do is set up our project using NPM if you haven't already downloaded NPM make sure you watch my last video which was about downloading node which will also download NPM for you so to get started all we need to do is go into our terminal and type in NPM in it and hit enter and it'll prompt you with a bunch of different questions about what project you're creating and I'm just gonna leave all of mine default so I just need to hit enter a bunch of times to get through all the different stuff and as soon as I finish that you'll see it creates a package.json file with all the different answers to the questions that I've put inside of it this is a way where you can put all the dependencies for your project as well as information such as the name and description of your project so it's easier for people to understand what's going on with your project next we want to download the different libraries that we're going to be using inside of this project we have just a few libraries that we're going to use so in order to install libraries we just use NPM install and then we type the name of the libraries we want in our case we're going to be using Express which is a framework for developing web applications and node we're going to be using ejs which is our view templating language so we can put server-side code inside of our front and HTML views and then we obviously need stripe since we're going to be integrating with stripe so we need that better library as well to integrate and then in order to save these all we need to do is put - tasks save and hit enter and it'll download all these different dependencies put them inside of a folder code node modules as you can see over here and then inside of our package JSON you see we got a bunch of different dependencies with their versions added into here you'll also see we have this lock file which essentially just locks the version of our libraries that we've installed so that when we deploy this we have the exact same libraries being deployed to production as we have in our look one by we still have one more library that we want to install this is going to be what's called a dev dependency which means it's only installed when you're working in the development environment such as on your own computer but it won't be installed in production so in order to do that you use the same exact command and then type the name of the library that you want in our case we want to use dot env and then just put save but it's going to be saved - dev and that'll save it as a dev dependency if we run that you'll see that it'll download that dependency and add it to the dev dependencies section right here and our package JSON file and now we have all the different project components that we need in order to start building our actual project so what we're going to do next is download on my old introduction to web development project which I actually built the shopping cart using Java Script and we're going to take that shopping cart and we're going to build the backend for it so we can integrate properly with stripe so in order to do that we need to go to my github account right here introduction to web development what we want to do is we just want to use the clone or download link you just want to copy this you're using SSH in my case I want to copy that and then we can just clone that library so we can just try to get clone paste in that URL and we'll clone that introduction to web development into our project right here as you can see and as soon as that finishes downloading I have all the different parts of my project and in our case we want to go to introduction to JavaScript lesson 1 and these are all the different files that we ended with in the last part of my building a JavaScript shopping cart tutorial that I'll link in the top right corner if you're interested in checking that out if you haven't already and what we want to do is we want to copy all these files into our current project but we want to put them inside of a folder called public because this project that we have right now contains both our server and our front-end code and we don't want to intermingle our front-end code in our server code together so we're going to use a public folder in order to put all of our front end facing code such as our HTML pages our JavaScript and our CSS and that's where everything that the browser can access is going to go so let's first create a new folder called public for us to put all this information in and we're going to copy the fonts images HTML files jazz and CSS files from this introduction to JavaScript course we're just going to paste that right here into the public section whoops into the public here and then once all those are in there we can completely delete this git repo that we cloned because we don't actually need it for our project and now as you can see we have everything that that project ended with inside of this public folder here which is exactly what we want and now we can work on starting creating the server for our application in order to create a server for our application we want to create a new file and we're just going to call it server J s so that we know that this is our server file and this is going to be in the root of our project so just say server dot J s right here and this is where all of our server-side code is going to run and then if you've been following along with my channel you know that my last video was how to set up and create a node server and in this video we're going to do something very similar if we're going to use a node server but we're going to use a framework called Express because it makes doing a lot of the things that you have to manually do much easier than if you were to just do a basic node based server so what we're going to do is we're going to create a variable we're gonna call it Express so that we can require that Express library that we need so we just type and require put in Express here and this is going to require the Express library into that express variable and then in order to create our app we just need to use that app variable here and we need to create this Express variable that we used that we required earlier and it is just a function so we can just call this Express variable since it's just a function and that will create a brand new app force inside of this app variable this is essentially the same thing as doing create server for the old node way of doing it just basically where you just use HTTP crazy server that's essentially what this is doing but a little bit more complex next we want to set the view engine that we're going to be using for our application and this just allows us to embed server-side code inside of our front-end HTML pages so we can just say app dot set and since we want to set the view engine we just put a new engine and then we put what we want to set it to and in our case we downloaded ejs so we're going to set it to ejs here and now our front end is going to be using ejs in order to render its views we want to tell our app where all of these public front end facing files are and in our case we put them in this public folder so we just say app diet use and we just need to say Express which is that variable with library Express that we talked about earlier dot static so this is saying where our static file is going to be and we'll say public so this is marking all the files inside of this public folder as static and they're going to be available on the front end which is exactly what we want and now we can work on actually creating the different views for our server by making it listen so all we need to do in order to do that is just type app dot listen and we can just tell it what port we want to listen on in our case we're just going to listen on port 3000 and now if we save that and run our application by typing node server j/s and we go over here to localhost 3000 as you can see we have our application being run here from our public folder it's serving all of our different HTML files so we can navigate through this is going to be the store we're going to be working on and we also have the about page here all this that we created earlier and paste it into this public folder here all of its available now because we added this line which is using that public folder as our static files now that we have this open I'm going to show you a quick demo of what our store does right now if you go into our store page and you click add to cart on any of these buttons here it'll add it down to the bottom of our cart here we can increase the quantity whatever we want to do add something else we can remove things if we don't want them and then when we click purchase it'll just give us a message saying we purchased it and remove it from the cart but it doesn't actually do any purchasing or require any credit card information and that's what we're going to integrate with stripe the way that stripe works is that when our user clicks the purchase button on our page here instead of popping up this message it's going to pop up a pop-up that allows the user to enter their credit card information there's it code address everything that they need to enter in order to purchase these items and it'll send that information to stripe stripe will then take that information parse it and send it back to us as a unique ID that we can use to reference that user's credit card information as well as their address and anything else they entered so we don't actually have to store any credit card information on our server all we needed to worry about is this idea that they send us which is perfectly safe for us to store ourselves because it doesn't contain any sensitive information we then are going to send that ID to our server which we created over here we're going to add a routes so we can send that to our server and then from there we can use the secret kree for stripe in order to send and create charges with that ID which is linked to that person's credit card that way our application doesn't have to handle any of the credit card information and we aren't liable for handling any credit card information so in order to get started with that we need to sign up for a stripe on their website so if you just go google for stripe go to their homepage here and I've already signed in so I can just click dashboard but for you you would want to click sign up and just sign up for their account and as soon as you're done with that it'll bring you to their dashboard here and you can go down to the developer section go down to API keys and here is where you can view your publishable API key as well as your secret API key which we are both going to need these for our application the secret API key is something that you want to keep secret you do not want to share this with anyone you don't want to put it in your front-end code you don't want to commit it to your github it needs to stay entirely secret because if people have that API key they can use it to charge your customers as well as charge your customers credit cards which you really don't want so make sure you keep the secret key secret the publisher will key on the other hand you don't have to worry about keeping secret so you can check that into your github or post it down to the front-end and it won't really matter in order to make keeping these secrets much easier we downloaded the library called E&V earlier and now I'm going to show you what that's really used for so if we go over here into our project and we just create a new file we're just going to call it dot e and V with a period not the actual word dot bring that into the root of our project and in here we can put all of our different environment variables such as our secret key and our publishable key so that we don't actually have to check these into our github repository or put them in our code and then if we just create a git ignore file and we just put env inside that get ignore so this dot V file will never be committed to your github account so you never have to worry about anyone seeing your public or secret keys in your github account and we can also reference these environment variables inside of our server by just using a peer real quick so if we wanted to get our secret key so we're on our stripe secret key always say is process env and anything we've put after this variable on this object is just whatever we put inside of this environment variable so for example we can put our stripe key in here we can just call it stripe secret key set it equal to whatever value we want for example we just set it to test for now for testing purposes and if we save that file go back to our service file and we just put that exact same thing that we typed in there so in our case is going to be striped secret key and then to test this we can just log out the secret key so we can just say a console dot log stripe secret key save that and we can run our server here and as you're on it you see that we get undefined while we should be getting the test which is what we put in our environment variable and that's because we need to first load our environment variables using the dot V library that we downloaded so we can end our server and at the very top of our file what we first want to do is we're going to check to see if we are running in production environment or developing environment so we can use our process env dot node E and V variable and this is a variable that is going to be set by node itself that'll tell you what environment you're on and we want to make sure that we are not on production because as you know we only downloaded the env library for development so if we're in production we don't want to use the dot env library because it won't actually exist we're going to run into errors so if we know it's not production then we're safe to use this library and we can just require that env library and then we can call on this library the load method which is going to load all the variables inside of this env file and put them inside of our process that env variable in our server and now if we run our server you'll see that we get printed out test which is exactly what we put in our env variable here and this is perfect because now we can hide our seeker keys inside of this env variable without actually putting them in our github repository or anywhere else in our server that is going to be easily accessible by other people so now let's just copy over the secret key and the publishable key from our web application for Streicher so if we go over here you can take our public key copy this and we're going to create a new variable we're gonna call it stripe public key I'm gonna paste in that public key that we have right here and we're also going to get our secret key as well and paste that instead of test and now we have two variables for our secret key and our public key for using stripe that we can access inside of our server here so let's create another variable for our public key and we're just gonna call it public key instead of secret key and we're going to access it by exiting the public key variable instead of the secret key and we can test that that's working by trying to print both of these out saving and restarting our server and you'll see that we get our secret key here first and then our public key right after that and that's perfect we now have our API credentials set up for stripe so that we can start actually using the application but you will notice these are only test credentials so we can actually hit the stripe API and send it certain charge requests without actually charging any of our credit cards or other people's credit cards for real money so we can use this for just testing which is exactly what we want for building this application the next thing that we're going to want to work on is modifying our store HTML page so that we can use it within our view templating engine of ejs and we also want to extract all the items that are in that store onto our server so that when we tell the server which items somebody bought we can actually reference it on the server instead of having the reference in from the front end which would allow people to be able to fake what items they bought for example if we got our request back from stripe with the token for their credit card number and everything and then the user for the front end sent us back the amount that we needed to charge that credit card the user could just change that amount to zero in their front-end click the purchase button and it would be able to purchase everything for $0 and we wouldn't have any control over it so instead we're going to send the different IDs of the items that they are purchasing to the server so that they can't actually think what they are buying so to do that we want to first create in our case we're just going to use an item dive JSON file item JSON in order to restore all the different items on our server and we're just using a JSON file here because it's easier than setting up a full database in order to do this so let's open up our project real quick go to the store page here so we can view the different items that we need to add to our project so as you can see we have two sections music and merge so our items are JSON we're going to have a music key and this is going to be all the different music that we have for sale so it'll be an array and then we're also going to have a merge which is going to be everything else that isn't music that we have for sale which will also be an array again and inside of this array will put all the different music so we're going to have a name price and an image name as well as an ID that we're going to use in order to reference that so first we'll have an ID and in our case we'll just make this one ID number one we're then going to have the name the name of this one is album one next we'll have price and we're going to put price using cents instead of using dollar amounts because it'll make us that we don't have any floating-point rounding errors when we are calculating our total price so instead of putting $12.99 like that we were going to put one thousand two hundred ninety nine and that's in pennies instead of in dollars then lastly we want to use the image name set that and we can find this inside of the actual let me just pull there here and you can see we have an image called album one jpg so album one dot PNG have you saved that we now have our first music item done and we just need to go through and do this for all of our different albums as well of all the different merch so I'm just going to copy that over real quick paste that down we're going to change the ID here to - the name is album - price is $14.99 and then album - dot PNG do this two more times for our other two albums so we have a album 3 which is ID 3 it's going to be a cost of $9.99 and then album 3 dot PNG and then finally album 4 and this one is $19.99 and then we have our merch section which has a t-shirt and coffee cup we're going to do essentially the exact same thing so we used ID 4 here so this will be ID number 5 the name is t-shirt price is $19.99 and then over here we have a shirt dot PNG which is the file that we used and go and then lastly we want to get a coffee cup item in here which will be ID number 6 a title right here there's coffee cup price is $6.99 and then lastly we have a coffee PNG over here which we can just use and if we save that now we have all of our items inside this item JSON which we can actually reference and use instead of our front-end code in order to make all of these different items show up and now they'll have an ID associated with them which is perfect so in order to access these different items inside of our front-end we first need to go into our server so let's go to our server Tijs file and we want to create a route for this store page that we created so in order to do that always say is app dot and here we want to put get because we're doing a get request which is essentially the same thing you do whenever you click on the link in a web page or type out the URL of a web page so we're going to say get since we're doing a get request and then we want to do for the route of storage so whenever someone gets the route store at the base of our thing so if they were to type into our URL here store just like this so slash and then store and it entered it would bring them to this get request here and as you can see it says cannot get slash store because we haven't restarted our server yet or provided a function for this store method so we're going to provide a function here this function is going to take our request parameter as well as the response parameter just like in a normal node.js server and inside of here we can do all the different code that we want to do in order to send variables to our store page so the first thing we want to do is read that item JSON file that we just created so we need to include a library in order to read that file so up here let's just include FS library which will allow us to read different files and now that we have that included we can go down here and type in FS read file in order to read the contents for our items JSON file and then of course that'll accept a function within ever ammeter if it air it out so we can first check if there is an error and if there is error we just want to set the status to 504 our response and then we want to end that response and this is very similar to how we would do this using a basic node server but it's much more streamlined we can just call res dot status to set it 500 and then end to end our response but of course if there was no error we want to actually pass down our file so we can say res dunder and in here we want to render that store page and right now we have it saved as an HTML page but since we want to use the values from our server in that HTML page we need to save it as it's EGS file ejs sorry and that way we can use our templating language on this so we'll say to render store that ejs and then after that we want to pass it all the different variables that we want to send to that server page so in our case we want to send the items in order to actually get the items you can just say json.parse and we can parse the data which is the second parameter here to our read file which is the actual information inside the file and says it's JSON we just want to parse that into valid JSON and it will send that JSON object with the name items down to our store HTML page which we've changed the name to store ejs and while we're using express by default all of your views that are rendered with this method here need to live in a folder called views so let's create a new folder call it views here and inside of this we're going to move our stored out HTML and we're also going to change the ending of this file to be stored at ejs so that we know that it's going to be our templating language of ejs and in order to get syntax highlighting for this ejs format you may want to install an extension called ejs language support which I already have installed so if you haven't done that try to install that now and then reload visual studio code so that you get syntax highlighting for ejs now back in our story J's file here instead of printing out all of our shop items manually inside of our HTML we can actually loop through that items variable that we just created you know do that we just gone to a new line here and in ejs in order to reference the server-side variables such as that items variable we would just need to put any code inside of this less than sign followed by a percent sign and then ended with the exact opposite and all the code inside of here is going to be executed on the actual server before it gets sent to the front-end client of the user and if we put an equal sign here it'll render whatever gets executed inside of here to this screen but in that case we don't want to render we just want to actually execute and what we want to do is we're gonna loop over all of the music items inside of our store so we can say items dot music that for each this will loop over each item and they'll have a function inside of it that'll take a single item which is going to be each item of the music array and then inside of this is where they're going to do a different code if we want to print out pretty much all the information inside of here we need to make sure that we actually end our loop down here on the outside of our actual information that we want to return so now inside of this loop we have this variable called item which contains all the different information instead of here we have ID name price and the image name that we can use inside of our story GS page here inside of this loop so instead of printing album one instead we can use this variable we put the equals sign since we actually want to render this in the code we can just say item that name and this will give the name property from this item variable and print it out inside of our code right here which is perfect and this is going to get printed out every single one time for each item in the music already in our items object so it's going to get printed out four times one for each album same thing here we have the name of our image we just need to change this to be image name and then we have price down here so change this to price and since our prices and cents and we want to display it as dollars we just divide by a hundred and then lastly we want to put the ID on our item here so we're going to put it inside of a data attribute which allows us to act this inside of JavaScript without actually putting a class or an ID so we can just say data item ID ID we're going to set that equal to we need to make sure we put this in close and we're going to set that to the item ID and now we can remove all these extra shop items down here for this section for music and as you can see our music section now just contains this loop that goes through all the different items in that items variable so now if we save that make sure we save our server end it and restart it and if we actually go to our store page here and hit refresh you'll see that it renders our store page and it renders these different items exactly how we wanted it to and to make sure that is coming from our items JSON file here let's just change the price of album 1 to be for example 10 times more expensive and if we save that we refresh our store here you'll see that it's now one hundred and $29 instead of $12.99 as it was earlier we could also change the name here save it and refresh and you'll see that it changes the name up here and that's perfect our information for our music section is now being pulled from our item JSON all we need to do is go back into our file here and do the exact same thing that we're doing for music but do it for the merch section as well so let's just copy what we have here we also need to make sure we put this divs back here excellent deleted the div associated with this Shop items class too so make sure I put that back in place copy this section and then we can do the same thing here we can remove all the shop items that already exist inside of this section just like that and now paste in the loop but instead of looping over all of the music we want to actually loop over the match and now if I just fix formatting here I Rigo save that now all of the merch and all the music should be coming from our items array and if we refresh it here go into our items JSON go down to the merge section let's change t-shirt to the t-shirt test and if I scroll down refresh you should see it says t-shirt test which means now our merge section is also being pulled from our items JSON and now we can add remove or edit all of our JSON items inside of this file here without actually having to modify our server or a front-end side code in that ejs file which is perfect let's change this back so just t-shirt refresh page make sure it actually works and there we go our store is exactly the same as it was before you see if we hit added to cart everything works as it did before so nothing has actually changed functionality wise but we are now rendering our items from the server side which means our server has total control over what items our front-end uses and it also has total control when we send back the different items the person purchases in order to determine the total price that we actually charge the users credit card so they can't actually fake it by telling us it's a zero dollar charge because the server will know that these items don't add up to zero dollars now that we finally have our server set up and our front-end code set up and working together we can get working on integrating stripe into our application in order to do that let's go over to our story Jas page and we need to import some new script tags into this page in order to get the stripe API into our page so let me just copy over here real quick the stripe script which you can find on stripes website and it's just checkout stripe comm slash check out Jas and we want to defer this script since we need this script to be loaded before the rest of our scripts because our storage is script is going to depend on that so we must also change that to defer since we need the checkout script to load first then we want to create another script tag here and instead of actually loading in an external script we're just going to use some inline JavaScript in order to set the stripe publishable key that we created earlier so we'll just create a variable we'll call it a stripe public key and we're going to set it equal we're going to use that ejs syntax that we talked about with the less-than and the parentheses an equal to actually output this content and we want to set it to the stripe public key which we need to send from our server so we'll just say a stripe public key and there we go now that variable will be set but we actually need to send it from our server first so in our server dodgiest we're sending items so let's also send a variable called stripe public key and there we go now we save that we're actually sending the Striped public key from our server down to our store das and we're sending it as a JavaScript variable here so that we can access it inside of our client-side JavaScript which is where we are going to start working on next so instead of our storage AS page we need to find the section for where we are adding items here we go we got purchased click and we need to change all of this functionality so that when we click on the purchase button it's going to call stripe and the stripe is going to call us back and say ok that's valid and then we can call our server and our server is going to do all the check out information that we need to do in order to get that set up we need to just create a variable anywhere we'll just call it stripe Handler and this is going to be a variable that will handle our stripe interactions so we're going to use a object called stripe checkout which is coming from that library we imported earlier from stripe and then we want to configure this so that we can send it the actual information that we need the first thing we need to send it is our key which we also set as a JavaScript variable we called it stripe public key so this is going to be the key the publishable key from our stripe profile that we sent from our server to our front and view page and now we can access it in our front in JavaScript we then want to tell it what locale to use which is essentially what language to use and we're just going to set this to auto so it will automatically set the stripe pop-up box language based on where the current user is or what their locale is set to then we're going to have a function here which is going to have attribute token and this function takes a single parameter called token and inside of this function is where we need to put all the information for how we want to respond when stripe sends us back information so this token function is going to be called after the person clicks the purchase button fills out all of the check out information like credit card number and clicks purchase it'll get sent to stripe and then one stripe verifies everything they will send it back and call this method for us so for now we're just going to leave this method completely blank and work on doing other things that we need to do inside of our price purchase click button here so let's just configure this so that everything looks right there we go so now we just have this empty function and instead of purchase clicked we actually want to call this stripe Handler so let's just comment everything out that's in here currently for now and we can say stripe Handler dot open and this is going to open that pop-up box that I talked about and all we need to do is set the amount that we want to have so we're going to create some price variable which we're going to set to the amount inside of the stripe handler in order to create this price variable what we want to do is we want to get the price from our actual HTML that we are calculating already in our shopping cart so in order to do it we'll just create a variable called price element we're gonna set this to the document got get elements by class name and the class name of this is cart total price and do we just want get the first element and this is where our total amount is saved but it has a dollar sign in the name so we want to remove that dollar sign so we'll just set the price is going to be equal to parse flow since parsing float is going to convert that number into a floating-point number so it's going to take our string and convert it to a floating-point number so we can do it with a take on it and we want to use the price element we want to get the text inside of that price element we want to replace all the dollar signs inside of that text to just be an empty string so that will even remove the dollar signs from the text before we actually parse it into a float and then this is in a decimal format so $12.99 would be twelve point nine nine but stripe expects it to be in Scent format so 12.9 9 1970 to have so now let's restart our server real quick so we get all of our server changes if we refresh our page here scroll down and we click this purchase button you'll see that we actually get a striped pop-up here where we can enter our email card number month year all the information that you need for a credit card and then we can click pay and if we actually fill out this information it'll send this to stripe send it back to us and it will call that token function with the token related to all the credit card and email information for that user in order to test that we can just put any email that we want in here so we just put some fake email to use a test credit card number we just want four to repeating which is the test credit card number for stripe and you can give it any date and month that is in the future as well as any verification number here that you want and if we click pay it is sent off to the stripe server and it will send back and call this token function so in order to test that let's just put a log in here and we'll just log this token variable inside this token function or refresh our page go back to the purchase process again put that card number of four two over and over again time that's in the future we click pay there we go and if we just want to check the console so if we inspect here go to the console tab you'll see that we got this object printed out which is of a token object resume item so you guys can see it you'll see it's got card information it's got IP information email information ID everything that you need but the really the only thing we're concerned with is the ID because that's what we need in order to charge the user tied with our secret key so if we send our secret key and the ID we can actually charge the user whatever amount that we want so let's work on actually making this token function call our server with this token ID so we can actually charge the user for the items that they purchased so we can get rid of this console dot log here and the first thing we want to do is we want to get all the items that the user purchased so when they click Add to Cart we have you know the coffee cup item here for example we have price we have quantity and we want to get the IDS of all these different items so what we need to do is we actually need to add the ID down here in this item section when we click that Add to Cart button so we just need to find the section where we're adding items to the cart let's make this full screen and you see we got Add to Cart clicked and we want to pass the ID to this add item to cart function as well so we're just going to also pass the ID and the ID is going to come from the shop item we created that data attribute called item ID so we can just say data set which accesses all of the properties on HTML that are prefixed with data - so they start like that data - and we created one called item ID but since JavaScript uses camel casing this will be written as item ID and this data set item ID will access the properties right here of data item ID on our HTML attribute so we now have the ID of the item that we sent in our HTML earlier now we can go to our add item to cart put that ID property in there and then inside of our cart we just want to put that ID as a property so cart row you know your data set again and we're going to set the item ID equal to the ID that we pass in and now the ID of our item is going to be saved in the cart so that when we access all of our rows they will all have IDs links to them so we go back up to where we are creating our token function we can work on starting to get all the different items for our shopping cart that are currently added there as well as the quantities because we need to send both of those items to the server so it can calculate the price so let's create a variable we'll just call items and it is going to be an empty array to start out with and then we want to get the section that contains all of our items so the item is Container carte items container this is going to be equal to the document dot get elements by class name and we just have a section called cart items so inside of this cart items is going to be all of our different car items and we want to get the rows inside of those card items so we can just cut another variable call the cart rows we can set that to the cart items container die get elements by class name and inside of here we want to get all the different elements that have the row or the class cart row now we can just loop through all these so we can just say for everything from I equals 0 I is less than cart rows dot length I plus plus so we're just looping through all of our different cart rows here could another variable instead of here for an individual cart row and we'll just set it took cart rows over the I tellement which is perfect so now we have our actual cart row inside of this loop and we can work on abstracting the quantity as well as the ID for each item and add that into our items array that we just created that's empty right now so the first thing we want to do is get the quantity element we're just going to set that equal to cart row die get elements by classman and this class is called cart quantity input and this is the input element on our page which actually contains the information for the number of cart items that they added and since we just want to get the first one we're just going to use the first element in that array and now we want to actually change that or get the value from that element so we can say quantity is equal to quantity element value and this gives the value of our input which is whatever they put in side of the quantity selector right here so in this case would be 1 2 3 etc so now we can work on getting the actual item ID as well and we just set that item ID on the cart row so we can say the ID is equal to cart row data set dot item ID which we just created and now we have the ID of the item as well as how many of that item they want to add purchased so we can just add this to our items alright so we can say items dot push which adds an element to the array which want to add an object with the ID set to the ID and the quantity set to the quantity and there we go we now have at the end of this for loop an array of items with all the different items in our shopping cart with the ID for them and the quantity for them which we can now send to our server along with the ID from this token element here so in order to send information to our server one of the easiest ways is to use something called fetch which allows us to either send requests out to servers and get back information asynchronously so we don't actually have to refresh the page and the user can stay on the same page and it will send the information and then as soon as the information gets back to us it'll do something with it whether it's an error or not so we just want to fetch a certain URL and to do then we type in the fetch command and we first pass it the URL that we want to send to and in our case we want to send to purchase URL which is just going to be a route on our server that we're going to create later for handling purchases and then after that we need to set all the different properties for this purchase fetch so we want to do a post request because in HTML and HTTP a post request is what you do when you want to send information to the server and have the server do certain calculations on it and a get request is when we send information to a server and we want to get back information so we're just going to set the method here to post which is going to be in all capitals and then since we're sending JSON information to the server we need to tell the server that we're sending it JSON information so inside of the headers here we want to set the content type and this is very similar to how you would have to set up a basic node.js server to tell it you're sending JSON so we'll say that we want to send JSON which is using application slash JSON as the type and we also are going to receive JSON from the server so we must also make sure we put accept and that we put application slash Jason so now this tells the server we're going to be sending it JSON and that we're going to receive so Jason from the server and then lastly body is going to be all the information that we send to the server and we can actually access this information inside the server so what we want to do is we need to call the JSON dot stringify method in order to make this JSON object into a string so that we can send it to the server and then inside the JSON object right here we're just going to put all the different information we want to send to our server so we first want to send that token ID we'll call it stripe token ID and that is just the token ID and this is how we're going to charge this person's credit card and then we want to send the items that they want to purchase we'll just send that as items so now we're actually fetching to the server and right now we're not handling what happens when we get the fetch back but that's okay what's going to our server adagios file and create that new route so we're going to do something very similar to how we have this get request setup solutionist copy this paste it down here and we're going to just remove everything the else statement here because we are going to need to get information from the item JSON array that we created in our JSON object so that we can determine which items the user is actually purchasing but for now let's just log something out so that we know that we're actually getting a request coming here so we'll just say console dot log purchase and then we want to change this to be post instead of gift since we're sending a post request and this is going to be purchase since that's a URL we're actually sending to restart our server here and if go over and refresh our page add something to our cart say we want three of them and we click purchase fill out all this information again make sure you use that test credit card number and a date that's in the future and if we click pay it'll send it to the server and it actually did not send it to the server so in order to debug this we're just going to inspect here and go over to our console and you see that cart Rose is not find so let's go over to our storage is open this up bigger and instead of here looks like I misspelled cart row here as well as a misspelled car row here so now if I say that corrected all my spellings whoops got one more spell in here cart throws so now all of my stuff is both correctly go over refresh this page add something to the cart increase the quantity fill all this information again very tedious click pay now we should see that we're actually getting a message logged perfect says purchase inside of our server here which means that our code called this fetch request here sent it all of our information to our server and now we log to this console dialogue purchase here which means we're inside of this else statement here which is perfect that's exactly what we want to be and inside of here we can actually charge this stripe user using that token as well as the items that we sent up to the server in order to do that we need to take the items JSON data and convert that into an actual JSON object we can use so we can just create a variable here we're just kind of call it comments the items JSON equals JSON dot parse data so now we have all the data from our items at JSON in this variable and since we have two properties of merge and music and we just want to search both of those we're just going to create a single array called items array we're going to set it to items JSON music which is all the music items and we're going to concatenate that array so combine that array with items json dot merch so now all of our merch and music items are in this single items are right here which we can use for finding all of the different items by ID next we want to create a total variable and we're just going to default this total variable to zero because at the beginning we have 0 and we're going to look through all the items that this server sent up and actually parse them so we're going to do that by accessing the body but in order to access JSON from the body we need to first tell Express that we're using JSON so up here in our app section we just want to add an apt I'd use and we're gonna say Express dot JSON and this essentially just tells our app that we can parse the body own as JSON and access the different properties on our body as if it was just a JSON object so now if we go back down here into a purchase section we can just create request dot body tight amande by using that expressed a JSON of above we're able to just access the items property from the body and this items property is exactly what we sent up here instead of this body so we can just say items can loop through all the items so we can say for each and this is just going to take the property so for each item in that items array we want to do is we want to find the item object so we'll just set a variable here we're gonna call it item JSON I'm just going to equal the items array which we have all of our items from our JSON file inside of we're going to do a fine so we're going to try to find the item inside at array which we call I and we're going to return ID ID equals item the ID so whenever this returns true it will return whichever item it is on inside loop so one the ID of the item in this array equals the ID of the item in the request body that we sent up it's going to output the JSON for that item so we're going to be able to access the price of that item and then all we want to do is we want to increment the total so we're going to take the total we're going to increment it by item JSON price times item quantity this should be times there we go and this quantity we also sent up instead of our thing here as you can see we added the quantity property to each of our items so this will take the quantity of items that they purchased multiply it by the price which is on our server so they can't fake this price and it will add it to our current total variable so then after the end of this loop our total variable will contain the toe press that we want to charge to the users credit card now we need to create a stripe variable that is going to be for accessing the stripe API so if we go up here we can just say cost stripe we're going to require that stripe library that we created earlier and this is just another function that we need to pass our secret key to in order to actually activate the API so this stripe variable is now going to be usable for actually charging the users credit card so if we go down here we can just say stripe which is that variable we just created dot charges dot create and this is so that we can create a charge we need to give it the amount which we know is our total variable right here and this amount is going to be in pennies because that's what we put it instead of our item JSON here which is exactly what stripe is expecting it wants pennies instead of dollar formatted for its amount so that's perfect if we have our amount we need to give it a source and this source is just the token ID that we sent up so we can say request request body dot stripe token ID and this is the ID that we're going to be charging and then we just want to tell it what currency we're charging in in our case we're just charging in u.s. dollars so we'll say USD and now we're actually creating a charge but we want to handle what do we do when that charge comes back successfully and what happens when that charge comes back as a failure so in order to do that this create is returning what's called a promise and a promise allows you to do something after the promise is complete or to catch any errors that happen so the first case that we want to handle is if it successfully occurred so if create successfully occurred and after it calls the stripe API and sends it back at the response it's going to call whatever this then function has inside of it so we're going to create a function here instead of then and this will be called if our create was successful so we're just going to log out here so we can see this inner server bring us a charge successful and then we also want to respond some JSON back to our server so we'll say res JSON this laaser to send JSON to the server or to the front end I just want to send a message back that says successfully purchased items and this isn't just a message that we can show to the user to show them that we successfully were able to make a charge on their credit card but if there's an error we want to catch that error using the catch function so again we're just going to pass it a function and we want to again log out that there is a problem so we'll just say charge fail here instead of success and then we want to send an error codes will say status of 500 which means that there's an error on the server and and that responds and that's everything we need to do on the server in order to actually charge the stripe API and get back the different items that we purchased to the user so let's end our server down here restart it and go back to our store j/s because now we want to handle the response from this fetch request which again this is using a promise so we can use the same then and catch format that we talked about earlier so if it was successful we'll say then and again we have a function and inside this function we have the response from the server which is JSON so we need to convert this to JSON so we'll say we want to return res dot JSON and this is just telling the then function that we have a bunch of information being returned from the server but I just want the JSON of it and I want you to return that JSON and we need to use another then because this works just like I promised again and instead of here this is going to be the actual data that is being responded from our server so here we can use that alert message that we had in our purchase click down here we alerted just a blank message we can alert data message which is the message the server is sending us and then we can do all the cleanup here to actually delete the items from the cart which is what this code is doing so let's just paste that in there so if is successful it'll alert a message to the user and remove all the items from their cart just perfect but if it was unsuccessful that's where we're going to do our catch which comes back with an error object we're just going to log that error because and we'll actually do counselled by error which will log it in red text instead of normal black text because we don't really have any way that we want to handle this error and it's not really part of this tutorial so we're just logging it out so that we can see this pattern so now we go here refresh our page let's say we want to buy a t-shirt and this album right here and we want to of the t-shirt so we should get $59 90 s 90 97 cents charge click on purchase fill out all the information here one last time hopefully there we go and if we click ok we should see that it says purchase successful over here on the Left charge successful perfect it says successfully purchased items inside of our actual client which means that we called in here we called our server Diaz went through all of this code it was successful so it logged charge successful sent this message back down into our client we converted it to JSON alerted it to the user and as soon as we click OK on that alert it's going to clear out our cart so always click OK and as you can see our cart completely emptied itself and we actually created a charge in stripe and we can even see that if we go to our stripe dashboard here we go to payments you can see that we have this $59 and 97 sent payment in our dashboard you can ignore this old payment here this was just when I was running to the tutorial creating it I created this payment but this $59 97 cent payment with that email address that we typed in this is the exact payment that we created in our page here and we could do it again let's do a $6.99 payment put in an email we're just gonna say test at gmail.com so we know that it's that email don't want to verify anything fill out all this information one last time click pay we should get that alert again telling us was successful we could go to our dashboard here and we should have a $6.99 payment showing up and there we go we have our six times nine payments showing up in our dashboard all we need to do to set up stripe to charge people's credit cards if you're confused about any of the code make sure to ask me down in the comments below or view my github repository with all the code from this tutorial also make sure to check out my video of where I created the front end of this javascript shopping cart which is going to be linked over here thank you guys very much for watching and have a good day
Info
Channel: Web Dev Simplified
Views: 179,226
Rating: undefined out of 5
Keywords: WebDevSimplfied, stripe tutorial, stripe checkout tutorial, stripe nodejs tutorial, nodejs shopping cart, nodejs shopping cart tutorial, nodejs stripe, node js payment system, node js tutorial, node js tutorials, node js beginner tutorial, node js shopping cart tutorial, node js express, node js express shopping cart, node js express shopping cart tutorial, node js express tutorial, node js express tutorial for beginners, shopping cart tutorial, js tutorial
Id: mI_-1tbIXQI
Channel Id: undefined
Length: 55min 33sec (3333 seconds)
Published: Thu Dec 13 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.