How to Connect Stripe to a Node.js App

Use Stripe as a Payment Gateway for Your Next Project

Adarsh gupta
Bits and Pieces

--

What we will need

  • An account with Stripe.
  • A Node.js server to integrate Stripe. The following steps will guide you through this part.

Setting Up An Express Server

  1. Run npm init to create a package.json file for your project
  2. Run npm i stripe express dotenv to install Stripe, Express, and dotenv.
  3. Create a file called server.js and include the following code:
// Load environment variables from the .env file 
require("dotenv").config()

// Setup express
const express = require("express")
const app = express()
app.use(express.json())

// Setup Stripe
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY)

// This is the list of items we are selling

const storeItems = new Map([
[1, { priceInCents: 10000, name: "JavaScript Tutorial" }],
[2, { priceInCents: 15000, name: "Ultimate CSS tutorial" }],
])

// Start up our server on port 3000
app.listen(3000)

Connecting the Frontend

Before going further, we need to connect our frontend to the server. You can use any libraries like request, Axios, or fetch API. Here we will use fetch:

//we are posting a request using POST to checkout page

fetch("/checkout", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
// Send along all the information about the items
body: JSON.stringify({
items: [
{
id: 1,
quantity: 5,
},
{
id: 2,
quantity: 2,
},
],
}),
})
.then(res => {
if (res.ok) return res.json()
// If there is an error then make sure we catch that
return res.json().then(e => console.error(err))
})
.then(({ url }) => {
// On success redirect the customer to the returned URL
window.location = url
})
.catch(e => {
console.error(e.error)
})

Here, we send a POST request to our backend, saying that we need this many things. Our backend then sends a response. If successful, it will redirect us to the merchant page, else we handle the error.

Key things to remember

  1. If your client and server are in different domains you need to show the exact path or else it will return an error:
//instead of /checkout you need to show
https://yourawesomedomain.com/checkout

2. Never send price information because we can alter the price in the front end and send in our price. To get rid of this you can use any other values like id or name.

Building a bridge from server to client

Right now we can call the /checkout URL, now we need to handle it in the Node.js server.

// Create a post request for /create-checkout-session
app.post("/checkout", async (req, res) => {
try {
// Create a checkout session with Stripe
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
// For each item use the id to get it's details
// Take that information and convert it to Stripe's format
line_items: req.body.items.map(({ id, quantity }) => {
const storeItem = storeItems.get(id)
return {
price_data: {
currency: "usd",
product_data: {
name: storeItem.name,
},
unit_amount: storeItem.priceInCents,
},
quantity: quantity,
}
}),
mode: "payment",
// Set a success and cancel URL we will send customers to
// They are complete urls
success_url: `${process.env.CLIENT_URL}/success.html`,
cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
})

res.json({ url: session.url })
} catch (e) {
// If there is an error send it to the client
res.status(500).json({ error: e.message })
}
})

We have an endpoint that is taking all the item information from our client.

This information is in the form of a JSON object that has an items key which contains an array of items with an id and a quantity.

Firstly we call tripe.checkout.sessions.create which takes a single object containing all the information for checkout:

  1. payment_method_types : This thing means what all are the accepted methods like debit/credit card, Internet banking, etc.
  2. mode : It's more like a monthly/yearly/one-time payment.
  3. success_url: URL after successful payment.
  4. cancel_url: URL after the failed payment
  5. line_items : This is an array of items that the customer is purchasing.
Line List from stripe
  • price_data: This is an object that contains information on the product such as name and price. It is important to note that all prices in Stripe are defined as cents so a 1 dollar item would have a unit_amount of 100.
  • quantity: This is the number of items the customer wants to buy.

One Last step

We need to get the API key in order to connect stripe from our backend. you just need to go to your Stripe account dashboard under the Developers section in the sidebar and click on API Keys.

That's all you need for a successful payment gateway set up for your web application.

While dealing with stripe I would recommend you to always reserve a tab for stripes official documentation, so whenever you get stuck you can just look into it, and believe me they have nice and clean docs.

Conclusion

And there we have it. We’ve connected a payment gateway to our Node.js app. I hope you have found this useful. If so, be sure to like and let me know in the comments.

Build composable frontend and backend

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →

Learn More

--

--