PayPal integration in React
Tags: react, paypal, javascript, paymentgateway
Published: 2020-07-14 16:20:05

Often as developers we tend to build services which might require us to get payment from the customers. The best examples could be an e-commerce site. For this purpose we need to integrate a dependable payment gateway in our application. So in this post I'll be writing about how you could integrate PayPal Checkout in your React application and get some money :moneybag::moneybag:.

So let's get going...
And yes, before we start I'd like to recommend you to code along because there are quite a few steps that are to be followed and some could be a bit tricky.
So incase you decide to follow my advice, there are a few links that should be open on your browser to follow up.

* [PayPal Developer Dashboard](https://developer.paypal.com/home/)
* [PayPal Sandbox Dashboard](https://www.sandbox.paypal.com/)

## Creating the React App
Since this is a React app integration, you'd need one to set up the payment gateway. To create a react app, simply write the command
```npx create-react-app paypal``` 
in your terminal and it will create a react app by the name "paypal" for you.

Now with the command `cd paypal` enter the app directory and run the command `npm start` to start a development server on your machine hosting your newly created app on `localhost:3000`.
You should see the following on you browser window.
![React App](https://dev-to-uploads.s3.amazonaws.com/i/bde285pajkisq34busvy.jpg)

Now I'll be making a few changes to the files 
* /src/App.js
* /src/App.css

to get a UI for calling the payment gateway. After which the app would look like
![UI](https://dev-to-uploads.s3.amazonaws.com/i/6gjs4q99d8xkqoc1aaly.jpg)
You can find the code at my [GitHub Repository](https://github.com/coder-KO/React-PayPal).
And we are done with the basic setup. It's time to start exploring the PayPal dashboard now.

## Creating PayPal Sandbox Accounts
Now go to the [PayPal Developer Dashboard](https://developer.paypal.com/home/) create a PayPal account and login with it. By default you'll be redirected to the *My apps & Credentials* section in Sandbox Mode.
![PayPal Dashboard](https://dev-to-uploads.s3.amazonaws.com/i/8vvff6gi3hegj4yf2a27.jpg)
We'll now create two sandbox accounts for testing purposes and mimicking live transactions by going to the *Accounts* tab in the Sandbox section. You'll find two sandbox accounts generated by default in the Sandbox Accounts Section.
![Sandbox Accounts](https://dev-to-uploads.s3.amazonaws.com/i/h6las0shr58tqfiny082.jpg)
We'll create two more for our application. One would be a **Business Account** that will accept payments while the other one would be **Personal Account** through which we'll be making the payments. To create them simply click on 
1. *Create account* 
2. Select the type of account
3. Select your Country/Region
4. Click on *Create*

By default the accounts will be created with terrible looking details. You can Edit them by clicking on the **...** button in the *Manage Accounts* column.
You now have two PayPal Sandbox Accounts to mimic a transaction. But wait, you'll also need a PayPal app to successfully accept a payment, so let's create one.

## Creating a PayPal App
Go back to the *My apps & Credentials* section. Under the *REST API apps* you can see one app generated by default. We'll create one for ourselves. To do this simply
1. Click on the **Create app** button
2. Give a name to your app, I have named it *React-Test*
3. Link it to the Sandbox Business Account you just created
4. Click on **Create**

You'll now get access to the credentials of your app including the **Client ID** and **Secret**. 
![PayPal App](https://dev-to-uploads.s3.amazonaws.com/i/7raovp65pm9vj8cbdz7s.jpg)
Copy them somewhere, we'll be needing them once we get back to coding our react app.  
 
Before moving any further let us login with our Business Sandbox Account in the [PayPal Sandbox Dashboard](sandbox.paypal.com) to check the Business Account Dashboard which would look like this
![sandbox-business-account-dashboard](https://dev-to-uploads.s3.amazonaws.com/i/31a5or7bl2kphhimeckz.jpg)

So now that we have both our sandbox accounts and our PayPal app ready, we can get to the coding part.

## Integrating Smart Payment Buttons
Before writing any code for our component we need to integrate the PayPal Smart Payment Button with our application. To do that go to the */public/index.html* and paste the following code in the **HEAD** tag.
```html
<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&currency=INR"></script>
```
The Client ID is the same that we got on registering our app with PayPal in the above section and yes, don't forget to place the `&currency=YOUR_CURRENCY` after your client ID because it wouldn't work properly without it.

## Creating the ReactPayPal Component
Let us now create out main component, the PayPal component. Starting with a basic functional component template
```js
import React from 'react'

export default function reactPayPal() {
    return (
        <div>
            
        </div>
    )
}
```
Now we will create two states, one to tell if the payment has been made, and the other to catch if an error occurs
```js
  const [paid, setPaid] = React.useState(false);
  const [error, setError] = React.useState(null);
```
Now we'll be using the *useRef* hook to get a mutable paypal ref object.
```js
  const paypalRef = React.useRef();
```
Our next step would be to get the PayPal buttons as soon as the component loads, for which we'll be using the *useEffect* hook
```js
React.useEffect(() => {
    window.paypal
      .Buttons({
        createOrder: (data, actions) => {
          return actions.order.create({
            intent: "CAPTURE",
            purchase_units: [
              {
                description: "Your description",
                amount: {
                  currency_code: "INR",
                  value: 500.0,
                },
              },
            ],
          });
        },
        onApprove: async (data, actions) => {
          const order = await actions.order.capture();
          setPaid(true);
          console.log(order);
        },
        onError: (err) => {
        //   setError(err),
          console.error(err);
        },
      })
      .render(paypalRef.current);
  }, []);
```
The window object contains paypal since we included its script in our index.html earlier. Also this object contains a function called Buttons which are to be rendered. Inside buttons we pass an object and once this is successful it renders the buttons. We have to pass three functions in the object that is to be passed to *Buttons*, they are *createOrder*, *onApprove*, *onError*. You can refer the (docs)[developers.paypal.com/docs] to know more about them.
Once the payment has been made we need to show some confirmation to the user which we'll do using conditional rendering
```js
  // If the payment has been made
  if (paid) {
    return <div>Payment successful.!</div>;
  }

  // If any error occurs
  if (error) {
    return <div>Error Occurred in processing payment.! Please try again.</div>;
  }
```
and we are done. We simply have to call this component in our main App component where we'll be rendering it once the Checkout button is clicked.

## Calling ReactPayPal
So currently we have a static page with a *Checkout* button with our ReactPaypal component ready. We want to get PayPal Smart Payment Buttons to access the PayPal payment gateway once we click checkout. So here I'll be doing some conditional rendering to get this done. 
```jsx
{(checkout === true) 
  ? <div className="payment-div">
    <ReactPayPal 
      total={500}
    />
  </div> 

  :<div>
    <h1>React-PayPal</h1>
    <button onClick={() => {setCheckout(true)}} className="checkout-button">Checkout</button>
  </div>
}
```
To do this I created a state, *checkout* to know whether the Checkout button us clicked.
So we are finally done,:nerd_face: and if everything went well we should see something like this once you click the *Checkout* button
![Final Result](https://dev-to-uploads.s3.amazonaws.com/i/o4t0i9zev11n102x4ky3.jpg)

Hope this article was of some help. The complete code, as I mentioned earlier is available on my repo, so go check it out. {% github coder-KO/React-PayPal no-readme %} Keep coding, and keep enjoying it! :smiley: