Sign in
An image of the Stripe logo
Create account
Sign in
Home
Payments
Business operations
Financial services
Developer tools
All products
Home
Payments
Business operations
Home
Payments
Business operations
Financial services
Developer tools
Support

Stripe.js v2 Reference

Stripe.js allows you to collect credit card—and other similarly sensitive—details without having the information touch your server.

This reference covers Stripe.js v2, the previous version of our foundational JavaScript library. Our current version of Stripe.js includes support for Elements, our prebuilt UI components. We recommend that users of Stripe.js v2 upgrade at their earliest convenience.

Stripe.js is Stripe’s foundational JavaScript library for securely sending sensitive information to Stripe directly from the customer’s browser. Stripe.js can be used for collecting:

  • Card details
  • Bank account details
  • Personally identifiable information
  • Apple Pay payments
  • Sources

Stripe.js includes supports source creation for use with Sources—our standardized approach to creating payments using any of our supported payment methods. It also has built-in validators to check the format of credit card, CVC, bank account, and routing numbers, as well as a credit card’s type and expiration.

Including Stripe.js

However you’re using Stripe.js, you always begin by including the library and setting your API key. Add this <script> tag to your page to get started with Stripe.js:

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

To best leverage Stripe’s advanced fraud functionality, include Stripe.js on every page on your site, not just the checkout page. Including the script on every page allows Stripe to detect suspicious behavior that may be indicative of fraud as users browse your website.

Stripe.js should be loaded directly from https://js.stripe.com/.

If you are migrating to the latest version of Stripe.js incrementally, both versions can be loaded and used on the same page:

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

Setting your publishable key

Your publishable API key identifies your website to Stripe during communications. Set your publishable key with setPublishableKey, after including Stripe.js and before making any requests to Stripe.

Stripe.setPublishableKey(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);

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.

You will need to replace the test key with your live key for production uses. When you’re ready, learn more about how the keys play into test and live modes.

Collecting card details

This method of using Stripe.js to collect card information has been deprecated. When creating a payment form to collect card information, use Stripe.js and Elements—our prebuilt UI components. Check out our Elements migration guide to learn how to migrate your checkout flow and maintain the simplest form of PCI compliance.

You can use these methods to validate and collect credit card details for when you want to process charges, create subscriptions, or send payouts to debit cards attached to connected Stripe accounts.

All of these methods are within the Stripe.card object.

card.createToken

Converts sensitive card data to a single-use token that you can safely pass to your server to charge the user.

Stripe.card.createToken({ number: $('.card-number').val(), cvc: $('.card-cvc').val(), exp_month: $('.card-expiry-month').val(), exp_year: $('.card-expiry-year').val(), address_zip: $('.address_zip').val() }, stripeResponseHandler);

Library agnostic

This example uses jQuery’s val() method to retrieve values entered in the credit card form. jQuery isn’t required; you can also use vanilla JavaScript to retrieve the card data from your payment form instead.

The first argument to createToken is a JavaScript object containing credit card data entered by the user. It should contain the following required members:

  • number: card number as a string without any separators (for example, “4242424242424242”)
  • exp_month: two digit number representing the card’s expiration month (for example, 12)
  • exp_year: two or four digit number representing the card’s expiration year (for example, 2023)
  • cvc: card security code as a string (for example, “123”)

(The expiration date can also be passed as a single string.)

The cvc field represents the card’s security code (for example, 123). While this is an optional field in some countries, always pass the CVC number. Banks and card issuers often decline charges if the CVC number is either incorrect or has not been provided. Additionally, passing the CVC number also helps prevent fraud as it means your customer is more likely in possession of the card, rather than potentially just a card number. You can then make use of the CVC verification check available in Radar that blocks payments where the CVC does not match what the card issuer has on file.

The following fields are entirely optional and cannot result in a token creation failure:

  • name: cardholder name
  • address_line1: billing address line 1
  • address_line2: billing address line 2
  • address_city: billing address city
  • address_state: billing address state
  • address_zip: billing postal code as a string (for example, “94301”)
  • address_country: billing address country

Although these fields are optional, we highly recommend collecting them. The customer’s postal code can be used to perform address and postal code verifications that help reduce fraud. Similar to CVC verification, Radar includes a built-in rule to block payments where the postal code verification with the issuer failed.

You may also pass a form element as the first argument to createToken. The relevant information will be pulled from inputs marked up with the data-stripe attribute, which should be set to one of the values specified above.

The second argument to card.createToken—stripeResponseHandler—is a callback you provide to handle the response from Stripe. It should do the following:

  • If the card information entered by the user returned an error, display it on the page
  • If no errors were returned—a single-use token was created successfully, add the returned token to the payment form and submit the form to your server

Here’s a sample implementation of stripeResponseHandler:

function stripeResponseHandler(status, response) { // Grab the form: var $form = $('#payment-form'); if (response.error) { // Problem! // Show the errors on the form $form.find('.payment-errors').text(response.error.message); $form.find('button').prop('disabled', false); // Re-enable submission } else { // Token was created! // Get the token ID: var token = response.id; // Insert the token into the form so it gets submitted to the server: $form.append($('<input type="hidden" name="stripeToken" />').val(token)); // Submit the form: $form.get(0).submit(); } }

The handler is written to accept two arguments:

  • status is one of the status codes described in the API docs
  • response is of the following form:
{ id: "tok_8DPg4qjJ20F1aM", // Token identifier card: { // Dictionary of the card used to create the token name: null, address_line1: "12 Main Street", address_line2: "Apt 42", address_city: "Palo Alto", address_state: "CA", address_zip: "94301", address_country: "US", country: "US", exp_month: 2, exp_year: 2023, last4: "4242", object: "card", brand: "Visa", funding: "credit" }, created: 1660415263, // Timestamp of when token was created livemode: true, // Whether this token was created with a live API key type: "card", object: "token", // Type of object, always "token" used: false // Whether this token has been used }

If the request to Stripe fails, response will instead be of following form:

{ error: { type: "card_error", // Type of error code: "invalid_expiry_year", // Optional identifier of specific error message: "Your card's expiration year is invalid.", // Description of the error param: "exp_year" // Optional identifier of the offending parameter } }

createToken is an asynchronous call. It returns immediately and invokes stripeResponseHandler when it receives a response from Stripe’s servers.

Client-side validation helpers

You can use the following methods to perform client-side validation before making a tokenization request.

card.validateCardNumber

validateCardNumber checks that the number is formatted correctly and passes the Luhn check.

// These will all return true, indicating a potentially valid card // number (letters, spaces, and other punctuation are ignored): Stripe.card.validateCardNumber('4242424242424242') Stripe.card.validateCardNumber('4242-42424242-4242') Stripe.card.validateCardNumber('4242 4242 4242 4242') // These invalid card numbers will all return false: Stripe.card.validateCardNumber('4242-1111-1111-1111') // (Doesn't pass the Luhn check.) Stripe.card.validateCardNumber('12345678') Stripe.card.validateCardNumber('mistake')

card.validateExpiry

Checks whether or not the expiration date represents an actual month in the future.

Stripe.card.validateExpiry('02', 2020) // false Stripe.card.validateExpiry('02', 2027) // true Stripe.card.validateExpiry(9, 2022) // true

card.validateCVC

Checks whether or not the supplied number could be a valid verification code.

Stripe.card.validateCVC('123') // true Stripe.card.validateCVC('') // false

card.cardType

Returns the type of the card as a string. The possible types are: Visa, MasterCard, American Express, Discover, Diners Club, and JCB. If a card isn’t recognized, the return value is Unknown.

Stripe.card.cardType('4242-4242-4242-4242') // "Visa" Stripe.card.cardType('378282246310005') // "American Express" Stripe.card.cardType('1234') // "Unknown"

Passing expiration dates

Stripe.js allows you to flexibly pass expiration dates as either separate exp_month and exp_year values or as a single exp string. As a single string, the expiration can be a two- or four-digit year, and a one- or two-digit month, in either order, so long as the two are separated by a hyphen, slash, or space.

You can use the single expiration date in both validation methods and tokenization requests:

Stripe.card.validateExpiry('09 2026') // true Stripe.card.validateExpiry('2026/09') // true Stripe.card.validateExpiry('2026/09') // true Stripe.card.validateExpiry('2026-09') // true Stripe.card.createToken({ number: $('.card-number').val(), cvc: $('.card-cvc').val(), exp: $('.card-expiry').val() // Assumes you've added this element to your form }, stripeResponseHandler);

Collecting bank account details

You can use these methods to validate and collect bank account details for when you want to make ACH payments or send payouts to bank accounts attached to connected Stripe accounts.

All of these methods are within the Stripe.bankAccount object.

bankAccount.createToken

We recommend using Stripe.js v3 to collect bank account information. If you need to perform bank account validation, use Stripe.js v2 for both collection and validation.

Converts sensitive bank account data to a single-use token which you can safely pass to your server to use in an API call.

Stripe.bankAccount.createToken({ country: $('.country').val(), currency: $('.currency').val(), routing_number: $('.routing-number').val(), account_number: $('.account-number').val(), account_holder_name: $('.name').val(), account_holder_type: $('.account_holder_type').val() }, stripeResponseHandler);

Analogous to the card.createToken method, the first argument to bank.createToken is a JavaScript object containing bank account data entered by the user. It should contain the following fields:

  • country: two character country code (for example, “US”)
  • currency: three character currency code (for example, **“USD” </strong>)
  • routing_number: number representing the bank routing number (for example, 111000025). Optional if the currency is EUR, as the account number will be an IBAN.
  • account_number: number representing the bank account number (for example, 000123456789)
  • account_holder_name: name of the person or business that owns the bank account (for example, “Jane Austen”)
  • account_holder_type: the type of entity that holds the account. Can be "individual" or "company".

When creating a bank account to be attached to a customer, the account_holder_name and account_holder_type fields are mandatory. Otherwise, they are optional.

You may also pass a form element as the first argument to createToken. The relevant information will be pulled from inputs marked up with the data-stripe attribute, which should be set to one of the values specified above.

The second argument to bank.createToken—stripeResponseHandler—is a callback you provide to handle the response from Stripe. It should do the following:

  • If the bank account information entered by the user returned an error, display it on the page
  • If no errors were returned—a single-use token was created successfully, add the returned token to the form and submit the form to your server

Here’s a sample implementation of stripeResponseHandler:

function stripeResponseHandler(status, response) { // Grab the form: var $form = $('#payment-form'); if (response.error) { // Problem! // Show the errors on the form: $form.find('.bank-errors').text(response.error.message); $form.find('button').prop('disabled', false); // Re-enable submission } else { // Token created! // Get the token ID: var token = response.id; // Insert the token into the form so it gets submitted to the server: $form.append($('<input type="hidden" name="stripeToken" />').val(token)); // Submit the form: $form.get(0).submit(); } }

The handler is written to accept two arguments:

  • status is one of the status codes described in the API docs
  • response is of the following form:
{ id: "btok_u5dg20Gra", // Token identifier bank_account: { // Dictionary of the bank account used to create the token country: "US", bank_name: "BANK OF AMERICA, N.A", last4: "6789", validated: false, object: "bank_account", }, created: 1660415263, // Timestamp of when token was created livemode: true, // Whether this token was created with a live API key type: "bank_account", object: "token", // Type of object, always "token" used: false // Whether this token has been used }

If the request to Stripe fails, response will instead be of following form:

{ error: { type: "invalid_request_error", // String identifier of the type of error message: "Invalid routing number", // String description of the error param: "bank_account" // Optional string identifier of the offending parameter. } }

createToken is an asynchronous call. It returns immediately and invokes stripeResponseHandler when it receives a response from Stripe’s servers.

Client-side validation helpers

Bank account validation with Stripe.js currently supports U.S. bank account and routing numbers.

bankAccount.validateRoutingNumber

Checks that the routing number is formatted correctly for the given country and that the number passes any appropriate checksums (for example, for U.S. routing numbers).

// This will return true, indicating a // potentially valid bank routing number: Stripe.bankAccount.validateRoutingNumber('111000025', 'US') // U.S. routing number // These invalid bank routing numbers will all return false: Stripe.bankAccount.validateRoutingNumber('990000001', 'US') // (Doesn't pass the checksum check.) Stripe.bankAccount.validateRoutingNumber('12345', 'US')

bankAccount.validateAccountNumber

Checks that the account number is formatted correctly for the given country and enforces any length restrictions.

// This will return true, indicating a // potentially valid bank account number: Stripe.bankAccount.validateAccountNumber('000123456789', 'US') // This invalid bank account number will return false: Stripe.bankAccount.validateAccountNumber('mistake', 'US')

Collecting personally identifiable information (PII)

This method of using Stripe.js to collect PII data has been deprecated. Use Stripe.js v3 to collect personally identifiable information.

You can use piiData.createToken to collect PII data for Custom account identity verification.

piiData.createToken

Converts sensitive PII data to a single-use token which you can safely pass to your server to verify a Custom account.

Stripe.piiData.createToken({ personal_id_number: $('.personal_id_number').val() }, stripeResponseHandler);

Analogous to the card.createToken method, the first argument to piiData.createToken is a JavaScript object containing the PII data entered by the user. It contains one field: personal_id_number, which is the personal ID number (for example, 000000000).

The second argument to piiData.createToken—stripeResponseHandler—is a callback you provide to handle the response from Stripe. It should do the following:

  • If the PII information entered by the user returned an error, display it on the page
  • If no errors were returned (that is, a single-use token was created successfully), add the returned token to the form and submit the form to your server

Here’s a sample implementation of stripeResponseHandler:

function stripeResponseHandler(status, response) { // Grab the form: var $form = $('#payment-form'); if (response.error) { // Problem! // Show the errors on the form: $form.find('.bank-errors').text(response.error.message); $form.find('button').prop('disabled', false); // Re-enable submission } else { // Token created! // Get the token ID: var token = response.id; // Insert the token into the form so it gets submitted to the server: $form.append($('<input type="hidden" name="stripeToken" />').val(token)); // Submit the form: $form.get(0).submit(); } }

The handler is written to accept two arguments:

  • status is one of the status codes described in the API docs
  • response is of the following form:
{ id: "tok_u5dg20Gra", // Token identifier created: 1660415263, // Timestamp of when token was created livemode: true, // Whether this token was created with a live API key type: "pii", object: "token", // Type of object, always "token" used: false // Whether this token has been used }

If the request to Stripe fails, response will instead be of following form:

{ error: { type: "invalid_request_error", // Type of error message: "Invalid PII", // Description of the error param: "pii" // Optional identifier of the offending parameter } }

Collecting Apple Pay details

Stripe.js supports Apple Pay payments. The full details are available in our integration guide.

This method of using Stripe.js to collect Apple Pay has been deprecated. Use Stripe.js v3 instead.

applePay.checkAvailability

Enables you to check whether your customer can use Apple Pay.

Stripe.applePay.checkAvailability(stripeResponseHandler);

The only argument to checkAvailability —stripeResponseHandler—is a callback you provide to handle the response from Stripe. If Apple Pay is available, it should display an Apple Pay button to the customer.

Here’s a sample implementation of stripeResponseHandler:

function stripeResponseHandler(available) { // If Apple Pay is available, display the button on your checkout page if (available) { document.getElementById('apple-pay-button').style.display = 'block'; } }

checkAvailability is an asynchronous call. It returns immediately and invokes stripeResponseHandler when it has determined if Apple Pay is available.

applePay.buildSession

Builds an ApplePaySession object, which manages the Apple Pay experience for your user.

Stripe.applePay.buildSession({ countryCode: 'US', currencyCode: 'USD', total: { label: 'Rocketship Inc', amount: '19.99' } }, onSuccessHandler, onErrorHandler);

The first argument to applePay.buildSession is a JavaScript object containing the elements of the payment sheet that you want to customize. It should contain the following fields:

  • countryCode: two character ISO 3166 country code (for example, “US”)
  • currencyCode: three character ISO 4217 currency code (for example, “USD”)
  • total.label: name of the business (for example, “Rocketship Inc”)
  • total.amount: the total amount for the payment. This is a string representing the formatted amount (for example, “5.00”). Apple’s format for this is slightly different than other instances in the Stripe API, where you would instead specify an integer amount in cents.

The following fields allow you to further customize the payment sheet but are optional:

  • lineItems: a set of line items that explain the total in additional detail
  • requiredBillingContactFields: collect customer’s billing contact information. To do so, set this value to ['postalAddress'].
  • requiredShippingContactFields: collect customer’s shipping contact information. It can be one or more of postalAddress, phone, email, or name
  • shippingMethods: an array of shipping methods available to the customer. Each object in this array must contain the keys:
    • label: A user-visible title for the shipping method (for example, “Ground Shipping”)
    • detail: A user-visible subtitle for the shipping method that explains the duration (for example, “Arrives in 5-7 business days”)
    • amount: The cost of the shipping method (for example, “5.00”)
    • identifier: An internal identifier for the shipping method. Not user-visible; you can use whatever you want (for example, “ground”)
  • shippingType: provide the customer with available shipping options. It must be shipping, delivery, storePickup, or servicePickup

The second argument to applePay.buildSession — onSuccessHandler — is a callback you provide to handle the response from Stripe. It provides you with a Stripe token that you should send to your server and use to create a charge.

Here’s a sample implementation of onSuccessHandler, using jQuery:

function onSuccessHandler(result, completion) { $.post( "/charges", { token: result.token.id }).done(function() { completion(true); }).fail(function() { completion(false); }); }

This function is written to accept two arguments:

  • result is of the following form:
{ token: { // Stripe token id: "pii_u5dg20Gra", // Token identifier card: { // Dictionary of the card used to create the token name: "Jenny Rosen", address_line1: "12 Main Street", address_line2: "Apt 42", address_city: "Palo Alto", address_state: "CA", address_zip: "94301", address_country: "US", country: "US", exp_month: 2, exp_year: 2023, last4: "4242", object: "card", brand: "Visa", funding: "credit" }, created: 1660415263, // Timestamp of when token was created livemode: true, // Whether this token was created with a live API key type: "card", object: "token", // Type of object, always "token" }, shippingContact: { // This will be present if you specified requiredShippingContactFields above emailAddress: 'jrosen@apple.com', phoneNumber: '8885551212', givenName: 'Jenny', familyName: 'Rosen', addressLines: ['1 Infinite Loop'], locality: 'Cupertino', administrativeArea: 'CA', postalCode: '95014', countryCode: 'US' }, shippingMethod: { // This will be present if you specified shippingMethods above label: 'Ground Shipping', detail: 'Arrives 5-7 business days', amount: '5.00', identifier: 'ground' } }
  • completion is a function that you must call with either ApplePaySession.STATUS_SUCCESS or ApplePaySession.STATUS_FAILURE when you’re done making your charge. When this is done, the Apple Pay sheet will display a success/failure animation and dismiss. You may also, instead of making a charge, call the function with ApplePaySession.STATUS_INVALID_BILLING_POSTAL_ADDRESS, ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, or ApplePaySession.STATUS_INVALID_SHIPPING_CONTACT. In this case, the user will see an error and have the chance to pick a different address without the sheet dismissing.

The third, optional, argument to applePay.buildSession — onErrorHandler — is a callback you provide to handle any errors in your Apple Pay configuration.

It should do the following:

  • Log the error so that you can debug your integration.

Here’s a sample implementation of onErrorHandler:

function onErrorHandler(error) { console.error(error.message); }

Sources

This method of using Stripe.js has been deprecated. We strongly recommend using Stripe.js v3 to create sources. This is also the version our Sources documentation uses. If you’re using sources to create card payments, use Stripe.js and Elements—our prebuilt UI components—to maintain the simplest form of PCI compliance.

You can use source.create when creating payments using Sources.

source.create

Use this method to convert collected payment information into a Source object that you safely pass to your server. This method takes an object containing information specific to the payment method being used. For instance, the following example creates a Source object for a Bancontact payment:

Stripe.source.create({ type: 'bancontact', amount: 1099, currency: 'eur', owner: { name: 'Jenny Rosen', }, redirect: { return_url: '__TOKEN_PLACEHOLDER_0__', }, }, stripeResponseHandler);

See the Sources documentation for more information and the supported payment methods you can use.

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. We currently support IE11 and above.
  • We support Chrome and Safari on all platforms and Firefox on desktop platforms.
  • We require TLS 1.2 to be supported by the browser.
  • 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.

Was this page helpful?
Questions? Contact us.
View developer tutorials on YouTube.
Check out our product changelog.
Powered by Markdoc
You can unsubscribe at any time. Read our privacy policy.
On this page
Including Stripe.js
Setting your publishable key
Collecting card details
Client-side validation helpers
Passing expiration dates
Collecting bank account details
Client-side validation helpers
Collecting personally identifiable information (PII)
Collecting Apple Pay details
Sources
Supported browsers
Stripe Shell
Test mode
▗▄ ▄▟█ █▀▀ ▗▟████▙▖ ██████ ███▗▟█ ███ ███▗▟██▙▖ ▗▟█████▙▖ ███▖ ▀▀ ███ ███▀▀▀ ███ ███▀ ███ ███ ███ ▝▜████▙▖ ███ ███ ███ ███ ███ █████████ ▄▄ ▝███ ███ ▄ ███ ███ ███▄ ███ ███ ▄▄ ▝▜████▛▘ ▝▜███▛ ███ ███ ███▝▜██▛▘ ▝▜█████▛▘ ███ ▀▘
Welcome to the Stripe Shell! Stripe Shell is a browser-based shell with the Stripe CLI pre-installed. Login to Stripe docs and press Control + Backtick on your keyboard to start managing your Stripe resources in test mode. - View supported commands: - Find webhook events: - Listen for webhook events: - Call Stripe APIs: stripe [api resource] [operation] (e.g. )
The Stripe Shell is best experienced on desktop.
$