PayPal Checkout Integration with React

paypal

Inhaltsübersicht

In this article, we will learn how to integrate PayPal Checkout with React Hooks. However, if you prefer Stripe, here’s Stripe integration with React article we wrote. 

You may also be interested in: „Unimedia’s latest project, Zellar, goes live!“

What is PayPal Checkout?

PayPal checkout seamlessly integrates PayPal’s popular online payments system into your Web App, leveraging the PayPal JavaScript SDK.

Goal

Our goal today is to learn the following tasks:

1. Integrate PayPal Javascript SDK using the PayPay React components wrapper.

2. How to create a sample product. 

3. Successfully integrate that product in our React.js App.

3. Successfully redirect to the PayPal Checkout page and record responses.

Prerequisites

1. Install PayPal CheckOut React Components Package

Using the direct PayPal SDK with our react app can be tasking which is why PayPal created the react package. So let’s get started by creating our react app and installing the package too. 

npx create-react-app react-paypal
npm install @paypal/react-paypal-js
cd react-paypal
npm start

Next, we will be getting essential credentials from the PayPal Developer Page. After signing up,  you will be able to create an app.

paypal

Click the ‘create app’ button and fill in the necessary details. PayPal will provide you with your clientID

paypal checkout

Next, we will be following the documentation of the package to call a sample checkout button.

import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
 
export default function App() {
   return (
       <PayPalScriptProvider options={{ "client-id": "test" }}>
           <PayPalButtons style={{ layout: "horizontal" }} />
       </PayPalScriptProvider>
   );
}

Fill in your client-id to get the sample checkout button shown below. Remember that you should create a .env file for your app credentials if it is a production app.

 if it is a production app.

paypal checkout

2. Create A Product Card

Next, we will be creating a product card inspired by our Stripe examples. 

   <div className="wrapper">
         <div className="product-img">
           <img
             src="https://cdn.pixabay.com/photo/2021/08/15/06/54/sunflower-6546993_1280.jpg"
             alt="SunFlower"
             height="420"
             width="327"
           />
         </div>
         <div className="product-info">
           <div className="product-text">
             <h1>Sunflower</h1>
             <h2>POPULAR HOUSE PLANT</h2>
             <p>
               Sunflowers are usually tall annual or perennial plants.
               <br />
               Each "flower" is actually a
               <br />
               disc made up of tiny flowers,
               <br />
               to better attract pollinators.{" "}
             </p>
           </div>
 
           <div className="product-price-btn">
             <p>
               <span>$20</span>
             </p>
             <button type="submit">
               Buy now
             </button>
           </div>
     </div>
</div>
paypal checkout

3. Integrate PayPal CheckOut into React App

To integrate PayPal checkout into our app, we need to tweak the API provided by PayPal for creating an order, checking approval, and errors.

Before doing that, let’s call a couple of hooks to handle our expected state.

 const [show, setShow] = useState(false);
 const [success, setSuccess] = useState(false);
 const [ErrorMessage, setErrorMessage] = useState(");
 const [orderID, setOrderID] = useState(false);

We will be calling the show useState Hook when our user is ready to buy the product.

Create An Order

// creates a paypal order
 const createOrder = (data, actions) => {
   return actions.order
     .create({
       purchase_units: [
         {
           description: "Sunflower",
           amount: {
             currency_code: "USD",
             value: 20,
           },
         },
       ],
       // not needed if a shipping address is actually needed
       application_context: {
         shipping_preference: "NO_SHIPPING",
       },
     })
     .then((orderID) => {
       setOrderID(orderID);
       return orderID;
     });
 };

Check Approval

// check Approval
 const onApprove = (data, actions) => {
   return actions.order.capture().then(function (details) {
     const { payer } = details;
     setSuccess(true);
   });
 };

Check Errors

//capture likely error
 const onError = (data, actions) => {
   setPaypalErrorMessage("An Error occured with your payment ");
 };

Here’s our App.js file in its entirety.

import React, { useState } from "react";
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
import "./App.css";
 
export default function App() {
 const [show, setShow] = useState(false);
 const [success, setSuccess] = useState(false);
 const [ErrorMessage, setErrorMessage] = useState(");
 const [orderID, setOrderID] = useState(false);
 
 // creates a paypal order
 const createOrder = (data, actions) => {
   return actions.order
     .create({
       purchase_units: [
         {
           description: "Sunflower",
           amount: {
             currency_code: "USD",
             value: 20,
           },
         },
       ],
       // not needed if a shipping address is actually needed
       application_context: {
         shipping_preference: "NO_SHIPPING",
       },
     })
     .then((orderID) => {
       setOrderID(orderID);
       return orderID;
     });
 };
 
 // check Approval
 const onApprove = (data, actions) => {
   return actions.order.capture().then(function (details) {
     const { payer } = details;
     setSuccess(true);
   });
 };
 //capture likely error
 const onError = (data, actions) => {
   setErrorMessage("An Error occured with your payment ");
 };
 return (
   <PayPalScriptProvider
     options={{
       "client-id":",
     }}
   >
     <div>
       <div className="wrapper">
         <div className="product-img">
           <img
             src="https://cdn.pixabay.com/photo/2021/08/15/06/54/sunflower-6546993_1280.jpg"
             alt="SunFlower"
             height="420"
             width="327"
           />
         </div>
         <div className="product-info">
           <div className="product-text">
             <h1>Sunflower</h1>
             <h2>POPULAR HOUSE PLANT</h2>
             <p>
               Sunflowers are usually tall annual or perennial plants.
               <br />
               Each "flower" is actually a
               <br />
               disc made up of tiny flowers,
               <br />
               to better attract pollinators.{" "}
             </p>
           </div>
 
           <div className="product-price-btn">
             <p>
               <span>$20</span>
             </p>
             <button type="submit" onClick={() => setShow(true)}>
               Buy now
             </button>
           </div>
         </div>
       </div>
 
       {show ? (
         <PayPalButtons
           style={{ layout: "vertical" }}
           createOrder={createOrder}
           onApprove={onApprove}
         />
       ) : null}
     </div>
   </PayPalScriptProvider>
 );
}

4. Testing Our PayPal CheckOut React App

Testing our app requires you to create a sandbox account

However, if you find it difficult to create one, you can try our useEffect + console.log method, which we will use to check our orderID and if our success state changed successfully. 

  useEffect(() => {
      if (success) {
        alert("Payment successful!!");
      }
    },
    [success]
  );
 
 console.log(1, orderID);
 console.log(2, success);
 console.log(3, ErrorMessage);

You can find test card numbers provided by Stripe here, which you can use to test the checkout page.

Summary

That’s all for now. We hope you had fun going through the tutorial. With PayPal Checkout, creating a smooth payment process for your React app is a seamless experience. 

You can get the complete code here for reference.


Unimedia Technology

Here at Unimedia Technology we have a team of Cloud Native Developers that can help you develop your most complex AWS and Azure Applications.

Vergessen Sie nicht, dass wir bei Unimedia Experten für neue Technologien sind. Wenden Sie sich an uns, wenn Sie Beratung oder Dienstleistungen benötigen. Wir helfen Ihnen gerne weiter.

Unimedia Technology

Ihr Software-Entwicklungspartner

Wir sind ein innovatives Technologieberatungsunternehmen, das sich auf kundenspezifische Softwarearchitektur und -entwicklung spezialisiert hat.

Unsere Dienstleistungen

Registrieren Sie sich für unsere Updates

Bleiben Sie auf dem Laufenden, bleiben Sie informiert, und lassen Sie uns gemeinsam die Zukunft der Technik gestalten!

Verwandte Lektüre

Tiefer eintauchen mit diesen Artikeln

Entdecken Sie mehr von Unimedia’s Expertenwissen und tiefgreifenden Analysen im Bereich der Softwareentwicklung und Technologie.

Let’s make your vision a reality!

Simply fill out this form to begin your journey towards innovation and efficiency.

Lassen Sie uns Ihre Vision Wirklichkeit werden!

Füllen Sie einfach dieses Formular aus, um Ihre Reise in Richtung Innovation und Effizienz zu beginnen.