forked from lamcuongdat/PTUDW-Nhom06-Paypal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (84 loc) · 2.42 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const express = require('express');
const paypal = require('paypal-rest-sdk');
const fs=require('fs');
const exphdbs=require('express-handlebars');
var path=require('path');
const app = express();
app.set('views',path.join(__dirname,"views"));
app.engine('handlebars',exphdbs({defaultLayout:'main'}));
app.set('view engine','handlebars');
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'AXMeJ1HaMiTJqoZAXDezOC_NQtXZjYGH55WmJVTvqtrZgkva2xN1NkPQzR8eFyrUWR6TiK9y3YzWLpws',
'client_secret': 'EDtLfGhK53kOEEbVhTb0kzwcLCwfmRBsgYzTvJ9q3HZ9SgWXL6fGlMWs33hCbKe7RQENxXkGpabYDmok'
});
var items=JSON.parse(fs.readFileSync('items.json'));
var total =0;
for(i = 0;i<items.length;i++)
{
total+=parseFloat(items[i].price)*items[i].quantity;
}
app.get('/', function(req, res){
res.render('index');
});
app.post('/pay',function(req,res){
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": items
},
"amount": {
"currency": "USD",
"total": total.toString()
},
"description": "Hat for the best team ever"
}]
};
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
res.render('cancle');
} else {
for(let i = 0;i < payment.links.length;i++){
if(payment.links[i].rel === 'approval_url'){
res.redirect(payment.links[i].href);
}
}
}
});
});
app.get('/cancle', function(req, res){
res.render('cancle');
});
app.get('/success', (req, res) => {
const payerId = req.query.PayerID;
const paymentId = req.query.paymentId;
const execute_payment_json = {
"payer_id": payerId,
"transactions": [{
"amount": {
"currency": "USD",
"total": total.toString()
}
}]
};
paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
if (error) {
res.render('cancle');
} else {
console.log(JSON.stringify(payment));
res.render('success');
}
});
});
app.get('/cancel', (req, res) => res.send('Cancelled'));
app.listen(3000, function(){
console.log(total);
});