条纹结帐会话不工作 nodejs

Stripe checkout session not working nodejs

我正在尝试使用 NodeJs 和 React 实现条带检查,它似乎从控制台日志中得到了这个错误:

Access to XMLHttpRequest at 'https://checkout.stripe.com/pay/cs_test_a1y3gwvPAqpqhArQ9B83g3Du9EvF87HVcxzcx5Opt6o1rKinGEQViuXIq' (redirected from 'http://localhost:5000/api/account/subscriptioncheckoutsession') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是我到目前为止所做的:

env 文件

REACT_APP_FETCH_URL=http://localhost:5000

server.js

var whitelist = ['http://localhost:3000', 'http://localhost:5000'];
app.use(cors({ credentials: true, origin: whitelist }));

路线api

const YOUR_DOMAIN = 'http://localhost:5000';

router.post('/account/subscriptioncheckoutsession', async (req, res) => {
  const session = await Stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'Product Subsciption',
            images: ['https://i.imgur.com/EHyR2nP.png'],
          },
          unit_amount: 100,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success.html`,
    cancel_url: `${YOUR_DOMAIN}/cancel.html`,
  });
  res.redirect(303, session.url)
})

客户

const handleCheckout = async (e) => {
        e.preventDefault()
        const response = await Axios.post(process.env.REACT_APP_FETCH_URL + '/api/account/subscriptioncheckoutsession')
    }


<div className="form-group">
  <button type="submit" className="btn btn-primary" onClick={handleCheckout}>
   Subscribe or Renew Subscription</button>
</div> 

我错过了什么?非常感谢,非常感谢任何帮助。再次感谢。

如果您使用 XMLHTTPRequest(例如,Axios.post)获取 CheckoutSession 的 URL,则无法通过这种方式直接从服务器重定向!该方法仅在您执行 Stripe 文档中描述的操作时才有效——从 <form>action 调用后端 /subscriptioncheckoutsession 路由:https://stripe.com/docs/billing/subscriptions/checkout#create-session

因此,您可以更改代码,使表单操作成为该路由,并完全摆脱 onClick 函数和 Axios 的使用!

如果您不想使用表单提交,而是想使用像 Axios 这样的 Ajax 方法,我建议您的后端应该 return URL 作为响应主体的一部分(例如 res.json({"url":session.url}; 而不是 res.redirect)并通过设置 window.location 在 JavaScript 中进行重定向(例如 let response = await axios.post(...); window.location = response.data.url

我使用 FastAPI 和 React 来做同样的事情,最后使用了表单操作类型。我试过使用 Fetch,但是你不能使用 window.location = response.url 方法,或者至少在 TypeScript 中是这样。

这些是FastAPI和pip install中的参数类型python-multipart session_id: str = 表格(...) price_id: str = 表格(...)