Skip to content

Instantly share code, notes, and snippets.

@SeraphimSerapis
Created June 9, 2014 11:23
Show Gist options
  • Select an option

  • Save SeraphimSerapis/cafa543ba18bad3e6252 to your computer and use it in GitHub Desktop.

Select an option

Save SeraphimSerapis/cafa543ba18bad3e6252 to your computer and use it in GitHub Desktop.
'use strict';
var express = require('express');
var router = express.Router();
var paypal = require('paypal-rest-sdk');
paypal.configure({
'host': 'api.sandbox.paypal.com',
'client_id': 'AVweyxD7IVfkvMjVS5E0RKTgQCUX7vEWgcfMqbkuKxJdsmMa5_SqpGXlZswl',
'client_secret': 'ED8MlRD5nfwljvkobSt61E7MoIspiU1y5JWNdvK3gbPKwOqRt0X6bRNCBYyX'
});
/* GET home page. */
router.get('/', function (req, res) {
var payment_details = {
'intent': 'sale',
'payer': {
'payment_method': 'paypal'
},
'redirect_urls': {
'return_url': 'http://tim.ngrok.com/return',
'cancel_url': 'http://tim.ngrok.com/cancel'
},
'transactions': [{
'description': 'Test transaction',
'amount': {
'total': '5.00',
'currency': 'USD'
}
}]
};
paypal.payment.create(payment_details, function (error, payment) {
if (!error) {
var redirectUrl;
for (var i=0; i<payment.links.length; i++) {
var link = payment.links[i];
if (link.rel === 'approval_url') {
redirectUrl = link.href;
break;
}
}
req.session.paymentID = payment.id;
res.redirect(redirectUrl);
} else {
res.render('error', {
'title': 'Error when generating payment',
'error': error
});
}
});
});
router.get('/return', function (req, res) {
var paymentID = req.session.id;
var payerID = req.param('PayerID');
var payment_details = {
'payer_id': payerID
};
paypal.payment.execute(paymentID, payment_details, function (error, payment) {
if (!error) {
res.render('output', {
title: 'Payment Success',
params: JSON.stringify(req.body, null, 2),
result: JSON.stringify(payment, null, 2)
});
} else {
console.log(error);
res.render('error', {
'title': 'Error when executing payment',
'error': error
});
}
});
});
router.get('/cancel', function (req, res) {
res.render('output', {
'title': 'Payment got canceled'
});
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment