React/PayPal/
2022-10-17T09:39:50.390861Z
Published on
With PayPal Checkout, your customers can complete transactions in just a few steps, using their shipping and billing information already stored securely at PayPal to check out so they don’t have to re-enter it on your site. PayPal Checkout is available to any merchant that has API access, and any customer with a PayPal account can use Checkout for their purchases. PayPal Checkout has many options that support many different checkout flows.
PayPal Developer account
PayPal package
React – PayPal ( npm: @paypal/react-paypal-js )
If you don't have an PayPal Developer account (PayPal Developer) , please proceed with the signup option. otherwise, log in with your existing credentials.
The sandbox provides a shielded space where you can initiate and watch while your apps process PayPal API requests without touching any live PayPal accounts.
The Business Sandbox account is a seller account . This account receives the payments from the clients.
In PayPal developer dashboard go to SANDBOX > click Accounts > Create account
It prompt a popup . In that popup click Create custom account
On the next page , fill the following details .
Account Type > choose Business (Merchant Account)
Email address : <email>
Password : <password>
PayPal balance : <type_some_amount>
After fill the details , click Create account.
To check your account , go to SANDBOX > click Accounts
The Personal account is a Buyer account . Performs test checkout payments using this account .
In PayPal developer dashboard go to SANDBOX > click Accounts > Create account
It prompt a popup . In that popup click Create custom account
On the next page , fill the following details .
Account Type > choose Personal (Buyer Account)
Email address : <email>
Password : <password>
PayPal balance : <type_some_amount>
After fill the details , click Create account.
To check your account , go to SANDBOX > click Accounts
PayPal apps give you sandbox and live credentials that you use to make API calls, build, and test integrations.
In PayPal developer dashboard click My Apps & Credentials > Create App
On the next page , fill the following details
App Name > <your_app_name>
Sandbox Business Account > select a Business account which you created in the Step 2 : Create a sandbox Account
click Create App
PayPal REST APIs use OAuth 2.0 access tokens to authenticate requests. Your access token authorizes you to use the PayPal REST API server.
To generate access token we need Client ID and Secret
In PayPal developer dashboard click My Apps & Credentials
Select app which you created in Step 3: Create an App
Copy Client ID and Secret paste it in a text file locally.
To install React follow the steps in the below reference page.
Ref – How to configure Tailwind CSS with React
Run the following command to create a React project.
1npx create-react-app paypal_checkout
Navigate to the created project directory
1cd paypal_checkout
Add a .env file and add your PayPal Client ID and Secret (i.e, Step 4 : To retrieve the Client ID and Secret )
1CLIENT_ID= <YOUR_CLIENT_ID>
2APP_SECRET= <YOUR_APP_SECRET>
A sample .env file can be found in the following git repository file.
Create a folder named Config under the src folder . After , create config.js file under the Config folder.
Add your PayPal Client ID and Secret (i.e. Step 4 : To retrieve the Client ID and Secret )
1export const CLIENT_ID = process.env.CLIENT_ID || "<YOUR_CLIENT_ID>"
2export const APP_SECRET = process.env.APP_SECRET || "<YOUR_APP_SECRET>"
A sample Config.js file can be found in the following git repository file.
Under the src folder create a folder named Component that contains Checkout.js
Final project structure is given below
In your package.json add the following dependencies
1{
2 "name": "stripe-react",
3 "version": "0.1.0",
4 "private": true,
5 "dependencies": {
6 "@paypal/react-paypal-js": "^7.8.1",
7 ...
8 ...
9 "react-paypal-button-v2": "^2.6.3",
10 "react-router-dom": "^6.3.0"
11}
Import PayPalButtons
from "@paypal/react-paypal-js"
package. It will provide the PayPal checkout.
In Checkout.js add the following code
1import { CLIENT_ID } from '../Config/Config'
2import React, { useState, useEffect } from "react" ;
3import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
4
5const Checkout = () => {
6 const [show, setShow] = useState(false);
7 const [success, setSuccess] = useState(false);
8 const [ErrorMessage, setErrorMessage] = useState("");
9 const [orderID, setOrderID] = useState(false);
10
11 // creates a paypal order
12 const createOrder = (data, actions) => {
13 return actions.order.create({
14 purchase_units: [
15 {
16 description: "Sunflower",
17 amount: {
18 currency_code: "USD",
19 value: 20,
20 },
21 },
22 ],
23 }).then((orderID) => {
24 setOrderID(orderID);
25 return orderID;
26 });
27 };
28
29 // check Approval
30 const onApprove = (data, actions) => {
31 return actions.order.capture().then(function (details) {
32 const { payer } = details;
33 setSuccess(true);
34 });
35 };
36
37 //capture likely error
38 const onError = (data, actions) => {
39 setErrorMessage("An Error occured with your payment ");
40 };
41
42 useEffect(() => {
43 if (success) {
44 alert("Payment successful!!");
45 console.log('Order successful . Your order id is--', orderID);
46 }
47 },[success]);
48
49 return (
50 <PayPalScriptProvider options={{ "client-id": CLIENT_ID }}>
51 <div>
52 <div className="wrapper">
53 <div className="product-img">
54 <img
55 src="https://cdn.pixabay.com/photo/2021/08/15/06/54/sunflower-6546993_1280.jpg"
56 alt="SunFlower"
57 height="320"
58 width="300" />
59 </div>
60 <div className="product-info">
61 <div className="product-text">
62 <h1>Sunflower</h1>
63 </div>
64 <div className="product-price-btn">
65 <p>$20</p>
66 <br></br>
67 <button className='buy-btn' type="submit" onClick={() => setShow(true)}>
68 Buy now
69 </button>
70 </div>
71 </div>
72 </div>
73 <br></br>
74 {show ? (
75 <PayPalButtons
76 style={{ layout: "vertical" }}
77 createOrder={createOrder}
78 onApprove={onApprove}
79 />
80 ) : null}
81 </div>
82 </PayPalScriptProvider>
83 );
84}
85
86export default Checkout
A sample Checkout.js file can be found in the following git repository file.
In App.js add routing for checkout.
1import { BrowserRouter as Router, Routes, Route } from "react-router-dom"
2import CheckoutForm from "./Component/Checkout"
3
4function App() {
5 return (
6 <>
7 <Router>
8 <Routes>
9 <Route exact path='checkout/' index element={<CheckoutForm />} />
10 </Routes>
11 </Router>
12 </>
13 );
14}
15
16export default App;
run the project using following command.
1npm start
After running the command . It will redirect to the browser ( http://localhost:3000 )
In browser check url – http://localhost:3000/checkout/
Click Buy now button ,t will show the PayPal payment buttons and click payment button will redirect to the PayPal payment page
Complete React example in the following github repo.
After running the react application , If we click on the Buy now button, it will show the PayPal payment buttons and click payment button will redirect to the PayPal payment page See the below image:
It will prompt a popup like below
In Payment page , In Email field give your Sandbox Personal account (i.e. created in Step 2: Create a sandbox Account ) and click Log In
After login , It prompt a checkout details . Review it and click
If payment success you will get alert like below
Comments