Stripe.js Reference

    Stripe.js makes it easy to collect certain kinds of sensitive information without having it touch your server. If you need help after reading this, search our documentation or check out answers to common questions. You can even chat live with other developers in #stripe on freenode.

    Stripe.js is our foundational JavaScript library for securely sending sensitive information to Stripe directly from the customer’s browser.

    Including Stripe.js

    However you’re using Stripe.js, you always begin by including the library and setting your API key. 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. This allows Stripe to detect anomalous behavior that may be indicative of fraud as users browse your web site.

    Setting your publishable key

    Your Stripe publishable API key is required when using Stripe.js as 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()
    • stripe.createToken()

    stripe.elements([options])

    Create pre-built UI components to collect sensitive card information with Elements.

    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 placeholders and error strings in. 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. Default is auto (Stripe detects the locale of the browser). Supported values are: da, de, en, es, fi, fr, it, ja, no, nl, sv, zh.

    stripe.createToken(element[, options])

    Use stripe.createToken to convert card information collected by Elements into a single-use token that you safely pass to your server to use in an API call.

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

    This method 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 containing 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.

    stripe.createToken('bank_account'[, options])

    Use stripe.createToken to convert bank account information into a single-use token that you safely pass to your server to use in an API call.

    stripe.createToken('bank_account', {
      country: 'us',
      currency: 'usd',
      routing_number: '110000000',
      account_number: '000123456789',
      account_holder_name: 'Jenny Rosen',
      account_holder_type: 'individual',
    }).then(function(result) {
      // handle result.error or result.token
    });
    const {token, error} = await stripe.createToken('bank_account', {
      country: 'us',
      currency: 'usd',
      routing_number: '110000000',
      account_number: '000123456789',
      account_holder_name: 'Jenny Rosen',
      account_holder_type: 'individual',
    });

    Using stripe.createToken for bank account details requires a JavaScript object containing the following parameters:

    country
    string
    Two character country code (e.g., us).
    currency
    string
    Three character currency code (e.g., usd).
    routing_number
    string
    The bank routing number (e.g., 111000025). Optional if the currency is eur, as the account number will be an IBAN.
    account_number
    string
    The bank account number (e.g., 000123456789)
    account_holder_name
    string
    The name of the account holder.
    account_holder_type
    string
    The type of entity that holds the account. Can be either individual or company.

    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.

    stripe.createToken('pii'[, options])

    Use stripe.createToken to convert personally identifiable information (PII) into a single-use token for managed account identity verification.

    stripe.createToken('pii', {
      personal_id_number: '123131185',
    }).then(function(result) {
      // handle result.error or result.token
    });
    const {token, error} = await stripe.createToken('pii', {
      personal_id_number: '123131185',
    });

    Using stripe.createToken for PII data requires a JavaScript object containing the following parameter:

    personal_id_number
    string
    The personal ID number.

    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.clear()
      • 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 the Element gains focus.
    ready Triggered when the Element is fully rendered and can accept element.focus() calls.

    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 U.S. 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 U.S. billing address country. When using these to test your payment form, you must also use a five-digit U.S. 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.
    clear() Clears the value(s) of 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.

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

    You can also dynamically change the styles of an Element using update(). This method can be used to simulate CSS media queries that automatically adjust the size of Elements when viewed on different devices.

    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.

    Collecting Apple Pay details

    Collecting sources

    Supported browsers

    Stripe.js strives to support all recent versions of major browsers. For the sake of security and providing the best experience to the majority of customers, we do not support browsers that are no longer receiving security updates and represent a small minority of traffic.

    • We support Internet Explorer and Edge per Microsoft's lifecycle policy. As of January 12, 2016, we support Internet Explorer 9 and above.
    • We support Chrome and Safari on all platforms and Firefox on desktop platforms.
    • We support the Android native browser on Android 4.4 and later.
    • We respond to bug reports but do not proactively test other mobile browsers.

    If you have an issue with Stripe.js on a specific browser, please contact us so we can improve its support.