Home / Articles / Blog

Paypal payment integration in Next.js
paypalpaymentsnextjsnodejsAPI

Paypal payment integration in Next.js

2 steps to add payments but still a task

Shrey Vijayvargiya

Welcome to the latest blog of iHateReading!

Last week, we explored over 10 payment methods available for developers.

Today, we'll focus on one of the most popular options: PayPal

PayPal is a widely accepted platform utilized across numerous online platforms, including mobile and web applications.

While many are familiar with PayPal, newcomers can refer to the PayPal Developer Documentation for more insights.

Creating a PayPal Developer Account

To get started, follow these steps:

  • Navigate to the PayPal Developer dashboard.
  • Create a new account or log in using your existing PayPal credentials.
  • Go to the API & SDKs section.
  • Create a new PayPal app and grab the newly generated app credentials.

Types of API Keys

PayPal provides two types of API keys:

  • Secret Key: Used to manage client secret projects.
  • Published Key: Used to manage app payments in production (live).

There's no need to memorize the significance of these keys, as you will not be prompted for them frequently.

Reference video

Client-side Paypal Payment Integration

2 ways to integrate the PayPal Pay Now button or Paypal payment on the client side as follows

  • Next.js Server-Side API - Server-side API to invoke Paypal APIs for payments
  • react-paypal-button-v2: npm package to directly add Paypal payment button

Server-side Paypal Payment Integration

Again for the server side, we have a couple of options one 

  • Express.js + Paypal payment API integration, create endpoints for capturing and creating Paypal orders
  • Fast API and Django-like Python frameworks to again create endpoints for creating and capturing order

APIs for creating orders and capturing orders are by default methods and ways to integrate Paypal payments within your app.

We will be invoking the same methods on both the client and server-side to integrate the payments.

So instead of explaining the process individually for client and server, I'll be providing Paypal create and capture methods as well npm package integration within the react app or frontend website.

Create Order

At the time of writing that is 11 Jan 2025, we need to create 2 methods for Paypal payment integration-

  • Install package: Install the paypal package using yarn or npm @paypal/checkout-server-sdk
  • Create Order API - API that takes product details such as currency and amount and other details as well to initiate the Paypal payments, read more
  • Capture Order API - Simply track and return the order status (Failed or Success) don't the basis of the order ID passed as a  param from createOrderApi, read more
text
Create Order API
// Example code for creating an order
import paypal from '@paypal/checkout-server-sdk';

export default async function Handler(req, res) {

  if(req.method != "POST")
    return res.status(404).json({success: false, message: "Not Found"})

  if(!req.body.order_price || !req.body.user_id)
    return res.status(400).json({success: false, message: "Please Provide order_price And User ID"})


  try{
    const PaypalClient = client()
    //This code is lifted from https://github.com/paypal/Checkout-NodeJS-SDK
    const request = new paypal.orders.OrdersCreateRequest()
    request.headers['prefer'] = 'return=representation'
    request.requestBody({
      intent: 'CAPTURE',
      purchase_units: [
        {
          amount: {
            currency_code: 'USD',
            value: req.body.order_price+"",
          },
        },
      ],
    })
    const response = await PaypalClient.execute(request)
    if (response.statusCode !== 201) {
      console.log("RES: ", response)
      return res.status(500).json({success: false, message: "Some Error Occured at backend"})
    }

    ...

    // Your Custom Code for doing something with order
    // Usually Store an order in the database like MongoDB

    ...   

    res.status(200).json({success: true, data: {order}})
  } 
  catch(err){
    console.log("Err at Create Order: ", err)
    return res.status(500).json({success: false, message: "Could Not Found the user"})
  }

}
text
Capture Order API
// Example code for capturing an order

import paypal from '@paypal/checkout-server-sdk';

export default async function Handler(req, res) {

  if(req.method != "POST")
    return res.status(404).json({success: false, message: "Not Found"})

  if(!req.body.orderID)
    return res.status(400).json({success: false, message: "Please Provide Order ID"})

  //Capture order to complete payment
  const { orderID } = req.body
  const PaypalClient = client()
  const request = new paypal.orders.OrdersCaptureRequest(orderID)
  request.requestBody({})
  const response = await PaypalClient.execute(request)
  if (!response) {
    return res.status(500).json({success: false, message: "Some Error Occured at backend"})
  }

  ...

  // Your Custom Code to Update Order Status
  // And Other stuff that is related to that order, like wallet
  // Here I am updateing the wallet and sending it back to frontend to update it on frontend

  ...

  res.status(200).json({success: true, data: {wallet}})
}

Adding APIs on the client side

  • For the client-side simply create server-side API in next.js, inside pages/api/paypal/createOrder and pages/api/paypal/captureOrder
  • For server-side simply add the above given methods inside the route/modules/payment/index.js file and export the methods to create endpoint for the same

Please note while using the createOrderApi and captureOrderApi endpoint invoke the methods in the same order, because createOrderApi will return the id of the order and captureOrderApi will check the order status using the same id.

Paypal Payment npm module

Install the package using yarn or npm

text
yarn add react-paypal-button-v2

react-paypal-button-v2 is the npm module for integrating Paypal payment and handling createOrder and captureOrder directly by passing as the prop.

text
import React from 'react';
import { PayPalButton } from "react-paypal-button-v2";

const PayPalPayment = () => {
    return (
         {
                console.log(error, "Error in payment");
            }}
            onSuccess={(details) => {
                console.log("Transaction completed by " + details.payer.name.given_name);
            }}
            style={{
                backgroundColor: "#000000",
                color: "white", // Changed to white for better contrast
                width: "100%",
            }}
            options={{
                clientId: process.env.paypalClientId,
                disableFunding: "card",
            }}
        />
    );
};

Below are the props taken by the react-paypal-button-v2 component

Use the props to style the paypal payment button as well remove debit cards and add/remove other options as well.

In production, you need to handle other props such as onError to handle errors efficiently or store the payment failed status in the backend database.

Well, how easy the payment integration has become in 2025 and the open-source world makes things a cakewalk. 

If you are using a paypal account from India you can't collect payments from indian users in that case. Paypal has this policy in India that Buyers and Suppliers can't be of the same origin country. How stupid this whole concept sounds but yeah it is what it is.

Testing Paypal Payments 

A Paypal developer account provides a sandbox for testing payments in test mode or development mode.

The switch box for sandbox and live mode does the same, live your Paypal provided API keys will automatically collect payments in real mode and the sandbox will collect payments in testing mode.

Payment setup is completed and the next part is to test using the test account in sandbox mode.

Similar to how Stripe, Razorpay, PhonePe and all other payment parties work, PayPal provides testing accounts and using them you can easily test the payment payment and test everything from scratch to bottom.

I am not putting everything in detail over here instead posting an article and reference YouTube video to help you with the same.

https://wpforms.com/docs/how-to-test-paypal-payments-before-accepting-real-payments/#test-form

Once this is done, your paypal payments are ready

Frontend vs Backend

One must understand the difference b/w frontend SSR integration and dedicated node server payment API integration.

It depends on the use case, for solo developers we can see SSR next.js payment integration sounds good idea and for the teams and companies node node-based servers sound scalable and secure way of payments.

One can even work smarter and create a dedicated node server and open-source the API for every other current/future project to collect payments.

Reuse the code/API, write once and use it everywhere

That's it

See you in the next one

Summary

Thisblog post explains PayPal payment integration. Developers use PayPal APIs and SDKs.Two key API types exist: secret keys for development and published keys for livepayments. Client-side integration uses react-paypal-button-v2, while server-side integration employs @paypal/checkout-server-sdk within frameworks like Next.js, Express.js, or FastAPI. createOrder and captureOrder APIs manage payment processes. Testing uses PayPal's sandbox environment. Choosing between client-side and server-side integration depends on project needs.Thisblog post explains PayPal payment integration. Developers use PayPal APIs and SDKs.Two key API types exist: secret keys for development and published keys for livepayments. Client-side integration uses react-paypal-button-v2, while server-side integration employs @paypal/checkout-server-sdk within frameworks like Next.js, Express.js, or FastAPI. createOrder and captureOrder APIs manage payment processes. Testing uses PayPal's sandbox environment. Choosing between client-side and server-side integration depends on project needs.

External Links (7)

Explore topics

More in

Weekly letter

Subscribe to iHateReading

Our once-a-week newsletter on programming, jobs, AI, and building products online.

Our once a week newsletter on Programming, Jobs, AI, and Business