Integrating Paypal REST API with React.js

  • Cubettech
  • React
  • 7 years ago
Integrating Paypal REST API with React.js

With the growing number of JavaScript libraries and architectural approaches, it becomes really difficult to figure out which one would suit our needs, and even whether we need to use one of these or not.

PayPal is the most popular payment gateway used in applications where a transaction has to happen. PayPal payments standard provides payment buttons as a quick and easy solution for accepting payments. It is widely accepted that PayPal is a secure option to accept credit card, debit card, and PayPal payments in your application.

This tutorial is intended to explain, how to integrate PayPal REST API with React.js. Includes two codebases, First one ‘PayPalExpressCheckOut.js’ is the main React component which includes the configuration part. This component can be kept in a common place and can be used anywhere we need to display the PayPal payment button. The second codebase shows an example of how to display the PayPal payment button in your web application.

Get your client ID:

Before you set up and execute payments using the REST API, you need a client ID. The client ID authenticates your account with PayPal.

Setting up Client:

Goto PayPal developer account and create your app to get client_id https://developer.paypal.com

  1. In the client option below, pass the client IDs for sandbox and production (live).
  2. While development set env as sandbox and when goes live set it as production.
  3. In the payment function, we call actions.payment.create() to set up the payment.
  4. In the onAuthorize function, we finalize the payment.
  5. Optionally show a confirmation page.

Codebase 1:  PayPalExpressCheckOut.js

import React from 'react'; import ReactDOM from 'react-dom'; import scriptLoader from 'react-async-script-loader'; import PropTypes from 'prop-types'; class PaypalButton extends React.Component {  constructor(props) {    super(props);    window.React = React;    window.ReactDOM = ReactDOM;    this.state = {      showButton: false,      env: 'sandbox', // Or 'sandbox'      client: {        sandbox:    'xxxxxxxxx', // sandbox client ID        production: 'xxxxxxxxx' // production client ID      },      commit: true, // Show a 'Pay Now' button    };  }  componentDidMount() {    const { isScriptLoaded, isScriptLoadSucceed } = this.props;    if (isScriptLoaded && isScriptLoadSucceed) {      this.setState({ showButton: true });    }  }  componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {    if (!this.state.show) {      if (isScriptLoaded && !this.props.isScriptLoaded) {        if (isScriptLoadSucceed) {          this.setState({ showButton: true });        } else {          console.log('Cannot load Paypal script!');          this.props.onError();        }      }    }  }  render() {    const payment = () => paypal.rest.payment.create(this.props.env, this.props.client, {      transactions: [                    { amount: { total: this.props.total, currency: this.props.currency } },      ],    });    const onAuthorize = (data, actions) => actions.payment.execute().then(() => {      const payment = Object.assign({}, this.props.payment);      payment.paid = true;      payment.cancelled = false;      payment.payerID = data.payerID;      payment.paymentID = data.paymentID;      payment.paymentToken = data.paymentToken;      payment.returnUrl = data.returnUrl;      this.props.onSuccess(payment);    });    let ppbtn = '';    if (this.state.showButton) {      ppbtn = (<paypal.Button.react        env={this.state.env}        client={this.state.client}        payment={payment}        commit        onAuthorize={onAuthorize}        onCancel={this.props.onCancel}      />);    }    return <div>{ppbtn}</div>;  } } PaypalButton.propTypes = {  currency: PropTypes.string.isRequired,  total: PropTypes.number.isRequired,  client: PropTypes.object.isRequired, }; PaypalButton.defaultProps = {  env: 'sandbox',  onSuccess: (payment) => {    console.log('The payment was succeeded!', payment);  },  onCancel: (data) => {    console.log('The payment was cancelled!', data);  },  onError: (err) => {    console.log('Error loading Paypal script!', err);  }, }; export default scriptLoader('https://www.paypalobjects.com/api/checkout.js')(PaypalButton);

Full Example:

Codebase 2:

import React from 'react'; import PaypalExpressBtn from './PayPalExpressCheckOut'; export default class MyApp extends React.Component {    render() {        const onSuccess = (payment) => {            console.log("Your payment was succeeded!", payment);        }                const onCancel = (data) => {            // User pressed "cancel" or close Paypal's popup!            console.log('You have cancelled the payment!', data);        }                const onError = (err) => { // The main Paypal's script cannot be loaded or somethings block the loading of that script!            console.log("Error!", err); // Since the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js" // => sometimes it may take about 0.5 second for everything to get set, or for the button to appear        }                    let currency = 'USD'; // or you can set this value from your props or state          let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout return (            <PaypalExpressBtn currency={currency} total={total} onError={onError} onSuccess={onSuccess} onCancel={onCancel} />        );    }   }

Props / State:

  1. currency: String (Eg: USD) – Required
  2. total: Number (1.00 or 1 – depends on currency) – Required
  3. onError: A callback function (happens when Paypal’s main script cannot be loaded)
  4. onSuccess: A callback function (happens after payment has been finished successfully)
  5. onCancel: A callback function (happens when users press “cancel” or close Paypal’s popup)

Sample Returned Data;

  • onSuccess – the returned payment object will look like:

{paid: true, cancelled: false, payerID: “H8S4CU73PFRAG”, paymentID: “PAY-85JK825PA3216TLESPCDA”, paymentToken: “EC-8JN5188N284574L”, returnUrl: “https://www.sandbox.paypal.com/?paymentId=PAY-85JK825PA3216TLESPCDA&token=EC-8JN5188N284574L&PayerID=K44CU73PFTGH”}

  • onCancel – the returned data object will look like:

{paymentToken: “EC-42A825696K839141X”, cancelUrl: “https://www.sandbox.paypal.com?token=EC-42A825696K839141X”}

Hope you did get to know about How to Integrate Paypal REST API with React.js. We will discuss more about this topic through our upcoming blogs. 

Cubet Techno Labs is a fast-growing, digital transformation solution company that helps you build your customer experience into real practice. With our niche and rich expertise in a wide range of technologies and services like React.js, Laravel, Meteor, Angularjs, Nodejs, Magento, WordPress etc.. 

Learn More From Our Techies

Other Blogs:

 

Table of Contents

    Contact Us

    Contact

    What's on your mind? Tell us what you're looking for and we'll connect you to the right people.

    Let's discuss your project.

    Phone