I am trying to retrieve the value of the full name field in the stripe modal, but i get undefined

Issue with Retrieving the Full Name in Stripe Checkout Modal
I am trying to retrieve the value of the full name field in the Stripe Checkout modal so that I can include it in the email I send after payment. However, the fullName is coming through as undefined in the email. I attempted to retrieve it using elements.getElement(‘payment’).getValue(), but that didn’t work. I also tried removing the field and adjusting the CSS, but the issue persists.

Below is my React component for handling Stripe payments and sending emails:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState, useEffect } from 'react';
import { useStripe, useElements, Elements, PaymentElement } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { useLocation } from 'react-router-dom';
const stripePromise = loadStripe('your-publishable-key-here');
const sendEmail = async (paymentIntentId, email, fullName) => {
try {
const response = await fetch('http://localhost:5000/send-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paymentIntentId, email, fullName }),
});
const data = await response.json();
if (data.success) {
console.log('Email sent successfully');
} else {
console.error('Failed to send email');
}
} catch (error) {
console.error('Error sending email:', error);
}
};
const CheckoutForm = ({ clientSecret, email }) => {
const stripe = useStripe();
const elements = useElements();
const [loading, setLoading] = useState(false);
const handleSubmit = async (event) => {
event.preventDefault();
if (!stripe || !elements) {
return;
}
try {
setLoading(true);
const { error, paymentIntent } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: window.location.href,
},
});
if (error) {
console.error('Payment Error:', error);
alert('Payment failed! Please try again.');
} else if (paymentIntent && paymentIntent.status === 'succeeded') {
console.log('Payment Intent:', paymentIntent);
alert('Payment successful!');
// Retrieve full name from the payment element
const { error: elementsError, value: { name } } = await elements.getElement('payment').getValue();
if (elementsError) {
console.error('Error retrieving name:', elementsError);
} else {
await sendEmail(paymentIntent.id, email, name);
}
}
} catch (error) {
console.error('Error in handleSubmit:', error);
alert('An error occurred. Please try again.');
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-lg font-medium mb-2">Payment Information</label>
<PaymentElement options={{
fields: {
billingDetails: {
name: 'auto',
},
},
}} />
</div>
<button
type="submit"
className="w-full py-3 bg-red-600 text-white font-semibold rounded-lg hover:bg-red-700 transition duration-300"
disabled={loading || !clientSecret}
>
{loading ? 'Processing...' : 'Pay Now with iDEAL'}
</button>
</form>
);
};
const Checkout = () => {
const [clientSecret, setClientSecret] = useState('');
const location = useLocation();
const state = location.state || {};
const { individualCount = 0, familyCount = 0, totalCost = 0, email = '' } = state;
useEffect(() => {
const fetchClientSecret = async () => {
if (totalCost === 0) {
console.error("Total cost is zero or undefined.");
return;
}
const response = await fetch('http://localhost:5000/create-payment-intent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: totalCost * 100, // amount in cents
individualCount,
familyCount,
totalCost,
email,
}),
});
const data = await response.json();
setClientSecret(data.clientSecret);
};
fetchClientSecret();
}, [individualCount, familyCount, totalCost, email]);
return (
<div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<h1 className="text-4xl font-bold text-center mb-8 text-gray-900">Checkout</h1>
<div className="mb-8 text-center">
<h2 className="text-3xl font-semibold mb-4">Total Cost</h2>
<p className="text-4xl font-bold text-red-600">{(totalCost || 0).toFixed(2)}</p>
</div>
{clientSecret && (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<CheckoutForm clientSecret={clientSecret} email={email} />
</Elements>
)}
</div>
);
};
export default Checkout;
</code>
<code>import React, { useState, useEffect } from 'react'; import { useStripe, useElements, Elements, PaymentElement } from '@stripe/react-stripe-js'; import { loadStripe } from '@stripe/stripe-js'; import { useLocation } from 'react-router-dom'; const stripePromise = loadStripe('your-publishable-key-here'); const sendEmail = async (paymentIntentId, email, fullName) => { try { const response = await fetch('http://localhost:5000/send-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentIntentId, email, fullName }), }); const data = await response.json(); if (data.success) { console.log('Email sent successfully'); } else { console.error('Failed to send email'); } } catch (error) { console.error('Error sending email:', error); } }; const CheckoutForm = ({ clientSecret, email }) => { const stripe = useStripe(); const elements = useElements(); const [loading, setLoading] = useState(false); const handleSubmit = async (event) => { event.preventDefault(); if (!stripe || !elements) { return; } try { setLoading(true); const { error, paymentIntent } = await stripe.confirmPayment({ elements, confirmParams: { return_url: window.location.href, }, }); if (error) { console.error('Payment Error:', error); alert('Payment failed! Please try again.'); } else if (paymentIntent && paymentIntent.status === 'succeeded') { console.log('Payment Intent:', paymentIntent); alert('Payment successful!'); // Retrieve full name from the payment element const { error: elementsError, value: { name } } = await elements.getElement('payment').getValue(); if (elementsError) { console.error('Error retrieving name:', elementsError); } else { await sendEmail(paymentIntent.id, email, name); } } } catch (error) { console.error('Error in handleSubmit:', error); alert('An error occurred. Please try again.'); } finally { setLoading(false); } }; return ( <form onSubmit={handleSubmit} className="space-y-4"> <div> <label className="block text-lg font-medium mb-2">Payment Information</label> <PaymentElement options={{ fields: { billingDetails: { name: 'auto', }, }, }} /> </div> <button type="submit" className="w-full py-3 bg-red-600 text-white font-semibold rounded-lg hover:bg-red-700 transition duration-300" disabled={loading || !clientSecret} > {loading ? 'Processing...' : 'Pay Now with iDEAL'} </button> </form> ); }; const Checkout = () => { const [clientSecret, setClientSecret] = useState(''); const location = useLocation(); const state = location.state || {}; const { individualCount = 0, familyCount = 0, totalCost = 0, email = '' } = state; useEffect(() => { const fetchClientSecret = async () => { if (totalCost === 0) { console.error("Total cost is zero or undefined."); return; } const response = await fetch('http://localhost:5000/create-payment-intent', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: totalCost * 100, // amount in cents individualCount, familyCount, totalCost, email, }), }); const data = await response.json(); setClientSecret(data.clientSecret); }; fetchClientSecret(); }, [individualCount, familyCount, totalCost, email]); return ( <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12"> <h1 className="text-4xl font-bold text-center mb-8 text-gray-900">Checkout</h1> <div className="mb-8 text-center"> <h2 className="text-3xl font-semibold mb-4">Total Cost</h2> <p className="text-4xl font-bold text-red-600">€{(totalCost || 0).toFixed(2)}</p> </div> {clientSecret && ( <Elements stripe={stripePromise} options={{ clientSecret }}> <CheckoutForm clientSecret={clientSecret} email={email} /> </Elements> )} </div> ); }; export default Checkout; </code>
import React, { useState, useEffect } from 'react';
import { useStripe, useElements, Elements, PaymentElement } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { useLocation } from 'react-router-dom';

const stripePromise = loadStripe('your-publishable-key-here');

const sendEmail = async (paymentIntentId, email, fullName) => {
  try {
    const response = await fetch('http://localhost:5000/send-email', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ paymentIntentId, email, fullName }),
    });
    const data = await response.json();
    if (data.success) {
      console.log('Email sent successfully');
    } else {
      console.error('Failed to send email');
    }
  } catch (error) {
    console.error('Error sending email:', error);
  }
};

const CheckoutForm = ({ clientSecret, email }) => {
  const stripe = useStripe();
  const elements = useElements();
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    try {
      setLoading(true);
      const { error, paymentIntent } = await stripe.confirmPayment({
        elements,
        confirmParams: {
          return_url: window.location.href,
        },
      });

      if (error) {
        console.error('Payment Error:', error);
        alert('Payment failed! Please try again.');
      } else if (paymentIntent && paymentIntent.status === 'succeeded') {
        console.log('Payment Intent:', paymentIntent);
        alert('Payment successful!');
        
        // Retrieve full name from the payment element
        const { error: elementsError, value: { name } } = await elements.getElement('payment').getValue();
        
        if (elementsError) {
          console.error('Error retrieving name:', elementsError);
        } else {
          await sendEmail(paymentIntent.id, email, name);
        }
      }
    } catch (error) {
      console.error('Error in handleSubmit:', error);
      alert('An error occurred. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label className="block text-lg font-medium mb-2">Payment Information</label>
        <PaymentElement options={{
          fields: {
            billingDetails: {
              name: 'auto',
            },
          },
        }} />
      </div>
      <button
        type="submit"
        className="w-full py-3 bg-red-600 text-white font-semibold rounded-lg hover:bg-red-700 transition duration-300"
        disabled={loading || !clientSecret}
      >
        {loading ? 'Processing...' : 'Pay Now with iDEAL'}
      </button>
    </form>
  );
};

const Checkout = () => {
  const [clientSecret, setClientSecret] = useState('');
  const location = useLocation();
  const state = location.state || {};

  const { individualCount = 0, familyCount = 0, totalCost = 0, email = '' } = state;

  useEffect(() => {
    const fetchClientSecret = async () => {
      if (totalCost === 0) {
        console.error("Total cost is zero or undefined.");
        return;
      }

      const response = await fetch('http://localhost:5000/create-payment-intent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          amount: totalCost * 100, // amount in cents
          individualCount,
          familyCount,
          totalCost,
          email,
        }),
      });

      const data = await response.json();
      setClientSecret(data.clientSecret);
    };

    fetchClientSecret();
  }, [individualCount, familyCount, totalCost, email]);

  return (
    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <h1 className="text-4xl font-bold text-center mb-8 text-gray-900">Checkout</h1>
      <div className="mb-8 text-center">
        <h2 className="text-3xl font-semibold mb-4">Total Cost</h2>
        <p className="text-4xl font-bold text-red-600">€{(totalCost || 0).toFixed(2)}</p>
      </div>
      {clientSecret && (
        <Elements stripe={stripePromise} options={{ clientSecret }}>
          <CheckoutForm clientSecret={clientSecret} email={email} />
        </Elements>
      )}
    </div>
  );
};

export default Checkout;

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật