【问题标题】:Stripe checkout session not working nodejs条带结帐会话不起作用nodejs
【发布时间】:2021-09-16 19:57:02
【问题描述】:

我正在尝试使用 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.

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

环境文件

REACT_APP_FETCH_URL=http://localhost:5000

server.js

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

路由接口

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> 

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

【问题讨论】:

    标签: node.js reactjs stripe-payments


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢,karllekko。再次感谢
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-04-24
      • 2016-06-01
      • 2021-10-25
      • 2021-08-25
      • 2019-10-24
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多