#rockywearsahat
1 messages · Page 1 of 1 (latest)
Hi, let me help you with this.
Could you please share the code that creates the Checkout Session?
Yea of course, inside of my src/app/ I have /api/checkout_sessions with index.js that has this code in it:
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export default async function handler(req, res) {
if (req.method === "POST") {
try {
const session = await stripe.checkout.sessions.create({
mode: "payment",
payment_method_types: ["card"],
line_items: req?.body?.items ?? [],
success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/cart`,
});
res.status(200).json(session);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader("Allow", "POST");
res.status(405).end("Method Not Allowed");
}
}
I'm not sure if this is necessary but the tutorial that I was following along with to try and get a very basic working example also added a [id].js catch all in that route for if the checkout_sesesion route has an id after with this code in it:
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export default async function handler(req, res) {
const id = req.query.id;
try {
if (!id.startsWith("cs_")) {
throw Error("Incorrect Checkout Session ID");
}
const checkoutSession = await stripe.checkout.sessions.retrieve(id);
res.status(200).json(checkoutSession);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
}
If you get a 404 in your own app it seems that your routing is not correctly configured and it's not related to Stripe.
then finally I'm trying to actually access the checkout page through this function which is run in an on click event on a specific page element:
export const redirectToCheckout = async () => {
const response = await fetch("/api/checkout_sessions", {
method: "POST",
}); //This is the post request I'm confused about, how can I correctly pass the body to this checkout sessions api to create the cart with the correct items and quantities I want in it??
const session = await response.json();
const stripe = await getStripe();
const result = await stripe.redirectToCheckout({ sessionId: session.id });
};
redirectToCheckout() is a deprecated function. Please use checkoutSession.url and redirect the user yourself: https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=checkout#redirect-customers