Learn how to collect payments from an API or SaaS product. In this tutorial, we build an Express.js API from scratch, then make money by integrating Stripe Metered Billing. https://fireship.io/lessons/api-monetization-stripe/

#js #makemoney #code

🔗 Resources

Full Stripe JavaScript Course https://fireship.io/courses/stripe-js/
Stripe Billing https://stripe.com/docs/billing/subscriptions/metered-billing
Source Code https://github.com/fireship-io/api-monetization-demo

RapidAPI approach:  @AniaKubow  https://youtu.be/GK4Pl-GmPHk

📚 Chapters

00:00 Intro
00:37 How API Monetization Works
01:59 Build an API with Express
04:17 Metered Billing Products
05:17 Stripe Checkout 
06:41 Listen to Webhooks
08:33 Generate API Keys
11:05 Record Usage

🔥 Get More Content - Upgrade to PRO

Upgrade to Fireship PRO at https://fireship.io/pro
Use code lORhwXd2 for 25% off your first payment. 

🎨 My Editor Settings

- Atom One Dark 
- vscode-icons
- Fira Code Font

🔖 Topics Covered

- Create custom API keys in node
- Node hashing crypto
- Stripe webhooks
- Metered billing for API
2024-02-04T05:41:36.562Z
nova-2
2-general-nova
2024-01-09.29447
30089e05-99d1-4376-b32e-c263170674af
b246256b-bc6f-41d2-993b-9068926ee1cc
602e508329d5a647d6012d0a897fc49cf3a4c8dc301840b77e9c615166c5cefb
67875a7f-c9c4-48a0-aa55-5bdb8a91c34a
deprecated
APIs are big business.
If you build one that developers love, you've got a $1,000,000,000 startup on your hands.
And thanks to modern cloud technology, you can throw a monetized API together in your mom's basement in just a few minutes.
In today's video, you'll learn how to, 1, build an API with Node.
Js and Express, 2, handle authentication and generate API keys for your users, and 3, monetize it with metered billing subscriptions using Stripe, where the customer is billed for each API request.
By the end of the video, you'll stand the steps required to make money from your side hustle API.
If you're new here, like and subscribe.
And if you wanna learn more about payments, check out my full Stripe course on Fireship IO.
Let's start by taking a look at how APIs work from a high level.
The owner of the API deploys some code to server.
That server might have a bunch of HTTP endpoints that do something useful, like maybe retrieve the current weather from a set of GPS coordinates.
At it.
Other developers out there want to use this data, but they don't want to have to implement a solution on their own.
So they reach out to you for permission to make requests to your server.
You say, sure.
No problem.
Just create an account and put a credit card on file and I will give you an API key.
Sounds good.
How will this work?
Whenever you make a request to my server, just attach this API key and I'll keep track of the number of requests you make each month.
How much does one API request cost?
It'll cost $1 per request and I'll charge your credit card for the volume of usage at the end of the month.
You got yourself a deal.
Take my money.
To build something like this, we'll need both front end and back end code.
On the front And, we'll need a place for a user to add a credit card and manage their subscription details.
Luckily, Stripe will host and manage all the front end code for us, which is made possible with a product known as Stripe Checkout that allows us to focus on the back end.
Now, even though Stripe makes our lives much easier, there are even more simplified solutions out there like rapid API.
If you wanna learn more about it, Anya Kubo has an excellent video about it.
It's basically API monetization as a service, but the main drawback is they take a much larger cut of your revenue.
What we're doing in this video is more low level, but allows us to keep all of our money minus the Stripe fees.
To get started, open up your editor to an empty directory and pull up the terminal.
Run npm init y to add node package manager to this folder.
The project has only 2 dependencies, expressjs as our web application framework and Stripe to interact with the Stripe API in Node.
Js.
From there, we'll define our server side code in the index dotjs file.
Inside that file, we will import Express, then call it as a function to create a new Express app.
The Express app allows you to define multiple HTTP endpoints that can access on the Internet.
In a REST API, every endpoint starts with a verb like get, post, put, or delete.
As a developer, this allows you to organize your API endpoints based on the actual operation that's taking place there.
For example, you would use get if you're just retrieving data, post if you're creating something new and delete if you're removing data.
In Express, we can define an API endpoint starting with the verb as a function.
In this case, we'll use get and then pass it a URL route where it can be accessed.
This will give us a route on HTTP local host 8080/API.
The second argument is a callback function that It will be executed anytime somebody tries to access this endpoint on our server.
Express will provide us with 2 objects, the request, which contains all the incoming data, and response, which provides a way for us to send data back to the user.
On the request, we're going to be looking for an API key that's provided by the end user.
And we can find that with the URL's query parameters, which are just variables encoded in the URL that are preceded by a question mark.
One side note I wanna make here though is that storing the API key in the URL is not necessarily the best choice.
You can also store it in a header, which tends to be a little more secure.
But for simplicity's sake, we're just going to store it in the URL.
Later in the video, we'll learn how to create and validate custom API keys.
But for right now, we'll just go ahead and send a response back to the user that is a string of emojis.
That's it.
That's all the API does, and we're going to charge people $1 per request to use it.
Now to run the express app in node, we'll call app dot listen with a port of 8080.
To run this code, pull up the terminal and enter node dot period and you should be able to go to localhost 8080/API in the browser and get a response.
Now, when working on code like this, I would highly recommend using an HTTP client like Insomnia.
It's a more developer friendly way to manage and test your endpoints.
As you can see here, I have a git request going to local host 8080/API and I can easily format my query parameters here as well.
Now that we have this awesome API, we need to go out and convince people to pay for it.
Always be closing.
Always be closing.
To handle that, you'll need a Stripe account, then go to the dashboard and make sure that you're in test mode.
Find the product screen and create a new product.
You can customize the settings however you want.
The important thing is that it's a recurring product and that the metered box is checked.
You can customize the billing behavior in pretty much any way imaginable, but we're just going to sum up the total amount of usage for each period.
When that's done, it It will create a product with a unique product ID and more importantly, a price ID.
A product can have multiple prices if you have different billing plans for this particular product.
Go ahead and make a note of that price ID, then go to the developers tab and click the button for API keys.
In order to interact with Stripe from our Node.
Js application, we're going to need our Stripe secret key.
We're in test mode, but you still don't want to expose this key publicly, so make sure to keep it safe.
Back in the JavaScript, we'll use that key to initialize the Stripe SDK.
And now we're ready to move on to phase 2, collect payment information from the user, and subscribe them to a plan.
Stripe checkout makes this part incredibly easy.
In our API, let's go ahead and create another endpoint called checkout, this time using post, and point it to the checkout route.
Make the callback an async function because the Stripe SDK is promise based.
When this URL is triggered, it's going to make a request to Stripe to start a new checkout session, and then it will send the details of that session back down to the client.
The important part here are the parameters that you pass when creating the session.
That will tell Stripe what the user is paying for.
In this case, the mode will be subscription And then, we'll put the price ID in the line items array.
And lastly, when the checkout session is done, Stripe will redirect back to your website and you can provide 2 different URLs, one for success and one for cancel.
Now, let's go ahead and restart the node server, then go to the HTTP client to make a request to the endpoint.
Make a post request to checkout And you'll notice we get back a big object here, but the only important thing we need out of it is the URL.
This is the URL that we want to direct our end user to.
That user will be greeted with a credit card form so they can pay for our API.
To test it out locally, Stripe provides a bunch of different testing card numbers.
When the form is submitted, Stripe will officially subscribe the user to the plan and charge their credit card on a recurring basis as they use the API.
Congratulations.
You have your 1st paying customer, but now what?
Now that the user is paid, we'll need to generate a custom API key for this user and keep track of their data on our servers.
There's a few different parts to this process, but the first thing I wanna focus on is webhooks.
A webhook is just an API endpoint on our server that can receive data from Stripe when an important event occurs.
At the very least, we'll want to listen to events like when the checkout session has as completed, so we know when the user has paid for the product and also invoice paid and invoice payment failed, so we can keep track of their account status when Stripe charges their actual credit card.
Stripe has some boilerplate code to handle webhook securely.
Every account has a webhook secret that you'll want to verify to make sure that a webhook was actually sent by Stripe and not being spoofed by a hacker.
You can copy and paste this code from the full article on Fireship IO.
The The important thing I want to point out is that there's a switch statement down here that listens to different events, so you can implement your own code when that event happens.
Now, here's the tricky thing.
How do we actually test a webhook locally?
Because Stripe has no way to send a webhook to our local host URL.
Luckily, Stripe has built a CLI tool that allows you to test webhooks locally.
Go ahead and download it onto your system, then run Stripe login to authenticate into it.
Once that's done, you can call Stripe listen and forward the events to your local host URL.
After it spins up, you'll notice that it prints out a webhook signing secret.
Go ahead and copy that value and add it as the signing secret in your webhook code.
The event that we want to listen to right now is checkout session completed.
Let's go ahead and console log and then fill out that checkout session credit card form.
When Stripe handles it, it will trigger a bunch of different webhooks that you can listen to and you'll see those printed out in the terminal.
If we go to the terminal for the node server, It should log out the data available in that event.
The important things here are the customer ID and subscription ID.
Now that we have a subscribed customer, we can move on to phase 3, The creation of a custom API key.
You'll need some way to store data about the user and their API key on your servers.
You should use your favorite production database for that.
But to keep things simple on this demo, I'm just going to store that information in memory.
You'll wanna have at least 2 different tables or collections to handle this data.
The first one is customers, which contains information about the customer like their Stripe customer ID and the plan that they're subscribed to.
The second collection you'll need is a reverse mapping that points an API key to the customer account.
You'll want a way to quickly look up a customer based on the API key that they pass in with a request.
Now, an important thing to point out here is that an API key is like a password, so you should never store the raw value in your database Because if somebody gets a hold of your database, then they have all your customer API keys and can immediately start exploiting them.
To overcome this vulnerability, we need to hash the API key before saving it to the database.
A hashing function can take the original API key or password and convert it to a new set of characters that would be useless to a hacker, but at the same time is very easy to compute when you know the real value.
It might be overkill for this little demo, But it's a really important concept to understand if you are storing API keys in your own database.
Let's take a look at how we can generate an API key with Node.
I'm creating a custom function here That's importing the random bytes function from the built in node crypto module.
Then I'm using it to generate a random string of characters, which is the value that we'll give to the consumer of the API.
Now like I said before, we need to store this value, but we can't store it directly in our database.
I'm creating a second function to hash it, which uses that createhash function from nodecrypto.
With this function, you first specify an algorithm like md5, then provide it with the value you want to hash, and we'll tell it to return a string using digesthex.
The hashed API key is now safe to store in the database.
And as one final touch, we'll make this a recursive function to verify that there aren't any duplicate API keys already stored in database.
Now that we can generate an API key, we can go back into our webhook handler and implement the code for checkout session completed.
The code here will be very application specific, but the gist of it is that we'll generate an API key and provide the unhashed version to the user while storing the hashed version in our database.
To To simulate that process, I'm just going to console log the values for now.
Another thing I'm doing in this code is grabbing the subscription items using the Stripe SDK from the customer's account.
Having this value stored on the server will make it easier and faster to report usage to Stripe in the next step.
And now, we're ready to move on to the final phase, allowing the user to make requests to the API.
Let's go back to our original API endpoint.
The first thing we'll do inside of it is check to make sure that an API key is present on the request query and if not, then we'll send a 400 response back.
Now, if we do have an API key, we'll go ahead and hash it so we can find the matching value in our database.
We can figure out which customer is associated with that API key because we have a collection with that reverse mapping, and then we can grab the customer details which would contain things like the user's account status.
In a real API, you'd likely want to cache this data to make your response times as quick as possible.
From there, If that customer's account is not active, then we'll send a not authorized response.
Otherwise, we're good to go.
When the request is made, we'll also want to report this usage to Stripe, which we can do by calling subscription items, create usage record, pass in the subscription item ID along with a quantity, timestamp, and action.
In.
The increment value will tell Stripe to increase the billing by 1 from whatever it previously was.
Reporting usage like this is not very efficient, So you'd likely want to optimize it by making this a background job.
Now at this point, we can make a request to the API by copying the user's API key, which Should be printed in the console when they finish their payment with Stripe checkout.
Go ahead and take that value and use it as a query parameter in the URL when sending a request with your HTTP client.
Without an API key, you should get an error response.
Otherwise, you'll get the usage report back from Stripe.
As a final touch to prove to you that everything Working as intended, I created another endpoint to get the current usage for a customer.
If we go ahead and send 10 requests with the same API key and then request a usage report.
You can see that the current bill is currently 1,000¢ or $10.
Congratulations.
You just built a $1,000,000,000 API from your mom's basement.
Make sure to check out my full Stripe course if you're serious about building a payment solution.
Thanks for watching, and I will see you in the next one.

Speaker 0: APIs are big business. If you build one that developers love, you've got a $1,000,000,000 startup on your hands. And thanks to modern cloud technology, you can throw a monetized API together in your mom's basement in just a few minutes. In today's video, you'll learn how to, 1, build an API with Node. Js and Express, 2, handle authentication and generate API keys for your users, and 3, monetize it with metered billing subscriptions using Stripe, where the customer is billed for each API request.

By the end of the video, you'll stand the steps required to make money from your side hustle API. If you're new here, like and subscribe. And if you wanna learn more about payments, check out my full Stripe course on Fireship IO. Let's start by taking a look at how APIs work from a high level. The owner of the API deploys some code to server.

That server might have a bunch of HTTP endpoints that do something useful, like maybe retrieve the current weather from a set of GPS coordinates. At it. Other developers out there want to use this data, but they don't want to have to implement a solution on their own. So they reach out to you for permission to make requests to your server. You say, sure.

No problem. Just create an account and put a credit card on file and I will give you an API key.

Speaker 1: Sounds good. How will this work?

Speaker 0: Whenever you make a request to my server, just attach this API key and I'll keep track of the number of requests you make each month.

Speaker 1: How much does one API request cost?

Speaker 0: It'll cost $1 per request and I'll charge your credit card for the volume of usage at the end of the month.

Speaker 1: You got yourself a deal. Take my money.

Speaker 0: To build something like this, we'll need both front end and back end code. On the front And, we'll need a place for a user to add a credit card and manage their subscription details. Luckily, Stripe will host and manage all the front end code for us, which is made possible with a product known as Stripe Checkout that allows us to focus on the back end. Now, even though Stripe makes our lives much easier, there are even more simplified solutions out there like rapid API. If you wanna learn more about it, Anya Kubo has an excellent video about it.

It's basically API monetization as a service, but the main drawback is they take a much larger cut of your revenue. What we're doing in this video is more low level, but allows us to keep all of our money minus the Stripe fees. To get started, open up your editor to an empty directory and pull up the terminal. Run npm init y to add node package manager to this folder. The project has only 2 dependencies, expressjs as our web application framework and Stripe to interact with the Stripe API in Node.

Js. From there, we'll define our server side code in the index dotjs file. Inside that file, we will import Express, then call it as a function to create a new Express app. The Express app allows you to define multiple HTTP endpoints that can access on the Internet. In a REST API, every endpoint starts with a verb like get, post, put, or delete.

As a developer, this allows you to organize your API endpoints based on the actual operation that's taking place there. For example, you would use get if you're just retrieving data, post if you're creating something new and delete if you're removing data. In Express, we can define an API endpoint starting with the verb as a function. In this case, we'll use get and then pass it a URL route where it can be accessed. This will give us a route on HTTP local host 8080/API.

The second argument is a callback function that It will be executed anytime somebody tries to access this endpoint on our server. Express will provide us with 2 objects, the request, which contains all the incoming data, and response, which provides a way for us to send data back to the user. On the request, we're going to be looking for an API key that's provided by the end user. And we can find that with the URL's query parameters, which are just variables encoded in the URL that are preceded by a question mark. One side note I wanna make here though is that storing the API key in the URL is not necessarily the best choice.

You can also store it in a header, which tends to be a little more secure. But for simplicity's sake, we're just going to store it in the URL. Later in the video, we'll learn how to create and validate custom API keys. But for right now, we'll just go ahead and send a response back to the user that is a string of emojis. That's it.

That's all the API does, and we're going to charge people $1 per request to use it. Now to run the express app in node, we'll call app dot listen with a port of 8080. To run this code, pull up the terminal and enter node dot period and you should be able to go to localhost 8080/API in the browser and get a response. Now, when working on code like this, I would highly recommend using an HTTP client like Insomnia. It's a more developer friendly way to manage and test your endpoints.

As you can see here, I have a git request going to local host 8080/API and I can easily format my query parameters here as well. Now that we have this awesome API, we need to go out and convince people to pay for it. Always be closing. Always be closing. To handle that, you'll need a Stripe account, then go to the dashboard and make sure that you're in test mode.

Find the product screen and create a new product. You can customize the settings however you want. The important thing is that it's a recurring product and that the metered box is checked. You can customize the billing behavior in pretty much any way imaginable, but we're just going to sum up the total amount of usage for each period. When that's done, it It will create a product with a unique product ID and more importantly, a price ID.

A product can have multiple prices if you have different billing plans for this particular product. Go ahead and make a note of that price ID, then go to the developers tab and click the button for API keys. In order to interact with Stripe from our Node. Js application, we're going to need our Stripe secret key. We're in test mode, but you still don't want to expose this key publicly, so make sure to keep it safe.

Back in the JavaScript, we'll use that key to initialize the Stripe SDK. And now we're ready to move on to phase 2, collect payment information from the user, and subscribe them to a plan. Stripe checkout makes this part incredibly easy. In our API, let's go ahead and create another endpoint called checkout, this time using post, and point it to the checkout route. Make the callback an async function because the Stripe SDK is promise based.

When this URL is triggered, it's going to make a request to Stripe to start a new checkout session, and then it will send the details of that session back down to the client. The important part here are the parameters that you pass when creating the session. That will tell Stripe what the user is paying for. In this case, the mode will be subscription And then, we'll put the price ID in the line items array. And lastly, when the checkout session is done, Stripe will redirect back to your website and you can provide 2 different URLs, one for success and one for cancel.

Now, let's go ahead and restart the node server, then go to the HTTP client to make a request to the endpoint. Make a post request to checkout And you'll notice we get back a big object here, but the only important thing we need out of it is the URL. This is the URL that we want to direct our end user to. That user will be greeted with a credit card form so they can pay for our API. To test it out locally, Stripe provides a bunch of different testing card numbers.

When the form is submitted, Stripe will officially subscribe the user to the plan and charge their credit card on a recurring basis as they use the API. Congratulations. You have your 1st paying customer, but now what? Now that the user is paid, we'll need to generate a custom API key for this user and keep track of their data on our servers. There's a few different parts to this process, but the first thing I wanna focus on is webhooks.

A webhook is just an API endpoint on our server that can receive data from Stripe when an important event occurs. At the very least, we'll want to listen to events like when the checkout session has as completed, so we know when the user has paid for the product and also invoice paid and invoice payment failed, so we can keep track of their account status when Stripe charges their actual credit card. Stripe has some boilerplate code to handle webhook securely. Every account has a webhook secret that you'll want to verify to make sure that a webhook was actually sent by Stripe and not being spoofed by a hacker. You can copy and paste this code from the full article on Fireship IO.

The The important thing I want to point out is that there's a switch statement down here that listens to different events, so you can implement your own code when that event happens. Now, here's the tricky thing. How do we actually test a webhook locally? Because Stripe has no way to send a webhook to our local host URL. Luckily, Stripe has built a CLI tool that allows you to test webhooks locally.

Go ahead and download it onto your system, then run Stripe login to authenticate into it. Once that's done, you can call Stripe listen and forward the events to your local host URL. After it spins up, you'll notice that it prints out a webhook signing secret. Go ahead and copy that value and add it as the signing secret in your webhook code. The event that we want to listen to right now is checkout session completed.

Let's go ahead and console log and then fill out that checkout session credit card form. When Stripe handles it, it will trigger a bunch of different webhooks that you can listen to and you'll see those printed out in the terminal. If we go to the terminal for the node server, It should log out the data available in that event. The important things here are the customer ID and subscription ID. Now that we have a subscribed customer, we can move on to phase 3, The creation of a custom API key.

You'll need some way to store data about the user and their API key on your servers. You should use your favorite production database for that. But to keep things simple on this demo, I'm just going to store that information in memory. You'll wanna have at least 2 different tables or collections to handle this data. The first one is customers, which contains information about the customer like their Stripe customer ID and the plan that they're subscribed to.

The second collection you'll need is a reverse mapping that points an API key to the customer account. You'll want a way to quickly look up a customer based on the API key that they pass in with a request. Now, an important thing to point out here is that an API key is like a password, so you should never store the raw value in your database Because if somebody gets a hold of your database, then they have all your customer API keys and can immediately start exploiting them. To overcome this vulnerability, we need to hash the API key before saving it to the database. A hashing function can take the original API key or password and convert it to a new set of characters that would be useless to a hacker, but at the same time is very easy to compute when you know the real value.

It might be overkill for this little demo, But it's a really important concept to understand if you are storing API keys in your own database. Let's take a look at how we can generate an API key with Node. I'm creating a custom function here That's importing the random bytes function from the built in node crypto module. Then I'm using it to generate a random string of characters, which is the value that we'll give to the consumer of the API. Now like I said before, we need to store this value, but we can't store it directly in our database.

I'm creating a second function to hash it, which uses that createhash function from nodecrypto. With this function, you first specify an algorithm like md5, then provide it with the value you want to hash, and we'll tell it to return a string using digesthex. The hashed API key is now safe to store in the database. And as one final touch, we'll make this a recursive function to verify that there aren't any duplicate API keys already stored in database. Now that we can generate an API key, we can go back into our webhook handler and implement the code for checkout session completed.

The code here will be very application specific, but the gist of it is that we'll generate an API key and provide the unhashed version to the user while storing the hashed version in our database. To To simulate that process, I'm just going to console log the values for now. Another thing I'm doing in this code is grabbing the subscription items using the Stripe SDK from the customer's account. Having this value stored on the server will make it easier and faster to report usage to Stripe in the next step. And now, we're ready to move on to the final phase, allowing the user to make requests to the API.

Let's go back to our original API endpoint. The first thing we'll do inside of it is check to make sure that an API key is present on the request query and if not, then we'll send a 400 response back. Now, if we do have an API key, we'll go ahead and hash it so we can find the matching value in our database. We can figure out which customer is associated with that API key because we have a collection with that reverse mapping, and then we can grab the customer details which would contain things like the user's account status. In a real API, you'd likely want to cache this data to make your response times as quick as possible.

From there, If that customer's account is not active, then we'll send a not authorized response. Otherwise, we're good to go. When the request is made, we'll also want to report this usage to Stripe, which we can do by calling subscription items, create usage record, pass in the subscription item ID along with a quantity, timestamp, and action. In. The increment value will tell Stripe to increase the billing by 1 from whatever it previously was.

Reporting usage like this is not very efficient, So you'd likely want to optimize it by making this a background job. Now at this point, we can make a request to the API by copying the user's API key, which Should be printed in the console when they finish their payment with Stripe checkout. Go ahead and take that value and use it as a query parameter in the URL when sending a request with your HTTP client. Without an API key, you should get an error response. Otherwise, you'll get the usage report back from Stripe.

As a final touch to prove to you that everything Working as intended, I created another endpoint to get the current usage for a customer. If we go ahead and send 10 requests with the same API key and then request a usage report. You can see that the current bill is currently 1,000¢ or $10. Congratulations. You just built a $1,000,000,000 API from your mom's basement.

Make sure to check out my full Stripe course if you're serious about building a payment solution. Thanks for watching, and I will see you in the next one.
APIs are big business. If you build one that developers love, you've got a $1,000,000,000 startup on your hands. And thanks to modern cloud technology, you can throw a monetized API together in your mom's basement in just a few minutes.
In today's video, you'll learn how to, 1, build an API with Node. Js and Express, 2, handle authentication and generate API keys for your users, and 3, monetize it with metered billing subscriptions using Stripe, where the customer is billed for each API request. By the end of the video, you'll stand the steps required to make money from your side hustle API.
programming
If you're new here, like and subscribe. And if you wanna learn more about payments, check out my full Stripe course on Fireship IO. Let's start by taking a look at how APIs work from a high level. The owner of the API deploys some code to server. That server might have a bunch of HTTP endpoints that do something useful, like maybe retrieve the current weather from a set of GPS coordinates.
At it. Other developers out there want to use this data, but they don't want to have to implement a solution on their own. So they reach out to you for permission to make requests to your server. You say, sure. No problem. Just create an account and put a credit card on file and I will give you an API key.
software development
Sounds good. How will this work? Whenever you make a request to my server, just attach this API key and I'll keep track of the number of requests you make each month. How much does one API request cost? It'll cost $1 per request and I'll charge your credit card for the volume of usage at the end of the month.
You got yourself a deal. Take my money. To build something like this, we'll need both front end and back end code. On the front And, we'll need a place for a user to add a credit card and manage their subscription details. Luckily, Stripe will host and manage all the front end code for us, which is made possible with a product known as Stripe Checkout that allows us to focus on the back end. Now, even though Stripe makes our lives much easier, there are even more simplified solutions out there like rapid API. If you wanna learn more about it, Anya Kubo has an excellent video about it. It's basically API monetization as a service, but the main drawback is they take a much larger cut of your revenue. What we're doing in this video is more low level, but allows us to keep all of our money minus the Stripe fees. To get started, open up your editor to an empty directory and pull up the terminal.
billing
streaming
youtube
video gaming
customer support
customers
banking
multimedia
Run npm init y to add node package manager to this folder. The project has only 2 dependencies, expressjs as our web application framework and Stripe to interact with the Stripe API in Node. Js. From there, we'll define our server side code in the index dotjs file. Inside that file, we will import Express, then call it as a function to create a new Express app. The Express app allows you to define multiple HTTP endpoints that can access on the Internet. In a REST API, every endpoint starts with a verb like get, post, put, or delete. As a developer, this allows you to organize your API endpoints based on the actual operation that's taking place there. For example, you would use get if you're just retrieving data, post if you're creating something new and delete if you're removing data. In Express, we can define an API endpoint starting with the verb as a function. In this case, we'll use get and then pass it a URL route where it can be accessed. This will give us a route on HTTP local host 8080/API.
The second argument is a callback function that It will be executed anytime somebody tries to access this endpoint on our server. Express will provide us with 2 objects, the request, which contains all the incoming data, and response, which provides a way for us to send data back to the user.
programming
On the request, we're going to be looking for an API key that's provided by the end user. And we can find that with the URL's query parameters, which are just variables encoded in the URL that are preceded by a question mark. One side note I wanna make here though is that storing the API key in the URL is not necessarily the best choice. You can also store it in a header, which tends to be a little more secure. But for simplicity's sake, we're just going to store it in the URL. Later in the video, we'll learn how to create and validate custom API keys. But for right now, we'll just go ahead and send a response back to the user that is a string of emojis. That's it. That's all the API does, and we're going to charge people $1 per request to use it. Now to run the express app in node, we'll call app dot listen with a port of 8080. To run this code, pull up the terminal and enter node dot period and you should be able to go to localhost 8080/API in the browser and get a response.
Now, when working on code like this, I would highly recommend using an HTTP client like Insomnia. It's a more developer friendly way to manage and test your endpoints. As you can see here, I have a git request going to local host 8080/API and I can easily format my query parameters here as well.
programming
software
Now that we have this awesome API, we need to go out and convince people to pay for it. Always be closing. Always be closing. To handle that, you'll need a Stripe account, then go to the dashboard and make sure that you're in test mode. Find the product screen and create a new product.
customer support
customers
billing
You can customize the settings however you want. The important thing is that it's a recurring product and that the metered box is checked. You can customize the billing behavior in pretty much any way imaginable, but we're just going to sum up the total amount of usage for each period. When that's done, it It will create a product with a unique product ID and more importantly, a price ID. A product can have multiple prices if you have different billing plans for this particular product. Go ahead and make a note of that price ID, then go to the developers tab and click the button for API keys.
billing
In order to interact with Stripe from our Node. Js application, we're going to need our Stripe secret key. We're in test mode, but you still don't want to expose this key publicly, so make sure to keep it safe. Back in the JavaScript, we'll use that key to initialize the Stripe SDK. And now we're ready to move on to phase 2, collect payment information from the user, and subscribe them to a plan. Stripe checkout makes this part incredibly easy. In our API, let's go ahead and create another endpoint called checkout, this time using post, and point it to the checkout route. Make the callback an async function because the Stripe SDK is promise based. When this URL is triggered, it's going to make a request to Stripe to start a new checkout session, and then it will send the details of that session back down to the client.
The important part here are the parameters that you pass when creating the session. That will tell Stripe what the user is paying for. In this case, the mode will be subscription And then, we'll put the price ID in the line items array. And lastly, when the checkout session is done, Stripe will redirect back to your website and you can provide 2 different URLs, one for success and one for cancel.
billing
Now, let's go ahead and restart the node server, then go to the HTTP client to make a request to the endpoint. Make a post request to checkout And you'll notice we get back a big object here, but the only important thing we need out of it is the URL.
This is the URL that we want to direct our end user to. That user will be greeted with a credit card form so they can pay for our API. To test it out locally, Stripe provides a bunch of different testing card numbers. When the form is submitted, Stripe will officially subscribe the user to the plan and charge their credit card on a recurring basis as they use the API. Congratulations. You have your 1st paying customer, but now what?
billing
customer support
Now that the user is paid, we'll need to generate a custom API key for this user and keep track of their data on our servers.
There's a few different parts to this process, but the first thing I wanna focus on is webhooks. A webhook is just an API endpoint on our server that can receive data from Stripe when an important event occurs. At the very least, we'll want to listen to events like when the checkout session has as completed, so we know when the user has paid for the product and also invoice paid and invoice payment failed, so we can keep track of their account status when Stripe charges their actual credit card.
billing
internet
Stripe has some boilerplate code to handle webhook securely. Every account has a webhook secret that you'll want to verify to make sure that a webhook was actually sent by Stripe and not being spoofed by a hacker. You can copy and paste this code from the full article on Fireship IO. The The important thing I want to point out is that there's a switch statement down here that listens to different events, so you can implement your own code when that event happens. Now, here's the tricky thing. How do we actually test a webhook locally? Because Stripe has no way to send a webhook to our local host URL. Luckily, Stripe has built a CLI tool that allows you to test webhooks locally. Go ahead and download it onto your system, then run Stripe login to authenticate into it. Once that's done, you can call Stripe listen and forward the events to your local host URL. After it spins up, you'll notice that it prints out a webhook signing secret. Go ahead and copy that value and add it as the signing secret in your webhook code. The event that we want to listen to right now is checkout session completed. Let's go ahead and console log and then fill out that checkout session credit card form. When Stripe handles it, it will trigger a bunch of different webhooks that you can listen to and you'll see those printed out in the terminal. If we go to the terminal for the node server, It should log out the data available in that event. The important things here are the customer ID and subscription ID.
Now that we have a subscribed customer, we can move on to phase 3, The creation of a custom API key. You'll need some way to store data about the user and their API key on your servers. You should use your favorite production database for that. But to keep things simple on this demo, I'm just going to store that information in memory. You'll wanna have at least 2 different tables or collections to handle this data. The first one is customers, which contains information about the customer like their Stripe customer ID and the plan that they're subscribed to. The second collection you'll need is a reverse mapping that points an API key to the customer account. You'll want a way to quickly look up a customer based on the API key that they pass in with a request. Now, an important thing to point out here is that an API key is like a password, so you should never store the raw value in your database Because if somebody gets a hold of your database, then they have all your customer API keys and can immediately start exploiting them.
data management
data
databases
customers
purchasing
data analysis
To overcome this vulnerability, we need to hash the API key before saving it to the database. A hashing function can take the original API key or password and convert it to a new set of characters that would be useless to a hacker, but at the same time is very easy to compute when you know the real value. It might be overkill for this little demo, But it's a really important concept to understand if you are storing API keys in your own database. Let's take a look at how we can generate an API key with Node. I'm creating a custom function here That's importing the random bytes function from the built in node crypto module. Then I'm using it to generate a random string of characters, which is the value that we'll give to the consumer of the API. Now like I said before, we need to store this value, but we can't store it directly in our database. I'm creating a second function to hash it, which uses that createhash function from nodecrypto. With this function, you first specify an algorithm like md5, then provide it with the value you want to hash, and we'll tell it to return a string using digesthex.
The hashed API key is now safe to store in the database. And as one final touch, we'll make this a recursive function to verify that there aren't any duplicate API keys already stored in database. Now that we can generate an API key, we can go back into our webhook handler and implement the code for checkout session completed.
databases
The code here will be very application specific, but the gist of it is that we'll generate an API key and provide the unhashed version to the user while storing the hashed version in our database.
To To simulate that process, I'm just going to console log the values for now. Another thing I'm doing in this code is grabbing the subscription items using the Stripe SDK from the customer's account. Having this value stored on the server will make it easier and faster to report usage to Stripe in the next step.
billing
programming
And now, we're ready to move on to the final phase, allowing the user to make requests to the API. Let's go back to our original API endpoint. The first thing we'll do inside of it is check to make sure that an API key is present on the request query and if not, then we'll send a 400 response back.
Now, if we do have an API key, we'll go ahead and hash it so we can find the matching value in our database. We can figure out which customer is associated with that API key because we have a collection with that reverse mapping, and then we can grab the customer details which would contain things like the user's account status. In a real API, you'd likely want to cache this data to make your response times as quick as possible. From there, If that customer's account is not active, then we'll send a not authorized response. Otherwise, we're good to go. When the request is made, we'll also want to report this usage to Stripe, which we can do by calling subscription items, create usage record, pass in the subscription item ID along with a quantity, timestamp, and action. In. The increment value will tell Stripe to increase the billing by 1 from whatever it previously was. Reporting usage like this is not very efficient, So you'd likely want to optimize it by making this a background job. Now at this point, we can make a request to the API by copying the user's API key, which Should be printed in the console when they finish their payment with Stripe checkout.
billing
databases
customer support
Go ahead and take that value and use it as a query parameter in the URL when sending a request with your HTTP client. Without an API key, you should get an error response. Otherwise, you'll get the usage report back from Stripe. As a final touch to prove to you that everything Working as intended, I created another endpoint to get the current usage for a customer.
If we go ahead and send 10 requests with the same API key and then request a usage report. You can see that the current bill is currently 1,000¢ or $10. Congratulations. You just built a $1,000,000,000 API from your mom's basement. Make sure to check out my full Stripe course if you're serious about building a payment solution. Thanks for watching, and I will see you in the next one.
billing
loans
APIs are big business. If you build one that developers love, you've got a $1,000,000,000 startup on your hands. And thanks to modern cloud technology, you can throw a monetized API together in your mom's basement in just a few minutes. In today's video, you'll learn how to, 1, build an API with Node. Js and Express, 2, handle authentication and generate API keys for your users, and 3, monetize it with metered billing subscriptions using Stripe, where the customer is billed for each API request. By the end of the video, you'll stand the steps required to make money from your side hustle API. If you're new here, like and subscribe. And if you wanna learn more about payments, check out my full Stripe course on Fireship IO. Let's start by taking a look at how APIs work from a high level. The owner of the API deploys some code to server. That server might have a bunch of HTTP endpoints that do something useful, like maybe retrieve the current weather from a set of GPS coordinates. At it. Other developers out there want to use this data, but they don't want to have to implement a solution on their own. So they reach out to you for permission to make requests to your server. You say, sure. No problem. Just create an account and put a credit card on file and I will give you an API key. Sounds good. How will this work? Whenever you make a request to my server, just attach this API key and I'll keep track of the number of requests you make each month. How much does one API request cost? It'll cost $1 per request and I'll charge your credit card for the volume of usage at the end of the month. You got yourself a deal. Take my money. To build something like this, we'll need both front end and back end code. On the front And, we'll need a place for a user to add a credit card and manage their subscription details. Luckily, Stripe will host and manage all the front end code for us, which is made possible with a product known as Stripe Checkout that allows us to focus on the back end. Now, even though Stripe makes our lives much easier, there are even more simplified solutions out there like rapid API. If you wanna learn more about it, Anya Kubo has an excellent video about it. It's basically API monetization as a service, but the main drawback is they take a much larger cut of your revenue. What we're doing in this video is more low level, but allows us to keep all of our money minus the Stripe fees. To get started, open up your editor to an empty directory and pull up the terminal. Run npm init y to add node package manager to this folder. The project has only 2 dependencies, expressjs as our web application framework and Stripe to interact with the Stripe API in Node. Js. From there, we'll define our server side code in the index dotjs file. Inside that file, we will import Express, then call it as a function to create a new Express app. The Express app allows you to define multiple HTTP endpoints that can access on the Internet. In a REST API, every endpoint starts with a verb like get, post, put, or delete. As a developer, this allows you to organize your API endpoints based on the actual operation that's taking place there. For example, you would use get if you're just retrieving data, post if you're creating something new and delete if you're removing data. In Express, we can define an API endpoint starting with the verb as a function. In this case, we'll use get and then pass it a URL route where it can be accessed. This will give us a route on HTTP local host 8080/API. The second argument is a callback function that It will be executed anytime somebody tries to access this endpoint on our server. Express will provide us with 2 objects, the request, which contains all the incoming data, and response, which provides a way for us to send data back to the user. On the request, we're going to be looking for an API key that's provided by the end user. And we can find that with the URL's query parameters, which are just variables encoded in the URL that are preceded by a question mark. One side note I wanna make here though is that storing the API key in the URL is not necessarily the best choice. You can also store it in a header, which tends to be a little more secure. But for simplicity's sake, we're just going to store it in the URL. Later in the video, we'll learn how to create and validate custom API keys. But for right now, we'll just go ahead and send a response back to the user that is a string of emojis. That's it. That's all the API does, and we're going to charge people $1 per request to use it. Now to run the express app in node, we'll call app dot listen with a port of 8080. To run this code, pull up the terminal and enter node dot period and you should be able to go to localhost 8080/API in the browser and get a response. Now, when working on code like this, I would highly recommend using an HTTP client like Insomnia. It's a more developer friendly way to manage and test your endpoints. As you can see here, I have a git request going to local host 8080/API and I can easily format my query parameters here as well. Now that we have this awesome API, we need to go out and convince people to pay for it. Always be closing. Always be closing. To handle that, you'll need a Stripe account, then go to the dashboard and make sure that you're in test mode. Find the product screen and create a new product. You can customize the settings however you want. The important thing is that it's a recurring product and that the metered box is checked. You can customize the billing behavior in pretty much any way imaginable, but we're just going to sum up the total amount of usage for each period. When that's done, it It will create a product with a unique product ID and more importantly, a price ID. A product can have multiple prices if you have different billing plans for this particular product. Go ahead and make a note of that price ID, then go to the developers tab and click the button for API keys. In order to interact with Stripe from our Node. Js application, we're going to need our Stripe secret key. We're in test mode, but you still don't want to expose this key publicly, so make sure to keep it safe. Back in the JavaScript, we'll use that key to initialize the Stripe SDK. And now we're ready to move on to phase 2, collect payment information from the user, and subscribe them to a plan. Stripe checkout makes this part incredibly easy. In our API, let's go ahead and create another endpoint called checkout, this time using post, and point it to the checkout route. Make the callback an async function because the Stripe SDK is promise based. When this URL is triggered, it's going to make a request to Stripe to start a new checkout session, and then it will send the details of that session back down to the client. The important part here are the parameters that you pass when creating the session. That will tell Stripe what the user is paying for. In this case, the mode will be subscription And then, we'll put the price ID in the line items array. And lastly, when the checkout session is done, Stripe will redirect back to your website and you can provide 2 different URLs, one for success and one for cancel. Now, let's go ahead and restart the node server, then go to the HTTP client to make a request to the endpoint. Make a post request to checkout And you'll notice we get back a big object here, but the only important thing we need out of it is the URL. This is the URL that we want to direct our end user to. That user will be greeted with a credit card form so they can pay for our API. To test it out locally, Stripe provides a bunch of different testing card numbers. When the form is submitted, Stripe will officially subscribe the user to the plan and charge their credit card on a recurring basis as they use the API. Congratulations. You have your 1st paying customer, but now what? Now that the user is paid, we'll need to generate a custom API key for this user and keep track of their data on our servers. There's a few different parts to this process, but the first thing I wanna focus on is webhooks. A webhook is just an API endpoint on our server that can receive data from Stripe when an important event occurs. At the very least, we'll want to listen to events like when the checkout session has as completed, so we know when the user has paid for the product and also invoice paid and invoice payment failed, so we can keep track of their account status when Stripe charges their actual credit card. Stripe has some boilerplate code to handle webhook securely. Every account has a webhook secret that you'll want to verify to make sure that a webhook was actually sent by Stripe and not being spoofed by a hacker. You can copy and paste this code from the full article on Fireship IO. The The important thing I want to point out is that there's a switch statement down here that listens to different events, so you can implement your own code when that event happens. Now, here's the tricky thing. How do we actually test a webhook locally? Because Stripe has no way to send a webhook to our local host URL. Luckily, Stripe has built a CLI tool that allows you to test webhooks locally. Go ahead and download it onto your system, then run Stripe login to authenticate into it. Once that's done, you can call Stripe listen and forward the events to your local host URL. After it spins up, you'll notice that it prints out a webhook signing secret. Go ahead and copy that value and add it as the signing secret in your webhook code. The event that we want to listen to right now is checkout session completed. Let's go ahead and console log and then fill out that checkout session credit card form. When Stripe handles it, it will trigger a bunch of different webhooks that you can listen to and you'll see those printed out in the terminal. If we go to the terminal for the node server, It should log out the data available in that event. The important things here are the customer ID and subscription ID. Now that we have a subscribed customer, we can move on to phase 3, The creation of a custom API key. You'll need some way to store data about the user and their API key on your servers. You should use your favorite production database for that. But to keep things simple on this demo, I'm just going to store that information in memory. You'll wanna have at least 2 different tables or collections to handle this data. The first one is customers, which contains information about the customer like their Stripe customer ID and the plan that they're subscribed to. The second collection you'll need is a reverse mapping that points an API key to the customer account. You'll want a way to quickly look up a customer based on the API key that they pass in with a request. Now, an important thing to point out here is that an API key is like a password, so you should never store the raw value in your database Because if somebody gets a hold of your database, then they have all your customer API keys and can immediately start exploiting them. To overcome this vulnerability, we need to hash the API key before saving it to the database. A hashing function can take the original API key or password and convert it to a new set of characters that would be useless to a hacker, but at the same time is very easy to compute when you know the real value. It might be overkill for this little demo, But it's a really important concept to understand if you are storing API keys in your own database. Let's take a look at how we can generate an API key with Node. I'm creating a custom function here That's importing the random bytes function from the built in node crypto module. Then I'm using it to generate a random string of characters, which is the value that we'll give to the consumer of the API. Now like I said before, we need to store this value, but we can't store it directly in our database. I'm creating a second function to hash it, which uses that createhash function from nodecrypto. With this function, you first specify an algorithm like md5, then provide it with the value you want to hash, and we'll tell it to return a string using digesthex. The hashed API key is now safe to store in the database. And as one final touch, we'll make this a recursive function to verify that there aren't any duplicate API keys already stored in database. Now that we can generate an API key, we can go back into our webhook handler and implement the code for checkout session completed. The code here will be very application specific, but the gist of it is that we'll generate an API key and provide the unhashed version to the user while storing the hashed version in our database. To To simulate that process, I'm just going to console log the values for now. Another thing I'm doing in this code is grabbing the subscription items using the Stripe SDK from the customer's account. Having this value stored on the server will make it easier and faster to report usage to Stripe in the next step. And now, we're ready to move on to the final phase, allowing the user to make requests to the API. Let's go back to our original API endpoint. The first thing we'll do inside of it is check to make sure that an API key is present on the request query and if not, then we'll send a 400 response back. Now, if we do have an API key, we'll go ahead and hash it so we can find the matching value in our database. We can figure out which customer is associated with that API key because we have a collection with that reverse mapping, and then we can grab the customer details which would contain things like the user's account status. In a real API, you'd likely want to cache this data to make your response times as quick as possible. From there, If that customer's account is not active, then we'll send a not authorized response. Otherwise, we're good to go. When the request is made, we'll also want to report this usage to Stripe, which we can do by calling subscription items, create usage record, pass in the subscription item ID along with a quantity, timestamp, and action. In. The increment value will tell Stripe to increase the billing by 1 from whatever it previously was. Reporting usage like this is not very efficient, So you'd likely want to optimize it by making this a background job. Now at this point, we can make a request to the API by copying the user's API key, which Should be printed in the console when they finish their payment with Stripe checkout. Go ahead and take that value and use it as a query parameter in the URL when sending a request with your HTTP client. Without an API key, you should get an error response. Otherwise, you'll get the usage report back from Stripe. As a final touch to prove to you that everything Working as intended, I created another endpoint to get the current usage for a customer. If we go ahead and send 10 requests with the same API key and then request a usage report. You can see that the current bill is currently 1,000¢ or $10. Congratulations. You just built a $1,000,000,000 API from your mom's basement. Make sure to check out my full Stripe course if you're serious about building a payment solution. Thanks for watching, and I will see you in the next one.
APIs
apis
are
are
big
big
business.
business
If
if
you
you
build
build
one
one
that
that
developers
developers
love,
love
you've
you've
got
got
a
a
$1,000,000,000
$1,000,000,000
startup
startup
on
on
your
your
hands.
hands
And
and
thanks
thanks
to
to
modern
modern
cloud
cloud
technology,
technology
you
you
can
can
throw
throw
a
a
monetized
monetized
API
api
together
together
in
in
your
your
mom's
mom's
basement
basement
in
in
just
just
a
a
few
few
minutes.
minutes
In
in
today's
today's
video,
video
you'll
you'll
learn
learn
how
how
to,
to
1,
1
build
build
an
an
API
api
with
with
Node.
node
Js
js
and
and
Express,
express
2,
2
handle
handle
authentication
authentication
and
and
generate
generate
API
api
keys
keys
for
for
your
your
users,
users
and
and
3,
3
monetize
monetize
it
it
with
with
metered
metered
billing
billing
subscriptions
subscriptions
using
using
Stripe,
stripe
where
where
the
the
customer
customer
is
is
billed
billed
for
for
each
each
API
api
request.
request
By
by
the
the
end
end
of
of
the
the
video,
video
you'll
you'll
stand
stand
the
the
steps
steps
required
required
to
to
make
make
money
money
from
from
your
your
side
side
hustle
hustle
API.
api
If
if
you're
you're
new
new
here,
here
like
like
and
and
subscribe.
subscribe
And
and
if
if
you
you
wanna
wanna
learn
learn
more
more
about
about
payments,
payments
check
check
out
out
my
my
full
full
Stripe
stripe
course
course
on
on
Fireship
fireship
IO.
io
Let's
let's
start
start
by
by
taking
taking
a
a
look
look
at
at
how
how
APIs
apis
work
work
from
from
a
a
high
high
level.
level
The
the
owner
owner
of
of
the
the
API
api
deploys
deploys
some
some
code
code
to
to
server.
server
That
that
server
server
might
might
have
have
a
a
bunch
bunch
of
of
HTTP
http
endpoints
endpoints
that
that
do
do
something
something
useful,
useful
like
like
maybe
maybe
retrieve
retrieve
the
the
current
current
weather
weather
from
from
a
a
set
set
of
of
GPS
gps
coordinates.
coordinates
At
at
it.
it
Other
other
developers
developers
out
out
there
there
want
want
to
to
use
use
this
this
data,
data
but
but
they
they
don't
don't
want
want
to
to
have
have
to
to
implement
implement
a
a
solution
solution
on
on
their
their
own.
own
So
so
they
they
reach
reach
out
out
to
to
you
you
for
for
permission
permission
to
to
make
make
requests
requests
to
to
your
your
server.
server
You
you
say,
say
sure.
sure
No
no
problem.
problem
Just
just
create
create
an
an
account
account
and
and
put
put
a
a
credit
credit
card
card
on
on
file
file
and
and
I
i
will
will
give
give
you
you
an
an
API
api
key.
key
Sounds
sounds
good.
good
How
how
will
will
this
this
work?
work
Whenever
whenever
you
you
make
make
a
a
request
request
to
to
my
my
server,
server
just
just
attach
attach
this
this
API
api
key
key
and
and
I'll
i'll
keep
keep
track
track
of
of
the
the
number
number
of
of
requests
requests
you
you
make
make
each
each
month.
month
How
how
much
much
does
does
one
one
API
api
request
request
cost?
cost
It'll
it'll
cost
cost
$1
$1
per
per
request
request
and
and
I'll
i'll
charge
charge
your
your
credit
credit
card
card
for
for
the
the
volume
volume
of
of
usage
usage
at
at
the
the
end
end
of
of
the
the
month.
month
You
you
got
got
yourself
yourself
a
a
deal.
deal
Take
take
my
my
money.
money
To
to
build
build
something
something
like
like
this,
this
we'll
we'll
need
need
both
both
front
front
end
end
and
and
back
back
end
end
code.
code
On
on
the
the
front
front
And,
and
we'll
we'll
need
need
a
a
place
place
for
for
a
a
user
user
to
to
add
add
a
a
credit
credit
card
card
and
and
manage
manage
their
their
subscription
subscription
details.
details
Luckily,
luckily
Stripe
stripe
will
will
host
host
and
and
manage
manage
all
all
the
the
front
front
end
end
code
code
for
for
us,
us
which
which
is
is
made
made
possible
possible
with
with
a
a
product
product
known
known
as
as
Stripe
stripe
Checkout
checkout
that
that
allows
allows
us
us
to
to
focus
focus
on
on
the
the
back
back
end.
end
Now,
now
even
even
though
though
Stripe
stripe
makes
makes
our
our
lives
lives
much
much
easier,
easier
there
there
are
are
even
even
more
more
simplified
simplified
solutions
solutions
out
out
there
there
like
like
rapid
rapid
API.
api
If
if
you
you
wanna
wanna
learn
learn
more
more
about
about
it,
it
Anya
anya
Kubo
kubo
has
has
an
an
excellent
excellent
video
video
about
about
it.
it
It's
it's
basically
basically
API
api
monetization
monetization
as
as
a
a
service,
service
but
but
the
the
main
main
drawback
drawback
is
is
they
they
take
take
a
a
much
much
larger
larger
cut
cut
of
of
your
your
revenue.
revenue
What
what
we're
we're
doing
doing
in
in
this
this
video
video
is
is
more
more
low
low
level,
level
but
but
allows
allows
us
us
to
to
keep
keep
all
all
of
of
our
our
money
money
minus
minus
the
the
Stripe
stripe
fees.
fees
To
to
get
get
started,
started
open
open
up
up
your
your
editor
editor
to
to
an
an
empty
empty
directory
directory
and
and
pull
pull
up
up
the
the
terminal.
terminal
Run
run
npm
npm
init
init
y
y
to
to
add
add
node
node
package
package
manager
manager
to
to
this
this
folder.
folder
The
the
project
project
has
has
only
only
2
2
dependencies,
dependencies
expressjs
expressjs
as
as
our
our
web
web
application
application
framework
framework
and
and
Stripe
stripe
to
to
interact
interact
with
with
the
the
Stripe
stripe
API
api
in
in
Node.
node
Js.
js
From
from
there,
there
we'll
we'll
define
define
our
our
server
server
side
side
code
code
in
in
the
the
index
index
dotjs
dotjs
file.
file
Inside
inside
that
that
file,
file
we
we
will
will
import
import
Express,
express
then
then
call
call
it
it
as
as
a
a
function
function
to
to
create
create
a
a
new
new
Express
express
app.
app
The
the
Express
express
app
app
allows
allows
you
you
to
to
define
define
multiple
multiple
HTTP
http
endpoints
endpoints
that
that
can
can
access
access
on
on
the
the
Internet.
internet
In
in
a
a
REST
rest
API,
api
every
every
endpoint
endpoint
starts
starts
with
with
a
a
verb
verb
like
like
get,
get
post,
post
put,
put
or
or
delete.
delete
As
as
a
a
developer,
developer
this
this
allows
allows
you
you
to
to
organize
organize
your
your
API
api
endpoints
endpoints
based
based
on
on
the
the
actual
actual
operation
operation
that's
that's
taking
taking
place
place
there.
there
For
for
example,
example
you
you
would
would
use
use
get
get
if
if
you're
you're
just
just
retrieving
retrieving
data,
data
post
post
if
if
you're
you're
creating
creating
something
something
new
new
and
and
delete
delete
if
if
you're
you're
removing
removing
data.
data
In
in
Express,
express
we
we
can
can
define
define
an
an
API
api
endpoint
endpoint
starting
starting
with
with
the
the
verb
verb
as
as
a
a
function.
function
In
in
this
this
case,
case
we'll
we'll
use
use
get
get
and
and
then
then
pass
pass
it
it
a
a
URL
url
route
route
where
where
it
it
can
can
be
be
accessed.
accessed
This
this
will
will
give
give
us
us
a
a
route
route
on
on
HTTP
http
local
local
host
host
8080/API.
8080/api
The
the
second
second
argument
argument
is
is
a
a
callback
callback
function
function
that
that
It
it
will
will
be
be
executed
executed
anytime
anytime
somebody
somebody
tries
tries
to
to
access
access
this
this
endpoint
endpoint
on
on
our
our
server.
server
Express
express
will
will
provide
provide
us
us
with
with
2
2
objects,
objects
the
the
request,
request
which
which
contains
contains
all
all
the
the
incoming
incoming
data,
data
and
and
response,
response
which
which
provides
provides
a
a
way
way
for
for
us
us
to
to
send
send
data
data
back
back
to
to
the
the
user.
user
On
on
the
the
request,
request
we're
we're
going
going
to
to
be
be
looking
looking
for
for
an
an
API
api
key
key
that's
that's
provided
provided
by
by
the
the
end
end
user.
user
And
and
we
we
can
can
find
find
that
that
with
with
the
the
URL's
url's
query
query
parameters,
parameters
which
which
are
are
just
just
variables
variables
encoded
encoded
in
in
the
the
URL
url
that
that
are
are
preceded
preceded
by
by
a
a
question
question
mark.
mark
One
one
side
side
note
note
I
i
wanna
wanna
make
make
here
here
though
though
is
is
that
that
storing
storing
the
the
API
api
key
key
in
in
the
the
URL
url
is
is
not
not
necessarily
necessarily
the
the
best
best
choice.
choice
You
you
can
can
also
also
store
store
it
it
in
in
a
a
header,
header
which
which
tends
tends
to
to
be
be
a
a
little
little
more
more
secure.
secure
But
but
for
for
simplicity's
simplicity's
sake,
sake
we're
we're
just
just
going
going
to
to
store
store
it
it
in
in
the
the
URL.
url
Later
later
in
in
the
the
video,
video
we'll
we'll
learn
learn
how
how
to
to
create
create
and
and
validate
validate
custom
custom
API
api
keys.
keys
But
but
for
for
right
right
now,
now
we'll
we'll
just
just
go
go
ahead
ahead
and
and
send
send
a
a
response
response
back
back
to
to
the
the
user
user
that
that
is
is
a
a
string
string
of
of
emojis.
emojis
That's
that's
it.
it
That's
that's
all
all
the
the
API
api
does,
does
and
and
we're
we're
going
going
to
to
charge
charge
people
people
$1
$1
per
per
request
request
to
to
use
use
it.
it
Now
now
to
to
run
run
the
the
express
express
app
app
in
in
node,
node
we'll
we'll
call
call
app
app
dot
dot
listen
listen
with
with
a
a
port
port
of
of
8080.
8080
To
to
run
run
this
this
code,
code
pull
pull
up
up
the
the
terminal
terminal
and
and
enter
enter
node
node
dot
dot
period
period
and
and
you
you
should
should
be
be
able
able
to
to
go
go
to
to
localhost
localhost
8080/API
8080/api
in
in
the
the
browser
browser
and
and
get
get
a
a
response.
response
Now,
now
when
when
working
working
on
on
code
code
like
like
this,
this
I
i
would
would
highly
highly
recommend
recommend
using
using
an
an
HTTP
http
client
client
like
like
Insomnia.
insomnia
It's
it's
a
a
more
more
developer
developer
friendly
friendly
way
way
to
to
manage
manage
and
and
test
test
your
your
endpoints.
endpoints
As
as
you
you
can
can
see
see
here,
here
I
i
have
have
a
a
git
git
request
request
going
going
to
to
local
local
host
host
8080/API
8080/api
and
and
I
i
can
can
easily
easily
format
format
my
my
query
query
parameters
parameters
here
here
as
as
well.
well
Now
now
that
that
we
we
have
have
this
this
awesome
awesome
API,
api
we
we
need
need
to
to
go
go
out
out
and
and
convince
convince
people
people
to
to
pay
pay
for
for
it.
it
Always
always
be
be
closing.
closing
Always
always
be
be
closing.
closing
To
to
handle
handle
that,
that
you'll
you'll
need
need
a
a
Stripe
stripe
account,
account
then
then
go
go
to
to
the
the
dashboard
dashboard
and
and
make
make
sure
sure
that
that
you're
you're
in
in
test
test
mode.
mode
Find
find
the
the
product
product
screen
screen
and
and
create
create
a
a
new
new
product.
product
You
you
can
can
customize
customize
the
the
settings
settings
however
however
you
you
want.
want
The
the
important
important
thing
thing
is
is
that
that
it's
it's
a
a
recurring
recurring
product
product
and
and
that
that
the
the
metered
metered
box
box
is
is
checked.
checked
You
you
can
can
customize
customize
the
the
billing
billing
behavior
behavior
in
in
pretty
pretty
much
much
any
any
way
way
imaginable,
imaginable
but
but
we're
we're
just
just
going
going
to
to
sum
sum
up
up
the
the
total
total
amount
amount
of
of
usage
usage
for
for
each
each
period.
period
When
when
that's
that's
done,
done
it
it
It
it
will
will
create
create
a
a
product
product
with
with
a
a
unique
unique
product
product
ID
id
and
and
more
more
importantly,
importantly
a
a
price
price
ID.
id
A
a
product
product
can
can
have
have
multiple
multiple
prices
prices
if
if
you
you
have
have
different
different
billing
billing
plans
plans
for
for
this
this
particular
particular
product.
product
Go
go
ahead
ahead
and
and
make
make
a
a
note
note
of
of
that
that
price
price
ID,
id
then
then
go
go
to
to
the
the
developers
developers
tab
tab
and
and
click
click
the
the
button
button
for
for
API
api
keys.
keys
In
in
order
order
to
to
interact
interact
with
with
Stripe
stripe
from
from
our
our
Node.
node
Js
js
application,
application
we're
we're
going
going
to
to
need
need
our
our
Stripe
stripe
secret
secret
key.
key
We're
we're
in
in
test
test
mode,
mode
but
but
you
you
still
still
don't
don't
want
want
to
to
expose
expose
this
this
key
key
publicly,
publicly
so
so
make
make
sure
sure
to
to
keep
keep
it
it
safe.
safe
Back
back
in
in
the
the
JavaScript,
javascript
we'll
we'll
use
use
that
that
key
key
to
to
initialize
initialize
the
the
Stripe
stripe
SDK.
sdk
And
and
now
now
we're
we're
ready
ready
to
to
move
move
on
on
to
to
phase
phase
2,
2
collect
collect
payment
payment
information
information
from
from
the
the
user,
user
and
and
subscribe
subscribe
them
them
to
to
a
a
plan.
plan
Stripe
stripe
checkout
checkout
makes
makes
this
this
part
part
incredibly
incredibly
easy.
easy
In
in
our
our
API,
api
let's
let's
go
go
ahead
ahead
and
and
create
create
another
another
endpoint
endpoint
called
called
checkout,
checkout
this
this
time
time
using
using
post,
post
and
and
point
point
it
it
to
to
the
the
checkout
checkout
route.
route
Make
make
the
the
callback
callback
an
an
async
async
function
function
because
because
the
the
Stripe
stripe
SDK
sdk
is
is
promise
promise
based.
based
When
when
this
this
URL
url
is
is
triggered,
triggered
it's
it's
going
going
to
to
make
make
a
a
request
request
to
to
Stripe
stripe
to
to
start
start
a
a
new
new
checkout
checkout
session,
session
and
and
then
then
it
it
will
will
send
send
the
the
details
details
of
of
that
that
session
session
back
back
down
down
to
to
the
the
client.
client
The
the
important
important
part
part
here
here
are
are
the
the
parameters
parameters
that
that
you
you
pass
pass
when
when
creating
creating
the
the
session.
session
That
that
will
will
tell
tell
Stripe
stripe
what
what
the
the
user
user
is
is
paying
paying
for.
for
In
in
this
this
case,
case
the
the
mode
mode
will
will
be
be
subscription
subscription
And
and
then,
then
we'll
we'll
put
put
the
the
price
price
ID
id
in
in
the
the
line
line
items
items
array.
array
And
and
lastly,
lastly
when
when
the
the
checkout
checkout
session
session
is
is
done,
done
Stripe
stripe
will
will
redirect
redirect
back
back
to
to
your
your
website
website
and
and
you
you
can
can
provide
provide
2
2
different
different
URLs,
urls
one
one
for
for
success
success
and
and
one
one
for
for
cancel.
cancel
Now,
now
let's
let's
go
go
ahead
ahead
and
and
restart
restart
the
the
node
node
server,
server
then
then
go
go
to
to
the
the
HTTP
http
client
client
to
to
make
make
a
a
request
request
to
to
the
the
endpoint.
endpoint
Make
make
a
a
post
post
request
request
to
to
checkout
checkout
And
and
you'll
you'll
notice
notice
we
we
get
get
back
back
a
a
big
big
object
object
here,
here
but
but
the
the
only
only
important
important
thing
thing
we
we
need
need
out
out
of
of
it
it
is
is
the
the
URL.
url
This
this
is
is
the
the
URL
url
that
that
we
we
want
want
to
to
direct
direct
our
our
end
end
user
user
to.
to
That
that
user
user
will
will
be
be
greeted
greeted
with
with
a
a
credit
credit
card
card
form
form
so
so
they
they
can
can
pay
pay
for
for
our
our
API.
api
To
to
test
test
it
it
out
out
locally,
locally
Stripe
stripe
provides
provides
a
a
bunch
bunch
of
of
different
different
testing
testing
card
card
numbers.
numbers
When
when
the
the
form
form
is
is
submitted,
submitted
Stripe
stripe
will
will
officially
officially
subscribe
subscribe
the
the
user
user
to
to
the
the
plan
plan
and
and
charge
charge
their
their
credit
credit
card
card
on
on
a
a
recurring
recurring
basis
basis
as
as
they
they
use
use
the
the
API.
api
Congratulations.
congratulations
You
you
have
have
your
your
1st
1st
paying
paying
customer,
customer
but
but
now
now
what?
what
Now
now
that
that
the
the
user
user
is
is
paid,
paid
we'll
we'll
need
need
to
to
generate
generate
a
a
custom
custom
API
api
key
key
for
for
this
this
user
user
and
and
keep
keep
track
track
of
of
their
their
data
data
on
on
our
our
servers.
servers
There's
there's
a
a
few
few
different
different
parts
parts
to
to
this
this
process,
process
but
but
the
the
first
first
thing
thing
I
i
wanna
wanna
focus
focus
on
on
is
is
webhooks.
webhooks
A
a
webhook
webhook
is
is
just
just
an
an
API
api
endpoint
endpoint
on
on
our
our
server
server
that
that
can
can
receive
receive
data
data
from
from
Stripe
stripe
when
when
an
an
important
important
event
event
occurs.
occurs
At
at
the
the
very
very
least,
least
we'll
we'll
want
want
to
to
listen
listen
to
to
events
events
like
like
when
when
the
the
checkout
checkout
session
session
has
has
as
as
completed,
completed
so
so
we
we
know
know
when
when
the
the
user
user
has
has
paid
paid
for
for
the
the
product
product
and
and
also
also
invoice
invoice
paid
paid
and
and
invoice
invoice
payment
payment
failed,
failed
so
so
we
we
can
can
keep
keep
track
track
of
of
their
their
account
account
status
status
when
when
Stripe
stripe
charges
charges
their
their
actual
actual
credit
credit
card.
card
Stripe
stripe
has
has
some
some
boilerplate
boilerplate
code
code
to
to
handle
handle
webhook
webhook
securely.
securely
Every
every
account
account
has
has
a
a
webhook
webhook
secret
secret
that
that
you'll
you'll
want
want
to
to
verify
verify
to
to
make
make
sure
sure
that
that
a
a
webhook
webhook
was
was
actually
actually
sent
sent
by
by
Stripe
stripe
and
and
not
not
being
being
spoofed
spoofed
by
by
a
a
hacker.
hacker
You
you
can
can
copy
copy
and
and
paste
paste
this
this
code
code
from
from
the
the
full
full
article
article
on
on
Fireship
fireship
IO.
io
The
the
The
the
important
important
thing
thing
I
i
want
want
to
to
point
point
out
out
is
is
that
that
there's
there's
a
a
switch
switch
statement
statement
down
down
here
here
that
that
listens
listens
to
to
different
different
events,
events
so
so
you
you
can
can
implement
implement
your
your
own
own
code
code
when
when
that
that
event
event
happens.
happens
Now,
now
here's
here's
the
the
tricky
tricky
thing.
thing
How
how
do
do
we
we
actually
actually
test
test
a
a
webhook
webhook
locally?
locally
Because
because
Stripe
stripe
has
has
no
no
way
way
to
to
send
send
a
a
webhook
webhook
to
to
our
our
local
local
host
host
URL.
url
Luckily,
luckily
Stripe
stripe
has
has
built
built
a
a
CLI
cli
tool
tool
that
that
allows
allows
you
you
to
to
test
test
webhooks
webhooks
locally.
locally
Go
go
ahead
ahead
and
and
download
download
it
it
onto
onto
your
your
system,
system
then
then
run
run
Stripe
stripe
login
login
to
to
authenticate
authenticate
into
into
it.
it
Once
once
that's
that's
done,
done
you
you
can
can
call
call
Stripe
stripe
listen
listen
and
and
forward
forward
the
the
events
events
to
to
your
your
local
local
host
host
URL.
url
After
after
it
it
spins
spins
up,
up
you'll
you'll
notice
notice
that
that
it
it
prints
prints
out
out
a
a
webhook
webhook
signing
signing
secret.
secret
Go
go
ahead
ahead
and
and
copy
copy
that
that
value
value
and
and
add
add
it
it
as
as
the
the
signing
signing
secret
secret
in
in
your
your
webhook
webhook
code.
code
The
the
event
event
that
that
we
we
want
want
to
to
listen
listen
to
to
right
right
now
now
is
is
checkout
checkout
session
session
completed.
completed
Let's
let's
go
go
ahead
ahead
and
and
console
console
log
log
and
and
then
then
fill
fill
out
out
that
that
checkout
checkout
session
session
credit
credit
card
card
form.
form
When
when
Stripe
stripe
handles
handles
it,
it
it
it
will
will
trigger
trigger
a
a
bunch
bunch
of
of
different
different
webhooks
webhooks
that
that
you
you
can
can
listen
listen
to
to
and
and
you'll
you'll
see
see
those
those
printed
printed
out
out
in
in
the
the
terminal.
terminal
If
if
we
we
go
go
to
to
the
the
terminal
terminal
for
for
the
the
node
node
server,
server
It
it
should
should
log
log
out
out
the
the
data
data
available
available
in
in
that
that
event.
event
The
the
important
important
things
things
here
here
are
are
the
the
customer
customer
ID
id
and
and
subscription
subscription
ID.
id
Now
now
that
that
we
we
have
have
a
a
subscribed
subscribed
customer,
customer
we
we
can
can
move
move
on
on
to
to
phase
phase
3,
3
The
the
creation
creation
of
of
a
a
custom
custom
API
api
key.
key
You'll
you'll
need
need
some
some
way
way
to
to
store
store
data
data
about
about
the
the
user
user
and
and
their
their
API
api
key
key
on
on
your
your
servers.
servers
You
you
should
should
use
use
your
your
favorite
favorite
production
production
database
database
for
for
that.
that
But
but
to
to
keep
keep
things
things
simple
simple
on
on
this
this
demo,
demo
I'm
i'm
just
just
going
going
to
to
store
store
that
that
information
information
in
in
memory.
memory
You'll
you'll
wanna
wanna
have
have
at
at
least
least
2
2
different
different
tables
tables
or
or
collections
collections
to
to
handle
handle
this
this
data.
data
The
the
first
first
one
one
is
is
customers,
customers
which
which
contains
contains
information
information
about
about
the
the
customer
customer
like
like
their
their
Stripe
stripe
customer
customer
ID
id
and
and
the
the
plan
plan
that
that
they're
they're
subscribed
subscribed
to.
to
The
the
second
second
collection
collection
you'll
you'll
need
need
is
is
a
a
reverse
reverse
mapping
mapping
that
that
points
points
an
an
API
api
key
key
to
to
the
the
customer
customer
account.
account
You'll
you'll
want
want
a
a
way
way
to
to
quickly
quickly
look
look
up
up
a
a
customer
customer
based
based
on
on
the
the
API
api
key
key
that
that
they
they
pass
pass
in
in
with
with
a
a
request.
request
Now,
now
an
an
important
important
thing
thing
to
to
point
point
out
out
here
here
is
is
that
that
an
an
API
api
key
key
is
is
like
like
a
a
password,
password
so
so
you
you
should
should
never
never
store
store
the
the
raw
raw
value
value
in
in
your
your
database
database
Because
because
if
if
somebody
somebody
gets
gets
a
a
hold
hold
of
of
your
your
database,
database
then
then
they
they
have
have
all
all
your
your
customer
customer
API
api
keys
keys
and
and
can
can
immediately
immediately
start
start
exploiting
exploiting
them.
them
To
to
overcome
overcome
this
this
vulnerability,
vulnerability
we
we
need
need
to
to
hash
hash
the
the
API
api
key
key
before
before
saving
saving
it
it
to
to
the
the
database.
database
A
a
hashing
hashing
function
function
can
can
take
take
the
the
original
original
API
api
key
key
or
or
password
password
and
and
convert
convert
it
it
to
to
a
a
new
new
set
set
of
of
characters
characters
that
that
would
would
be
be
useless
useless
to
to
a
a
hacker,
hacker
but
but
at
at
the
the
same
same
time
time
is
is
very
very
easy
easy
to
to
compute
compute
when
when
you
you
know
know
the
the
real
real
value.
value
It
it
might
might
be
be
overkill
overkill
for
for
this
this
little
little
demo,
demo
But
but
it's
it's
a
a
really
really
important
important
concept
concept
to
to
understand
understand
if
if
you
you
are
are
storing
storing
API
api
keys
keys
in
in
your
your
own
own
database.
database
Let's
let's
take
take
a
a
look
look
at
at
how
how
we
we
can
can
generate
generate
an
an
API
api
key
key
with
with
Node.
node
I'm
i'm
creating
creating
a
a
custom
custom
function
function
here
here
That's
that's
importing
importing
the
the
random
random
bytes
bytes
function
function
from
from
the
the
built
built
in
in
node
node
crypto
crypto
module.
module
Then
then
I'm
i'm
using
using
it
it
to
to
generate
generate
a
a
random
random
string
string
of
of
characters,
characters
which
which
is
is
the
the
value
value
that
that
we'll
we'll
give
give
to
to
the
the
consumer
consumer
of
of
the
the
API.
api
Now
now
like
like
I
i
said
said
before,
before
we
we
need
need
to
to
store
store
this
this
value,
value
but
but
we
we
can't
can't
store
store
it
it
directly
directly
in
in
our
our
database.
database
I'm
i'm
creating
creating
a
a
second
second
function
function
to
to
hash
hash
it,
it
which
which
uses
uses
that
that
createhash
createhash
function
function
from
from
nodecrypto.
nodecrypto
With
with
this
this
function,
function
you
you
first
first
specify
specify
an
an
algorithm
algorithm
like
like
md5,
md5
then
then
provide
provide
it
it
with
with
the
the
value
value
you
you
want
want
to
to
hash,
hash
and
and
we'll
we'll
tell
tell
it
it
to
to
return
return
a
a
string
string
using
using
digesthex.
digesthex
The
the
hashed
hashed
API
api
key
key
is
is
now
now
safe
safe
to
to
store
store
in
in
the
the
database.
database
And
and
as
as
one
one
final
final
touch,
touch
we'll
we'll
make
make
this
this
a
a
recursive
recursive
function
function
to
to
verify
verify
that
that
there
there
aren't
aren't
any
any
duplicate
duplicate
API
api
keys
keys
already
already
stored
stored
in
in
database.
database
Now
now
that
that
we
we
can
can
generate
generate
an
an
API
api
key,
key
we
we
can
can
go
go
back
back
into
into
our
our
webhook
webhook
handler
handler
and
and
implement
implement
the
the
code
code
for
for
checkout
checkout
session
session
completed.
completed
The
the
code
code
here
here
will
will
be
be
very
very
application
application
specific,
specific
but
but
the
the
gist
gist
of
of
it
it
is
is
that
that
we'll
we'll
generate
generate
an
an
API
api
key
key
and
and
provide
provide
the
the
unhashed
unhashed
version
version
to
to
the
the
user
user
while
while
storing
storing
the
the
hashed
hashed
version
version
in
in
our
our
database.
database
To
to
To
to
simulate
simulate
that
that
process,
process
I'm
i'm
just
just
going
going
to
to
console
console
log
log
the
the
values
values
for
for
now.
now
Another
another
thing
thing
I'm
i'm
doing
doing
in
in
this
this
code
code
is
is
grabbing
grabbing
the
the
subscription
subscription
items
items
using
using
the
the
Stripe
stripe
SDK
sdk
from
from
the
the
customer's
customer's
account.
account
Having
having
this
this
value
value
stored
stored
on
on
the
the
server
server
will
will
make
make
it
it
easier
easier
and
and
faster
faster
to
to
report
report
usage
usage
to
to
Stripe
stripe
in
in
the
the
next
next
step.
step
And
and
now,
now
we're
we're
ready
ready
to
to
move
move
on
on
to
to
the
the
final
final
phase,
phase
allowing
allowing
the
the
user
user
to
to
make
make
requests
requests
to
to
the
the
API.
api
Let's
let's
go
go
back
back
to
to
our
our
original
original
API
api
endpoint.
endpoint
The
the
first
first
thing
thing
we'll
we'll
do
do
inside
inside
of
of
it
it
is
is
check
check
to
to
make
make
sure
sure
that
that
an
an
API
api
key
key
is
is
present
present
on
on
the
the
request
request
query
query
and
and
if
if
not,
not
then
then
we'll
we'll
send
send
a
a
400
400
response
response
back.
back
Now,
now
if
if
we
we
do
do
have
have
an
an
API
api
key,
key
we'll
we'll
go
go
ahead
ahead
and
and
hash
hash
it
it
so
so
we
we
can
can
find
find
the
the
matching
matching
value
value
in
in
our
our
database.
database
We
we
can
can
figure
figure
out
out
which
which
customer
customer
is
is
associated
associated
with
with
that
that
API
api
key
key
because
because
we
we
have
have
a
a
collection
collection
with
with
that
that
reverse
reverse
mapping,
mapping
and
and
then
then
we
we
can
can
grab
grab
the
the
customer
customer
details
details
which
which
would
would
contain
contain
things
things
like
like
the
the
user's
user's
account
account
status.
status
In
in
a
a
real
real
API,
api
you'd
you'd
likely
likely
want
want
to
to
cache
cache
this
this
data
data
to
to
make
make
your
your
response
response
times
times
as
as
quick
quick
as
as
possible.
possible
From
from
there,
there
If
if
that
that
customer's
customer's
account
account
is
is
not
not
active,
active
then
then
we'll
we'll
send
send
a
a
not
not
authorized
authorized
response.
response
Otherwise,
otherwise
we're
we're
good
good
to
to
go.
go
When
when
the
the
request
request
is
is
made,
made
we'll
we'll
also
also
want
want
to
to
report
report
this
this
usage
usage
to
to
Stripe,
stripe
which
which
we
we
can
can
do
do
by
by
calling
calling
subscription
subscription
items,
items
create
create
usage
usage
record,
record
pass
pass
in
in
the
the
subscription
subscription
item
item
ID
id
along
along
with
with
a
a
quantity,
quantity
timestamp,
timestamp
and
and
action.
action
In.
in
The
the
increment
increment
value
value
will
will
tell
tell
Stripe
stripe
to
to
increase
increase
the
the
billing
billing
by
by
1
1
from
from
whatever
whatever
it
it
previously
previously
was.
was
Reporting
reporting
usage
usage
like
like
this
this
is
is
not
not
very
very
efficient,
efficient
So
so
you'd
you'd
likely
likely
want
want
to
to
optimize
optimize
it
it
by
by
making
making
this
this
a
a
background
background
job.
job
Now
now
at
at
this
this
point,
point
we
we
can
can
make
make
a
a
request
request
to
to
the
the
API
api
by
by
copying
copying
the
the
user's
user's
API
api
key,
key
which
which
Should
should
be
be
printed
printed
in
in
the
the
console
console
when
when
they
they
finish
finish
their
their
payment
payment
with
with
Stripe
stripe
checkout.
checkout
Go
go
ahead
ahead
and
and
take
take
that
that
value
value
and
and
use
use
it
it
as
as
a
a
query
query
parameter
parameter
in
in
the
the
URL
url
when
when
sending
sending
a
a
request
request
with
with
your
your
HTTP
http
client.
client
Without
without
an
an
API
api
key,
key
you
you
should
should
get
get
an
an
error
error
response.
response
Otherwise,
otherwise
you'll
you'll
get
get
the
the
usage
usage
report
report
back
back
from
from
Stripe.
stripe
As
as
a
a
final
final
touch
touch
to
to
prove
prove
to
to
you
you
that
that
everything
everything
Working
working
as
as
intended,
intended
I
i
created
created
another
another
endpoint
endpoint
to
to
get
get
the
the
current
current
usage
usage
for
for
a
a
customer.
customer
If
if
we
we
go
go
ahead
ahead
and
and
send
send
10
10
requests
requests
with
with
the
the
same
same
API
api
key
key
and
and
then
then
request
request
a
a
usage
usage
report.
report
You
you
can
can
see
see
that
that
the
the
current
current
bill
bill
is
is
currently
currently
1,000¢
1,000¢
or
or
$10.
$10
Congratulations.
congratulations
You
you
just
just
built
built
a
a
$1,000,000,000
$1,000,000,000
API
api
from
from
your
your
mom's
mom's
basement.
basement
Make
make
sure
sure
to
to
check
check
out
out
my
my
full
full
Stripe
stripe
course
course
if
if
you're
you're
serious
serious
about
about
building
building
a
a
payment
payment
solution.
solution
Thanks
thanks
for
for
watching,
watching
and
and
I
i
will
will
see
see
you
you
in
in
the
the
next
next
one.
one
success
The speakers discuss the process of creating an API and managing subscriptions using Stripe and Express. They provide instructions on creating an account, managing subscriptions, and using the Stripe app in node. The importance of protecting code and privacy is emphasized, and the speakers provide guidance on creating a key and testing it locally using Stripe's credit card form. They also discuss generating a custom API key and adjusting usage reports, potentially achieving a $1,000,000 API build from a basement, and requesting a usage report.
Make Money from your API Tutorial
APIs are big business. If you build one that developers love, you've got a $1,000,000,000 startup on your hands. And thanks to modern cloud technology, you can throw a monetized API together in your mom's basement in just a few minutes. In today's video, you'll learn how to, 1, build an API with Node. Js and Express, 2, handle authentication and generate API keys for your users, and 3, monetize it with metered billing subscriptions using Stripe, where the customer is billed for each API request. By the end of the video, you'll stand the steps required to make money from your side hustle API. If you're new here, like and subscribe. And if you wanna learn more about payments, check out my full Stripe course on Fireship IO. Let's start by taking a look at how APIs work from a high level. The owner of the API deploys some code to server. That server might have a bunch of HTTP endpoints that do something useful, like maybe retrieve the current weather from a set of GPS coordinates. At it. Other developers out there want to use this data, but they don't want to have to implement a solution on their own. So they reach out to you for permission to make requests to your server. You say, sure. No problem. Just create an account and put a credit card on file and I will give you an API key. Sounds good. How will this work? Whenever you make a request to my server, just attach this API key and I'll keep track of the number of requests you make each month. How much does one API request cost? It'll cost $1 per request and I'll charge your credit card for the volume of usage at the end of the month. You got yourself a deal. Take my money. To build something like this, we'll need both front end and back end code. On the front And, we'll need a place for a user to add a credit card and manage their subscription details. Luckily, Stripe will host and manage all the front end code for us, which is made possible with a product known as Stripe Checkout that allows us to focus on the back end. Now, even though Stripe makes our lives much easier, there are even more simplified solutions out there like rapid API. If you wanna learn more about it, Anya Kubo has an excellent video about it. It's basically API monetization as a service, but the main drawback is they take a much larger cut of your revenue. What we're doing in this video is more low level, but allows us to keep all of our money minus the Stripe fees. To get started, open up your editor to an empty directory and pull up the terminal. Run npm init y to add node package manager to this folder. The project has only 2 dependencies, expressjs as our web application framework and Stripe to interact with the Stripe API in Node. Js. From there, we'll define our server side code in the index dotjs file. Inside that file, we will import Express, then call it as a function to create a new Express app. The Express app allows you to define multiple HTTP endpoints that can access on the Internet. In a REST API, every endpoint starts with a verb like get, post, put, or delete. As a developer, this allows you to organize your API endpoints based on the actual operation that's taking place there. For example, you would use get if you're just retrieving data, post if you're creating something new and delete if you're removing data. In Express, we can define an API endpoint starting with the verb as a function. In this case, we'll use get and then pass it a URL route where it can be accessed. This will give us a route on HTTP local host 8080/API. The second argument is a callback function that It will be executed anytime somebody tries to access this endpoint on our server. Express will provide us with 2 objects, the request, which contains all the incoming data, and response, which provides a way for us to send data back to the user. On the request, we're going to be looking for an API key that's provided by the end user. And we can find that with the URL's query parameters, which are just variables encoded in the URL that are preceded by a question mark. One side note I wanna make here though is that storing the API key in the URL is not necessarily the best choice. You can also store it in a header, which tends to be a little more secure. But for simplicity's sake, we're just going to store it in the URL. Later in the video, we'll learn how to create and validate custom API keys. But for right now, we'll just go ahead and send a response back to the user that is a string of emojis. That's it. That's all the API does, and we're going to charge people $1 per request to use it. Now to run the express app in node, we'll call app dot listen with a port of 8080. To run this code, pull up the terminal and enter node dot period and you should be able to go to localhost 8080/API in the browser and get a response. Now, when working on code like this, I would highly recommend using an HTTP client like Insomnia. It's a more developer friendly way to manage and test your endpoints. As you can see here, I have a git request going to local host 8080/API and I can easily format my query parameters here as well. Now that we have this awesome API, we need to go out and convince people to pay for it. Always be closing. Always be closing. To handle that, you'll need a Stripe account, then go to the dashboard and make sure that you're in test mode. Find the product screen and create a new product. You can customize the settings however you want. The important thing is that it's a recurring product and that the metered box is checked. You can customize the billing behavior in pretty much any way imaginable, but we're just going to sum up the total amount of usage for each period. When that's done, it It will create a product with a unique product ID and more importantly, a price ID. A product can have multiple prices if you have different billing plans for this particular product. Go ahead and make a note of that price ID, then go to the developers tab and click the button for API keys. In order to interact with Stripe from our Node. Js application, we're going to need our Stripe secret key. We're in test mode, but you still don't want to expose this key publicly, so make sure to keep it safe. Back in the JavaScript, we'll use that key to initialize the Stripe SDK. And now we're ready to move on to phase 2, collect payment information from the user, and subscribe them to a plan. Stripe checkout makes this part incredibly easy. In our API, let's go ahead and create another endpoint called checkout, this time using post, and point it to the checkout route. Make the callback an async function because the Stripe SDK is promise based. When this URL is triggered, it's going to make a request to Stripe to start a new checkout session, and then it will send the details of that session back down to the client. The important part here are the parameters that you pass when creating the session. That will tell Stripe what the user is paying for. In this case, the mode will be subscription And then, we'll put the price ID in the line items array. And lastly, when the checkout session is done, Stripe will redirect back to your website and you can provide 2 different URLs, one for success and one for cancel. Now, let's go ahead and restart the node server, then go to the HTTP client to make a request to the endpoint. Make a post request to checkout And you'll notice we get back a big object here, but the only important thing we need out of it is the URL. This is the URL that we want to direct our end user to. That user will be greeted with a credit card form so they can pay for our API. To test it out locally, Stripe provides a bunch of different testing card numbers. When the form is submitted, Stripe will officially subscribe the user to the plan and charge their credit card on a recurring basis as they use the API. Congratulations. You have your 1st paying customer, but now what? Now that the user is paid, we'll need to generate a custom API key for this user and keep track of their data on our servers. There's a few different parts to this process, but the first thing I wanna focus on is webhooks. A webhook is just an API endpoint on our server that can receive data from Stripe when an important event occurs. At the very least, we'll want to listen to events like when the checkout session has as completed, so we know when the user has paid for the product and also invoice paid and invoice payment failed, so we can keep track of their account status when Stripe charges their actual credit card. Stripe has some boilerplate code to handle webhook securely. Every account has a webhook secret that you'll want to verify to make sure that a webhook was actually sent by Stripe and not being spoofed by a hacker. You can copy and paste this code from the full article on Fireship IO. The The important thing I want to point out is that there's a switch statement down here that listens to different events, so you can implement your own code when that event happens. Now, here's the tricky thing. How do we actually test a webhook locally? Because Stripe has no way to send a webhook to our local host URL. Luckily, Stripe has built a CLI tool that allows you to test webhooks locally. Go ahead and download it onto your system, then run Stripe login to authenticate into it. Once that's done, you can call Stripe listen and forward the events to your local host URL. After it spins up, you'll notice that it prints out a webhook signing secret. Go ahead and copy that value and add it as the signing secret in your webhook code. The event that we want to listen to right now is checkout session completed. Let's go ahead and console log and then fill out that checkout session credit card form. When Stripe handles it, it will trigger a bunch of different webhooks that you can listen to and you'll see those printed out in the terminal. If we go to the terminal for the node server, It should log out the data available in that event. The important things here are the customer ID and subscription ID. Now that we have a subscribed customer, we can move on to phase 3, The creation of a custom API key. You'll need some way to store data about the user and their API key on your servers. You should use your favorite production database for that. But to keep things simple on this demo, I'm just going to store that information in memory. You'll wanna have at least 2 different tables or collections to handle this data. The first one is customers, which contains information about the customer like their Stripe customer ID and the plan that they're subscribed to. The second collection you'll need is a reverse mapping that points an API key to the customer account. You'll want a way to quickly look up a customer based on the API key that they pass in with a request. Now, an important thing to point out here is that an API key is like a password, so you should never store the raw value in your database Because if somebody gets a hold of your database, then they have all your customer API keys and can immediately start exploiting them. To overcome this vulnerability, we need to hash the API key before saving it to the database. A hashing function can take the original API key or password and convert it to a new set of characters that would be useless to a hacker, but at the same time is very easy to compute when you know the real value. It might be overkill for this little demo, But it's a really important concept to understand if you are storing API keys in your own database. Let's take a look at how we can generate an API key with Node. I'm creating a custom function here That's importing the random bytes function from the built in node crypto module. Then I'm using it to generate a random string of characters, which is the value that we'll give to the consumer of the API. Now like I said before, we need to store this value, but we can't store it directly in our database. I'm creating a second function to hash it, which uses that createhash function from nodecrypto. With this function, you first specify an algorithm like md5, then provide it with the value you want to hash, and we'll tell it to return a string using digesthex. The hashed API key is now safe to store in the database. And as one final touch, we'll make this a recursive function to verify that there aren't any duplicate API keys already stored in database. Now that we can generate an API key, we can go back into our webhook handler and implement the code for checkout session completed. The code here will be very application specific, but the gist of it is that we'll generate an API key and provide the unhashed version to the user while storing the hashed version in our database. To To simulate that process, I'm just going to console log the values for now. Another thing I'm doing in this code is grabbing the subscription items using the Stripe SDK from the customer's account. Having this value stored on the server will make it easier and faster to report usage to Stripe in the next step. And now, we're ready to move on to the final phase, allowing the user to make requests to the API. Let's go back to our original API endpoint. The first thing we'll do inside of it is check to make sure that an API key is present on the request query and if not, then we'll send a 400 response back. Now, if we do have an API key, we'll go ahead and hash it so we can find the matching value in our database. We can figure out which customer is associated with that API key because we have a collection with that reverse mapping, and then we can grab the customer details which would contain things like the user's account status. In a real API, you'd likely want to cache this data to make your response times as quick as possible. From there, If that customer's account is not active, then we'll send a not authorized response. Otherwise, we're good to go. When the request is made, we'll also want to report this usage to Stripe, which we can do by calling subscription items, create usage record, pass in the subscription item ID along with a quantity, timestamp, and action. In. The increment value will tell Stripe to increase the billing by 1 from whatever it previously was. Reporting usage like this is not very efficient, So you'd likely want to optimize it by making this a background job. Now at this point, we can make a request to the API by copying the user's API key, which Should be printed in the console when they finish their payment with Stripe checkout. Go ahead and take that value and use it as a query parameter in the URL when sending a request with your HTTP client. Without an API key, you should get an error response. Otherwise, you'll get the usage report back from Stripe. As a final touch to prove to you that everything Working as intended, I created another endpoint to get the current usage for a customer. If we go ahead and send 10 requests with the same API key and then request a usage report. You can see that the current bill is currently 1,000¢ or $10. Congratulations. You just built a $1,000,000,000 API from your mom's basement. Make sure to check out my full Stripe course if you're serious about building a payment solution. Thanks for watching, and I will see you in the next one.
The speakers discuss the process of creating an API and managing subscriptions using Stripe and Express. They provide instructions on creating an account, managing subscriptions, and using the Stripe app in node. The importance of protecting code and privacy is emphasized, and the speakers provide guidance on creating a key and testing it locally using Stripe's credit card form. They also discuss generating a custom API key and adjusting usage reports, potentially achieving a $1,000,000 API build from a basement, and requesting a usage report.

        [INST]
        You are youtuber called Fireship you make engaging high-intensity and entertaining coding tutorials and tech news. 
        you covers a wide range of topics relevant to programmers, aiming to help them learn and improve their skills quickly.
        
        Given the title of the video : Make Money from your API Tutorial 
        and a small summary : The speakers discuss the process of creating an API and managing subscriptions using Stripe and Express. They provide instructions on creating an account, managing subscriptions, and using the Stripe app in node. The importance of protecting code and privacy is emphasized, and the speakers provide guidance on creating a key and testing it locally using Stripe's credit card form. They also discuss generating a custom API key and adjusting usage reports, potentially achieving a $1,000,000 API build from a basement, and requesting a usage report.
        [/INST]
        
        Generate the video : APIs are big business. If you build one that developers love, you've got a $1,000,000,000 startup on your hands. And thanks to modern cloud technology, you can throw a monetized API together in your mom's basement in just a few minutes. In today's video, you'll learn how to, 1, build an API with Node. Js and Express, 2, handle authentication and generate API keys for your users, and 3, monetize it with metered billing subscriptions using Stripe, where the customer is billed for each API request. By the end of the video, you'll stand the steps required to make money from your side hustle API. If you're new here, like and subscribe. And if you wanna learn more about payments, check out my full Stripe course on Fireship IO. Let's start by taking a look at how APIs work from a high level. The owner of the API deploys some code to server. That server might have a bunch of HTTP endpoints that do something useful, like maybe retrieve the current weather from a set of GPS coordinates. At it. Other developers out there want to use this data, but they don't want to have to implement a solution on their own. So they reach out to you for permission to make requests to your server. You say, sure. No problem. Just create an account and put a credit card on file and I will give you an API key. Sounds good. How will this work? Whenever you make a request to my server, just attach this API key and I'll keep track of the number of requests you make each month. How much does one API request cost? It'll cost $1 per request and I'll charge your credit card for the volume of usage at the end of the month. You got yourself a deal. Take my money. To build something like this, we'll need both front end and back end code. On the front And, we'll need a place for a user to add a credit card and manage their subscription details. Luckily, Stripe will host and manage all the front end code for us, which is made possible with a product known as Stripe Checkout that allows us to focus on the back end. Now, even though Stripe makes our lives much easier, there are even more simplified solutions out there like rapid API. If you wanna learn more about it, Anya Kubo has an excellent video about it. It's basically API monetization as a service, but the main drawback is they take a much larger cut of your revenue. What we're doing in this video is more low level, but allows us to keep all of our money minus the Stripe fees. To get started, open up your editor to an empty directory and pull up the terminal. Run npm init y to add node package manager to this folder. The project has only 2 dependencies, expressjs as our web application framework and Stripe to interact with the Stripe API in Node. Js. From there, we'll define our server side code in the index dotjs file. Inside that file, we will import Express, then call it as a function to create a new Express app. The Express app allows you to define multiple HTTP endpoints that can access on the Internet. In a REST API, every endpoint starts with a verb like get, post, put, or delete. As a developer, this allows you to organize your API endpoints based on the actual operation that's taking place there. For example, you would use get if you're just retrieving data, post if you're creating something new and delete if you're removing data. In Express, we can define an API endpoint starting with the verb as a function. In this case, we'll use get and then pass it a URL route where it can be accessed. This will give us a route on HTTP local host 8080/API. The second argument is a callback function that It will be executed anytime somebody tries to access this endpoint on our server. Express will provide us with 2 objects, the request, which contains all the incoming data, and response, which provides a way for us to send data back to the user. On the request, we're going to be looking for an API key that's provided by the end user. And we can find that with the URL's query parameters, which are just variables encoded in the URL that are preceded by a question mark. One side note I wanna make here though is that storing the API key in the URL is not necessarily the best choice. You can also store it in a header, which tends to be a little more secure. But for simplicity's sake, we're just going to store it in the URL. Later in the video, we'll learn how to create and validate custom API keys. But for right now, we'll just go ahead and send a response back to the user that is a string of emojis. That's it. That's all the API does, and we're going to charge people $1 per request to use it. Now to run the express app in node, we'll call app dot listen with a port of 8080. To run this code, pull up the terminal and enter node dot period and you should be able to go to localhost 8080/API in the browser and get a response. Now, when working on code like this, I would highly recommend using an HTTP client like Insomnia. It's a more developer friendly way to manage and test your endpoints. As you can see here, I have a git request going to local host 8080/API and I can easily format my query parameters here as well. Now that we have this awesome API, we need to go out and convince people to pay for it. Always be closing. Always be closing. To handle that, you'll need a Stripe account, then go to the dashboard and make sure that you're in test mode. Find the product screen and create a new product. You can customize the settings however you want. The important thing is that it's a recurring product and that the metered box is checked. You can customize the billing behavior in pretty much any way imaginable, but we're just going to sum up the total amount of usage for each period. When that's done, it It will create a product with a unique product ID and more importantly, a price ID. A product can have multiple prices if you have different billing plans for this particular product. Go ahead and make a note of that price ID, then go to the developers tab and click the button for API keys. In order to interact with Stripe from our Node. Js application, we're going to need our Stripe secret key. We're in test mode, but you still don't want to expose this key publicly, so make sure to keep it safe. Back in the JavaScript, we'll use that key to initialize the Stripe SDK. And now we're ready to move on to phase 2, collect payment information from the user, and subscribe them to a plan. Stripe checkout makes this part incredibly easy. In our API, let's go ahead and create another endpoint called checkout, this time using post, and point it to the checkout route. Make the callback an async function because the Stripe SDK is promise based. When this URL is triggered, it's going to make a request to Stripe to start a new checkout session, and then it will send the details of that session back down to the client. The important part here are the parameters that you pass when creating the session. That will tell Stripe what the user is paying for. In this case, the mode will be subscription And then, we'll put the price ID in the line items array. And lastly, when the checkout session is done, Stripe will redirect back to your website and you can provide 2 different URLs, one for success and one for cancel. Now, let's go ahead and restart the node server, then go to the HTTP client to make a request to the endpoint. Make a post request to checkout And you'll notice we get back a big object here, but the only important thing we need out of it is the URL. This is the URL that we want to direct our end user to. That user will be greeted with a credit card form so they can pay for our API. To test it out locally, Stripe provides a bunch of different testing card numbers. When the form is submitted, Stripe will officially subscribe the user to the plan and charge their credit card on a recurring basis as they use the API. Congratulations. You have your 1st paying customer, but now what? Now that the user is paid, we'll need to generate a custom API key for this user and keep track of their data on our servers. There's a few different parts to this process, but the first thing I wanna focus on is webhooks. A webhook is just an API endpoint on our server that can receive data from Stripe when an important event occurs. At the very least, we'll want to listen to events like when the checkout session has as completed, so we know when the user has paid for the product and also invoice paid and invoice payment failed, so we can keep track of their account status when Stripe charges their actual credit card. Stripe has some boilerplate code to handle webhook securely. Every account has a webhook secret that you'll want to verify to make sure that a webhook was actually sent by Stripe and not being spoofed by a hacker. You can copy and paste this code from the full article on Fireship IO. The The important thing I want to point out is that there's a switch statement down here that listens to different events, so you can implement your own code when that event happens. Now, here's the tricky thing. How do we actually test a webhook locally? Because Stripe has no way to send a webhook to our local host URL. Luckily, Stripe has built a CLI tool that allows you to test webhooks locally. Go ahead and download it onto your system, then run Stripe login to authenticate into it. Once that's done, you can call Stripe listen and forward the events to your local host URL. After it spins up, you'll notice that it prints out a webhook signing secret. Go ahead and copy that value and add it as the signing secret in your webhook code. The event that we want to listen to right now is checkout session completed. Let's go ahead and console log and then fill out that checkout session credit card form. When Stripe handles it, it will trigger a bunch of different webhooks that you can listen to and you'll see those printed out in the terminal. If we go to the terminal for the node server, It should log out the data available in that event. The important things here are the customer ID and subscription ID. Now that we have a subscribed customer, we can move on to phase 3, The creation of a custom API key. You'll need some way to store data about the user and their API key on your servers. You should use your favorite production database for that. But to keep things simple on this demo, I'm just going to store that information in memory. You'll wanna have at least 2 different tables or collections to handle this data. The first one is customers, which contains information about the customer like their Stripe customer ID and the plan that they're subscribed to. The second collection you'll need is a reverse mapping that points an API key to the customer account. You'll want a way to quickly look up a customer based on the API key that they pass in with a request. Now, an important thing to point out here is that an API key is like a password, so you should never store the raw value in your database Because if somebody gets a hold of your database, then they have all your customer API keys and can immediately start exploiting them. To overcome this vulnerability, we need to hash the API key before saving it to the database. A hashing function can take the original API key or password and convert it to a new set of characters that would be useless to a hacker, but at the same time is very easy to compute when you know the real value. It might be overkill for this little demo, But it's a really important concept to understand if you are storing API keys in your own database. Let's take a look at how we can generate an API key with Node. I'm creating a custom function here That's importing the random bytes function from the built in node crypto module. Then I'm using it to generate a random string of characters, which is the value that we'll give to the consumer of the API. Now like I said before, we need to store this value, but we can't store it directly in our database. I'm creating a second function to hash it, which uses that createhash function from nodecrypto. With this function, you first specify an algorithm like md5, then provide it with the value you want to hash, and we'll tell it to return a string using digesthex. The hashed API key is now safe to store in the database. And as one final touch, we'll make this a recursive function to verify that there aren't any duplicate API keys already stored in database. Now that we can generate an API key, we can go back into our webhook handler and implement the code for checkout session completed. The code here will be very application specific, but the gist of it is that we'll generate an API key and provide the unhashed version to the user while storing the hashed version in our database. To To simulate that process, I'm just going to console log the values for now. Another thing I'm doing in this code is grabbing the subscription items using the Stripe SDK from the customer's account. Having this value stored on the server will make it easier and faster to report usage to Stripe in the next step. And now, we're ready to move on to the final phase, allowing the user to make requests to the API. Let's go back to our original API endpoint. The first thing we'll do inside of it is check to make sure that an API key is present on the request query and if not, then we'll send a 400 response back. Now, if we do have an API key, we'll go ahead and hash it so we can find the matching value in our database. We can figure out which customer is associated with that API key because we have a collection with that reverse mapping, and then we can grab the customer details which would contain things like the user's account status. In a real API, you'd likely want to cache this data to make your response times as quick as possible. From there, If that customer's account is not active, then we'll send a not authorized response. Otherwise, we're good to go. When the request is made, we'll also want to report this usage to Stripe, which we can do by calling subscription items, create usage record, pass in the subscription item ID along with a quantity, timestamp, and action. In. The increment value will tell Stripe to increase the billing by 1 from whatever it previously was. Reporting usage like this is not very efficient, So you'd likely want to optimize it by making this a background job. Now at this point, we can make a request to the API by copying the user's API key, which Should be printed in the console when they finish their payment with Stripe checkout. Go ahead and take that value and use it as a query parameter in the URL when sending a request with your HTTP client. Without an API key, you should get an error response. Otherwise, you'll get the usage report back from Stripe. As a final touch to prove to you that everything Working as intended, I created another endpoint to get the current usage for a customer. If we go ahead and send 10 requests with the same API key and then request a usage report. You can see that the current bill is currently 1,000¢ or $10. Congratulations. You just built a $1,000,000,000 API from your mom's basement. Make sure to check out my full Stripe course if you're serious about building a payment solution. Thanks for watching, and I will see you in the next one.
        