Stripe Elements Reference

    Securely collect sensitive card details using Elements, our pre-built UI components. If you need help after reading this, check out our answers to common questions or chat live with other developers in #stripe on freenode.

    Contents

    Including the JavaScript library

    Elements is available as part of Stripe.js. To get started, include this script on your pages—it should always be loaded directly from https://js.stripe.com:

    <script src="https://js.stripe.com/v3/"></script>

    To best leverage Stripe’s advanced fraud functionality, include this script on every page on your site, not just the checkout page.

    Setting your publishable key

    Initializing a stripe object requires your Stripe publishable API key. This identifies your website to Stripe:

    var stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
    const stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');

    We've placed a random API key in the code. Replace it with your actual publishable API key to test this code through your Stripe account.

    When you’re ready to accept live payments, replace the test key with your live key in production. Learn more about how API keys work in test mode and live mode.

    The stripe object

    • stripe.elements([options])
    • stripe.createToken(element[, options])

    stripe.elements([options])

    var elements = stripe.elements();
    const elements = stripe.elements();

    This method creates an instance of elements, which manages a group of Elements. It accepts an optional options object. Available options are documented below.

    Elements options

    fonts
    array
    An array of custom fonts Elements created from the elements object can use.
    Font attributes:
    • family: The name to give the font. You can use it later in style as a fontFamily by referencing this name.
    • src: A valid src value referencing your custom font.
    • style: One of normal, italic, oblique. Defaults to normal.
    • unicodeRange: A valid unicode-range value.
    • weight: A valid font-weight.
    locale
    string
    The IETF language tag of the locale to display strings in. Default is auto; Stripe will detect the locale of the browser. Setting the locale does not affect the behavior of postal code validation—a valid postal code for the billing country of the card is still required.

    stripe.createToken(element[, options])

    Use stripe.createToken to convert the payment data collected by Elements into a single-use token that you safely pass to your server and use when creating charges, setting up subscriptions, or sending transfers to debit cards attached to connected Stripe accounts.

    stripe.createToken(card).then(function(result) {
      // handle result.error or result.token
    });
    const {token, error} = await stripe.createToken(card);

    stripe.createToken takes two arguments:

    • element: the Element you wish to tokenize data from. The Element will pull data from other Elements you’ve created on the same instance of elements to tokenize.
    • options: an optional JavaScript object with any of the following parameters:
    name
    string
    Cardholder name
    address_line1 address_line2 address_city address_state address_zip address_country
    string
    Billing address information
    currency
    currency
    Required in order to be able to add the card to a Connect account (in all other cases, this parameter is not used). Currently, the only supported currency for debit card transfers is usd.

    Although these fields are optional, we highly recommend collecting name and address. This information can be used to perform a number of verifications, such as CVC, ZIP, and address verification. Radar includes built-in rules that can block payments where the ZIP or CVC verifications with the cardholder’s bank failed.

    stripe.createToken returns a Promise which resolves with a result object. This object has either:

    • result.token: a Token was created successfully.
    • result.error: there was an error. This includes client-side validation errors. Refer to the API reference for all possible errors.

    The elements object

    • elements.create(type[, options])

    elements.create(type[, options])

    var card = elements.create('card');
    const card = elements.create('card');

    This method creates an instance of a specific Element.

    It takes the type of Element to create as well as an optional options object.

    Element types

    card
    recommended
    A flexible single-line input that collects all necessary card details.
    cardNumber The card number.
    cardExpiry The card's expiration date.
    cardCvc The card's CVC number.
    postalCode the ZIP/postal code.

    Element options

    classes
    object
    Set custom class names on the container DOM element when the Stripe Element is in a particular state.
    Show child attributes
    base
    string
    The base class applied to the container. Defaults to StripeElement.
    complete
    string
    The class name to apply when the Element is complete. Defaults to StripeElement--complete.
    empty
    string
    The class name to apply when the Element is empty. Defaults to StripeElement--empty.
    focus
    string
    The class name to apply when the Element is focused. Defaults to StripeElement--focus.
    invalid
    string
    The class name to apply when the Element is invalid. Defaults to StripeElement--invalid.
    webkitAutofill
    string
    The class name to apply when the Element has its value autofilled by the browser (only on Chrome and Safari). Defaults to StripeElement--webkit-autofill.
    hidePostalCode
    boolean
    Hide the postal code field (if applicable to the Element you're creating). Default is false. If you are already collecting a billing ZIP or postal code on the checkout page, you should set this to true.
    hideIcon
    boolean
    Hides any icons in the Element. Default is false.
    iconStyle
    string
    Appearance of the icons in the Element. Either 'solid' or 'default'.
    style
    object
    Customize appearance using CSS properties. Style is specified as an object for any of the following variants:
    • base: base style—all other variants inherit from this style
    • complete: applied when the Element has valid input
    • empty: applied when the Element has no user input
    • invalid: applied when the Element has invalid input
    For each of the above, the following properties can be customized:
    • color
    • fontFamily
    • fontSize
    • fontSmoothing
    • fontStyle
    • fontVariant
    • iconColor
    • lineHeight
    • letterSpacing
    • textDecoration
    • textShadow
    • textTransform
    The following pseudo-classes and pseudo-elements can also be styled with the above properties, as a nested object inside the variant:
    • :hover
    • :focus
    • ::placeholder
    • ::selection
    • :-webkit-autofill
    value
    string, object
    A pre-filled value (for single-field inputs) or set of values (for multi-field inputs) to include in the input, e.g. {postalCode: '94110'}. Note that sensitive card information (card number, CVC, and expiration date) cannot be pre-filled.

    Here is an example that customizes the base and invalid states of a card Element:

    var style = {
      base: {
        color: '#303238',
        fontSize: '16px',
        lineHeight: '48px',
        fontSmoothing: 'antialiased',
        '::placeholder': {
          color: '#ccc',
        },
      },
      invalid: {
        color: '#e5424d',
        ':focus': {
          color: '#303238',
        },
      },
    };
    var cardElement = elements.create('card', {style: style})
    const style = {
      base: {
        color: '#303238',
        fontSize: '16px',
        lineHeight: '48px',
        fontSmoothing: 'antialiased',
        '::placeholder': {
          color: '#ccc',
        },
      },
      invalid: {
        color: '#e5424d',
        ':focus': {
          color: '#303238',
        },
      },
    };
    const cardElement = elements.create('card', {style})

    The Element

    • element.mount(domElement)
    • element.on(event, handler)
    • Other methods
      • element.blur()
      • element.focus()
      • element.unmount()
      • element.update(options)

    element.mount(domElement)

    You will need to create a container DOM element in order to mount an Element. If it has a label, it will be automatically focused when its label is clicked. There are two ways to do this:

    1. Mount the instance within a <label>.
      <label>Card
        <div id="card-element"></div>
      </label>
    2. Create a <label> with a for attribute, referencing the ID of your container.
      <label for="card-element">Card</label>
      <div id="card-element"></div>

    The mount method attaches your element to the DOM. mount accepts either a CSS Selector (e.g. '#card-element') or a DOM element.

    cardElement.mount('#card-element');

    element.on(event, handler)

    Attach an event listener to listen for Element events. The following events can be triggered:

    blur Triggered when the Element loses focus.
    change Triggered when any of the following values changes on the Element:
    empty
    boolean
    true if the value is empty.
    complete
    boolean
    true if the value is complete and valid.
    brand
    string
    Applies to the card and cardNumber Elements only. Contains the card brand (e.g. visa or amex) of the card number being entered.
    error
    object
    The current validation error, if any. Comprised of message, code, and type set to validation_error.
    value
    string, object
    An object similar to the one used for value when creating an Element. Only present for non-sensitive values, like postalCode.
    focus Triggered when Element gains focus.

    Input validation

    Elements validates user input as it is typed. To help your customers catch mistakes, you should listen to change events on the card Element and display any errors:

    card.addEventListener('change', function(event) {
      var displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = event.error.message;
      } else {
        displayError.textContent = '';
      }
    });
    
    card.addEventListener('change', ({error}) => {
      const displayError = document.getElementById('payment-errors');
      if (error) {
        displayError.textContent = error.message;
      }
    });

    Postal code formatting

    Elements automatically determines your customer’s billing address country based on their card number. Using this information, the postal code field validation reflects whether that country uses numeric or alphanumeric-formatted postal codes, or if the country uses postal codes at all. For instance, if a US card is entered, the postal code field only accepts a five-digit numeric value. If it’s a UK card, an alphanumeric value can be provided instead.

    Many of our test cards have a US billing address country. When using these to test your payment form, you must also use a five-digit US ZIP code (e.g., 12345). To test Elements with other postal code formats, use our international test card numbers.

    Other methods

    blur() Blurs the Element.
    focus() Focuses the Element.
    unmount() Unmounts the Element from the DOM.
    update(options) Updates the options the Element was initialized with. Updates are merged into the existing configuration. Accepts the same options as elements.create.

    If you collect certain information in a different part of your interface (e.g. ZIP or postal code), use update() with the appropriate information.

    document.querySelector('input[name="my-postal-code"]').on('change', function(event) {
      card.update({value: {postalCode: event.target.value}});
    });
    document.querySelector('input[name="my-postal-code"]').on('change', ({target}) => {
      card.update({value: {postalCode: target.value}});
    });

    You can also dynamically change the styles of an Element:

    window.addEventListener('resize', function(event) {
      if (window.innerWidth <= 320) {
        card.update({style: {base: {fontSize: '13px'}}});
      } else {
        card.update({style: {base: {fontSize: '16px'}}});
      }
    });
    
    var previousBrand;
    card.on('change', function(event) {
      if (event.brand !== previousBrand && event.brand === 'mastercard') {
        card.update({style: {base: {color: 'orange'}}});
        previousBrand = payload.brand;
      }
    });
    window.addEventListener('resize', (event) => {
      if (window.innerWidth <= 320) {
        card.update({style: {base: {fontSize: '13px'}}});
      } else {
        card.update({style: {base: {fontSize: '16px'}}});
      }
    });
    
    let previousBrand;
    card.on('change', ({brand}) => {
      if (brand !== previousBrand && brand === 'mastercard') {
        card.update({style: {base: {color: 'orange'}}});
        previousBrand = payload.brand;
      }
    });

    The Element container

    You should style the container you mount an Element to as if it were an <input> on your page. For example, to control padding and border on an Element, set these properties on the container. This is usually done by re-using the classes that you have applied to your DOM <input>s. Example:

    <style>
     .my-input {
       padding: 10px;
       border: 1px solid #ccc;
     }
    </style>
    
    <form>
      <div>
        <label>Name</label>
        <input class="my-input">
      </div>
      <div>
        <label>Card</label>
        <!-- Using the same "my-input" class on the -->
        <!-- regular input above and on this container. -->
        <div class="my-input" id="card-element"></div>
      </div>
    </form>

    After the Element is mounted, the .StripeElement class is added to the container. Additionally, the following classes are automatically added to the container when the Element is complete, empty, focused, invalid, or autofilled by the browser:

    • .StripeElement--complete
    • .StripeElement--empty
    • .StripeElement--focus
    • .StripeElement--invalid
    • .StripeElement--webkit-autofill (Chrome and Safari only)

    You can override these class names using the classes option when you create an Element.