#Sebboseb-checkout

1 messages ยท Page 1 of 1 (latest)

ashen siren
#

hello @elder wing! can you share more on what you've tried and the errors you're seeing?

elder wing
#

Hi, yeah, so what I want to do is pass my shopping cart object to the checkout session

#

So first I tried this ```js
async function sendCart(cart) {
const response = await fetch('/api/checkout_sessions', {
method: 'POST',
body: JSON.stringify({cart}),
headers: {
'Content-Type': 'application/json'
}
});
}

#

And that gives me this

#

First one says provisional headers are shown

#

I've also tried this one ```js
const handleClick = async (e) => {
e.preventDefault();

try {
  const res = await axios.post(
    '/api/checkout_sessions',
    {
      murloc: "Warleader",
    },
  );
} catch (e) {}

};
+ this{
headers: {
"Content-Type": "application/json",
},
},```

#

But the problem is that I don't know if I'm messing up the POST or how I'm trying to implement the data in the checkou_sessions file

#

But I've also only managed to be redirected when using your example button that's just ```js
<form action="/api/checkout_sessions" method="POST">

ashen siren
#

can you share the exact error message received?

elder wing
#

In the console I'm just getting POST http://localhost:3000/api/checkout_sessions 400 (Bad Request) but then in the network tab I'm getting

#
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 { murloc } = req.body;
            // Create Checkout Sessions from body params.
            const session = await stripe.checkout.sessions.create({
                shipping_address_collection: {
                    allowed_countries: ['SE'],
                },
                line_items: [
                    {
                        // Provide the exact Price ID (for example, pr_1234) of the product you want to sell
              
                        quantity: 1,
                        currency: 'sek',
                        amount: 1000,
                        name: "murloc.namn"
                    },],
                mode: 'payment',
                success_url: `${req.headers.origin}/?success=true`,
                cancel_url: `${req.headers.origin}/?canceled=true`,
            });
            res.redirect(303, session.url);
        } catch (err) {
            res.status(err.statusCode || 500).json(err.message);
        }
    } else {
        res.setHeader('Allow', 'POST');
        res.status(405).end('Method Not Allowed');
    }
}
``` This is my entire checkout_sessions
ashen siren
#

If you're using an XMLHTTPRequest(e.g., Axios.post) to get the URL for the CheckoutSession, it's not possible to redirect directly from the sever that way. That approach only works if you're doing what is described in Stripe's docs โ€” calling that backend /create-checkout-session route from the action of a <form> : https://stripe.com/docs/billing/subscriptions/checkout#create-session

So you could change your code to just have the form action be that route, and get rid of the handleClick function and that usage of Axios entirely.

Or if you don't want to use a form submission and instead want to use an Ajax approach like Axios, what I'd suggest instead is your backend should just return the URL as part of the response body (e.g. res.json({"url":session.url}; instead of res.redirect) and do the redirect in JavaScript by setting window.location (e.g. let response = await axios.post(...); window.location = response.data.url).

elder wing
#

Ah okay, but shouldn't the first approach without axios work then? ```js
async function sendCart(cart) {
const response = await fetch('/api/checkout_sessions', {
method: 'POST',
body: JSON.stringify({cart}),
headers: {
'Content-Type': 'application/json'
}
});
}

#

This one gets crazy in the network tab

#

and also gives me this like it's trying to fetch and redirect at the same time

ashen siren
#

i don't have enough knowledge about NextJS to comment on what's going on in the first screenshot with the multiple lines of NextJS fetch calls

With regards to the Unhandled Runtime error - can you trace down where exactly the error is coming from in your code? For example, did the call reach your server? Are there any errors when processing on your server?

elder wing
#

No idea, it looks like it's going through fine but then fails on the redirect?

#

That's the response from checkout_sessions, and it's got no errors, then the errors after are just CORS again which I doubt it actually is

#
<form action="/api/checkout_sessions" method="POST">

This works fine though, is there no way to pass an object just via the form?

#

Okay, just did what you said about the axios thing and it seems to be working, now it seems like I'm populating the line_item wrong and getting this error ```js
Missing required param: line_items[0][name].

#

But this isn't working either line_items[0][name] murloc.namn

#

nvm got everything working now with the axios thing, thank you so much ๐Ÿ‘ Is that method equally safe to use as if it was redirecting in the backend?

ashen siren
#

yep, it's an alternative we suggest to users who don't want to use the form redirect