More Tutorials

PayPal integration with Chargebee.js

Payment Method Helper
Chargebee.js
Payments

PayPal is a preferred global payments platform that enables you to pay safely and get paid online.

This tutorial guides you on the following:

  • Using Chargebee.js to integrate PayPal on your website.
  • Create a subscription after the user checks out post making a purchase.

Gateway prerequisites

Chargebee currently supports the below PayPal services:

  • Braintree. To enable PayPal via Braintree, read more.

  • PayPal Express Checkout. To enable, read more.

  • PayPal Commerce. To enable, read more.

  • Adyen. To enable PayPal via Adyen, read more

Set up Chargebee.js

Include the Chargebee.js script on your page and initialize a Chargebee instance before you start. For the script tag, the Chargebee.init options, and the tearDown() caveat, see Set up Chargebee.js.

Create a Payment Intent

You should create a payment intent before submitting the form to authorize the payments.

payment_intent performs the essential function of tracking different events involved in a transaction. This includes:

  • Automatically changing its status based on the outcome of authorization and capture events.

  • Automatically refunding in case of an error post-payment.

A payment_intent can be created at your server-side using create a payment intent API and returned to the client side. The payment method handler uses the created payment_intent internally to perform authorization.

Here's the sample code to create a payment_intent.

Example:

curl https://{site-name}.chargebee.com/api/v2/payment_intents \
  -u {fullaccess_api_key}: \
  -d  amount=500 \
  -d  currency_code="USD" \
  -d  payment_method_type="paypal_express_checkout"

The above step should be initiated as a request from your frontend.

Frontend code:

function createPaymentIntent() {
  return fetch("/payment-intents", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      amount: 500,
      currency_code: "USD",
      payment_method_type: "paypal_express_checkout",
    }),
  })
    .then(function (response) {
      return response.json();
    })
    .then(function (responseJson) {
      return responseJson.payment_intent;
    });
}

Authorize payment intent

Follow these steps to integrate PayPal payments into your website.

1. Create a container in DOM to load the PayPal button

Create a DOM container to hold and display the PayPal button component.

<div  id='paypal-button'></div>

2. Setup PayPal

Set up PayPal on your checkout page using the below steps:

a. Load PayPal integration

load PayPal integration using cbInstance.load("paypal").

b. Set payment intent

Pass the payment_intent object to paypalHandler.setPaymentIntent(payment_intent).

c. Mount the payment button

Use the paypalHandler.mountPaymentButtonfunction to mount the PayPal button inside the container element. This function takes the query selector for the container element as an input parameter.

Learn more on the customization of the Paypal button.

Once you choose the style, click Copy code.

PayPal Button

Search for paypal.Buttons in the copied code, inside which you will find style object.

PayPal Button Sample code

You need to copy the style object and then use the same in the mountPaymentButton function of Chargebee, refer below snippet:

Example:

cbInstance.load("paypal").then((paypalHandler) => {
			createPaymentIntent().then((payment_intent) => {
				paypalHandler.setPaymentIntent(payment_intent);
				return paypalHandler.mountPaymentButton("#paypal-button", {
					style: {
						shape: "pill",
						color: "blue",
						layout: "horizontal",
						label: "paypal",
					},
				});
			});
});

Learn more on the supported parameters for paypalHandler.mountPaymentButton.

Sample code below:

cbInstance.load("paypal").then((paypalHandler) => {
  createPaymentIntent()
    .then((payment_intent) => {
      paypalHandler.setPaymentIntent(payment_intent);
      return paypalHandler.mountPaymentButton("#paypal-button");
    })
    .then(() => {
      // once button mounted
      return paypalHandler.handlePayment();
    })
    .then((paymentIntent) => {
      // handle success
    })
    .catch((error) => {
      // handle error
    });
});

3. Handle Payment

Use the paypalHandler.handlePayment function to initiate the transaction. The handlePayment function resolves to an authorized payment intent once the user authorizes the payment using the PayPal wallet.

Example for promises and callbacks

cbInstance.load('paypal')
     .then((h) => {
     h.setPaymentIntent(payment_intent);
     h.mountPaymentButton("#paypal_button")
    .then(() => h.handlePayment())
     .then((intent) => console.log("success", intent))
     .catch((error) => console.log("error", error));
    });

Create a subscription (server)

Pass the ID of the successfully authorized payment_intent to Chargebee’s create a subscription API.

curl  https://{site}.chargebee.com/api/v2/customers/__test__8asz8Ru9WhHOJO/subscription_for_items \
     -X POST \
     -u {site_api_key}: \
     -d payment_intent[id]="<Id of authorized payment_intent recieved in last step.>" \
     -d subscription_items[item_price_id][0]="basic-USD" \
     -d subscription_items[billing_cycles][0]=2 \
     -d subscription_items[quantity][0]=1 \
     -d subscription_items[item_price_id][1]="day-pass-USD" \
     -d subscription_items[unit_price][1]=100
Was this tutorial helpful ?
Need more help?

We're always happy to help you with any questions you might have! Click here to reach out to us.