我正在将 Stripe 与我的 React Vite 应用程序集成,但是当我付款时,我得到了 {type: 'invalid_request_error', message: '提供的 API 密钥无效:“pk_test****************...**************** *****************************sB";'} 我在环境文件中设置条带发布者密钥时出错,但为什么我得到此类错误请帮助解决此问题。
import CheckoutInformation from "../../components/root/checkout/CheckoutInformation";
import OrderSummary from "../../components/root/checkout/OrderSummary";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
const stripePromise = loadStripe(`${import.meta.env.VITE_STRIPE_PUBLIC_KEY}`);
const StripeProvider = ({ children }: { children: React.ReactNode }) => {
return <Elements stripe={stripePromise}>{children}</Elements>;
};
const Checkout = () => {
return (
<StripeProvider>
<div className="container py-4 my-8 flex lg:flex-row flex-col gap-8">
<div className="flex-1">
<CheckoutInformation />
</div>
<div className="lg:w-[500px] w-full">
<OrderSummary />
</div>
</div>
</StripeProvider>
);
};
export default Checkout;
const stripe = useStripe();
const elements = useElements();
const paymentHandler = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const paymentData = {
amount: 10,
currency: currencyCode,
};
const { data } = await axiosInstance.post(
"/payment/process",
paymentData
);
console.log(data);
const client_secret = data.client_secret;
const cardElement = elements?.getElement(CardNumberElement);
if (!cardElement) {
// Handle case where card element is not available
console.error("Card element is not available");
return;
}
const result = await stripe?.confirmCardPayment(client_secret, {
payment_method: {
card: cardElement,
},
});
if (result?.error) {
// Show error to your customer
console.error(result?.error);
toast.error(result?.error?.message as string);
} else {
console.log(result);
// Payment successful
console.log("Payment succeeded:", result.paymentIntent);
}
// const { data} = await axiosInstance.post("/payment/process")
} catch (error) {
let message;
if (error instanceof AxiosError) {
message = handleApiError(error);
} else {
message = "An unexpected error occurred.";
}
toast.error(message);
}
};
看起来
.env
文件包含无效的 Stripe 可发布密钥。检查您是否使用从 Stripe 仪表板获取的正确可发布密钥,然后重试。