@stripe/react-stripe-js#CardNumberElement JavaScript Examples

The following examples show how to use @stripe/react-stripe-js#CardNumberElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StripeForm.jsx    From saasgear with MIT License 6 votes vote down vote up
CardNumberEl = styled(CardNumberElement)`
  padding: 11.6px 10px;
  background: ${COLORS.LIGHT_GRAY};
  border: 1px solid ${COLORS.WHITE_BLUE};
  border-radius: 10px;
  font-size: 16px;
  line-height: 19px;
  text-align: center;
  color: ${COLORS.WHITE_GRAY};
  box-sizing: border-box;
`
Example #2
Source File: index.jsx    From rysolv with GNU Affero General Public License v3.0 6 votes vote down vote up
CreditCard = ({ setZipCode, zipCode }) => (
  <Fragment>
    <OptionWrapper>
      <OptionLabel>Credit card number</OptionLabel>
      <StyledStripeInput component={CardNumberElement} />
    </OptionWrapper>
    <HorizontalWrapper>
      <OptionWrapper width="49%">
        <OptionLabel>Expiration date</OptionLabel>
        <StyledStripeInput component={CardExpiryElement} />
      </OptionWrapper>
      <OptionWrapper width="49%">
        <OptionLabel>CVC</OptionLabel>
        <StyledStripeInput component={CardCvcElement} />
      </OptionWrapper>
    </HorizontalWrapper>
    <OptionWrapper width="49%">
      <OptionLabel>Zip code</OptionLabel>
      <Input
        height="4.9rem"
        onChange={e => setZipCode(e.target.value)}
        placeholder="12345"
        type="text"
        value={zipCode}
      />
      <OptionError />
    </OptionWrapper>
  </Fragment>
)
Example #3
Source File: StripeForm.jsx    From saasgear with MIT License 5 votes vote down vote up
StripeForm = ({
  onSubmitSuccess,
  className,
  onGoBack,
  apiLoading,
  apiError,
  submitText = 'Submit',
}) => {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');
  const stripe = useStripe();
  const elements = useElements();

  useEffect(() => {
    setIsSubmitting(apiLoading);
  }, [apiLoading]);

  useEffect(() => {
    setError(apiError);
  }, [apiError]);

  async function onSubmit(e) {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      const card = elements.getElement(CardNumberElement);
      const result = await stripe.createToken(card);
      if (result.error) {
        setError(result.error.message);
      } else {
        onSubmitSuccess(result.token.id);
      }
    } catch (err) {
      setError(err.toString());
    }

    setIsSubmitting(false);
  }

  return (
    <StripeFormContainer onSubmit={onSubmit} className={className}>
      <div>
        {onGoBack && <BackButton type="button" onClick={onGoBack} />}
        <div>
          <FormGroup>
            <FormGroupLabel htmlFor="street_address">
              Card Number
            </FormGroupLabel>
            <CardNumberEl className="card-el" />
          </FormGroup>
          <RowGroup>
            <FormGroupCardExpire>
              <FormGroupLabel htmlFor="first_name">Expiration</FormGroupLabel>
              <CardExpiryElementEl />
            </FormGroupCardExpire>
            <FormGroupCardCvc>
              <FormGroupLabel htmlFor="last_name">CVC</FormGroupLabel>
              <CardCvcElementEl />
            </FormGroupCardCvc>
          </RowGroup>
        </div>
      </div>
      {error && (
        <p className="text-red-500 text-xs italic mt-1 text-center">{error}</p>
      )}
      <SubmitButton
        type="submit"
        disabled={isSubmitting}
        color="primary"
        width="100%"
      >
        {isSubmitting ? 'Please wait' : submitText}
      </SubmitButton>
    </StripeFormContainer>
  );
}
Example #4
Source File: CheckoutForm.js    From jamstack-ecommerce with MIT License 5 votes vote down vote up
export default function CheckoutForm() {
    const stripe = useStripe();
    const elements = useElements();

    const checkoutSubmit = async()=>{
        const response = await fetch("/.netlify/functions/checkout", {method: "post"});
        const data = await response.json();
        console.log("DAta = ",data);

        const result = await stripe.confirmCardPayment(data.client_secret, {
            payment_method: {
                card: elements.getElement(CardNumberElement),
                billing_details: {
                  name: 'Zia Khan',
                  email: "[email protected]"
                },
            }
        })

        console.log("Result = ",result);


    }
  return (
    <div>
      Checkout Form
      <div>
          {/*<CardElement options={CARD_ELEMENT_OPTIONS} />*/ }

        <CardNumberElement options={CARD_ELEMENT_OPTIONS}/>
        <CardExpiryElement options={CARD_ELEMENT_OPTIONS}/>
        <CardCvcElement options={CARD_ELEMENT_OPTIONS}/>

      </div>
      <button onClick={checkoutSubmit}>
          Checkout
      </button>
    </div>
  )
}
Example #5
Source File: checkout.js    From turqV2 with GNU General Public License v3.0 5 votes vote down vote up
function CheckoutForm({location, dispatch, isComplete, isSuccess, isFetching}) {

  const stripe = useStripe();
  const elements = useElements();
  const [cardName, setCardName] = useState("");
  const [amount, setAmount] = useState(0);

  useEffect(() => {
    if (location.state.contest === undefined) {
      toast.error("No contest");
    }
  }, [location]);

  const handleSubmit = async () => {
    if (!stripe || !elements) {
      // Stripe.js has not loaded yet. Make sure to disable
      // form submission until Stripe.js has loaded.
      return;
    }

    if (amount === undefined || amount === null || amount === 0) {
      toast.error("Payment Failed: Please select a donation amount");
      return;
    } else if (amount < 1) {
      toast.error("Payment Failed: Minimum donation is $1.00");
      return;
    } else if (cardName === undefined || cardName === null || cardName === "") {
      toast.error("Payment Failed: Please Provide the name on your credit card");
      return
    }
    dispatch(payment(location.state.contest, amount, elements.getElement(CardNumberElement), cardName, stripe))
  };

  const handleChange = (event) => {
    setCardName(event.target.value)
  }

  return(
    <>
    { !isFetching && isComplete && isSuccess
    ? <Redirect to={THANKYOU_URL} />
    : <Layout fullWidth>
      <div className="checkout-page">
        <Grid container spacing={5} justify="center" alignItems="stretch">
          <Grid container item xs={12} md={6}>
            <Donation setAmount={setAmount} />
          </Grid>
          <Grid container item xs={12} md={6}>
            <Checkout
                handleChange={handleChange}
                handleSubmit={handleSubmit}
                cardName={cardName}
                stripe={stripe}
                isFetching={isFetching}
              />
          </Grid>
          <Grid container item xs={12} justify="center">
            <Grid item>
              <img src="/images/stripe-blurple.png" alt="Powered by Stripe" style={{height:50}}/>
            </Grid>
          </Grid>
        </Grid>
      </div>
    </Layout>
}
    </>
  )
}
Example #6
Source File: CompanyPayment.jsx    From rysolv with GNU Affero General Public License v3.0 4 votes vote down vote up
CompanyPaymentModal = ({
  dispatchClearAlerts,
  dispatchFetchPlaidToken,
  dispatchResetModalState,
  dispatchSetModalAlerts,
  dispatchUpdatePaymentMethod,
  handleClose,
  modalAlerts,
  modalLoading,
  paymentConfirmed,
  plaidToken,
}) => {
  const [selectedMethod, setSelectedMethod] = useState('Credit card');
  const [zipCode, setZipCode] = useState('');
  const elements = useElements();
  const stripe = useStripe();

  useEffect(() => {
    if (!plaidToken) dispatchFetchPlaidToken();
    return dispatchResetModalState;
  }, []);

  const handleSubmit = async () => {
    if (!stripe || !elements) return;

    const cardElement = elements.getElement(CardNumberElement);
    const { error, token } = await stripe.createToken(cardElement, zipCode);

    if (!error) {
      const { id, card } = token;
      dispatchUpdatePaymentMethod({
        metadata: card,
        provider: 'stripe',
        token: id,
      });
    } else {
      // Using standardized 'Something went wrong' errors for now
      // Stripe provides more detailed errors
      dispatchSetModalAlerts({ error: stripeError });
    }
  };

  return (
    <ModalContainer>
      <ConditionalRender
        Component={
          <Fragment>
            <StyledTitle>
              {paymentConfirmed ? 'Update' : 'Add'} payment method
            </StyledTitle>
            <StyledErrorSuccessBanner
              error={modalAlerts.error}
              onClose={dispatchClearAlerts}
              success={modalAlerts.success}
            />
            <BaseRadioButtonGroup
              handleRadioChange={e => setSelectedMethod(e.target.value)}
              selectedValue={selectedMethod}
              values={['Credit card', 'ACH']}
            />
            <ConditionalRender
              Component={
                <CreditCard setZipCode={setZipCode} zipCode={zipCode} />
              }
              FallbackComponent={
                <ACH
                  dispatchSetModalAlerts={dispatchSetModalAlerts}
                  dispatchUpdatePaymentMethod={dispatchUpdatePaymentMethod}
                  plaidToken={plaidToken}
                />
              }
              shouldRender={selectedMethod === 'Credit card'}
            />
            <ButtonWrapper>
              <StyledPrimaryButton label="Cancel" onClick={handleClose} />
              <ConditionalRender
                Component={
                  <StyledPrimaryAsyncButton
                    disabled={!stripe || !zipCode}
                    label="Save"
                    loading={modalLoading}
                    onClick={handleSubmit}
                  />
                }
                shouldRender={selectedMethod === 'Credit card'}
              />
            </ButtonWrapper>
            <DisclaimerWrapper>
              <Asterisk>*</Asterisk> Payment authorized with&nbsp;
              {selectedMethod === 'Credit card' ? 'Stripe' : 'Plaid'}.
            </DisclaimerWrapper>
          </Fragment>
        }
        FallbackComponent={PaymentLoadingIndicator}
        shouldRender={!modalLoading}
      />
    </ModalContainer>
  );
}
Example #7
Source File: CreditCardView.js    From rysolv with GNU Affero General Public License v3.0 4 votes vote down vote up
CreditCardView = ({
  emailValue,
  fundValue,
  handleClearAlerts,
  handleStripeToken,
  handleZipChange,
  isCreditPaymentOpen,
  isPersonalInfoComplete,
  setFundValue,
  setStripeError,
  setZipValue,
  values,
  zipValue,
}) => {
  const stripe = useStripe();
  const elements = useElements();

  const fundAmount = Number(fundValue);
  const feeValue = fundAmount * 0.03 + 0.3;
  const totalValue = fundAmount + feeValue;

  const handleSubmit = async event => {
    event.preventDefault();
    if (!stripe || !elements) {
      return;
    }

    const card = elements.getElement(CardNumberElement);
    const { error, token } = await stripe.createToken(card, zipValue);
    handleClearAlerts();

    if (error) {
      setStripeError({ message: error.message });
    } else {
      handleStripeToken({
        amount: fundValue,
        email: emailValue,
        token,
        values,
      });
      setFundValue('10');
    }
  };
  return (
    <ConditionalRender
      Component={
        <Fragment>
          <CreditCardViewContainer>
            <TextWrapper>
              A 3% + $0.30 standard transaction fee will be added to cover
              credit card processing and the safe transfer of funds.
            </TextWrapper>
            <ChargeBreakdownWrapper>
              <ChargeTitle>
                <Title>Transaction fee</Title>
                <Title isBold>Total due today</Title>
              </ChargeTitle>
              <ChargeValue>
                <Value>{formatDollarAmount(parseFloat(feeValue, 10))}</Value>
                <Value isBold>
                  {formatDollarAmount(parseFloat(totalValue, 10))}
                </Value>
              </ChargeValue>
            </ChargeBreakdownWrapper>
            <InputWrapper>
              <StyledPaymentTextInput
                adornmentComponent="Number"
                InputProps={{
                  inputComponent: StripeInput,
                  inputProps: {
                    component: CardNumberElement,
                  },
                }}
                fontSize="1rem"
              />
              <StyledPaymentTextInput
                adornmentComponent="MM/YY"
                InputProps={{
                  inputComponent: StripeInput,
                  inputProps: {
                    component: CardExpiryElement,
                  },
                }}
                fontSize="1rem"
              />
              <HorizontalInputWrapper>
                <StyledPaymentTextInput
                  adornmentComponent="CVC"
                  InputProps={{
                    inputComponent: StripeInput,
                    inputProps: {
                      component: CardCvcElement,
                    },
                  }}
                  fontSize="1rem"
                />
                <StyledPaymentTextInput
                  adornmentComponent="Zip"
                  fontSize="1rem"
                  inputProps={{ maxLength: 5 }}
                  onChange={e =>
                    handleZipChange(e, e.target.value, setZipValue)
                  }
                  value={zipValue}
                />
              </HorizontalInputWrapper>
            </InputWrapper>
            <StyledPrimaryAsyncButton
              disabled={!isPersonalInfoComplete || !stripe}
              label="Confirm"
              onClick={handleSubmit}
            />
          </CreditCardViewContainer>
        </Fragment>
      }
      shouldRender={isCreditPaymentOpen}
    />
  );
}
Example #8
Source File: CreditCardPaymentComponent.js    From rysolv with GNU Affero General Public License v3.0 4 votes vote down vote up
CreditCardPaymentComponent = ({
  amount,
  handleClearAllAlerts,
  handleStripeToken,
  handleZipChange,
  setStripeError,
  setZipValue,
  zipValue,
}) => {
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async event => {
    event.preventDefault();
    if (!stripe || !elements) {
      return;
    }

    const card = elements.getElement(CardNumberElement);
    const result = await stripe.createToken(card, zipValue);
    handleClearAllAlerts();

    if (result.error) {
      setStripeError({ message: result.error.message });
    } else {
      handleStripeToken({
        amount,
        token: result.token,
        values: { depositValue: amount },
      });
    }
  };
  return (
    <div>
      <InputWrapper width="50%">
        <InputHeader>Card Number</InputHeader>
        <StyledBaseTextInput
          InputProps={{
            inputComponent: StripeInput,
            inputProps: {
              component: CardNumberElement,
            },
          }}
          variant="outlined"
        />
      </InputWrapper>
      <HorizontalWrapper>
        <InputWrapper width="50%">
          <InputHeader>Expiration Date</InputHeader>
          <StyledBaseTextInput
            InputProps={{
              inputComponent: StripeInput,
              inputProps: {
                component: CardExpiryElement,
              },
            }}
            variant="outlined"
          />
        </InputWrapper>
        <InputWrapper width="35%">
          <InputHeader>
            CVV
            <TooltipIconWrapper>
              <TooltipIcon Icon={InfoIcon} Tooltip={CvvTooltip} />
            </TooltipIconWrapper>
          </InputHeader>
          <StyledBaseTextInput
            InputProps={{
              inputComponent: StripeInput,
              inputProps: {
                component: CardCvcElement,
              },
            }}
            variant="outlined"
          />
        </InputWrapper>
      </HorizontalWrapper>
      <InputWrapper width="25%">
        <InputHeader>Postal Code</InputHeader>
        <StyledBaseTextInput
          inputProps={{ maxLength: 5 }}
          onChange={e => handleZipChange(e, e.target.value, setZipValue)}
          value={zipValue}
          variant="outlined"
        />
      </InputWrapper>
      <StyledPrimaryAsyncButton
        disabled={amount <= 0}
        label="Confirm"
        onClick={handleSubmit}
      />
    </div>
  );
}
Example #9
Source File: checkout.js    From turqV2 with GNU General Public License v3.0 4 votes vote down vote up
Checkout = ({handleChange, cardName, handleSubmit, isFetching, stripe}) => {

  return (
    <Card className="checkout-card">
      <CardHeader title="Credit Card Details" />
      <CardContent>
        <Grid container xs={12} spacing={2} alignItems="center" justify="flex-start">
          <Grid item xs={12}>
            <TextField
              id="cardName"
              label="Name on Card"
              fullWidth
              margin="normal"
              required
              onChange={event => handleChange(event)}
              value={cardName}
              InputLabelProps={{
                shrink: true,
              }}
              variant="outlined"
            />
          </Grid>
          <Grid item xs={12} md={6}>
            <TextField
              label="Credit Card Number"
              name="ccnumber"
              variant="outlined"
              margin="normal"
              required
              fullWidth
              InputLabelProps={{ shrink: true }}
              InputProps={{
                  inputComponent: StripeInput,
                  inputProps: {
                      component: CardNumberElement
                  },
              }}
            />
          </Grid>
          <Grid item xs={12} md={3}>
            <TextField
              label="Experation Date"
              name="Experation Date"
              variant="outlined"
              margin="normal"
              required
              fullWidth
              InputLabelProps={{ shrink: true }}
              InputProps={{
                  inputComponent: StripeInput,
                  inputProps: {
                      component: CardExpiryElement
                  },
              }}
            />
          </Grid>
          <Grid item xs={12} md={3}>
            <TextField
              label="cvc"
              name="cvc"
              variant="outlined"
              margin="normal"
              required
              fullWidth
              InputLabelProps={{ shrink: true }}
              InputProps={{
                  inputComponent: StripeInput,
                  inputProps: {
                      component: CardCvcElement
                  },
              }}
            />
          </Grid>
        </Grid>
      </CardContent>
      <CardActions>
        <Grid container xs={12} alignItems="center" justify="center">
          <Grid item>
            <Button size="large" variant="contained" color="primary" type="submit" disabled={!stripe || isFetching} onClick={() => handleSubmit()}>
              Pay Now
            </Button>
          </Grid>
        </Grid>
      </CardActions>
    </Card>
  )
}