Stripe API, ReactJS, and Express

Written by jamesonbrown | Published 2018/11/17
Tech Story Tags: javascript | expressjs | react | stripe | tutorial

TLDRvia the TL;DR App

During my time at Lambda School(a 30 week immersive full stack web development and CS program) I was exposed to everything from HTML/CSS, Javascript, ReactJS, ExpressJS, APIs, Python, Django, C, and much more. I learned and explored computer science topics like data structures, algorithms and time complexity. However, the particular topic I wanted to talk about and provide a tutorial on was a task I came across in my Lambda Labs project. Integrating Stripe Checkout with a React client and an Express/Node server.

When using Stripe Checkout there are two routes you can take, one time charge or subscription charge. I will cover the one time charge today. If you are interested in subscription charge, I will cover this in a future article. There is one step you need to do before we start coding. Create a Stripe account. This is a free account that is pretty quick to set up. I will wait here while you get that set up. Head back here once you are at your dashboard.

Awesome so now you should be set up with a Stripe account. Take note the dashboard is in test mode. Keep it here until it’s time to take your project to production. Now let‘s start coding.

Front End/Client

Setup

Let’s start with creating the client. I am going to use create-react-app to boilerplate our React app. Use the commands below in your terminal for setup.

create-react-app stripe-clientcd stripe-clientyarn start

You should now have a development server running in your terminal and be able to view your client in the new browser window. As you make and save changes to your app, the client in your browser will automatically refresh. Next we need to add all our libraries. In a new terminal, use the following commands to install the libraries.

yarn add react-stripe-checkout axios

Next lets create a stripeBtn component. This component will be a button that when clicked will open up the react-stripe-checkout modal. Follow the steps below.

cd srctouch stripeBtn.js

Create React Component

Now copy and paste the following code for this component in the new folder and we will discuss details below.

import React, { Fragment } from "react";import StripeCheckout from "react-stripe-checkout";import axios from "axios";

const stripeBtn = () => {const publishableKey = "pk_test_ZU3mlTy0q00DATc9EyF9A8jX";

const onToken = token => {const body = {amount: 999,token: token};

axios.post("http://localhost:8000/payment", body).then(response => {console.log(response);alert("Payment Success");}).catch(error => {console.log("Payment Error: ", error);alert("Payment Error");});};

return (<StripeCheckoutlabel="Go Premium" //Component button textname="Business LLC" //Modal Headerdescription="Upgrade to a premium account today." panelLabel="Go Premium" //Submit button in modalamount={999} //Amount in cents $9.99token={onToken}stripeKey={publishableKey}image="https://www.vidhub.co" //Pop-in header imagebillingAddress={false}/>);};

export default stripeBtn;

To review what we have done above. We create a variable to hold our publishable key. You get this from your dashboard. From side bar click Developers>API Keys. This key is not a secret and does not need to be placed in an .env file. We have a function onToken() that we will cover in a moment. The component returns a StripeCheckout element that comes from react-stripe-checkout. The props passed are used to customize the modal and other transaction details. Make sure you include the prop stripeKey.

The onToken() function “behind the scenes” sends the card info to Stripe and returns a token object. This object contains limited details about the transaction(card type, last 4 digits, email, etc.) Our function sends this token and the amount to our backend in the body with an axios request to finish the transaction. That is pretty much it. With React being modular, we can import the component in multiple places anywhere on our app. I am including the code below for the App.js where I will import and render our stripeBtn component.

Final Steps and Finalize

import React, { Component } from "react";import logo from "./logo.svg";import "./App.css";import StripeBtn from "./StripeBtn";

class App extends Component {

render() {return (<div className="App"><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><p>Stripe Checkout - ReactJS</p><StripeBtn /></header></div>);}}

export default App;

Head to your browser and checkout your new Stripe component that can be reused anywhere on your project. Check out some screenshots below.

Clicking the button on the left will make the modal appear on the right.

Backend/Server

Setup

Now for our server… the backend. This is where a lot of people start to get nervous. But don’t worry, I am going to make this a painless and easy as possible. Remember our backend is simply receiving the token from the front end and sending it to stripe to complete the payment. Start by navigating to the root of your project in the terminal and run the following commands.

mkdir servercd servertouch server.js

yarn init -y

yarn add express stripe cors dotenv

Inside the server directory we create an index and initialize a yarn project. Setting the -y flag uses the defaults for the project. We then installed some packages we will need like we did in the front end.

Next we will create a .env file that will hold our environment variables. You will want to put .env in your .gitignore file. This is so we are not uploading our sensitive information like API keys to Github or having them available to the public. We will also create a new a routes directory and two new files inside there.

touch .env

mkdir routescd routestouch index.js payment.js

Inside the .env file add STRIPE_SECRET_KEY="YOUR SECRET KEY HERE". Make sure you use your secret key from the sidebar your dashboard(Developers > API Keys). Let’s create the base of your server in /server/servers.js that will be created with Express. Get the code below.

Create Your Server

const express = require("express");const cors = require("cors");const bodyParser = require("body-parser");const dotenv = require("dotenv");

dotenv.config()

const app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());

const configureRoutes = require("./routes")

configureRoutes(app);

app.listen(8000, error => {if (error) throw error;console.log("Server running on port " + 8000);});

Above we import express to create an app/server. Import and configure dotenv to use our environment variables(.env). Apply cors to the app and configure the app with our routes directory. Last step is have your app listen on local server 8000. Now we need to create our /routes/payments.js endpoints. Copy and paste the code below to get started.

Payment Endpoints

const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);

const stripeChargeCallback = res => (stripeErr, stripeRes) => {if (stripeErr) {res.status(500).send({ error: stripeErr });} else {res.status(200).send({ success: stripeRes });}};

const paymentApi = app => {app.get("/", (req, res) => {res.send({message: "Hello Stripe checkout server!",timestamp: new Date().toISOString()});});

app.post("/", (req, res) => {const body = {source: req.body.token.id,amount: req.body.amount,currency: "usd"};stripe.charges.create(body, stripeChargeCallback(res));});

return app;};

module.exports = paymentApi;

At the top we create a stripe instance by passing in our STRIPE_SECRET_KEY from the .env file. Then created a callback that will send a response or error back to front end. Next we will create the endpoints(get, post, etc.) for the payment route. The get request is just your server up and running endpoint. This is whereThe post request creates a body of the token id, amount, and currency. We use our stripe instance to creates a charge by passing in the body object from the client and the callback for the response. This will finalize the purchase and charge the customer once. If you’re looking for a subscription or recurring billing, check out my other post.

Last step is going to be to connect your server.js and the routes. This has already been configured in server.js so simple add in /routes/index.js the below code.

const paymentApi = require("./payment");

const configureRoutes = app => {paymentApi(app);};

module.exports = configureRoutes;

You Made It

That is it. In a terminal cd into /server and run yarn start. This will run the server in local host 8000. Go back to your client in your browser and give your new button a try. Here are a couple cards you can try:

Visa: 4242 4242 4242 4242 — Exp: 01/20 — CVV: 123

Mastercard: 5555 5555 5555 4444 — Exp: 01/20 — CVV: 123

If you run into any issues please message me and I will do my best to help you out. If you enjoyed this, please share and follow me on Github and Twitter. Keep an eye out for future articles like Stripe subscription charges and more. Have an awesome day!


Published by HackerNoon on 2018/11/17