Stripe.js Reference
Stripe.js makes it easy to collect certain kinds of sensitive information without having it touch your server.
This is the API reference for Stripe.js. Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data using customizable Stripe Elements, and accept payments with browser payment APIs like Apple Pay and the Payment Request API.
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 of your site, not just the checkout page. This allows Stripe to detect anomalous behavior that may be indicative of fraud as customers browse your website.
Stripe(publishableKey[, options])
Use Stripe(publishableKey[, options]) to create an instance of the Stripe object. Your Stripe publishable API key is required when calling this function, as it 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.
This function accepts an optional options object. Available options are documented below:
| stripeAccount
string |
Connect only. Specifying a connected account ID (e.g., acct_24BFMpJ1svR5A89k) allows you to perform actions on behalf of that account. |
The Stripe object
stripe.elements()stripe.createToken()stripe.createSource()stripe.retrieveSource()stripe.paymentRequest()
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:
| Option | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
fonts
optional Array
|
An array of custom fonts, which Elements created from the elements object can use.
Fonts can either be loaded via a CSS file by passing an object with the cssSrc attribute:
|
||||||||||||
|
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: ar, da, de, en, es, fi, fr, he, it, ja, no, nl, pl, sv, zh.
|
stripe.createToken(element[, cardData])
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 pulls data from other Elements you’ve created on the same instance ofelementsto tokenize.cardData, an optional object containing any of the following parameters:
|
name
recommended string
|
Cardholder name |
|
address_line1
address_line2
address_city
address_state
address_zip
address_country
recommended string
|
Fields for billing address information. The address_country field is a two character country code (for example, 'US').
|
|
currency
optional string
|
Required order 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 payouts 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', bankAccountData)
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 an 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 is 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', piiData)
Use stripe.createToken() to convert personally identifiable information (PII) into a single-use token for 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 an 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.
stripe.createSource(element[, sourceData])
Use stripe.createSource(element, sourceData) to convert payment information collected by Elements into a Source object that you safely pass to your server to use in an API call. See the Sources documentation for more information about Sources.
stripe.createSource(card, {
owner: {
name: 'Jenny Rosen',
},
}).then(function(result) {
// Handle result.error or result.source
});
const {source, error} = await stripe.createSource(card, {
owner: {
name: 'Jenny Rosen',
},
});
This method takes two arguments.
element, the Element containing payment source information. The Element pulls data from other Elements you’ve created on the same instance ofelements. The Element determines the type of the Source returned. For example, thecardandcardNumberElements createcardSources.sourceData, an optional object containing additional payment source information that you have collected. See the Sources API reference for details.
stripe.createSource returns a Promise which resolves with a result object. This object has either:
result.source: a Source 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.createSource(sourceData)
Use stripe.createSource(sourceData) to convert raw non-card payment information into a Source object that you safely pass to your server to use in an API call. See the Sources documentation for more information about Sources. Note that you must use stripe.createSource(element, sourceData) for card Sources.
stripe.createSource({
type: 'ideal',
amount: 1099,
currency: 'eur',
owner: {
name: 'Jenny Rosen',
},
redirect: {
return_url: 'https://shop.example.com/crtA6B28E1',
},
}).then(function(result) {
// Handle result.error or result.source
});
const {source, error} = await stripe.createSource({
type: 'ideal',
amount: 1099,
currency: 'eur',
owner: {
name: 'Jenny Rosen',
},
redirect: {
return_url: 'https://shop.example.com/crtA6B28E1',
},
});
This method accepts one argument, sourceData, which is an object containing payment source information that you have collected. See the Sources API reference for details.
stripe.createSource returns a Promise which resolves with a result object. This object has either:
result.source: a Source 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.retrieveSource(source)
Retrieve a Source using its unique ID and client secret.
stripe.retrieveSource({
id: "src_18eYalAHEMiOZZp1l9ZTjSU0",
client_secret: "src_client_secret_NibvRz4PMmJqjfb0sqmT7aq2",
}).then(function(result) {
// Handle result.error or result.source
});
const {source, error} = await stripe.retrieveSource({
id: "src_18eYalAHEMiOZZp1l9ZTjSU0",
client_secret: "src_client_secret_NibvRz4PMmJqjfb0sqmT7aq2",
});
This method accepts an object source with the following required parameters:
| id
string |
Unique identifier of the source. |
| client_secret
string |
A secret available to the web client that created the Source, for purposes of retrieving the Source later from that same client. |
You can use a Source object created with stripe.createSource as the argument to stripe.retrieveSource, as every Source object has both id and client_secret keys.
stripe.retrieveSource returns a Promise which resolves with a result object. This object has either:
result.source: a Source was retrieved successfully.result.error: there was an error. Refer to the API reference for all possible errors.
stripe.paymentRequest(options)
Use stripe.paymentRequest() to create a PaymentRequest object. A PaymentRequest object is used to collect payment
information through an interface controlled and styled by the browser itself (i.e., not by you or your page).
See the Payment Request Button Element quickstart for a high-level overview of when you’d want to do this.
In Safari, stripe.paymentRequest() uses Apple Pay, and in other browsers it uses the Payment Request API standard.
Creating a PaymentRequest requires that you configure it with an options object.
Available options are documented below.
These options can be updated using paymentRequest.update().
| Option | Description | ||||||
|---|---|---|---|---|---|---|---|
|
country
string
|
The two-letter country code of your Stripe account (e.g., 'US'). |
||||||
|
currency
string
|
Three character currency code (e.g., 'usd'). |
||||||
|
total
object
|
A payment item object. This payment item is shown to the customer in the browser‘s payment interface.
|
||||||
|
displayItems
optional Array
|
An array of payment item objects. These payment items are shown as line items
in the browser‘s payment interface. Note that the sum of the line item
amounts does not need to add up to the total amount above.
|
||||||
|
requestPayerName
requestPayerEmail
requestPayerPhone
requestShipping
optional Boolean
|
By default, the browser‘s payment interface only asks the customer for actual payment information.
Other information, such as shipping address and customer email, can be collected by setting any of these to
true. This information appears in the PaymentResponse.
In particular, with requestShipping you must also eventually supply a valid ShippingOptions to the shippingOptions property. This can be up front
at the time stripe.paymentRequest() is called, or in response to a
shippingaddresschange event using the updateWith callback.
|
||||||
|
shippingOptions
optional Array
|
An array of ShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option. |
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. |
| paymentRequestButton | An all-in-one checkout button backed by either Apple Pay or the Payment Request API. Requires that you also create a corresponding PaymentRequest object with stripe.paymentRequest(). |
Element options
|
classes
object
|
Set custom class names on the container DOM element when the Stripe Element is in a particular state.
|
||||||||||||
|
hidePostalCode
Boolean
|
Hide the postal code field (if applicable to the Element you‘re creating). Default is false. If you are already collecting a full billing address or postal code elsewhere, 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'. |
||||||||||||
|
placeholder
string
|
Customize the placeholder text. This is only available for the cardNumber, cardExpiry, and cardCvc Elements. |
||||||||||||
|
style
object
|
Customize appearance using CSS properties. Style is specified as an object for any of the variants below.
paymentRequestButton Element supports a single variant: paymentRequestButton. The properties below are customizable for this variant.
|
||||||||||||
|
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',
color: "#32325d",
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',
color: "#32325d",
fontSmoothing: 'antialiased',
'::placeholder': {
color: '#ccc',
},
},
invalid: {
color: '#e5424d',
':focus': {
color: '#303238',
},
},
};
const cardElement = elements.create('card', {style})
The Element
element.mount(domElement)
You need to create a container DOM element to mount an Element. If the container DOM element has a label, the Element is automatically focused when its label is clicked. There are two ways to do this:
- Mount the instance within a
<label>.<label>Card <div id="card-element"></div> </label> - Create a
<label>with aforattribute, referencing the ID of your container.<label for="card-element">Card</label> <div id="card-element"></div>
The element.mount() method attaches your element to the DOM. element.mount() accepts either a CSS Selector (e.g., '#card-element') or a DOM element.
cardElement.mount('#card-element');
element.on(event, handler)
The only way to communicate with your element is by listening to an event. Elements might emit any of these events:
| blur | Triggered when the Element loses focus. | ||||||||||
| change | Triggered when any of the following values changes on the Element:
|
||||||||||
| click |
Triggered when the Element is clicked. Only available on the
paymentRequestButton
Element. The event payload is an object with the following callback
function:
|
||||||||||
| 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 customer input as it is typed. To help your customers catch mistakes, 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
The card Element 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. |
destroy() |
Removes the Element from the DOM and destroys it. Note: a destroyed element can not be re-activated or re-mounted to the DOM. |
focus() |
Focuses the Element. |
unmount() |
Unmounts the Element from the DOM. Call element.mount() to re-attach it to 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}});
});
The styles of an Element can be dynamically changed 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 = event.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 = event.brand;
}
});
The Element container
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> elements. 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)
These class names can be customized using the classes option when you create an Element.
The PaymentRequest object
For a quick overview of how to use the PaymentRequest object, see the Payment Request Button guide.
paymentRequest.canMakePayment()
Returns a Promise that resolves with a payload if a browser payment API is available. If no API is available, it resolves with null.
The resolution object has these properties:
|
applePay
Boolean
|
true if the browser payment API supports Apple Pay. In this case, you‘ll want to show a button that conforms to the Apple Pay Human Interface Guidelines.
Note that using the paymentRequestButton Element is automatically cross-browser. If you use this PaymentRequest object to create a paymentRequestButton Element, you don‘t need to check applePay yourself.
|
paymentRequest.show()
Shows the browser’s payment interface. When using the paymentRequestButton Element, this is called for you under the hood.
This method must be called as the result of a user interaction (for example, in a click handler).
paymentRequest.update(options)
PaymentRequest instances can be updated with an options object. Available options are documented below.
paymentRequest.update() can only be called when the browser payment interface is not showing. Listen to the click and cancel events to detect if the payment interface has been initiated.
To update the PaymentRequest right before the payment interface is initiated, call paymentRequest.update() in your click event handler.
| Option | Description | ||||||
|---|---|---|---|---|---|---|---|
|
currency
optional string
|
Three character currency code (e.g., 'usd'). |
||||||
|
total
optional object
|
A payment item object. This payment item is shown to the customer in the browser‘s payment interface.
|
||||||
|
displayItems
optional Array
|
An array of payment item objects. These payment items are shown as line items
in the browser‘s payment interface. Note that the sum of the line item
amounts does not need to add up to the total amount above.
|
||||||
|
shippingOptions
optional Array
|
An array of ShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option. |
paymentRequest.on(event, handler)
PaymentRequest instances receive the following events
|
token
source
|
Stripe.js automatically tokenizes or creates a source after the customer is done interacting with the browser‘s payment interface. To access the created token or source, listen for the respective event. Only listen for either token or source, not both. The emitted event is a PaymentResponse object. | ||||
| cancel | Emitted when the browser‘s payment interface is dismissed. | ||||
| shippingaddresschange |
Emitted whenever the customer selects a new address in the browser‘s payment interface. The event payload is an object with these parameters:
|
||||
| shippingoptionchange |
Emitted whenever the customer selects a new shipping option in the browser‘s payment interface. The event payload is an object with these parameters:
|
Other Payment Request object types
A number of types show up in multiple places the when using the PaymentRequest object or the paymentRequestButton.
- The PaymentResponse object
- The UpdateDetails object
- The ShippingOption object
- The ShippingAddress object
The PaymentResponse object
This object is returned as the payload of the token and source event handlers.
|
token
source
object
|
Either a Token or Source object, depending whether this is the token or source event, respectively. Note that only one of these parameters is present, depending on the event listener you register. | ||||||
|
complete
function
|
Call this when you have processed the token data provided by the API.
complete accepts one of the following values:
|
||||||
|
payerName
payerEmail
payerPhone
string
|
Information about the customer. Each is only present if it was explicitly asked for when creating the PaymentRequest object. | ||||||
|
shippingAddress
ShippingAddress
|
The final ShippingAddress the customer selected. Only present when requestShipping is true when creating the PaymentRequest object,
and you've supplied at least one ShippingOption. |
||||||
|
shippingOption
ShippingOption
|
The final ShippingOption the customer selected. Only present when requestShipping is true when creating the PaymentRequest object,
and you've supplied at least one ShippingOption. |
||||||
|
methodName
string
|
The unique name of the payment handler the customer chose to authorize payment.
For example, 'basic-card'.
|
The UpdateDetails object
The UpdateDetails object is used to update certain parts of a PaymentRequest object after it has already been created. See the updateWith callback functions above.
|
status
string
|
The browser uses this value to show an error message to the customer if they‘ve
taken an action that invalidates the payment request. The value must be one of the following:
|
||||||
|
total
optional object
|
The new total amount, if applicable.
|
||||||
|
displayItems
optional Array
|
An array of payment item objects. These payment items are shown as line items
in the browser‘s payment interface. Note that the sum of the line item
amounts does not need to add up to the total amount above.
|
||||||
|
shippingOptions
optional Array
|
An array of ShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option. |
The ShippingOption object
A ShippingOption is a normal JavaScript object you create that has the following parameters. Use these objects to let the customer select their preferred shipping method.
|
id
string
|
A unique ID you create to keep track of this shipping option. You‘ll be told the ID of the selected option on changes and on completion. |
|
label
string
|
A short “title” for this shipping option. |
|
detail
string
|
A longer description of this shipping option. |
|
amount
number
|
The amount to show for this shipping option. If the cost of this shipping option depends on the shipping address the customer enters, listen for the shippingaddresschange event. |
The ShippingAddress object
Use the requestShipping option to stripe.paymentRequest() to collect shipping information from the customer. This is the shape of the shipping address the customer enters:
|
country
string
|
Two-letter country code, capitalized. Valid two-letter country codes are specified by ISO3166 alpha-2. |
|
addressLine
Array<string>
|
An array of address line items. For example, '185 Berry St.', 'Suite 500', 'P.O. Box 12345', etc.
|
|
region
string
|
The most coarse subdivision of a country. Depending on the country, this might correspond to a state, a province, an oblast, a prefecture, or something else along these lines. |
|
city
string
|
The name of a city, town, village, etc. |
|
postalCode
string
|
The postal code or ZIP code, also known as PIN code in India. |
|
recipient
string
|
The name of the recipient. This might be a person, a business name, or contain “care of” (c/o) instructions. |
|
phone
string
|
The phone number of the recipient. Note that this might be
different from any phone number you collect with requestPayerPhone.
|
|
sortingCode
string
|
(Not present on Apple platforms) The sorting code as used in, for example, France. |
|
dependentLocality
string
|
(Not present on Apple platforms) A logical subdivision of a city. Can be used for things like neighborhoods, boroughs, districts, or UK dependent localities. |
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 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.