-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathindex.js
106 lines (87 loc) · 2.7 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
98
99
100
101
102
103
104
105
106
const { Router } = require('express');
const { Transaction } = require('braintree');
const logger = require('debug');
const gateway = require('../lib/gateway');
const router = Router(); // eslint-disable-line new-cap
const debug = logger('braintree_example:router');
const TRANSACTION_SUCCESS_STATUSES = [
Transaction.Status.Authorizing,
Transaction.Status.Authorized,
Transaction.Status.Settled,
Transaction.Status.Settling,
Transaction.Status.SettlementConfirmed,
Transaction.Status.SettlementPending,
Transaction.Status.SubmittedForSettlement,
];
function formatErrors(errors) {
let formattedErrors = '';
for (let [, { code, message }] of Object.entries(errors)) {
formattedErrors += `Error: ${code}: ${message}
`;
}
return formattedErrors;
}
function createResultObject({ status }) {
let result;
if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
result = {
header: 'Sweet Success!',
icon: 'success',
message:
'Your test transaction has been successfully processed. See the Braintree API response and try again.',
};
} else {
result = {
header: 'Transaction Failed',
icon: 'fail',
message: `Your test transaction has a status of ${status}. See the Braintree API response and try again.`,
};
}
return result;
}
router.get('/', (req, res) => {
res.redirect('/checkouts/new');
});
router.get('/checkouts/new', (req, res) => {
gateway.clientToken.generate({}).then(({ clientToken }) => {
res.render('checkouts/new', {
clientToken,
messages: req.flash('error'),
});
});
});
router.get('/checkouts/:id', (req, res) => {
let result;
const transactionId = req.params.id;
gateway.transaction.find(transactionId).then((transaction) => {
result = createResultObject(transaction);
res.render('checkouts/show', { transaction, result });
});
});
router.post('/checkouts', (req, res) => {
// In production you should not take amounts directly from clients
const { amount, payment_method_nonce: paymentMethodNonce } = req.body;
gateway.transaction
.sale({
amount,
paymentMethodNonce,
options: { submitForSettlement: true },
})
.then((result) => {
const { success, transaction } = result;
return new Promise((resolve, reject) => {
if (success || transaction) {
res.redirect(`checkouts/${transaction.id}`);
resolve();
}
reject(result);
});
})
.catch(({ errors }) => {
const deepErrors = errors.deepErrors();
debug('errors from transaction.sale %O', deepErrors);
req.flash('error', { msg: formatErrors(deepErrors) });
res.redirect('checkouts/new');
});
});
module.exports = router;