Are you facing challenges with NEXT JS and trying to insert the content of a state variable "cart" into the body of a POST request to the STRIPE API? The format of the cart is [{id: 1, amount: 1}, {id: , amount: }.......]
You attempted placing items directly into the API handler (list_items), which worked. However, you're struggling to get your "cart" variable to display there. It seems like you need to include the items in the POST request itself. You tried incorporating an object and JSON.stringify as a property to a line_items variable, but it did not work. Could someone assist?
API handler:
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.send({
error: 'Method needs to be POST',
});
}
const domainURL = 'http://localhost:3000';
// const { quantity, mode, productKey } = req.body;
const pmTypes = ['card'];
const session = await stripe.checkout.sessions.create({
payment_method_types: pmTypes,
mode: 'payment',
locale: 'en',
line_items: the_variable????,
success_url: `${domainURL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainURL}/cart`,
});
res.send({
sessionId: session.id,
});
}
POST request :
const stripeLoader = loadStripe(props.pk);
const redirectToCheckout = async () => {
const stripeClient = await stripeLoader;
const { sessionId } = await fetch('api/checkout_sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body : {????}
}).then((res) => res.json());
stripeClient.redirectToCheckout({ sessionId });
};