Saving Stripe Card Details using JavaScript: A Guide

Upon the first user’s arrival, they are given two options: either access their previously saved cards or enter new card details. If the latter option is chosen, the customer’s card details are collected and a token is generated. This token, along with the customer’s ID (if they are an existing customer), is fetched from the database. If no customer ID is found, a new customer is created using the Stripe token obtained after adding payment information. However, it’s important to note that this token is only valid for one use, and customer ID cannot be used directly to charge the customer. So, the question arises: how can customers be charged in the future, and how can saved payment methods be viewed, deleted, or updated? The solution is to generate a token for the new card that has been added to the customer’s account on Stripe. This token is then used to save the card to the customer’s account by storing the customer ID (cust_###) and card ID (card_###).

Question:

Upon reviewing my query, I am experiencing a state of perplexity due to encountering several articles and Stripe documentation, each offering varying solutions for saving a card. In my application flow, the user is presented with two options upon arrival.

  1. previous saved cards
  2. enter new card
Enter New card

To begin, I gather
card details
from the customer. Next, I create a token and send it along with the customer’s ID (which is retrieved from the database if they are a returning customer). This process confirms that the customer already exists. If no ID is found, I create a new one using the
stripe token
provided after adding payment information. Once the customer’s ID is established, I am able to charge them accordingly.

stripe.charges.create({
        amount:amount,
        description: '',
        currency: 'usd',
        customer: customerid
      })
Now here my question starts

After providing payment details, the token I received cannot be utilized more than once. Directly charging the customer using their customerId is not possible. Therefore, I am uncertain about how to charge the customer in the future and how to manage their payment methods, such as deleting or updating them.


Solution 1:

Initially, upon a customer’s addition of a card on the frontend, you have the ability to retain it as a payment technique to utilize at a later time.

Frontend:

const result = await stripe.createPaymentMethod({
    type: 'card',
    card: cardElement,
    billing_details: {
        // Some details of your customer like email, name, etc
    },
});

The

result.paymentMethod.id

must be sent to the backend, and then the

paymentMethod

should be shared with the customer.

stripe.customers.create({
    email: emailAddress,
    invoice_settings: {
        default_payment_method: paymentMethodId,
    },
    payment_method: paymentMethodId,
});
// paymentMethodId is the payment method id passed from frontend

You can check the below documents:

The link for saving and reusing payments can be found at https://
stripe.com
/docs/payments/save-and-reuse.

check out the documentation on how to save money while making payments on Stripe’s website.

It’s not necessary to save anything in your database for future use because Stripe will handle all other customer information, and only the customer ID needs to be saved.


Solution 2:


Stripe offers limited choices for card storage. You can opt to either save the paymentMethod after the first payment, or you can save the card details before making a payment.

To retain credit card information prior to making a payment:

  1. Crete StripeCustomer
CustomerCreateParams params = CustomerCreateParams.builder()
            .setName("Customer name")
            .setEmail("customer@email")
            .build();
Customer customer = Customer.create(params);
  1. Create a SetupIntent instance on the server side.
SetupIntentCreateParams setupIntentCreateParams = SetupIntentCreateParams.builder().setCustomer(customer.getId()).build();
SetupIntent intent = SetupIntent.create(setupIntentCreateParams);
return new PrepareSetupResponse(intent.getClientSecret());
  1. Send

    intent.getClientSecret()

    as

    prepareSetupResponse.data.clientSecret

    to frontend

  2. Send

    stripe.confirmCardSetup

    and use

    result.setupIntent.payment_method

    to create

    PaymentIntent

    on backend


    .setOffSession(true).setConfirm(true);

    is important for offline payments

Builder paramsBuilder = builder()
            .setCurrency("USD")
            .addPaymentMethodType("card")
            .setOffSession(true)
            .setConfirm(true);
            .setPaymentMethod(confirmSubscriptionRequest.getPaymentMethod())
            .setCustomer(customer.getId());
            
PaymentIntent intent = PaymentIntent.create(paymentIntentParameters.build());

Complete JS side example

axios.post(prepareSetupUrl).then(prepareSetupResponse => {
      if (prepareSetupResponse.status === 200) {
        const clientSecret = prepareSetupResponse.data.clientSecret;
        stripe.confirmCardSetup(clientSecret, {
          payment_method: {
            card: elements.getElement(CardElement),
            billing_details: {
              name: "cardholder name"
            }
          }
        }).then(result => {
          if (result.setupIntent && result.setupIntent.payment_method) {
            axios.post(preparePaymentUrl, {
              paymentMethod: result.setupIntent.payment_method
            }).then((confirmPaymentResponse) => {
              if (confirmPaymentResponse.status === 200) {
                this.props.history.push("/checkout/success");
              } else {
                this.props.history.push("/checkout/failed");
                console.log(confirmPaymentResponse.statusText);
              }
            }).catch(exception => {
              console.log(exception);
              this.props.history.push("/checkout/failed");
            });
          } else {
            that.props.history.push("/checkout/failed");
          }
        });
      }


Solution 3:


After obtaining a token from Stripe, it must be utilized in the next step to create a customer. This can be achieved via the

stripe.customers.create

call. The token will be transformed into a source, which can be utilized multiple times. For more information, refer to https://stripe.com/docs/api/customers/create#create_customer-source.

Upon retrieving the customer object, you will observe that the source remains intact for future reference. Check out: https://stripe.com/docs/api/customers/retrieve.

Instead of using the source parameter, utilize the new source_id within the customer object when generating a new charge. In case you don’t provide a source_id, the default one assigned to the customer will be used.

To add more cards for a customer, the Card Creation API can be used. This API enables creating, updating, and deleting cards. Refer to: https://stripe.com/docs/api/cards/create

Frequently Asked Questions