stripe / react-stripe-js

React components for Stripe.js and Stripe Elements
https://stripe.com/docs/stripe-js/react
MIT License
1.75k stars 267 forks source link

paymentRequestButton onclick event not working #455

Closed png-prakash closed 10 months ago

png-prakash commented 11 months ago

What happened?

Hi, I want to check if product option selected or not before payment request send when button onClick. But onClick function not working.

useEffect(() => {
  if (stripe) {
    let displayItems = [
      {
        label: product.name,
        amount: product.price
      }
    ];
    const pr = stripe.paymentRequest({
      country: 'US',
      currency: appContext.currency.toLowerCase(),
      displayItems: displayItems,
      total: {
        label: loc.orderTotal,
        amount: parseFloat(product.orderTotal) * 100,
      },
      requestPayerName: true,
      requestPayerEmail: true,
      requestPayerPhone: true,
      requestShipping: true,
    });

    pr.on('click', (event) => {
      if (!formValidated) {
        event.preventDefault();
      }
    });

    pr.canMakePayment().then((result) => {
      if (result) {
        pr.on('paymentmethod', handlePaymentMethodReceived);
        setPaymentRequest(pr);
      }
    });

    pr.on('shippingaddresschange', async (ev) => {
    });

    pr.on('shippingoptionchange', async (ev) => {
    });
  }
}, [stripe]);

const formValidated = () => {
  if (product.attributeType === 'single') {
    if (typeof selectedSingleOption === 'undefined') {
      alert('Please select variant');
      return false;
    }
  } else {
    return true;
  }
}

If they select variant automatically send request to Stripe? How can solve this issue? Thanks

Environment

No response

Reproduction

No response

brendanm-stripe commented 10 months ago

The click handler is not something you'd attach to the paymentRequest instance, here. Instead, it belongs to the Payment Request Button Element. In other words, you want to add an onClick handler to your <PaymentRequestButtonElement /> as seen in this demo: https://codesandbox.io/s/react-stripe-official-q1loc?fontsize=14&hidenavigation=1&theme=dark&file=/src/components/demos/PaymentRequestForm.js:2189-2284

<PaymentRequestButtonElement
      onReady={() => {
        console.log("PaymentRequestButton [ready]");
      }}
      onClick={event => {
        console.log("PaymentRequestButton [click]", event);
      }}
    />