#aldale

1 messages ยท Page 1 of 1 (latest)

small violetBOT
lethal jackal
#

const redirectToStripe = async () => {
console.log('Button clicked');
try {
// Make a request to your server to create a checkout session
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
credentials: 'include', // Include cookies
});

        if (!response.ok) {
            const errorMessage = `Failed to create checkout session (${response.status}): ${await response.text()}`;
            console.error(errorMessage);

            // You can choose to display an error message to the user here if needed.
            // For example, set a state variable to display an error message in your component.

            throw new Error(errorMessage);
        }

        const session = await response.json();
        console.log('Session ID:', session.id);

        // Redirect to the checkout session's URL
        console.log('Session URL:', session.url);
        window.location.href = session.url;
    } catch (error) {
        console.error('Error:', error);
        // Handle other unexpected errors
        setError("An unexpected error occurred. Please try again later.");
    }
};
#

here is a snippet of my front end for the redirect

shrewd edge
#

This doesn't work because redirection doesn't work well with AJAX (the fetch() function you wrote)

#

Try to use a form a redirect from server, like the example code does

lethal jackal
#

like the example code does, can you show me where is this exemple code

shrewd edge
lethal jackal
#

so the redirect should be executed in the backend ?

#

can you copy paste the snippet you are refering to in this page ?

shrewd edge
#

Yes, for example in Node.js

res.redirect(303, session.url);
small violetBOT
lethal jackal
#

so i made a quick ajustement, it still dont get redirected ๐Ÿ˜

#

const redirectToStripe = async () => {
console.log('Button clicked');
try {
// Make a request to your server to create a checkout session
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
credentials: 'include', // Include cookies
});

        if (!response.ok) {
            const errorMessage = `Failed to create checkout session (${response.status}): ${await response.text()}`;
            console.error(errorMessage);

            // You can choose to display an error message to the user here if needed.
            // For example, set a state variable to display an error message in your component.

            throw new Error(errorMessage);
        }

    } catch (error) {
        console.error('Error:', error);
        // Handle other unexpected errors
        setError("An unexpected error occurred. Please try again later.");
    }
};
jagged depot
#

What happens? Does it hang? Does it show a loading spinner? Please be specific

lethal jackal
#

it show the correct url session log in my server console, it create a 200 OK session looking in stripe log, but it stay in my checkout front page

#

it look like a simple refresh in my front end when i call the route i showed you

jagged depot
#

If you open up the console in the browser, are you seeing any errors when you attempt to redirect?

lethal jackal
#

yes alot of r.stripe cors related but i read to ignore those, i will check preserve log and run pay "pay with stripe" button and show all the log in the console

#

i guess first line about https can be ignored as im using test mode api keys

jagged depot
#

This is really hard to read. Can you just screenshot the developer console with all the errors in it?

lethal jackal
jagged depot
#

Ohhhhhh, okay. I think I know what's going on. Okay, ignore the previous person's answer here. The problem is you're using fetch() to trigger the back-end function, then attempting redirect from there. You can't redirect to Stripe from within a fetch() chain.

To solve this, remove res.redirect() entirely and just do res.send(checkoutURL: session.url). This will send the URL to the front-end where you can perform the redirect.

lethal jackal
#

still the same problem, i will show a better view

#

i made your last recommandation maybe the problem is this part in my front end ? // Redirect the user to the Stripe hosted checkout page
window.location.href = responseData.checkoutURL;

jagged depot
#

Perhaps. Can you do a console.log(); on the client-side to make sure that the Checkout Session's URL is actually making it there? I think that would be console.log(responseData.checkoutURL);

small violetBOT
lethal jackal
#

i added the console.log like you told me, example: const redirectToStripe = async () => {
console.log('Button clicked');
try {
// Make a request to your server to create a checkout session
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
credentials: 'include', // Include cookies
});

        if (!response.ok) {
            const errorMessage = `Failed to create checkout session (${response.status}): ${await response.text()}`;
            console.error(errorMessage);

            // You can choose to display an error message to the user here if needed.
            // For example, set a state variable to display an error message in your component.

            throw new Error(errorMessage);
        }

        // Parse the response to get the checkout URL
        const responseData = await response.json();

        // Log the checkoutURL
        console.log('Checkout URL:', responseData.checkoutURL);

        // Redirect the user to the Stripe hosted checkout page
        window.location.href = responseData.checkoutURL;
    } catch (error) {
        console.error('Error:', error);
        // Handle other unexpected errors
        setError("An unexpected error occurred. Please try again later.");
    }
};
#

but in the console when calling the api route i have no logs about checkoutURL, i used a filter "checkoutURL" to be sure and also tried with preserve logs checkbox

jagged depot
#

You liely need to put the log line inside of the if statement, as well as inside the catch block (idk which of these are triggering at this point, so just copy/paste it everywhere and narrow it down to see which block you're hitting)

neat ravine
#

Hey there, stepping in for @jagged depot here. It looks like you're trying to redirect a fetch call to your server, which isn't possible. Fetch doesn't support following redirects.

#

You either need to (full) redirect the client to your server endpoint then redirect to checkout from there, or more likely what you want it returning the checkout session url from your server call then having the client redirect that on success

lethal jackal
#

yeah, its the later im trying to do

#

here is a snippet from my backend // Send the checkout URL as a JSON response
res.send({ checkoutURL: session.url });

#

and front end with // Redirect the user to the Stripe hosted checkout page
window.location.href = responseData.checkoutURL;

#

im confused how to make that redirect happen

neat ravine
#

You're getting the response successfully, and setting the location alread, but not seeing a redirect?

lethal jackal
#

yep, stripe is getting 200 OK, my backend logs show me a valid Session URL also, it just that it stay in my page

neat ravine
#

Does it change if you try window.location = url?

#

Or window.location.replace(url)?

#

One of those ought to work, but that's a browser API

#

And outside of stripe's control

lethal jackal
neat ravine
#

What do you mean?

#

I thought you said you were getting the response from your server (with the url payload) successfully

small violetBOT
lethal jackal
buoyant kayak
#

๐Ÿ‘‹ not sure what I am looking at, can you elaborate ?

lethal jackal
#

look, i have data.totalPrice calculated with a working backend route, now i need to create a checkout session + redirect based on my price, is there a samples so i can make it work quickly and play around a working code, im using react front end and express lib in the backend

#

also i sent all the 3 concerning files im working with earlier: checkout.js paymentIntentRoute.js createCheckoutSession.js but can't seem to redirect even if the session work

buoyant kayak
lethal jackal
#

well i tried to log potential error around the redirect but i cannot find any error in the console about this

buoyant kayak
#

It can't fail silently. What exactly are you seeing in your console?

In your network tab, instead of looking at the headers you can switch to response and see if there are any traces of the errors

lethal jackal
#

i think you said the redirect in my front end exemple indow.location.replace(responseData.checkoutURL); should be outside of the fetch function, maybe like inside a useeffect

#

yeah with some tweaks i get: An unexpected error occurred. Please try again later.

buoyant kayak
lethal jackal
#

alright i will do some work on it on my end, you can close this chat, thanks