React无服务器集成Stripe支付遭CORS策略阻塞求解决方案
Stripe无服务器React支付功能CORS问题求助
我正在开发基于Stripe的无服务器React支付功能,已通过Stripe CLI完成dotenv等所有依赖安装,用.env文件存储Secret Key和Public Key。但点击「Pay Now」按钮发起支付时,请求被CORS策略阻止,无法完成支付。
相关代码
Payment-form.component.js
import { useState } from "react"; import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js"; import { useSelector } from "react-redux"; import { selectCurrentUser } from "../../store/user/user.selector"; import { selectCartTotal } from "../../store/cart/cart.selector"; import { BUTTON_TYPE_CLASSES } from "../button/button.component"; import { PaymentFormContainer, FormContainer, PaymentButton, } from "./payment-form.styles"; const PaymentForm = () => { const stripe = useStripe(); const elements = useElements(); const amount = useSelector(selectCartTotal); const currentUser = useSelector(selectCurrentUser); const [isIsProcessingPayment, setIsProcessingPayment] = useState(false); const paymentHandler = async (e) => { // 阻止默认表单提交行为 e.preventDefault(); // 确保Stripe和Elements已加载完成 if (!stripe || !elements) { return; } setIsProcessingPayment(true); // 请求创建Payment Intent const response = await fetch("/.netlify/functions/create-payment-intent", { method: "post", //request: "no-cors", headers: { "Content-Type": "application/json", Accept: "application/json", }, body: JSON.stringify({ amount: amount * 100 }), }).then((res) => res.json()); const { paymentIntent: { client_secret }, } = response; const paymentResult = await stripe.confirmCardPayment(client_secret, { payment_method: { card: elements.getElement(CardElement), billing_details: { name: currentUser ? currentUser.displayName : "Guest", }, }, }); setIsProcessingPayment(false); if (paymentResult.error) { alert(paymentResult.error); } else { if (paymentResult.paymentIntent.status === "succeeded") { alert("Payment Successfull"); } } }; return ( <PaymentFormContainer> <FormContainer onSubmit={paymentHandler}> <h2>Credit Card Payment: </h2> <CardElement /> <PaymentButton isLoading={isIsProcessingPayment} buttonType={BUTTON_TYPE_CLASSES.inverted} > Pay Now </PaymentButton> </FormContainer> </PaymentFormContainer> ); }; export default PaymentForm;
create-payment-intent.js
require("dotenv").config(); const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); exports.handler = async (event) => { try { const { amount } = JSON.parse(event.body); const paymentIntent = await stripe.paymentIntents.create({ amount, currency: "usd", payment_method_types: ["card"], }); return { statusCode: 200, body: JSON.stringify({ paymentIntent }), }; } catch (error) { console.log({ error }); return { status: 400, body: JSON.stringify({ error }), }; } };
解决思路
- 确保Netlify函数正确部署与启动:本地开发必须使用
netlify dev命令,而非React自带的npm start,这样才能将函数请求正确代理到Netlify的本地服务。 - 修正函数错误返回字段:
create-payment-intent.js错误处理中返回的status字段需改为statusCode,否则Netlify会返回500错误,导致CORS异常。 - 调整前端请求配置:移除
Accept请求头(或确保后端支持),不要启用no-cors模式,该模式会限制前端读取响应内容。 - 验证环境变量配置:确认Netlify控制台已添加
STRIPE_SECRET_KEY环境变量,本地开发时.env文件需放在项目根目录且未被忽略。 - 检查函数文件路径:确保函数文件位于
netlify/functions目录下,前端请求路径与实际函数路径完全匹配。
内容的提问来源于stack exchange,提问作者ShemaValentin
相关产品推荐
相关产品推荐

