Integrating PayPal API with Node.js: A Step-by-Step Guide

Posted by



Integrating PayPal API with Node.js can be a powerful way to accept payments on your website or app. In this tutorial, we will walk you through the steps required to integrate PayPal API with Node.js. Before we get started, make sure you have Node.js installed on your machine.

Step 1: Create a PayPal Developer account

To start using the PayPal API, you will need to create a PayPal Developer account. Go to the PayPal Developer website (https://developer.paypal.com/) and click on the “Sign Up” button to create an account. Once you have signed up, log in to your account and navigate to the “My Apps & Credentials” section.

Step 2: Create an application

In the “My Apps & Credentials” section, click on the “Create App” button to create a new application. Give your application a name and select the Sandbox or Live environment depending on whether you are testing or going live with your integration. Once you have created your application, you will be provided with a Client ID and Secret key that you will need to use in your Node.js application.

Step 3: Install the PayPal SDK

Next, you will need to install the PayPal SDK for Node.js in your project. Open your terminal and run the following command:

npm install paypal-rest-sdk

This will install the PayPal SDK and its dependencies in your Node.js project.

Step 4: Set up a PayPal payment

Now, let’s create a simple example to demonstrate how to set up a PayPal payment using the PayPal SDK in Node.js. Create a new JavaScript file in your project and require the PayPal SDK at the top of the file:

const paypal = require(‘paypal-rest-sdk’);

Next, configure the PayPal SDK with your Client ID and Secret key:

paypal.configure({
mode: ‘sandbox’,
client_id: ‘YOUR_CLIENT_ID’,
client_secret: ‘YOUR_CLIENT_SECRET’
});

Now, let’s create a PayPal payment. Add the following code to your JavaScript file:

const createPayment = (callback) => {
const paymentData = {
intent: ‘sale’,
payer: {
payment_method: ‘paypal’
},
redirect_urls: {
return_url: ‘http://localhost:3000/success’,
cancel_url: ‘http://localhost:3000/cancel’
},
transactions: [{
amount: {
total: ‘10.00’,
currency: ‘USD’
}
}]
};

paypal.payment.create(paymentData, (err, payment) => {
if (err) {
console.error(err);
} else {
const approvalUrl = payment.links.find(link => link.rel === ‘approval_url’).href;
callback(approvalUrl);
}
});
};

In this code snippet, we are creating a new PayPal payment with an intent to make a sale, specifying the payer’s payment method as PayPal, setting up redirect URLs for success and cancel actions, and defining the amount and currency for the transaction.

Step 5: Handle payment approval

Now, let’s set up routes in your Node.js application to handle the approval or cancellation of the PayPal payment. Add the following code to your JavaScript file:

app.get(‘/success’, (req, res) => {
const { paymentId, PayerID } = req.query;

const executePayment = {
payer_id: PayerID
};

paypal.payment.execute(paymentId, executePayment, (err, payment) => {
if (err) {
console.error(err);
} else {
res.send(‘Payment completed successfully’);
}
});
});

app.get(‘/cancel’, (req, res) => {
res.send(‘Payment cancelled’);
});

In these route handlers, we are extracting the payment ID and Payer ID from the query parameters, then executing the payment with the provided Payer ID to complete the transaction. If there is an error, it will be logged to the console. If the payment is successful, a success message will be sent to the client. If the payment is cancelled, a cancellation message will be sent.

Step 6: Test your integration

To test your PayPal integration, start your Node.js server and navigate to the approval URL that was returned when you created the payment. Log in with a PayPal account and complete the payment. You should see the success message on the success route handler.

Congratulations! You have successfully integrated PayPal API with Node.js. You can now customize your integration further by adding payment details, handling errors, and implementing additional features such as refunds and subscriptions. PayPal’s documentation (https://developer.paypal.com/docs/api/overview/) provides a wealth of information on how to use their API effectively. Happy coding!

0 0 votes
Article Rating

Leave a Reply

26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@neoseleka
3 days ago

Thanks from South Africa, this was really helpful

@RAKHIRAI-xw8vk
3 days ago

bro can you make video on ' how to switch from sandbox to live' if you are not able to make it then please guide me

@jmg9509
3 days ago

5:10

@hemalpansuriya4665
3 days ago

Please Help!! Followed same flow but facing below error.
We’re sorry. This seller doesn’t accept payments in your currency. Please return to the seller and choose another way to pay. Thank you in Advance 🙌

@jbcdtv5012
3 days ago

Thanks for the video it helps a lot. I have some question, will it work for more than one product purchase? could you please make tutorial for that? thanks again.

@venkateshJJmaticz
3 days ago

Hi mat, how to do this live mode transfer one account to another account in nodejs

@GL33T
3 days ago

🔥

@leandrodeoliveira6779
3 days ago

Thanks from Brazil
Good video

@phoney_the_Hypo
3 days ago

could you guys
please save this video for future reference

@mostafaedoctor4766
3 days ago

Error: AxiosError: Request failed with status code 403

@phoney_the_Hypo
3 days ago

Superb mate ❤

@lalitkumardev
3 days ago

Thanks for the video really brief and helpful

@juacocos
3 days ago

wow great tutorial !!!

@airacovers.c3
3 days ago

Thanks for this video. but, AxiosError422 Why? :c

@omartaha7105
3 days ago

Thanks for this video. Do you know if it's possible to retrieve all the transactions of my application using this Restful API? and is it time sensitive? I did everything correctly but when I try the endpoint of transaction in Postman, it never shows up

@yyyd6559
3 days ago

how to implement subscription

@bradleygangnou2077
3 days ago

U save my school year , thanks

@mr.key7
3 days ago

bro you are amazing.
But can you explain how to live because it is different from sandbox mode?!

@marfin7.7
3 days ago

Thank you very much for the useful and clear explanation! It helped me a lot in understanding the topic and applying it correctly. I appreciate your effort and time in helping us.

@beautyofworld1700
3 days ago

How to track our item and user after successful payment? item ID and user ID

26
0
Would love your thoughts, please comment.x
()
x