mail
What are Customers, Products and Prices and how to create them in Stripe.
Published on July 16, 2022 . 5 min read
Author : Gautham Vijayan

Introduction

In this post we will see what are customers, products and prices and how to create them in stripe.

Before diving into one time payments and subscriptions in Stripe, we need to understand how we can create a customer in stripe, when a user registers in our application, create a product and price via the Dashboard and the API. All these parameters will be used when trying to create a payment session. So lets look into it.

Stripe needs to have a backend server to create customers, checkout sessions etc.,

Explanation

We are going to use firebase to create a user when user signs up via their email and then create a customer in the stripe dashboard as well. You can use any backend programming language and database to accomplish this task, but I am going to use firebase for ease of development.

If you see carefully, once user registers with our app, we have to create a customer id in stripe and get that customer id and update our data base with the customer id given by stripe. Once we do this, we can attach the customer id to all the payments that the user is going to make inside our application. Its a simple and neat trick and concept which we can use to our advantage.

Code

For all the tutorials I am going to use Next JS (React JS) for the frontend, Firebase for the backend which can be divided as Firebase functions with Node JS and Express JS for serverless functions, Firestore as the database. As said before you can use any backend programming language you want but the concept remains the same.

To setup firebase for your next js or react js project you can view the below article by freecodecamp. We will be using firestore database, email authentication so please make sure you have enabled them in your firebase dashboard.

Free Code Camp Link

I am going to create a new next js project with the following command.

yarn create next-app stripe

With Next JS we can create Node JS apis from the api folder. We will be using it to create all the stripe apis.

I am going to install the required packages which will be stripe , firebase ,react-firebase-hooks and axios.

npm i stripe firebase react-firebase-hooks axios

Now lets start implementing the logic. When a user signs up with his email address, we are going to authenticate the user and register the user details to our firebase firestore database. Then we are going to call the stripe Api to create a customer with the user details like email address, get the customer id and update our firestore document.

So in index.js or any where in your project you can create a form where you can get the user's email and authenticate them and then get those details and add it to the database. Then once we added the data to the database we are going to call the stripe api to create a customer with the email id the user has provided and update our data base.

So first lets create the stripe api. I am going to use the next js given api folder to create a small node js API which we can access in the frontend.The code below will be located in api/stripe.js folder. For the styling I have used bootstrap.

import { db } from "../../public/firebaseconfig"; import { updateDoc, doc } from "@firebase/firestore"; const stripe = require("stripe")( "sk_test_51JdHnKSFyour_key" ); const handler = async (req, res) => { const response = await stripe.customers.create({ email: req.body.email, }); const userRef = doc(db, "users", req.body.uid); await updateDoc(userRef, { stripeCustomerId: response.id, }); res.send({ message: response.id }); }; export default handler;

Now in the frontend of the application which is in pages folder, we create a registration page route to handle the form submission.

/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable @next/next/no-sync-scripts */ import React, { useState, useEffect } from "react"; import { createUserWithEmailAndPassword, signOut } from "firebase/auth"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db } from "../../public/firebaseconfig"; import { setDoc, doc, getDoc } from "@firebase/firestore"; import axios from "axios"; import Head from "next/head"; const Registration = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [userData, setUserData] = useState({}); const [user] = useAuthState(auth); useEffect(() => { getUserData(); }, [user]); const getUserData = async () => { if (user) { const docRef = doc(db, "users", user?.uid); const docSnap = await getDoc(docRef); if (docSnap.exists()) { setUserData(docSnap.data()); } else { console.log("No such document!"); } } }; const handleSubmit = async () => { try { const res = await createUserWithEmailAndPassword(auth, email, password); await setDoc(doc(db, "users", res.user.uid), { email: email, uid: res.user.uid, stripeCustomerId: "", }); // The route here is the node js api route we have used in the //api/stripe.js file. You can provide the server url you have hosted your //stripe node js apis. const response = await axios.post("/api/stripe", { uid: res.user.uid, email: email, }); setUserData({ email: email, stripeCustomerId: response.data.message }); alert("Successfully Created"); } catch (err) { alert(err.message); } }; const logOut = () => { signOut(auth); }; return ( <div> <Head> <link rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossOrigin="anonymous" ></link> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossOrigin="anonymous" ></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossOrigin="anonymous" ></script> </Head> <div className=" d-flex align-items-center justify-content-center" style={{ height: "100vh" }} > {!user ? ( <div> <h2 className="m-2">Stripe Registration Example</h2> <div className="m-2"> <div className="my-3"> <label>Email</label> </div> <input type="text" placeholder="Email or Phone" id="username" value={email} onChange={(e) => setEmail(e.target.value)} style={{ borderRadius: 10, padding: 10 }} /> </div> <div className="m-2"> <div className="my-3"> <label>Password</label> </div> <input type="password" placeholder="Password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} style={{ borderRadius: 10, padding: 10 }} /> </div> <div className="m-2 "> <button onClick={() => handleSubmit()} className="btn btn-primary" > Sign Up </button> </div> </div> ) : ( <div> <h2 className="m-2">Email : {userData?.email}</h2> <h2 className="m-2"> Stripe customerId : {userData?.stripeCustomerId} </h2> <div className="m-2 "> <button onClick={() => logOut()} className="btn btn-danger"> Sign Out </button> </div> </div> )} </div> </div> ); }; export default Registration;

So what are we doing here.

I have given a form where user can enter their login details like email and password then once user has entered the details he will be registered within our auth database and their data will be added to the firestore collection. Once that data is added to the firestore collection we call the stripe api which I have made in the api/stripe.js folder. When we call this api we send the email to stripe api and create a customer in the stripe dashboard. Here we get the customer id as a response and we add the customer id to our user data in our database.

With this concept we have created a registration form where users can register and then their data will be saved in our database along with the function of creating their data in stripe dashboard aswell. We reference their presence in the stripe dashboard with the help of the customer id and set that to the registered user data.

We do this because when we are going to accept a subscription from a user we need to attach this particular customer id to the subscription api.

By this we have successfully learnt how to create a customer in stripe and add that reference to our database.

This can be done in any programming langugage but the underlying logic is this.

Now lets create a product and a price via the stripe dashboard. We can also create products and prices via the stripe api, but we will discuss that in later posts.

Now in stripe dashboard follow as below to create a product.

Stripe-product

If you see carefully here for a price id has been created for this particular product. We will be using this particular price id to create a payment session to get a one time payment from our users in our next post.

While creating a product via the stripe api, we have to call another stripe api to create a price for that particular product. But when creating via the dashboard this additional step is not required.

For example,

app.post("/create_product", (req, res) => { const product = await stripe.products.create({ name:req.body.name, }); res.json({product}) // Here we will get the productID }); app.post("/create_price", (req, res) => { const price = await stripe.prices.create({ unit_amount: req.body.amount, currency: req.body.currency, product: req.body.product // Here we will place the productId To get Price }); res.json({price}) });

The above method will be discussed in another post.

We can also create the customer from the stripe dashboard but the process mentioned in this blog will help you automate your application's integration with stripe, because you cannot manually create millions of customers in stripe.

Conclusion

In this post we have seen how to create a stripe customer and integrate it with our application database and then how to create a product and a price with stripe dashboard.

Lets see in our next post where we get an one time payment from our registered user.

Below is the source code for this post:

GitHub Link

Here is the live demo url:

Demo Link