4

How to Connect Stripe to a Node.js App

 2 years ago
source link: https://blog.bitsrc.io/your-payment-gateway-for-your-next-project-4246452bbadf
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Connect Stripe to a Node.js App

Use Stripe as a Payment Gateway for Your Next Project

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.
1*QVWohvWuWtBI8Aak3rbdFA.png?q=20
your-payment-gateway-for-your-next-project-4246452bbadf
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.

Unlock 10x development with independent components

Building monolithic apps means all your code is internal and is not useful anywhere else. It just serves this one project. And as you scale to more code and people, development becomes slow and painful as everyone works in one codebase and on the same version.

But what if you build independent components first, and then use them to build any number of projects? You could accelerate and scale modern development 10x.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing modular applications. Many teams start by building their Design Systems or Micro Frontends, through independent components. Give it a try →

0*Y0zQ4BTnuoNrwE5n?q=20
your-payment-gateway-for-your-next-project-4246452bbadf
An independent product component: watch the auto-generated dependency graph

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK