How to integrate paypal payment gateway in nodejs

In this tutorial i am going to show you, How to integrate paypal payment gateway in nodejs.
Paypal is a very popular payment gateway to send and receive money from other region.
nodejs-paypal-2
So i am here with the tutorial to integrate paypal payment gateway in nodejs.



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

First of all create your paypal app see attached image.
nodejs-paypal

After that you can see your client_id and client_secret to authenticate your paypal request from your server.
nodejs-paypal-1

Create package.json file in your project directory.

package.json

{
  "name": "NodeJs-Paypal",
  "version": "0.0.1",
  "description": "Paypal Integration using Nodejs",
  "dependencies": {
    "body-parser": "^1.13.2",
    "express": "^4.13.1",
    "paypal-rest-sdk": "^1.6.0"
  }
}

After that goto your project directory by terminal and run.

$ npm install

This command will read all the dependencies from package.json file and install them in your project directory.

Create html file by which you can set payment information this is just for demonstration purpose.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>INTEGRATE PAYPAL PAYMENT GATEWAY IN NODEJS</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="panel panel-primary" style="width:50%;margin:0 auto; margin-top:10%">
<div class="panel-heading"><h3>Paypal Payment Gateway in NodeJs</h3></div>
<div class="panel-body" style="height:40%; text-align:center;" >
<p class="bg-info" id="msg"></p>
 <form class="form-horizontal" role="form" id="paypalForm" method="post" action="/paynow">
  <div class="form-group">
    <label class="control-label col-sm-2" for="amount">Amount:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" name="amount" placeholder="Enter Amount" required="required" value="10">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="currency">Currency:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" name="currency" placeholder="Enter Currency Type" value="USD" required="required">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="description">Description:</label>
    <div class="col-sm-10">
      <textarea class="form-control" name="description" placeholder="Enter Description">My First Payment</textarea>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button id="send" class="btn btn-primary btn-lg" type="submit">
         <span class="glyphicon glyphicon-send" ></span> Pay Now
      </button>
    </div>
  </div>
</form>
</div>
</div>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>
</html>





Now create your server file.

app.js

/*
 * Author: Rohit Kumar
 * Date: 22-07-2015
 * App Name: Nodejs-Paypal
 * Website: iamrohit.in
 * Description: Program to Integrate paypal payment gateway in nodejs
 */
var http=require('http');
var express    = require("express");
var paypal = require('paypal-rest-sdk');
var bodyParser = require('body-parser');
var app = express();
var port = Number(process.env.PORT || 5000);
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
  extended: true
}));
app.locals.baseurl = 'http://localhost:5000';
 
// paypal auth configuration
var config = {
  "port" : 5000,
  "api" : {
    "host" : "api.sandbox.paypal.com",
    "port" : "",            
    "client_id" : "YOUR TEST CLIENT ID",  // your paypal application client id
    "client_secret" : "YOUR TEST CLIENT SECRET" // your paypal application secret id
  }
}
 
paypal.configure(config.api);
 
// Page will display after payment has beed transfered successfully
app.get('/success', function(req, res) {
  res.send("Payment transfered successfully.");
});
 
// Page will display when you canceled the transaction 
app.get('/cancel', function(req, res) {
  res.send("Payment canceled successfully.");
});
 
app.get('/', function(req, res) {
   res.sendFile(__dirname+'/index.html');
});
 
app.post('/paynow', function(req, res) {
   // paypal payment configuration.
  var payment = {
  "intent": "sale",
  "payer": {
    "payment_method": "paypal"
  },
  "redirect_urls": {
    "return_url": app.locals.baseurl+"/success",
    "cancel_url": app.locals.baseurl+"/cancel"
  },
  "transactions": [{
    "amount": {
      "total":parseInt(req.body.amount),
      "currency":  req.body.currency
    },
    "description": req.body.description
  }]
};
 
  paypal.payment.create(payment, function (error, payment) {
  if (error) {
    console.log(error);
  } else {
    if(payment.payer.payment_method === 'paypal') {
      req.paymentId = payment.id;
      var redirectUrl;
      console.log(payment);
      for(var i=0; i < payment.links.length; i++) {
        var link = payment.links[i];
        if (link.method === 'REDIRECT') {
          redirectUrl = link.href;
        }
      }
      res.redirect(redirectUrl);
    }
  }
});
});
 
// Starting server
var server = http.createServer(app).listen(port, function() {
console.log("Listening on " + port);
});

Finally run your application

$ node app.js

and hit http://localhost:5000 on browser and fill payment details and click on Pay Now button it’ll automatically redirected to paypal with the payment details you filled.

See the working demo and you can also download source code form my github repository.

Hope this example will help you to integrate paypal payment gateway using nodejs.

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.