/
checkout.js
122 lines (108 loc) · 4.18 KB
/
checkout.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const express = require('express');
const router = express.Router();
const stripe = require("stripe")(process.env.STRIPE_TEST_KEY)
// Require database in router
const db = require('../models/index');
const bodyParser = require('body-parser');
const { response } = require('express');
const TAX_RATE = 0.1;
function errorHandling(err) {
console.log();
console.log('There was an error!');
console.log(err);
console.log();
return res.send(500, { error: err });
}
const calculateOrderAmount = (items) => {
const subtotal = items.slice().reduce((acc, obj) => (acc += obj.price), 0).toFixed(2);
const tax = (subtotal * TAX_RATE).toFixed(2);
const total = (parseFloat(subtotal) + parseFloat(tax)).toFixed(2);
// return (subtotal*100);
return ((total*100).toFixed(0)); // returning the total w/ sales tax. fixing to 0 because we only need the two decimal points
}
/*
==============================
CHECKOUT ROUTES
==============================
*/
router.post('/checkout', async (req, res) => {
// TODO - save the data of the user and their order in the database
// console.log(req.body);
const data = req.body;
const amount = calculateOrderAmount(data.items);
await stripe.paymentIntents.create(
{
payment_method_types: ['card'],
amount: amount,
currency: 'usd',
// application_fee_amount: 0 // if there's no application fee then remove it (having it be 0 causes an error)
},
{
stripeAccount: process.env.TEST_CONNET_ACCOUNT_ID,
})
.then( (paymentIntent) => {
try {
return res.send({
publishableKey: process.env.STRIPE_TEST_PUBLISHABLE_KEY,
clientSecret: paymentIntent.client_secret,
});
} catch (err) {
// TODO - handle errors here, would be a server/network error
errorHandling(err);
return res.status(500).send({
error: err.message
});
}
});
});
const webhookSecret = process.env.TEST_WEBHOOK_SECRET; // TEST WEBHOOK
// const webhookSecret = process.env.LIVE_WEBHOOK_SECRET; // LIVE WEBHOOK
const handleSuccessfulPaymentIntent = (connectedAccountId, paymentIntent) => {
// fulfill the purchase logic
console.log('payment intent successfully triggered the webhook!! - idode');
console.log('Connected account id', connectedAccountId);
console.log(JSON.stringify(paymentIntent));
}
// trying to send notif that a new order was made to the local server. that way restarurants can see order and details
router.post('/onlineorders', bodyParser.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers["stripe-signature"];
console.log('webhook request: ', req);
// can grab payment_intent from raw req data to look up the contents of the order
// can grab receipt_email, receipt_url
let event;
try {
event = stripe.webhooks.constructEvent(req.rawBody, sig, webhookSecret);
} catch (err) {
console.log(`❌ Error message: ${err.message}`);
return res.status(400).send(`there's a mf Webhook error!!!: ${err.message}`);
}
// TODO - figure out how to extract items out of webhook event so can pass to restaurant
// TODO - write logic to send to add to order list
switch (event.type) {
case 'payment_intent.succeeded':
// const paymentIntent = event.data.object;
break;
case 'payment_method.attached':
// const paymentMethod = event.data.object;
break;
case 'payment_intent.payment_failed':
break;
case 'charge.succeeded':
const chargeSuccess = event.data.object;
console.log();
console.log('charge.succeeded webhook: ', chargeSuccess);
// retrieve charge ID from stripe API and send to database
// can grab payment_intent from raw req data to look up the contents of the order
//
// can grab receipt_email, receipt_url
break;
case 'charge.failed':
// console.log('charge failed');
break;
default:
return response.status(400).end();
}
// returns a 200 response to acknowledge receipt of the event
res.json({received: true});
});
module.exports = router;