CodeSolution

Please wait...

Create rest api to stripe payment gateway in nodeJs and AngularJs/ionic

Create rest api to stripe payment gateway in nodeJs and AngularJs/ionic

@api  @ stripe   @ payment   @ gateway   @ nodejs  @ ionic  @ angularjs  

Stripe Payment Gateway  

Stripe is the best software platform for running an internet business. We handle billions of dollars every year for forward-thinking businesses around the world.

Create rest api in nodejs for stripe payment gateway and implement using angularjs and stripe npm module.

 

Project Structure :

nodeStripe                       // Project directory
   - node_modules                // Npm Package
   -  package-lock.json.         // package-lock.json
   -  package.json.              // package.json
   -  www                        // Forend Side code
   -  server.js.                 // server.js file

Create a new directory, we can run the following command:

mkdir <project name>

then move into the newly created directory:

cd <project name>

then  run this command : 

npm init

and fill this information like that :

package name: (project name)
version: (1.0.0)
description:
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC) 

After creating project install node package run command:

npm install --save express mongoose morgan body-parser method-override stripe

create the server.js file and add this code :

var express = require('express');
var morgan = require('morgan');        
var bodyParser = require('body-parser'); 
var methodOverride = require('method-override');
var stripe = require('stripe')('*******************************');
var app = express();

//allow cross origin requests
app.use(function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Max-Age", "3600");
    res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    next();
});
// configuration
app.use(express.static(__dirname + '/www'));                 // set the static files location /public/img will be /img for users
app.use(morgan('dev'));              
app.use(bodyParser.json({limit: '50mb'}));                          // log every request to the console
app.use(bodyParser.urlencoded({limit: '50mb','extended':'true'}));            // parse application/x-www-form-urlencoded                                // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json

app.get('/', function (req, res) {
  res.sendfile('./www/index.html')
})

app.post('/api/checkout', function(req, res) {
  console.log(req.body);
    var token = req.body.token;
    var chargeAmount = req.body.amount;
    var discription = req.body.discription;
    let amount = chargeAmount;

    stripe.customers.create({
        email: req.body.email,
        card: token
    })
    .then(customer =>
        stripe.charges.create({
          amount,
          description: discription,
          currency: "usd",
          customer: customer.id
    }))
    .then(charge => {
         res.json({"payment":charge, "order": "Done"});
        
    })
    .catch(err => {
        console.log("Error:", err);
        res.status(500).json({error: "Purchase Failed"});
      });
});
app.listen(process.env.PORT || 3000, function(){console.log("App listening on port 3000");});

After Open index.html in www->index.html and modify code

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link rel="manifest" href="manifest.json">

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <!-- <script src="cordova.js"></script> -->
    
    <script type="text/javascript" src="https://js.stripe.com/v2/"></script>
    <script src="lib/angular-stripe-checkout.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/Services/APIServices.js"></script>
    <script src="js/controllers/checkout.js"></script>
  </head>
  <body ng-app="NodeStripe" animation="slide-left-right-ios7" class="platform-android platform-ios platform-cordova platform-webview">
    <ion-nav-view></ion-nav-view>
  </body>
</html>
 

After open app.js in www->js->app.js and modify code

// Ionic Starter App
Stripe.setPublishableKey("****************************");
angular.module('NodeStripe', ['ionic', 'CheckOut.controllers', 'APIModule'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() { 
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})
.directive('stripeForm', ['$window',
   function($window) {
       var directive = { restrict: 'A' };
       directive.link = function(scope, element, attributes) {
           var form = angular.element(element);
           form.bind('submit', function() {
               var button = form.find('button');
               button.prop('disabled', true);
               $window.Stripe.createToken(form[0], function() {
                   button.prop('disabled', false);
                   var args = arguments;
                   scope.$apply(function() {
                       scope.$eval(attributes.stripeForm).apply(scope, args);
                   });
               });
           });
       };
       return directive;
   }
])

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
 
  .state('checkout', {
    url: '/checkout',
    cache: false,
    templateUrl: 'templates/checkout.html',
    controller: 'CheckOutCtrl'
  })

  // if none of the above states are matched, use this as the fallback
  // $urlRouterProvider.otherwise('/welcome');
  $urlRouterProvider.otherwise('/checkout');

});

After open checkout.html in www->Templates->checkout.html and modify code

<ion-view view-title="cart">
  <ion-header-bar class="content">
    <div class="h1 title">Checkout</div>
  </ion-header-bar>
  <ion-content scroll="true"  class="content mainBody"> 
       <form stripe:form="saveCustomer">
        <br /><br />
            <label class="item item-input ">
                    <i class="icon ion-ios-person placeholder-icon" style="font-size: 25px !important;"></i>
                    <input type="text" ng-model="sforms.name" placeholder="Account Holder Name">
                </label>
            <label class="item item-input no_background margin5 topDownText">
                <i class="icon ion-card placeholder-icon" style="font-size: 25px !important;"></i>
                <input type="tel" class="placeholderWhite inputform" data-stripe="number" ng-model="sforms.creditcard" placeholder="Credit Card">
            </label>
            <div class="row no_padding topDownText" style="padding:0px !important;">
                <div class="col col-50 no_padding" style="padding:0px !important;">
                    <label class="item item-input no_background inputform" style="padding-left:0px !important;width: 100%;float: right;">
                        <select data-stripe="exp-month" ng-model="sforms.month" style="width:100% !important; color:rgb(0, 0, 0) !important; border:none !important; height:30px !important;background-color:transparent !important;">
                            <option value="">Month</option>
                             <option value="01">01</option>
                             <option value="02">02</option>
                             <option value="03">03</option>
                             <option value="04">04</option>
                             <option value="05">05</option>
                             <option value="06">06</option>
                             <option value="07">07</option>
                             <option value="08">08</option>
                             <option value="09">09</option>
                             <option value="10">10</option>
                             <option value="11">11</option>
                             <option value="12">12</option>
                        </select>
                    </label>
                </div>
              &nbsp;&nbsp;
                <div class="col col-50 no_padding" style="padding:0px !important;">
                    <label class="item item-input no_background inputform" style="padding-left:0px !important;">
                        <select data-stripe="exp-year" ng-model="sforms.year" style="width:98% !important; color:rgb(0, 0, 0) !important; border:none !important; height:30px !important;background-color:transparent !important;">
                            <option value="">Year</option>
                            <option ng-repeat ="n in range(2018,2030) track by $index" value="{{n}}">{{n}}</option>
                        </select>
                    </label>
                </div>
            </div>
            <label class="item item-input no_background margin5 topDownText">
                <i class="icon ion-ios-locked placeholder-icon" style="font-size: 25px !important;"></i>
                <input type="tel" size="4" class="placeholderWhite inputform" data-stripe="cvc" ng-model="sforms.cvv" placeholder="CVV">
            </label>
            <button  ng-click="checkvalid()" class="button button-block button-positive" style="width: 96%; margin-left: 2%;margin-top: 24px;border-radius: 3px !important;font-size: 20px;">
                NEXT
            </button>
        </form>
  </ion-content>
</ion-view>

After open checkout.js in www->js->controllers->checkout.js and modify code

angular.module('CheckOut.controllers', [])

.controller('CheckOutCtrl', function($scope, $ionicModal, $state, $ionicSlideBoxDelegate, $ionicPopup,  $ionicLoading, APIService) {

  $scope.remeber = true;

$scope.sforms={};

$scope.sforms.name = "CodeSolution";

$scope.sforms.month = "08";

$scope.sforms.creditcard = "4242424242424242";

$scope.sforms.year = "2018";

$scope.sforms.cvv ="123";

$scope.sforms.amount = "20000"; //usd 200

$scope.sforms.user_email = "info@codesolution.co.in";

console.log($scope.sforms);

var id = 1;


$scope.range = function(min, max, step){

        step = step || 1;

        var input = [];

        for (var i = min; i <= max; i += step) input.push(i);

        return input;

    };

    // $scope.range();


$scope.checkvalid = function(){

var Name = $scope.sforms.name;

var MOnth = $scope.sforms.month;

var Card = $scope.sforms.creditcard;

var Year = $scope.sforms.year;

var Cvv = $scope.sforms.cvv;

if(Name==""){

$scope.showAlert("Message", "Name is required");

return false;

}

if(Card==""){

$scope.showAlert("Message","Card Number is required");

return false;

}

if(MOnth==""){

$scope.showAlert("Message","Month is required");

return false;

}

if(Year==""){

$scope.showAlert("Message","Year is required");

return false;

}

if(Cvv==""){

$scope.showAlert("Message","Cvv is required");

return false;

}

$scope.saveCustomer = function(status, response){

console.log(response.id);

var TokenID = response.id;

if(TokenID==undefined || TokenID==null){

var alertPopup = $ionicPopup.alert({

title: '<h5 class="text-center">Enter a valid card number</h5>',

template: ''

});

alertPopup.then(function(res) {

console.log('');

});

return false;

}

$scope.sforms.token = TokenID;

$ionicLoading.show();

APIService.setData({

req_url: 'http://localhost:3000/api/checkout',

data: $scope.sforms

}).then(function(resp) {

$ionicLoading.hide();

console.log(resp.data);

if(resp.data.payment.status=="succeeded"){

var alertPopup = $ionicPopup.alert({

title: '<h5 class="text-center">'+resp.data.payment.outcome.seller_message+'</h5>',

template: ''

});

alertPopup.then(function(res) {

console.log(res);

});


}else{

var alertPopup = $ionicPopup.alert({

title: '<h5 class="text-center">Payment failed.</h5>',

template: ''

});

alertPopup.then(function(res) {


});

}

},function(resp) {

$ionicLoading.hide();

var alertPopup = $ionicPopup.alert({

title: '<h5 class="text-center">Something went wrong please try again later</h5>',

template: ''

});

alertPopup.then(function(res) {

console.log('');

});

});

};

}


$scope.remberUncheck = function(){

if($scope.remeber == false){
$scope.remeber = true;
}
}
})

After open APIServices.js in www->js->Services->APIServices.js and modify code

//Generic service for calling API
angular.module('APIModule', []).factory('APIService', ['$http', function($http) {
    return {
        getData: function(obj){
            var xhr = $http({
                url: obj.req_url,
                method: 'GET',
                data: obj.data,
                headers: {'Content-Type': 'application/json'}
            });
            return xhr;
        },
        setData: function(obj){
            var xhr = $http({
                url: obj.req_url,
                method: 'POST',
                data: obj.data,
                headers: {'Content-Type': 'application/json'}
            });
            return xhr;
        },
        removeData: function(obj){
            var xhr = $http({
                url: obj.req_url,
                method: 'DELETE',
                data: obj.data,
                headers: {'Content-Type': 'application/json'}
            });
            return xhr;
        },
        updateData: function(obj){
            var xhr = $http({
                url: obj.req_url,
                method: 'PUT',
                data: obj.data,
                headers: {'Content-Type': 'application/json'}
            });
            return xhr;
        }
    };
}]);

 

Thank you :)

 

Github Link: https://github.com/Sudarshan101/nodeStripe

See demo: https://www.youtube.com/watch?v=M55MdfJmRmA

Comments 0

Reply

>