Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3644

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T04:38:08+00:00 2024-11-26T04:38:08+00:00

Integrate a Stripe Payment with React

  • 61k

I have recently implemented the frontend side of an online payment system, and surprisingly it was not as complicated as I had thought. I confess Stripe handled most of it.

The Forntend Side
So, let's create a React app and install the necessary dependencies.

// in a terminal npx create-react-app react-stripe cd react-stripe yarn add @stripe/stripe-js @stripe/react-stripe-js axios 
Enter fullscreen mode Exit fullscreen mode

Next, we need to create a Stripe account to get the publishable key that we’ll use to integrate Stripe into our project.

Note: Stripe has two modes, a test mode for development and a live mode for production. Each mode has its secret and publishable keys. Secret keys are for the backend code and should always be private. Publishable ones are for the frontend code, and they are not as sacred as the secret ones.

Now, to configure Stripe, we need loadStripe from @stripe/stripe-js, Elements from @stripe/react-stripe-js, and a PaymentForm.

// App.js import { loadStripe } from "@stripe/stripe-js"; import { Elements } from "@stripe/react-stripe-js"; import PaymentForm from "./PaymentForm"; // not implemented yet  // when you toggle to live mode, you should add the live publishale key. const stripePromise = loadStripe(STRIPE_PK_TEST);  function App() {   return (     <div className="App">       {/* Elements is the provider that lets us access the Stripe object.           It takes the promise that is returned from loadStripe*/}       <Elements stripe={stripePromise}>         <PaymentForm />        </Elements>     </div>   ); }  export default App; 
Enter fullscreen mode Exit fullscreen mode

In its simplest form, PaymentForm can be like this:

// PaymentForm.js import { CardElement } from "@stripe/react-stripe-js"; import axios from "axios";  const PaymentForm = () => {    const handleSubmit = async (e) => {     e.preventDefault();     // stripe code here   };   return (     <form onSubmit={handleSubmit}>       <CardElement />       <button>BUY</button>     </form>   ); };  export default PaymentForm; 
Enter fullscreen mode Exit fullscreen mode

Now, we need to use Stripe to submit our form.

//PaymentForm.js import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js"; import axios from "axios";  const PaymentForm = () => {   const stripe = useStripe();   const elements = useElements();   const handleSubmit = async (e) => {     e.preventDefault();     if (!stripe || !elements) {       // Stripe.js has not loaded yet. Make sure to disable       // form submission until Stripe.js has loaded.       return;     }     // Get a reference to a mounted CardElement. Elements knows how     // to find your CardElement because there can only ever be one of     // each type of element.     const cardElement = elements.getElement(CardElement);      // use stripe.createToken to get a unique token for the card     const { error, token } = await stripe.createToken(cardElement);      if (!error) {       // Backend is not implemented yet, but once there isn’t any errors,       // you can pass the token and payment data to the backend to complete       // the charge       axios         .post("http://localhost:5000/api/stripe/charge", {           token: token.id,           currency: "EGP",           price: 1000, // or 10 pounds (10*100). Stripe charges with the smallest price unit allowed         })         .then((resp) => {           alert("Your payment was successful");         })         .catch((err) => {           console.log(err);         });     } else {       console.log(error);     }   };    return (     <form onSubmit={handleSubmit}>       <CardElement />       <button>PAY</button>     </form>   ); };  export default PaymentForm; 
Enter fullscreen mode Exit fullscreen mode


Note: I used <CardElement/> here but you can use <CardNumberElement/>, <CardExpiryElement/>, and <CardCvcElement/> and then use elements.getElement(CardNumberElement) to access the card number element.

The Backend Side
For the backend, Stripe supports many languages, but here I'm using Node.js.

Move the React code into a client directory inside stripe-react. Run yarn init so that the outer directory can have the package.json for the backend code and then create server.js.

The project directory should look something like this:

  • react-stripe
    • client (holds all React files).
    • .gitignore
    • package.json
    • server.js
    • yarn.lock

Install the necessary dependencies for the backend:

 yarn add express stripe dotenv cors  yarn add --dev concurrently nodmon 
Enter fullscreen mode Exit fullscreen mode

Add to the outer package.json:

  "scripts": {     "client": "cd client && yarn start",     "server": "nodemon server.js",     "start": "node server.js",     "dev": "concurrently --kill-others-on-fail "yarn server" "yarn client""   }, 
Enter fullscreen mode Exit fullscreen mode

Now, in server.js, create the post api/route that will recieve the payment data and Stripe token from the FE to complete the charge.

require("dotenv").config(); const express = require("express"); const app = express(); const cors = require("cors");  app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cors());  const PORT = process.env.PORT || 5000;  const stripe = require("stripe")(env.process.STRIPE_SECRET_KEY_TEST);  // same api we used in the frondend app.post("/api/stripe/charge", async (req, resp) => {   const { token, currency, price } = req.body;   const charge = await stripe.charges.create({     amount: price,     currency,     source: token,   });    if (!charge) throw new Error("charge unsuccessful"); });  app.listen(PORT, () => {   console.log(`Server running on port: ${PORT}`); }); 
Enter fullscreen mode Exit fullscreen mode

Finally, run yarn dev and use one of these test cards to test the integration.
You should see all the payments under Payments on your Stripe dashboard.

References:
Stripe docs.
Stripe charges.
A more detailed tutorial

beginnersjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.