我正在编写一个使用 Stripe 执行支付的无服务器 React 函数。我已经使用 stripe CLI(如 dotenv)成功安装了所有 stripe 依赖项,无法使用 .env 来存储密钥和公钥。
当我点击立即付款按钮处理付款时,由于 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) => {
// Pevent typical form to be submitted
e.preventDefault();
// Making sure that the above two hooks are loaded in when payment handler fired
if (!stripe || !elements) {
return;
}
// setting processing payment to true when it stats to process payments
setIsProcessingPayment(true);
// Request to get the payment
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",
},
},
});
// set processing payments to false when it ends to process
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 的无服务器函数组件中,我将其编写如下
创建支付意图.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 }),
};
}
};
根据您的错误消息,您似乎安装了一些卡巴斯基浏览器扩展程序,这些扩展程序干扰了 Stripe 库发出的一些内部请求。我建议在没有扩展程序/隐身窗口的新浏览器中进行测试,看看是否有帮助。