Version: 0.0.2
Last Updated: Unknown
These collecton of components can be used within a form to attempt to process a payment through Stripe.
They are adapters on Stripe's React Elements library.
You require a component that wraps the form to enable elements. This same <Elements> HOC is also where you load Stripe and set the required font conditions (within the cssSrc, the component will not load custom Google Fonts).
function Stripe() { const theme = useContext(ThemeContext); const options = { fonts: [ { cssSrc: `https://fonts.googleapis.com/css?family=${theme.fonts.body.replace( /\s/g, '+', )}`, }, ], }; return ( <Elements stripe={loadStripe('PK_TEST_KEY')} options={options}> <CheckoutForm /> </Elements> ); }
onSubmit by using both the useStripe hook to grab a Stripe instance that can process payments and useElements hook that can be used to determine which Stripe element we are targeting the get the card payment informaton.function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const handleSubmit = async (event: React.SyntheticEvent) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js has not yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } // ! NOTE: I believe this is actually what we want to use - will update when confirmed // const payload = await stripe.createPaymentMethod({ // type: 'card', // card: elements.getElement(CardElement), // billing_details: billingDetails, // }); const result = await stripe.confirmCardPayment( 'PK_TEST_KEY', // @ts-ignore - not happy with current form { payment_method: { card: elements.getElement(CardElement), billing_details: { name: 'Jenny Rosen', }, }, }, ); if (result.error) { // Show error to your customer (e.g., insufficient funds) console.log(result.error.message); } else { // The payment has been processed! if (result.paymentIntent.status === 'succeeded') { // Show a success message to your customer // There's a risk of the customer closing the window before callback // execution. Set up a webhook or plugin to listen for the // payment_intent.succeeded event that handles any business critical // post-payment actions. } } }; return ( <form onSubmit={handleSubmit}> <CardSection /> <button disabled={!stripe}>Confirm order</button> </form> ); }
const cardElementOptions = (theme: any) => ({ style: { hidePostalCode: true, base: { color: theme.colors.black, fontFamily: `${theme.fonts.body}, sans-serif`, fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4', }, }, invalid: { color: theme.colors.error, iconColor: theme.colors.error, }, }, }); function CardSection() { const theme = useContext(ThemeContext); return <CardElement options={cardElementOptions(theme)} />; }