从localhost遇到CORS错误的条带签出示例 [英] Stripe Checkout example running into CORS error from localhost

查看:22
本文介绍了从localhost遇到CORS错误的条带签出示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此处给出的说明为节点集成条纹签出。https://stripe.com/docs/payments/accept-a-payment?integration=checkout

我已按照TEE的说明进行操作,并已使用我的帐户中的实际(测试)API密钥更新了示例中的API密钥。

我在前端使用REACTION,在后端使用EXPRESS。我已启用CORS。

从Reaction到后端的请求成功,并且印前检查请求被触发到Stripe。条带的印前检查响应是403,实际请求因CORS错误而被阻止-PreflightMissingAllowOriginHeader

后端代码(最小)

const express = require("express");
const app = express();
const cors = require("cors");

const stripe = require("stripe")(
  process.env.STRIPE_SECRET_KEY
);

app.use(
  cors({
    origin: ["http://localhost:8000", "https://checkout.stripe.com"],
  })
);

app.post("/create-checkout-session", async (req, res) => {
  console.log('getting here 1')
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: "T-shirt",
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: "http://localhost:4242/success.html",
    cancel_url: "http://localhost:4242/cancel.html",
  });
  
  console.log('getting here 2')
  res.redirect(303, session.url);
});

app.listen(4242, () => console.log(`Listening on port ${4242}!`));

前端代码

  handleClick = () => {
    const res = fetch(`${process.env.BACKEND_API_URL}/create-checkout-session`, {
      method: 'POST',
      headers: {
        "Content-Type": 'text/html'
      }
    })
  }

推荐答案

以下是我在尝试调试时学到的一些东西。

  1. 条带结账使用AWS CloudFront,不允许OPTIONS请求(根据条带的配置)
  2. 当我在前端将请求类型更改为text/plain时,OPTIONS请求不会发送到STRIPE。(是的,没错,在我的服务器返回303之后,服务器返回了带有条纹的url的303,Chrome不会向条纹发送OPTIONS请求)
  3. 使用Reaction时最好避免重定向

以下分别是解决该问题的更新后的后端代码和前端代码

app.post("/create-checkout-session", async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: [
      {
        price_data: {
          currency: "usd",
          product_data: {
            name: "T-shirt",
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: "http://localhost:8000/success",
    cancel_url: "http://localhost:8000/cancel",
  });

  res.json({url: session.url}) // <-- this is the changed line
});
  handleClick = async () => {
    const res = await fetch(`${process.env.BACKEND_API_URL}/create-checkout-session`, {
      method: 'POST',
      headers: {
        "Content-Type": 'application/json'
      }
    })
    const body = await res.json()
    window.location.href = body.url
  }

这篇关于从localhost遇到CORS错误的条带签出示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆