#aldale
1 messages ยท Page 1 of 1 (latest)
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
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
like the example code does, can you show me where is this exemple code
Sure, here! https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=checkout#redirect-customers
so the redirect should be executed in the backend ?
can you copy paste the snippet you are refering to in this page ?
Yes, for example in Node.js
res.redirect(303, session.url);
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.");
}
};
What happens? Does it hang? Does it show a loading spinner? Please be specific
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
If you open up the console in the browser, are you seeing any errors when you attempt to redirect?
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
This is really hard to read. Can you just screenshot the developer console with all the errors in it?
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.
still the same problem, i will show a better view
Frond end
Calculating services price
Stripe checkout session
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;
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);
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
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)
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
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
You're getting the response successfully, and setting the location alread, but not seeing a redirect?
yep, stripe is getting 200 OK, my backend logs show me a valid Session URL also, it just that it stay in my page
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
not redirecting for both suggestions, also when using calling checkout route http://localhost:3000/api/create-checkout-session the response Headers is empty
What do you mean?
I thought you said you were getting the response from your server (with the url payload) successfully
๐ not sure what I am looking at, can you elaborate ?
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
What error are you getting when your code attempts to redirect to the url?
We have a quickstart demo here for checkout sessions
https://stripe.com/docs/checkout/quickstart
well i tried to log potential error around the redirect but i cannot find any error in the console about this
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
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.
If you're having trouble following the steps in our guide, we also have a few video tutorials which might be helpful
https://www.youtube.com/watch?v=4KogT5i7Guk
https://www.youtube.com/watch?v=UjcSWxPNo18
alright i will do some work on it on my end, you can close this chat, thanks