unicorn_surprise
unicorn_surprise

Reputation: 1109

Stripe cardElement is null when using confirmCardPayment

I'm struggling to confirm the stripe card payment in the following Checkout form. I believe it's because I'm rendering the component instead of the , so elements.getElement(CardElement) is returning null, however how can I reference the Payment element and pass it into confirmCardPayment method? Or is this not possible. I'd just rather use the PaymentElement instead of the CardElement.

const CheckoutForm: React.FC<CheckoutFormProps> = ({ clientSecret }) => {
  const stripe = useStripe();
  const elements = useElements();

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

    console.log('does this hit')
    if (!stripe || !elements) {
        console.log('!stripe or !elements')
      return;
    }
    try {
      const cardElement = elements.getElement(CardElement);
      console.log(cardElement, 'card element')
      let paymentMethod;
      if (cardElement) {
        paymentMethod = await stripe.confirmCardPayment(clientSecret, {
          payment_method: {
            card: cardElement,
          },
        });
        console.log(paymentMethod, 'payment method')
      }
    } catch (err: any) {
        console.log(err?.message, 'error');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <PaymentElement />
      <button disabled={!stripe}>Submit</button>
    </form>
  );
};

Upvotes: 0

Views: 1590

Answers (1)

alex
alex

Reputation: 2799

In your code, you're rendering the Payment Element,

  <PaymentElement />

but attempting to access the Card Element.

elements.getElement(CardElement)

That's why you're seeing that the cardElement is null.

The Payment Element and Card Element are two entirely different components : https://stripe.com/docs/payments/payment-card-element-comparison.

I suggest you refer to the following guides.

If you want to use the Payment Element :

If you want to use the Card Element :

Upvotes: 2

Related Questions