I am trying to integrate Stripe’s subscription gateway into my project, however the fetch request failed. The console show error404. Is there any simpler tutorial to integrate Stripe to MERN stack?
Here’s the code of my frontend:
const handleSubscription = async () => {
const stripe = await stripePromise;
const response = await fetch(
"http://localhost:3001/create-subscription",
{
method: "POST",
headers: { "Content-Type": "application/JSON" },
body: JSON.stringify({
priceId: 'price_1POfQjKQg5ex9zFS675yF3KS',
customerEmail: '[email protected]',
}),
}
);
if (!response.ok) {
console.error(`Error: ${response.status}`);
if (response.status === 404) {
console.error('Error: The requested resource was not found.');
} else if (response.status === 500) {
console.error('Error: There was a problem with the server.');
}
return;
}
if (response.status === 409) {
const data = await response.json();
if (data && data.redirectUrl) {
window.location.href = data.redirectUrl;
}
} else {
const session = await response.json();
await stripe.redirectToCheckout({ sessionId: session.id });
}
};
here’s the server code:
app.post('/create-subscription', async (req, res) => {
const { priceId, customerEmail } = req.body;
try {
// Create a new customer if necessary
let customer = await stripe.customers.list({ email: customerEmail, limit: 1 });
if (customer.data.length === 0) {
customer = await stripe.customers.create({ email: customerEmail });
} else {
customer = customer.data[0];
}
// Create the Checkout session
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
customer: customer.id,
line_items: [{
price: priceId,
quantity: 1,
}],
mode: 'subscription',
success_url: 'http://localhost:3000/success',
cancel_url: 'http://localhost:3000/cancel',
});
res.json({ id: session.id });
} catch (error) {
res.status(400).json({ error: { message: error.message } });
}
});
ive already verify that my sever is running, but when i go to the local host it said Cannot GET /
New contributor
user25469053 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.