Making payments using PayPal Node SDK

Licio Lentimo
3 min readJan 22, 2020

Last year, I did a blog post on PayPal integration on Android and I thought I would reciprocate the same for web. In that post, I explained the necessary requirements of creating a PayPal sandbox account before we get into coding. If you haven’t checked it out kindly do so before we get started. But for reference, click here to create a sandbox account. When creating a sandbox account, put any amount of money you want as the initial balance. Afterwards, click on Create App. You can retrieve your ClientID and ClientSecret when you create the app.

Prerequisites

Ensure the following are installed on your machine:

Create a folder in your working directory and give it a name and cd into it. Next, run npm init to create your package.json file. Fill in the prompts appropriately.

Install dependencies

We require the PayPal REST SDK, Express and Ejs for this project. Run the following command to install them:

npm install -- save paypal-rest-sdk express ejs

Creating the web app

Create a file and name it index.js. Paste the code below:

The code snippet above contains our dependencies, ejs as our template engine, a route for our homepage which is index and the app will be running on localhost:3000.

Next, create a folder and name it views and in it create a file and name it index.ejs. This will contain our HTML. Feel free to add styling as you wish. Paste this below:

Head over to the PayPal node SDK Github repository and read through. We are going to copy some code and add it to our index.js file. We need to configure our app with our ClientID and Client Secret which we obtain from our sandbox. Add the following code below the declaration of the dependencies:

paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'your-client-id',
'client_secret': 'your-client-secret'
});

The next methods involve defining our routes. We will add a /pay route to redirect to the PayPal payment window, a /success route where we can add a success message and a /cancel route where we can add a cancel message. Our redirect urls are at the moment localhost:3000 since we are running locally, you can change this once you go live. The full code for the index.js is as below:

Payment window

Also, our values for the product are not dynamic as we have pre-filled them ourselves. You can get the values dynamically if you have a database or get them from your form fields in the HTML. We also have some console.log messages which will be useful in viewing the responses from the server. Run the app using the command node index.js in your terminal. Upon successful payment, the app redirects to /success with the message ‘Success’. Feel free to check out the repository on GitHub here.

--

--

Licio Lentimo

I write content on Android and Web technologies. Currently focusing on Cybersecurity. Find me on liciolentimo.com