Context: I have an e-commerce website where you can add products to a cart and then checkout and pay using the stripe API. Website is a NodeJS/Express application that uses MongoDB for the database. What I want, though, is when a customer pays for his order, I want the products’ inventory to update. So I have a page where the customer fills out billing info in a form. On the same page I have a script attached that takes the billing information and charges the customer. The script calls the POST request that’s in a route file:
var form = document.getElementById('checkout-form');
form.addEventListener('submit', function(ev) {
// Here, I want to access database inventory to see if there
// is enough products to fulfill customers order. If product is
// sold out then redirect to another page, avoiding
// charging the customer
.
.
.
stripe.createPaymentMethod("card", card)
.then(function(result) {
if (result.error) {
errorHandler(result.error.message);
} else {
orderData.paymentMethodId = result.paymentMethod.id;
return fetch("/pay", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(orderData)
});
}
})
.then(function(result) {
return result.json();
})
.then(function(response) {
if (response.error) {
errorHandler(response.error);
} else {
window.location.href = "/home"
}
}).catch(function(err) {
errorHandler(err.error);
});
});
Below is the POST route from the route file that the script requests:
// POST pay
router.post("/pay", async (req, res) => {
const { paymentMethodId, items, currency } = req.body;
const amount = 1000;
try {
// Create new PaymentIntent with a PaymentMethod ID
// from the client.
const intent = await stripe.paymentIntents.create({
amount,
currency,
// Verify your integration in this guide by
// including this parameter
metadata: {
integration_check: "accept_a_payment"
},
payment_method: paymentMethodId,
error_on_requires_action: true,
confirm: true,
receipt_email: receipt_email
});
console.log("💰 Payment received!");
});
How do I access the mongodb database from the addEventListener that’s in the script from the first block of code so that I can redirect and avoid the POST request that’s in the second block of code so the customer doesn’t get charges if an item is already sold out?