我不确定出了什么问题,一切似乎都正常。直到我建立我的产品。条带元素未在生产中加载。我尝试将正确的 Stripe 可发布密钥从 @stripe/react-stripe-js 传递到 Elements 组件。没有运气。还尝试在
clientSecret &&
之前添加 <Elements>
,但都给出了未加载元素的相同错误。
'use client';
import React, { useEffect, useState, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { Elements } from '@stripe/react-stripe-js';
import stripePromise from '@/lib/stripe';
import SubscriptionForm from '@/app/signup/SubscriptionForm';
import axios from 'axios';
const SubscribePage: React.FC = () => {
const searchParams = useSearchParams();
const [clientSecret, setClientSecret] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const userId = searchParams?.get('userId') || '';
const plan = (searchParams?.get('plan') as 'free' | 'basic' | 'premium') || 'free';
const firstName = searchParams?.get('firstName') || '';
const lastName = searchParams?.get('lastName') || '';
const email = searchParams?.get('email') || '';
useEffect(() => {
if (plan !== 'free') {
const fetchClientSecret = async () => {
try {
console.log('Requesting client secret with:', {
userId,
plan,
firstName,
lastName,
email,
});
const { data } = await axios.post('/api/create-payment-intent', {
userId,
plan,
firstName,
lastName,
email,
});
console.log('Received client secret:', data.clientSecret);
setClientSecret(data.clientSecret);
} catch (error) {
console.error('Error fetching client secret:', error);
setError('Failed to fetch payment details.');
}
};
fetchClientSecret();
}
}, [userId, plan, firstName, lastName, email]);
if (!userId || !plan || !firstName || !lastName || !email) {
return <p>Invalid subscription details. Please try again.</p>;
}
return (
<div>
{/*<h1>Complete Your Subscription</h1>*/}
{plan !== 'free' && clientSecret && (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<SubscriptionForm
userId={userId}
plan={plan}
firstName={firstName}
lastName={lastName}
email={email}
/>
</Elements>
)}
{plan === 'free' && (
<SubscriptionForm
userId={userId}
plan={plan}
firstName={firstName}
lastName={lastName}
email={email}
/>
)}
{error && <p>{error}</p>}
</div>
);
};
const SubscribePageWithSuspense: React.FC = () => (
<Suspense fallback={<div>Loading...</div>}>
<SubscribePage />
</Suspense>
);
export default SubscribePageWithSuspense;
打开浏览器控制台并检查 Stripe.js 是否有任何错误消息。使用实时模式可发布密钥时,还要确保您的页面是通过 HTTPS 提供的。