React Logoreact-paypal-express-checkout

react-paypal-express-checkout is a React component library that provides a straightforward way to integrate PayPal Express Checkout into React applications. It acts as a wrapper around PayPal's official JavaScript SDK, abstracting away much of the complexity involved in setting up and handling PayPal payment flows on the client-side.

Key Features and Workflow:

1. Simplified Integration: It allows developers to render a customizable PayPal button with minimal configuration directly within their React components.
2. Client-Side Payment Flow: When a user clicks the PayPal button, the library handles the redirection to PayPal's secure environment for payment authorization.
3. Callbacks: It provides essential callback functions (`onSuccess`, `onCancel`, `onError`) to manage different outcomes of the payment process:
* `onSuccess(paymentData)`: Triggered when the user successfully completes the payment on PayPal. The `paymentData` object contains details about the transaction.
* `onCancel(data)`: Triggered if the user cancels the payment process on the PayPal side.
* `onError(err)`: Triggered if an error occurs during the payment process.
4. Configurable Props: The component accepts various props to configure the payment, such as `amount`, `currency`, `client` (an object containing PayPal client IDs for different environments), `env` (sandbox or production), `commit` (whether to show "Pay Now" or "Continue"), and others.
5. Environment Handling: It supports both 'sandbox' (for testing) and 'production' (for live transactions) environments, allowing easy switching based on development needs.

How it works (under the hood):
The library dynamically loads the PayPal JavaScript SDK (`https://www.paypalobjects.com/api/checkout.js`) and then initializes a PayPal button instance. When the button is clicked, it leverages the PayPal SDK's `paypal.Button.render()` method to open the PayPal payment window or redirect the user.

Prerequisites:
* A PayPal Developer account.
* PayPal Client IDs for both sandbox and production environments, obtained from your PayPal Developer Dashboard.
* Basic understanding of React components and state management.

Installation:
First, install the library using npm or yarn:
```bash
npm install react-paypal-express-checkout
# or
yarn add react-paypal-express-checkout
```
This library significantly reduces the boilerplate code required to implement PayPal Express Checkout, making it a popular choice for React developers looking to add payment functionality to their applications efficiently.

Example Code

import React, { useState } from 'react';
import PaypalExpressBtn from 'react-paypal-express-checkout';

function PayPalButtonComponent() {
  const [paymentStatus, setPaymentStatus] = useState(null);
  const [paymentDetails, setPaymentDetails] = useState(null);

  // --- Configuration for PayPal Button ---
  // Replace with your actual PayPal Client IDs from your PayPal Developer Dashboard
  const client = {
    sandbox: 'YOUR_SANDBOX_CLIENT_ID', 
    production: 'YOUR_PRODUCTION_CLIENT_ID',
  };

  const currency = 'USD';
  const total = 10.00; // The amount to be paid

  // Callback function for a successful payment
  const onSuccess = (payment) => {
    // Congratulation, an error free payment has been received and captured.
    console.log("The payment was successful!", payment);
    setPaymentStatus('success');
    setPaymentDetails(payment);
    // IMPORTANT: Send 'payment' object to your server-side to verify the payment
    // and fulfill the order securely. Do NOT rely solely on client-side success.
  };

  // Callback function if the user cancels the payment
  const onCancel = (data) => {
    console.log('The payment was cancelled!', data);
    setPaymentStatus('cancelled');
    setPaymentDetails(data);
  };

  // Callback function if an error occurs during the payment process
  const onError = (err) => {
    console.error("Error during payment!", err);
    setPaymentStatus('error');
    setPaymentDetails(err);
  };

  // Optional: Specify environment ('sandbox' for testing, 'production' for live payments)
  const env = 'sandbox'; 

  // Optional: Whether to commit payment immediately (true, button says "Pay Now") 
  // or allow user review (false, button says "Continue")
  const commit = true; 

  // Optional: Custom styling for the button
  const style = {
    size: 'responsive', // small, medium, large, responsive
    color: 'gold',      // gold, blue, silver, black
    shape: 'rect',      // pill, rect
    label: 'checkout',  // checkout, credit, pay, buynow, paypal
    tagline: false      // true, false (show "The safer, easier way to pay")
  };

  return (
    <div style={{ maxWidth: '300px', margin: '50px auto', textAlign: 'center', padding: '20px', border: '1px solid #eee', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
      <h2>React PayPal Express Checkout Example</h2>
      <p>Total Amount: <strong>${total.toFixed(2)} {currency}</strong></p>

      <div style={{ marginTop: '20px' }}>
        <PaypalExpressBtn
          env={env}
          client={client}
          currency={currency}
          total={total}
          onSuccess={onSuccess}
          onError={onError}
          onCancel={onCancel}
          commit={commit}
          style={style}
        />
      </div>

      {paymentStatus && (
        <div style={{ marginTop: '30px', padding: '15px', borderTop: '1px solid #eee', textAlign: 'left' }}>
          <h3>Payment Outcome: <span style={{ color: paymentStatus === 'success' ? 'green' : paymentStatus === 'cancelled' ? 'orange' : 'red' }}>{paymentStatus.toUpperCase()}</span></h3>
          {paymentDetails && (
            <pre style={{ backgroundColor: '#f9f9f9', padding: '10px', borderRadius: '4px', overflowX: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
              <code>{JSON.stringify(paymentDetails, null, 2)}</code>
            </pre>
          )}
        </div>
      )}
    </div>
  );
}

export default PayPalButtonComponent;