import express from "express";
import ModemPay from "modem-pay";
const modempay = new ModemPay(process.env.MODEMPAY_SECRET_KEY);
const app = express();
const DOMAIN = "http://localhost:7024";
// 1. Create the payment on the server, with the price from your database.
app.post("/checkout", express.urlencoded({ extended: false }), async (req, res) => {
const order = { id: "1042", amount: 2000, title: "Stubborn Attachments" };
const intent = await modempay.paymentIntents.create({
amount: order.amount,
title: order.title,
metadata: { order_id: order.id },
return_url: `${DOMAIN}/success.html`,
cancel_url: `${DOMAIN}/cancel.html`,
});
// 2. Send the customer to pay.
res.redirect(303, intent.data.payment_link);
});
// 3. Mark the order paid when Modem Pay tells you. Use the raw body to check the signature.
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
let event;
try {
event = modempay.webhooks.composeEventDetails(
req.body.toString("utf8"),
req.headers["x-modem-signature"],
process.env.MODEMPAY_WEBHOOK_SECRET,
);
} catch {
return res.status(400).send("Invalid signature");
}
res.sendStatus(200);
if (event.event === "charge.succeeded") {
const orderId = event.payload.metadata?.order_id;
// markOrderPaid(orderId, event.payload.amount)
}
});
app.use(express.static("public"));
app.listen(7024, () => console.log("Running on http://localhost:7024"));