|
| 1 | +import React, { forwardRef, Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react"; |
| 2 | +import { CardCvcElement, CardExpiryElement, CardNumberElement, useElements, useStripe } from "@stripe/react-stripe-js"; |
| 3 | +import { Box, Grid, TextField } from "@material-ui/core"; |
| 4 | +import { makeStyles } from "@material-ui/core/styles"; |
| 5 | +import Alert from "@material-ui/lab/Alert"; |
| 6 | +import useStripePaymentIntent from "./hooks/useStripePaymentIntent"; |
| 7 | +import StripeInput from "./StripeInput"; |
| 8 | + |
| 9 | +const useStyles = makeStyles(() => ({ |
| 10 | + stripeForm: { |
| 11 | + display: "flex", |
| 12 | + flexDirection: "column" |
| 13 | + } |
| 14 | +})); |
| 15 | + |
| 16 | +function SplitForm( |
| 17 | + { |
| 18 | + isSaving, |
| 19 | + onSubmit, |
| 20 | + onReadyForSaveChange, |
| 21 | + stripeCardNumberInputLabel = "Card Number", |
| 22 | + stripeCardExpirationDateInputLabel = "Exp.", |
| 23 | + stripeCardCVCInputLabel = "CVC" |
| 24 | + }, |
| 25 | + ref |
| 26 | +) { |
| 27 | + const classes = useStyles(); |
| 28 | + const stripe = useStripe(); |
| 29 | + const elements = useElements(); |
| 30 | + const options = useMemo( |
| 31 | + () => ({ |
| 32 | + showIcon: true, |
| 33 | + style: { |
| 34 | + base: { |
| 35 | + fontSize: "18px" |
| 36 | + } |
| 37 | + } |
| 38 | + }), |
| 39 | + [] |
| 40 | + ); |
| 41 | + const [error, setError] = useState(); |
| 42 | + |
| 43 | + const [formCompletionState, setFormCompletionState] = useState({ |
| 44 | + cardNumber: false, |
| 45 | + cardExpiry: false, |
| 46 | + cardCvc: false |
| 47 | + }); |
| 48 | + |
| 49 | + const [isConfirmationInFlight, setIsConfirmationInFlight] = useState(false); |
| 50 | + |
| 51 | + const [createStripePaymentIntent] = useStripePaymentIntent(); |
| 52 | + |
| 53 | + const isReady = useMemo(() => { |
| 54 | + const { cardNumber, cardExpiry, cardCvc } = formCompletionState; |
| 55 | + |
| 56 | + if (!isSaving && !isConfirmationInFlight && cardNumber && cardExpiry && cardCvc) return true; |
| 57 | + |
| 58 | + return false; |
| 59 | + }, [formCompletionState, isSaving, isConfirmationInFlight]); |
| 60 | + |
| 61 | + useEffect(() => { |
| 62 | + onReadyForSaveChange(isReady); |
| 63 | + }, [onReadyForSaveChange, isReady]); |
| 64 | + |
| 65 | + const onInputChange = useCallback( |
| 66 | + ({ elementType, complete }) => { |
| 67 | + if (formCompletionState[elementType] !== complete) { |
| 68 | + setFormCompletionState({ |
| 69 | + ...formCompletionState, |
| 70 | + [elementType]: complete |
| 71 | + }); |
| 72 | + } |
| 73 | + }, |
| 74 | + [formCompletionState, setFormCompletionState] |
| 75 | + ); |
| 76 | + |
| 77 | + const handleSubmit = useCallback( |
| 78 | + async (event) => { |
| 79 | + if (event) { |
| 80 | + event.preventDefault(); |
| 81 | + } |
| 82 | + |
| 83 | + if (!stripe || !elements || isSaving || isConfirmationInFlight) { |
| 84 | + // Stripe.js has not loaded yet, saving is in progress or card payment confirmation is in-flight. |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + setError(); |
| 89 | + setIsConfirmationInFlight(true); |
| 90 | + |
| 91 | + // Await the server secret here |
| 92 | + const { paymentIntentClientSecret } = await createStripePaymentIntent(); |
| 93 | + |
| 94 | + const result = await stripe.confirmCardPayment(paymentIntentClientSecret, { |
| 95 | + // eslint-disable-next-line camelcase |
| 96 | + payment_method: { |
| 97 | + card: elements.getElement(CardNumberElement) |
| 98 | + } |
| 99 | + }); |
| 100 | + |
| 101 | + setIsConfirmationInFlight(false); |
| 102 | + |
| 103 | + if (result.error) { |
| 104 | + // Show error to your customer (e.g., insufficient funds) |
| 105 | + console.error(result.error.message); // eslint-disable-line |
| 106 | + setError(result.error.message); |
| 107 | + } else if (result.paymentIntent.status === "succeeded" || result.paymentIntent.status === "requires_capture") { |
| 108 | + // Show a success message to your customer |
| 109 | + // There's a risk of the customer closing the window before callback |
| 110 | + // execution. Set up a webhook or plugin to listen for the |
| 111 | + // payment_intent.succeeded event that handles any business critical |
| 112 | + // post-payment actions. |
| 113 | + const { amount, id } = result.paymentIntent; |
| 114 | + onSubmit({ |
| 115 | + amount: amount ? parseFloat(amount / 100) : null, |
| 116 | + data: { stripePaymentIntentId: id }, |
| 117 | + displayName: "Stripe Payment" |
| 118 | + }); |
| 119 | + } else { |
| 120 | + console.error("Payment was not successful"); // eslint-disable-line |
| 121 | + setError("Payment was not successful"); |
| 122 | + } |
| 123 | + }, |
| 124 | + [createStripePaymentIntent, onSubmit, stripe, setError, isConfirmationInFlight, setIsConfirmationInFlight] |
| 125 | + ); |
| 126 | + |
| 127 | + useImperativeHandle(ref, () => ({ |
| 128 | + submit() { |
| 129 | + handleSubmit(); |
| 130 | + } |
| 131 | + })); |
| 132 | + |
| 133 | + return ( |
| 134 | + <Fragment> |
| 135 | + <Box my={2}> |
| 136 | + <Grid container spacing={2}> |
| 137 | + {error && ( |
| 138 | + <Grid item xs={12}> |
| 139 | + <Alert severity="error">{error}</Alert> |
| 140 | + </Grid> |
| 141 | + )} |
| 142 | + <Grid item xs={12}> |
| 143 | + <form onSubmit={handleSubmit} className={classes.stripeForm}> |
| 144 | + <Grid container spacing={2}> |
| 145 | + <Grid item xs={12}> |
| 146 | + <TextField |
| 147 | + label={stripeCardNumberInputLabel} |
| 148 | + name="ccnumber" |
| 149 | + variant="outlined" |
| 150 | + fullWidth |
| 151 | + InputProps={{ |
| 152 | + inputComponent: StripeInput, |
| 153 | + inputProps: { |
| 154 | + component: CardNumberElement, |
| 155 | + options |
| 156 | + } |
| 157 | + }} |
| 158 | + InputLabelProps={{ |
| 159 | + shrink: true |
| 160 | + }} |
| 161 | + onChange={onInputChange} |
| 162 | + required |
| 163 | + /> |
| 164 | + </Grid> |
| 165 | + |
| 166 | + <Grid item xs={6}> |
| 167 | + <TextField |
| 168 | + label={stripeCardExpirationDateInputLabel} |
| 169 | + name="ccexp" |
| 170 | + variant="outlined" |
| 171 | + fullWidth |
| 172 | + InputProps={{ |
| 173 | + inputComponent: StripeInput, |
| 174 | + inputProps: { |
| 175 | + component: CardExpiryElement, |
| 176 | + options |
| 177 | + } |
| 178 | + }} |
| 179 | + InputLabelProps={{ |
| 180 | + shrink: true |
| 181 | + }} |
| 182 | + onChange={onInputChange} |
| 183 | + required |
| 184 | + /> |
| 185 | + </Grid> |
| 186 | + |
| 187 | + <Grid item xs={6}> |
| 188 | + <TextField |
| 189 | + label={stripeCardCVCInputLabel} |
| 190 | + name="cvc" |
| 191 | + variant="outlined" |
| 192 | + fullWidth |
| 193 | + InputProps={{ |
| 194 | + inputComponent: StripeInput, |
| 195 | + inputProps: { |
| 196 | + component: CardCvcElement, |
| 197 | + options |
| 198 | + } |
| 199 | + }} |
| 200 | + InputLabelProps={{ |
| 201 | + shrink: true |
| 202 | + }} |
| 203 | + onChange={onInputChange} |
| 204 | + required |
| 205 | + /> |
| 206 | + </Grid> |
| 207 | + </Grid> |
| 208 | + </form> |
| 209 | + </Grid> |
| 210 | + </Grid> |
| 211 | + </Box> |
| 212 | + </Fragment> |
| 213 | + ); |
| 214 | +} |
| 215 | + |
| 216 | +export default forwardRef(SplitForm); |
0 commit comments