#rk0660-react-cart

1 messages · Page 1 of 1 (latest)

wintry atlas
#

Hello. This isn't really a Stripe issue. Have you attempted to create a handler for your form submission which will make the fetch request?

atomic mural
#

Hi thanks - I did put a onSubmit={handleSubmit} on my form and got rid of the action attribute, then in the handleSubmit function I sent a post fetch request to the endpoint

#

I did it last night but the stripe checkout page never loaded

#

This was my code yesterday

#

I'm trying to pass in custom data to my node.js backend when the user wants to checkout, but clicking my button doesn't take me to the checkout page.

const Cart = () => {
  
    const cart = useSelector(state => state.cart);

    
    const handleStripe = async (e) => {
        e.preventDefault();
        const { url } = (await fetch("http://localhost:5000/api/stripe/checkout", {
            method: "POST",
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
            products: cart.products,
            }),
        })).json()

        window.location.href(url)
    }



  return (
    <Container>
     
                    <Form onSubmit={handleStripe>
                        <SummaryButton> CHECKOUT NOW</SummaryButton>
                    </Form>
                </Summary>
            </Bottom>
        </Wrapper>
        <Footer />
    </Container>
  )
}
#

@wintry atlas

wintry atlas
atomic mural
#

That’s all the code I had in my front end, in my back end I followed the stripe docs example of router.post(‘/checkout’, etc)

wintry atlas
#

Can you share your backend code?

wintry atlas
atomic mural
#

Sure, I will be home in 15 minutes I’ll immediately copy my backend code here

wintry atlas
#

My guess is you had a server redirect (res.redirect(url)) when you used the <form> action. That won't work with fetch, so you'll need to implement a client-side redirect, either via redirectToCheckout from Stripe.js or with window.location.href()

#
const { url } = await (await fetch("http://localhost:5000/api/stripe/checkout", {
            method: "POST",
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
            products: cart.products,
            }),
        })).json()

window.location.href(url)
atomic mural
#

Here is my backend code

router.post("/checkout", async (req, res) => {

    const session = await stripe.checkout.sessions.create({

        line_items: [
          {
            price_data: {
              currency: 'usd',
              product_data: {
                name: 'T-shirt',
              },
              unit_amount: 2000,
            },
            quantity: 1,
          },
          {
            price_data: {
                currency: 'usd',
                product_data: {
                    name: 'Mug',
                },
                unit_amount: 500,
            },
            quantity: 1,
          }
        ],
        mode: 'payment',
        success_url: 'http://localhost:3000/',
        cancel_url: 'http://localhost:3000/cart',
      });
    
      res.redirect(303, session.url);
});


module.exports = router;
atomic mural
#

So it's a bit better, the problem is the page just reloads now when I click my button. I'll update my frontend and backend in the code above

fair burrow
#

the problem is the page just reloads now when I click my button.
that usually means you don't call event.preventDefault() in the event handler function

#

though seems like you have that

atomic mural
#

Oh no that's not it, I have it

#

Oh its a cors issue

#

I have require cors and app.use(cors()); in my backend, do i somehow need it in frontend too?

fair burrow
#

I think the issue is maybe with what ynnoj shared, try window.location.replace(url) instead

atomic mural
#

Nope, it still gives

Access to fetch at 'https://checkout.stripe.com/pay/cs_test_b1uW0PTCbSMtLCdWTWIM0SfIFQWXZUsn0bjxGxxiIDiNuTpJtYgqypyoUH#fidkdWxOYHwnPyd1blpxYHZxWjA0TlBjPHJMN2NTNXZnNVZyNmp9a0phczVibWFmRG80ajJjYHVrMnY3MEtfV1xiaTxTb1RvMD1cSTJyXzR3U05fdEw8ZlMzNzNyT3xnPExKN0duUnZsZl1xNTVjbmJoa0BQVScpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPydocGlxbFpscWBoJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl' (redirected from 'http://localhost:5000/api/stripe/checkout') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
#

Should I make my headers headers: {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},

fair burrow
#

yeah this is what ynnoj said

#

its' because you return res.redirect(303, session.url); on the backend

#

which you can't do

atomic mural
#

Ohh sorry I didn't see that part I just followed the stripe docs for that I think

fair burrow
#

it should be something like res.json({url:session.url})

#

yeah but the docs assume you have a simple form action

atomic mural
#

Ohhh ok, what you two suggested got it to work. Thank you very much! Out of curiousity, I saw there is a new way of doing checkout with 'elements'? Is that something easy to implement without many changes or

#

is it a whole different implementation

fair burrow
#

it's entirely different

#

it's for embedding payment components into your own page instead of a redirect to a Stripe-hosted page, so it's more complicated.

atomic mural
#

Ohh ok I got it

#

Well thanks for the help! :)

#

When I push this into production

#

I need to change the .env from sk_test to the sk production key?