嘿,
页面加载时 Gatsby 中的 Stripe 出现错误
未捕获(承诺中)类型错误:maybeStripe.apply 不是函数
import React, { useEffect, useState } from 'react';
import { loadStripe } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import StripeCheckout from './stripeCheckout'
const stripePromise = loadStripe('pk_test_xyz');
function App() {
const [clientSecret, setClientSecret] = useState('');
useEffect(() => {
fetch("/.netlify/functions/createIntent")
.then((res) => res.json())
.then(({ clientSecret }) => setClientSecret(clientSecret));
}, [])
const options = {
clientSecret,
}
return (
<main>
<h1>Payment</h1>
{clientSecret && (
<Elements stripe={stripePromise} options={options}>
<StripeCheckout />
</Elements>
)}
</main>
);
}
export default App;
import {
PaymentElement
} from '@stripe/react-stripe-js'
import React, {useState} from 'react'
import {useStripe, useElements} from '@stripe/react-stripe-js';
export default function CheckoutForm() {
const stripe = useStripe();
const elements = useElements();
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) {
return;
}
setIsLoading(true);
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: "http://localhost:8888",
},
});
if (error.type === "card_error" || error.type === "validation_error") {
setMessage(error.message);
} else {
setMessage("An unexpected error occured.");
}
setIsLoading(false);
}
return (
<form id="payment-form" onSubmit={handleSubmit}>
<PaymentElement id="payment-element" />
<button disabled={isLoading || !stripe || !elements} id="submit">
<span id="button-text">
{isLoading ? <div className="spinner" id="spinner"></div> : "Pay now"}
</span>
</button>
{message && <div id="payment-message">{message}</div>}
</form>
)
}
似乎无法在此处或 stripes 文档中找到此问题的任何参考,不确定这是 Gatsby 问题还是我只是做错了什么。
非常感谢任何帮助
干杯
删除了node_modules并重新安装并添加了 import { loadStripe } from '@stripe/stripe-js/pure';
您可能已经安装了其他模块,例如@stripe/stripe-js,但我认为您没有安装主 stripe 模块。所以运行
npm i stripe
或 yarn add stripe
错误就会被修复
就我而言,PUBLIC_KEY 在传递给 loadStripe(PUBLIC_KEY) 时未定义。 提供适当的 PUBLIC_KEY 后,问题就解决了
所以就我而言,我试图获取条带承诺,例如 const stripe = wait loadStripe(process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY);
后来我发现错误是由于 process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY 有时会在刷新或重新加载屏幕时返回未定义。所以添加硬编码解决了我的问题。