Stripe.js

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>

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

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()
}, 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, we highly recommend collecting the user's postal code as address and postal code verifications help reduce fraud. Simply provide an address_zip value and enable declines on verification failures in your account settings.

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: "tok_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: 1464012137, // 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, 2021)           // 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 2020')  // 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: 1464012137, // 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

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
Stripe.bankAccount.validateRoutingNumber('11111-111', 'CA') // Canadian routing number

// These invalid bank routing numbers will all return false:

Stripe.bankAccount.validateRoutingNumber('990000000', 'US')
// (Doesn't pass the checksum check.)
Stripe.bankAccount.validateRoutingNumber('12345', 'US')
Stripe.bankAccount.validateRoutingNumber('mistake', 'CA')

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: 1464012137, // 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: '[email protected]'
}, 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");