简体   繁体   中英

How can I retrieve the result value from stripe.redirectToCheckout()?

I am trying to get the result value from a stripe.redirectToCheckout(). It is said to return a Promise https://stripe.com/docs/js/checkout/redirect_to_checkout . Here is the code that I thought would work but it doesn't

    stripe.redirectToCheckout({
      lineItems: [
        {
          price: stripePrice,
          quantity: token,
        },
      ],
      mode: "payment",
      successUrl: someurl
      cancelUrl: someurl
    }).then(result => {
        if (result.error) {
            alert(result.error.message);
        }
    })

Both client-only Checkout and redirectToCheckout are no longer recommended.

Instead you can use Payment Links (if you need a client-only solution) or you can create Checkout Sessions on your server and send people to the url on the Checkout Session object .

Regarding your original question, though, redirectToCheckout will only return a promise if the redirect fails. If the redirect succeeds the JavaScript running on your page will stop running because the browser will have navigated to another page (the Stripe Checkout page), so there's no chance for anything to be returned.

You can't get data out of this function as you are redirected and your script ceases to exist

Stripe wile redirect you back after user checkout and then you have to read the data.

You can add session_id query param to get checkout data:

  1. Modify the success URL:
success_url: "http://yoursite.com/order/success?session_id={CHECKOUT_SESSION_ID}"

Note that CHECKOUT_SESSION_ID is a literal string and must be added exactly as you see it here.

  1. Use session_id to get checkout data:
const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
const customer = await stripe.customers.retrieve(session.customer);

Source: https://stripe.com/docs/payments/checkout/custom-success-page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM