@stripe/stripe-js#StripeElement TypeScript Examples

The following examples show how to use @stripe/stripe-js#StripeElement. 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: handle_update_payments.ts    From app-stormkit-io with GNU General Public License v3.0 5 votes vote down vote up
handleUpdatePaymentMethod =
  (props: UpdatePaymentMethodProps) =>
  async (formValues: UpdatePaymentMethodFormValues): Promise<void> => {
    const { api, stripe, elements, setLoading, setError, history } = props;
    const name = formValues.name?.trim();

    if (!stripe || !elements) {
      return setError("Stripe is not loaded yet.");
    }

    if (!name) {
      return setError("Please provide a cardholder's name.");
    }

    try {
      setError(null);
      setLoading(true);

      const element = elements.getElement(CardNumberElement);

      const { source, error } = await stripe.createSource(
        element as StripeElement,
        {
          type: "card",
          currency: "usd",
          owner: { name },
        }
      );

      if (!source?.id) {
        setLoading(false);
        return handleStripeError({ error, setError });
      }

      if (source?.status === "chargeable") {
        const options = { sourceId: source.id };

        try {
          const response = await api.post<UpdatePaymentMethodAPIResponse>(
            "/user/subscription/card",
            options
          );

          if (response && response.customerId) {
            setLoading(false);
            return history.push({ state: { cards: Date.now() } });
          }
        } catch (e) {
          // Do nothing
        }
      }

      setLoading(false);
      return setError(
        "Your card seems not to be chargeable. Please try using a different card."
      );
    } catch (e) {
      console.error(e.message);
      setLoading(false);
      setError(
        "We were not able to create a payment source on Stripe. Please contact us on Discord or through email."
      );
    }
  }