I have a function called stripe.js as follows
const stripe = require("stripe")(process.env.STRIPE_SECRET_TEST);
exports.handler = async (event, context) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "gbp",
product_data: {
name: "Prunus serrulata",
},
unit_amount: 6000,
},
quantity: 1,
},
],
mode: "payment",
success_url: "/success",
cancel_url: "/cancel",
});
return {
statusCode: 200,
body: JSON.stringify({
id: session.id,
}),
};
};
that is called from the checkout component
import React from "react";
import Stripe from "stripe";
const stripe = Stripe(
"pk_test_51HqgwdGKpDMhyEuL11A63hDc42CNdjZbMH93xDPIumVyYlgGe5byVF9rXhgW0rs64r0uaDjQUqlwOUDXrbTZy9nx00cyCIwiBm"
);
const callApi = () => {
fetch("/api/stripe", {
method: "POST",
})
.then((response) => response.json())
.then((response) => console.log(response))
.then((session) => {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then((result) => {
if (result.err) {
alert(result.err.message);
}
})
.catch((err) => {
console.error("Error:", err);
});
};
const Checkout = () => {
return (
<div>
<form
onSubmit={callApi}
>
<ChkButton>Checkout</ChkButton>
</form>
</div>
);
};
I get this in Stripe: Stripe session
The data is going to stripe successfully but the payment page does not load because I think I have the redirect wrong? Can anyone point me out in the right direction please?
Any help would be much appreciated
I have been following this tutorial https://www.freecodecamp.org/news/serverless-online-payments/ trying to modify it to work in my app but I have only got this far. I have googled it and I have not found a solution and neither in Netlify forums.
session
is currently undefined because you aren't returning theresponse.json()
.Overall, that second .then chain is not necessary as well though I assume you just have it for logging purposes. Try: