Stripe.js Reference

Stripe.js makes it easy to collect credit card—and other similarly sensitive—details without having the information touch your server. If you need help after reading this, check out our answers to common questions or chat live with other developers in #stripe on freenode.

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:

Stripe.js 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>

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_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.

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

You can use these methods to validate and collect credit card details for when you want to process charges, create subscriptions, or send transfers 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. The tutorial explains this flow in more detail.

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);

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 (e.g., "4242424242424242")
  • exp_month: two digit number representing the card's expiration month (e.g., 12)
  • exp_year: two or four digit number representing the card's expiration year (e.g., 2017)

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

The cvc field is optional, but we highly recommend you provide it to help prevent fraud. This is the card's security code, as a string (e.g., "123").

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 (e.g., "94301")
  • address_country: billing address country

Although optional, using address and postal code verifications is highly recommended as they'll help reduce fraud.

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.createTokenstripeResponseHandler—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 from the custom form tutorial:

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: "pii_u5dg20Gra", // 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: 2017,
    last4: "4242",
    object: "card",
    brand: "Visa",
    funding: "credit"
  },
  created: 1475026744, // 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', '2014')      // false
Stripe.card.validateExpiry('02', '2014')      // false
Stripe.card.validateExpiry('02', '2021')      // true
Stripe.card.validateExpiry(2, 2016)           // 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 2016')  // true
Stripe.card.validateExpiry('2020/09')  // true
Stripe.card.validateExpiry('2020/09')  // true
Stripe.card.validateExpiry('2020-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 transfers to bank accounts attached to connected Stripe accounts.

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

bankAccount.createToken

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 (e.g., "US")
  • currency: three character currency code (e.g., "USD" )
  • routing_number: number representing the bank routing number (e.g., 111000025). Optional if the currency is EUR, as the account number will be an IBAN.
  • account_number: number representing the bank account number (e.g., 000123456789)
  • account_holder_name: name of the person or business that owns the bank account (e.g., "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.createTokenstripeResponseHandler—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: 1475026744, // 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 US 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 (e.g., for US routing numbers).

// This will return true, indicating a
// potentially valid bank routing number:

Stripe.bankAccount.validateRoutingNumber('111000025', 'US') // US 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)

You can use these methods to collect PII data for managed account identity verification.

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

piiData.createToken

Converts sensitive PII data to a single-use token which you can safely pass to your server to verify a managed 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 should contain one field: personal_id_number, which is the personal ID number (e.g., 000000000).

The second argument to piiData.createTokenstripeResponseHandler—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 (i.e., 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: 1475026744, // 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 Bitcoin payments

When accepting Bitcoin payments, you'll need to:

  • Create a BitcoinReceiver object via bitcoinReceiver.createReceiver with the customer's email address, the amount you'd like to charge, and the currency
  • Display the relevant information—converted bitcoin, or BTC, amount, and Bitcoin address to send payments to—on your checkout page
  • Since Bitcoin payments are asynchronous, poll the receiver and post to your server once the receiver has been paid by the customer

For more detailed instructions and code examples, see the Bitcoin guide.

bitcoinReceiver.createReceiver

Creates a BitcoinReceiver object. Given an amount and currency, returns a receiver object containing the converted bitcoin amount (in Satoshi units) and the Bitcoin address the payment should be sent to.

Stripe.bitcoinReceiver.createReceiver({
    amount: 1000,
    currency: 'usd',
    description: 'some_description',
    email: 'payinguser@example.com'
}, stripeResponseHandler);

bitcoinReceiver.pollReceiver

A helper method that polls the BitcoinReceiver and calls the specified callback method when the receiver has been "filled" (when the customer has pushed the required amount of bitcoin to the linked address) or when the poll returns an error from Stripe.

Stripe.bitcoinReceiver.pollReceiver("btcrcv_3hwhfVWdCKxqi9", filledReceiverHandler);

bitcoinReceiver.cancelReceiverPoll

A BitcoinReceiver expires after 10 minutes. Stripe will still process a transaction if bitcoin are pushed to it after the expiration, but the conversion rate will no longer be guaranteed. You should detect in your browser logic whether 10 minutes have elapsed, and create a new receiver and clean up the previous receiver poll, if so.

Stripe.bitcoinReceiver.cancelReceiverPoll("btcrcv_3hwhfVWdCKxqi9");

Collecting Apple Pay details

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

applePay.checkAvailability

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

Stripe.applePay.checkAvailability(stripeResponseHandler);

The only argument to checkAvailabilitystripeResponseHandler—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 (e.g. "US")
  • currencyCode: three character ISO 4217 currency code (e.g. "USD")
  • total.label: name of the business (e.g. "Rocketship Inc")
  • total.amount: the total amount for the payment. This is a string representing the formatted amount, e.g. "5.00". Note that 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, e.g. "Ground Shipping"
    • detail: A user-visible subtitle for the shipping method that explains the duration, e.g. "Arrives in 5-7 business days"
    • amount: The cost of the shipping method, e.g. "5.00"
    • identifier: An internal identifier for the shipping method (not user-visible; you can use whatever you want), e.g. "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: 2017,
      last4: "4242",
      object: "card",
      brand: "Visa",
      funding: "credit"
    },
    created: 1475026744, // 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);
}

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 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 for three years from version release
  • We respond to bug reports but do not proactively test the latest version of Firefox on Android and iOS, Silk on Fire OS, and Opera for Windows.

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