重定向到 ReactJS 中的结帐

IT技术 javascript reactjs stripe-payments
2021-05-25 14:25:33

我正在尝试在 ReactJS 中实现 Stripe 函数“重定向到结帐”。我一直在环顾四周,似乎没有任何软件包可以帮助您做到这一点。

const stripe = 
Stripe('key');

stripe.redirectToCheckout({
  items: [
    // Replace with the ID of your SKU
    {sku: 'sku_123', quantity: 1}
  ],
  successUrl: 'https://your-website.com/success',
  cancelUrl: 'https://your-website.com/canceled',
}).then(({error}) => {
  // If `redirectToCheckout` fails due to a browser or 
network
  // error, display the localized error message to your 
customer
  // using `error.message`.
});

这是我得到这个源代码的地方:https : //stripe.com/docs/stripe-js/reference#stripe-redirect-to-checkout

StripeJS 似乎只支持不接收产品 SKU 作为参数的标准结账

2个回答

在我阅读了新stripe-js文档https://stripe.com/docs/stripe-js/react 后, 我发现这可能对你有用

而是使用stripe, install@stripe/stripe-js 然后可以通过以下方式完成工作

import { loadStripe } from "@stripe/stripe-js";

...

const stripePromise = loadStripe(
    "pk_.........."
  );

const stripe = await stripePromise;

stripe.redirectToCheckout({
      ...
    })

我发现了它是如何工作的。

基本上根据文档,需要在 public/index.html 中导入 Stripe 脚本

stripe.redirectToCheckout(...)

可以简单地放入一个按钮的onClick。文档中真正不清楚的事情,可能会误导像我这样的新手,在于设置公钥:

const stripe = Stripe('key');

不起作用,因为在编译时找不到脚本。
这可以通过使用来解决:

const stripe = window.Stripe('key');

这对我有用。