Stripe Elements Web Components

The <stripe-elements> custom element is an easy way to use stripe.js in your web app, across frameworks, or inside shadow roots.

Installation

You don't need to set up node and npm to use stripe elements web components. You can simply load the definitions directly in HTML via a CDN.

<script type="module" src="https://unpkg.com/@power-elements/stripe-elements?module"></script>

If you would like to bundle the components, install using NPM and import as usual:

npm i @power-elements/stripe-elements
import '@power-elements/stripe-elements';

<stripe-elements> Web Component

Usage

Add the element to your page with the publishable-key attribute set to your Stripe publishable key. You can also set the publishableKey DOM property using JavaScript.

Enter a valid testing publishable key in the input below to activate the examples on this page.

Careful! never add your secret key to an HTML page, only publish your publishable key.

Once you've set the publishable-key attribute (or the publishableKey DOM property), Stripe will create a Stripe Card Element on your page.

For use with Stripe Connect, you can provide the optional stripe-account attribute set to the account ID of the connected account.

Accepting Payments

Fill out some payment information here, then choose the type of payment object you'd like to generate.

Once you're set your publishable key and Stripe has instantiated (listen for the ready event if you need to know exactly when this happens), you may generate a token from the filled-out form by calling the createToken() method.

OK

Validation and Styling

<stripe-elements> has a show-error boolean attribute which will display the error message for you. This is useful for simple validation in cases where you don't need to build your own validation UI.

<stripe-elements publishable-key="should-error-use-bad-key"
show-error>
</stripe-elements>

Custom Validation

<stripe-elements> comes with several properties, events, and methods for validation. Listen for the change and error events and check the complete, empty, error, and invalid properties to react to validation changes.

These states reflect as attributes, so you can use CSS to style your element in its various states.

Use the stripe and error CSS Shadow Parts to style the element as needed. If your target browsers don't yet support shadow parts, You can still configure the element somewhat using the exposed CSS Custom Properties, see the README for more information.

stripe-elements::part(stripe) {
border-radius: 4px;
border: 1px solid var(--theme-primary);
box-shadow: none;
height: 36px;
display: flex;
flex-flow: column;
justify-content: center;
}

stripe-elements[complete]::part(stripe) {
border-color: var(--success);
}

stripe-elements[invalid]::part(stripe) {
border-color: var(--warning);
}

stripe-elements[error]::part(stripe) {
border-color: var(--error);
}

stripe-elements::part(error) {
text-align: right;
color: var(--text);
}

Automatically Posting the Payment Info

For simple integrations, you can automatically post the source or token to your backend by setting the action property

NOTE: For this demo, we've overridden window.fetch to return a mocked response with the text body "A-OK!".

<stripe-elements publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
generate="token"
action="/my-endpoint"
>
</stripe-elements>

<stripe-payment-request> Web Component

The <stripe-payment-request> custom element is an easy way to use stripe.js in your web app, across frameworks, or inside shadow roots. Add the element to your page with the publishable-key attribute set to your Stripe publishable key. You can also set the publishableKey DOM property using JavaScript.

Unlike the <stripe-elements> element, <stripe-payment-request> has a number of up-front requirements. The first of those is browser support. Listen for the unsupported event to handle the case when the user agent cannot make the payment. Listen for the ready event to be sure that the browser is able to make payment.

You also need to preload the element with information about the payment request in order for it to render to the page. Like with the publishable-key attribute, paste a valid testing client secret into the input above to activate the payment-request demos on this page.

For example, to display a payment request button to request a payment to a Canadian Stripe account for a purchase labelled "Double Double" that costs $1.25 Canadian, add this element to your page:

<stripe-payment-request
publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
client-secret="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
generate="source"
amount="125"
label="Double Double"
country="CA"
currency="cad">

</stripe-payment-request>

You can also display multiple line-items with the <stripe-payment-item> element:

<stripe-payment-request
publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
generate="token"
amount="326"
label="Double Double"
country="CA"
currency="cad">

<stripe-display-item data-amount="125" data-label="Double Double"></stripe-display-item>
<stripe-display-item data-amount="199" data-label="Box of 10 Timbits"></stripe-display-item>
</stripe-payment-request>

To add multiple shipping options, you can use the <stripe-shipping-option> element:

<stripe-payment-request
publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
generate="payment-method"
request-payer-name
request-payer-email
request-payer-phone
amount="326"
label="Double Double"
country="CA"
currency="cad">

<stripe-display-item data-amount="125" data-label="Double Double"></stripe-display-item>
<stripe-display-item data-amount="199" data-label="Box of 10 Timbits"></stripe-display-item>
<stripe-shipping-option data-id="pick-up" data-label="Pick Up" data-detail="Pick Up at Your Local Timmy's" data-amount="0"></stripe-shipping-option>
<stripe-shipping-option data-id="delivery" data-label="Delivery" data-detail="Timbits to Your Door" data-amount="200"></stripe-shipping-option>
</stripe-payment-request>

You may also set the payment request options using JavaScript:

const el = document.querySelector('stripe-payment-request');

el.displayItems = [
{ amount: '125', label: 'Double Double' },
{ amount: '199', label: 'Box of 10 Timbits' },
]

el.shippingOptions = [
{ id: 'pick-up', amount: 0, label: 'Pick Up', detail: "Pick Up at Your Local Timmy's" },
{ id: 'delivery', amount: 200, label: 'Delivery', detail: 'Timbits to Your Door' }
]

If you update the element's amount or label properties, it will update the payment requestUpdate

<stripe-payment-request
publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
generate="payment-method"
request-payer-name
request-payer-email
request-payer-phone
country="CA"
currency="cad">

</stripe-payment-request>
<mwc-textfield label="Amount (CAD)" type="number" data-prop="amount"></mwc-textfield>
<mwc-textfield label="Label" data-prop="label"></mwc-textfield>

<script type="module">
const spr = document.querySelector("stripe-payment-request");
for (const textfield of document.querySelectorAll('mwc-textfield')) {
textfield.addEventListener('input', event => {
switch (event.target.dataset.prop) {
case 'amount':
spr.amount = parseFloat(event.target.value) * 100;
break;
case 'label':
spr.label = event.target.value;
break;
}
})
}
</script>

Payment Intents

Stripe provides a PaymentIntent API which is both more secure and more compatible with EU regulations. To take advantage of those features, generate a PaymentIntent object on your server and pass it's client_secret property to the <stripe-payment-request> element.

You can generate one quickly using the stripe cli:

stripe payment_intents create --amount=326 --currency=cad | jq -r '.client_secret'
<stripe-payment-request
generate="payment-method"
publishable-key="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
client-secret="pk_test_XXXXXXXXXXXXXXXXXXXXXXXX"
request-payer-name
request-payer-email
request-payer-phone
amount="326"
label="Double Double"
country="CA"
currency="cad">

</stripe-payment-request>

Fallback to Stripe Elements

You might often want to show users a <stripe-payment-request> button if they are able (i.e. if canMakePayment is true), but fall back to a <stripe-elements> card form if they are not.

To accomplish this, listen for the unsupported and ready events on <stripe-payment-request>, which fire when the element is finally unable or able to display a Payment Request button, respectively.

We recommend that you don't set publishable-key on <stripe-elements> until unsupported fires from <stripe-payment-request>, as setting the publishable key will kick off the element's initialization, even if payment request is supported.

class PaymentForm extends LitElement {
static get properties() {
return {
error: { type: Object },
output: { type: Object },
unsupported: { type: Boolean, reflect: true },
publishableKey: { type: String, attribute: 'publishable-key', reflect: true },
submitDisabled: { type: Boolean },
}
}

static get styles() {
return css`
[hidden] { display: none !important; }

:host {
align-items: center;
display: grid;
grid-gap: 12px;
grid-template-areas:
'support support'
'stripe submit'
'output output';
}

stripe-elements { grid-area: stripe; }

stripe-payment-request { grid-area: submit/stripe/stripe/submit; }

mwc-button { grid-area: submit; }

json-viewer { grid-area: output; }
`
;
}

constructor() {
super();
this.submitDisabled = true;
}

render() {
return html`
<output ?hidden="
${this.unsupported === undefined}">
Payment Request is
${this.unsupported ? 'un' : ''}supported on this Browser
</output>

<stripe-payment-request
?hidden="
${this.output || this.unsupported}"
@success="
${this.onSuccess}"
@fail="
${this.onFail}"
@error="
${this.onError}"
@unsupported="
${this.onUnsupported}"
@ready="
${this.onReady}"
publishable-key="
${ifDefined(this.publishableKey)}"
generate="source"
request-payer-name
request-payer-email
request-payer-phone
amount="326"
label="Double Double"
country="CA"
currency="cad">
<stripe-display-item data-amount="125" data-label="Double Double"></stripe-display-item>
<stripe-display-item data-amount="199" data-label="Box of 10 Timbits"></stripe-display-item>
<stripe-shipping-option data-id="pick-up" data-label="Pick Up" data-detail="Pick Up at Your Local Timmy's" data-amount="0"></stripe-shipping-option>
<stripe-shipping-option data-id="delivery" data-label="Delivery" data-detail="Timbits to Your Door" data-amount="200"></stripe-shipping-option>
</stripe-payment-request>

<stripe-elements
?hidden="
${this.output || !this.unsupported}"
generate="source"
publishable-key="
${ifDefined(this.unsupported ? this.publishableKey : undefined)}"
@change="
${this.onChange}"
@source="
${this.onSuccess}"
@error="
${this.onError}"
></stripe-elements>

<mwc-button
?hidden="
${this.output || !this.unsupported}"
?disabled="
${this.submitDisabled}"
@click="
${this.onClick}"
>Submit</mwc-button>

<json-viewer .object="
${this.output}"></json-viewer>
`
;
}

onChange({ target: { complete, hasError } }) {
this.submitDisabled = !(complete && !hasError);
}

onClick() {
this.shadowRoot.querySelector('stripe-elements').submit();
}

onError({ target: { error } }) {
this.error = error;
}

onFail(event) {
this.output = event.detail;
}

onReady() {
this.unsupported = false;
}

onSuccess(event) {
this.output = event.detail;
}

onUnsupported() {
this.unsupported = true;
}
}

Usage in Frameworks

API

The following API tables are automatically generated.

./stripe-elements.js:

class: StripeElements, stripe-elements

Superclass
Name Module Package
StripeBase /src/StripeBase.js
Static Fields
Name Privacy Type Default Description Inherited From
is string 'stripe-elements'
elementType string 'card'
Fields
Name Privacy Type Default Description Inherited From
element Stripe.StripeCardElement
hideIcon boolean false Whether to hide icons in the Stripe form.
hidePostalCode boolean false Whether or not to hide the postal code field. Useful when you gather shipping info elsewhere.
iconStyle IconStyle 'default' Stripe icon style.
value StripeFormValues {} Prefilled values for form.
brand CardBrand | null null The card brand detected by Stripe
complete boolean false Whether the form is complete.
empty boolean true If the form is empty.
invalid boolean false Whether the form is invalid.
Methods
Name Privacy Description Parameters Return Inherited From
createPaymentMethod public Submit payment information to generate a paymentMethod paymentMethodData: Stripe.CreatePaymentMethodData Promise<Stripe.PaymentMethodResult>
createSource public Submit payment information to generate a source sourceData: Stripe.CreateSourceData Promise<Stripe.SourceResult>
createToken public Submit payment information to generate a token tokenData Promise<Stripe.TokenResult>
isPotentiallyValid public Checks for potential validity. A potentially valid form is one that is not empty, not complete and has no error. A validated form also counts as potentially valid. boolean
reset public Resets the Stripe card. void
submit public Generates a payment representation of the type specified by `generate`. Promise<StripePaymentResponse>
validate public Checks if the Stripe form is valid. boolean
updateStyle public
Events
Name Type Description Inherited From
'change' Stripe Element change event
Attributes
Name Field Inherited From
hide-icon hideIcon
hide-postal-code hidePostalCode
icon-style iconStyle
value value
brand brand
complete complete
empty empty
invalid invalid
CSS Properties
Name Default Description
--stripe-elements-border-radius `4px` border radius of the element container
--stripe-elements-border `1px solid transparent` border property of the element container
--stripe-elements-box-shadow `0 1px 3px 0 #e6ebf1` box shadow for the element container
--stripe-elements-transition `box-shadow 150ms ease` transition property for the element container
--stripe-elements-base-color `color` property for the element in its base state
--stripe-elements-base-font-family `font-family` property for the element in its base state
--stripe-elements-base-font-size `font-size` property for the element in its base state
--stripe-elements-base-font-smoothing `font-smoothing` property for the element in its base state
--stripe-elements-base-font-variant `font-variant` property for the element in its base state
--stripe-elements-base-icon-color `icon-color` property for the element in its base state
--stripe-elements-base-line-height `line-height` property for the element in its base state
--stripe-elements-base-letter-spacing `letter-spacing` property for the element in its base state
--stripe-elements-base-text-decoration `text-decoration` property for the element in its base state
--stripe-elements-base-text-shadow `text-shadow` property for the element in its base state
--stripe-elements-base-text-transform `text-transform` property for the element in its base state
--stripe-elements-complete-color `color` property for the element in its complete state
--stripe-elements-complete-font-family `font-family` property for the element in its complete state
--stripe-elements-complete-font-size `font-size` property for the element in its complete state
--stripe-elements-complete-font-smoothing `font-smoothing` property for the element in its complete state
--stripe-elements-complete-font-variant `font-variant` property for the element in its complete state
--stripe-elements-complete-icon-color `icon-color` property for the element in its complete state
--stripe-elements-complete-line-height `line-height` property for the element in its complete state
--stripe-elements-complete-letter-spacing `letter-spacing` property for the element in its complete state
--stripe-elements-complete-text-decoration `text-decoration` property for the element in its complete state
--stripe-elements-complete-text-shadow `text-shadow` property for the element in its complete state
--stripe-elements-complete-text-transform `text-transform` property for the element in its complete state
--stripe-elements-empty-color `color` property for the element in its empty state
--stripe-elements-empty-font-family `font-family` property for the element in its empty state
--stripe-elements-empty-font-size `font-size` property for the element in its empty state
--stripe-elements-empty-font-smoothing `font-smoothing` property for the element in its empty state
--stripe-elements-empty-font-variant `font-variant` property for the element in its empty state
--stripe-elements-empty-icon-color `icon-color` property for the element in its empty state
--stripe-elements-empty-line-height `line-height` property for the element in its empty state
--stripe-elements-empty-letter-spacing `letter-spacing` property for the element in its empty state
--stripe-elements-empty-text-decoration `text-decoration` property for the element in its empty state
--stripe-elements-empty-text-shadow `text-shadow` property for the element in its empty state
--stripe-elements-empty-text-transform `text-transform` property for the element in its empty state
--stripe-elements-invalid-color `color` property for the element in its invalid state
--stripe-elements-invalid-font-family `font-family` property for the element in its invalid state
--stripe-elements-invalid-font-size `font-size` property for the element in its invalid state
--stripe-elements-invalid-font-smoothing `font-smoothing` property for the element in its invalid state
--stripe-elements-invalid-font-variant `font-variant` property for the element in its invalid state
--stripe-elements-invalid-icon-color `icon-color` property for the element in its invalid state
--stripe-elements-invalid-line-height `line-height` property for the element in its invalid state
--stripe-elements-invalid-letter-spacing `letter-spacing` property for the element in its invalid state
--stripe-elements-invalid-text-decoration `text-decoration` property for the element in its invalid state
--stripe-elements-invalid-text-shadow `text-shadow` property for the element in its invalid state
--stripe-elements-invalid-text-transform `text-transform` property for the element in its invalid state
Private API
Methods
Name Privacy Description Parameters Return Inherited From
getPaymentMethodData private Generates PaymentMethodData from the element. Stripe.CreatePaymentMethodData
getStripeElementsStyles private Returns a Stripe-friendly style object computed from CSS custom properties Stripe.StripeElementStyle
initElement protected Promise<void>
createElement private options: Stripe.StripeCardElementOptions
onChange private Updates the element's state. event: Stripe.StripeCardElementChangeEvent Promise<void>

Exports

Kind Name Declaration Module Package
js StripeElements StripeElements ./stripe-elements.js
custom-element-definition stripe-elements StripeElements ./stripe-elements.js

./stripe-payment-request.js:

class: StripePaymentRequest, stripe-payment-request

Superclass
Name Module Package
StripeBase /src/StripeBase.js
Static Fields
Name Privacy Type Default Description Inherited From
is string 'stripe-payment-request'
Fields
Name Privacy Type Default Description Inherited From
amount number | undefined The amount in the currency's subunit (e.g. cents, yen, etc.)
canMakePayment Stripe.CanMakePaymentResult | null null Whether or not the device can make the payment request.
country CountryCode | undefined The two-letter country code of your Stripe account
currency StripeCurrency | undefined Three character currency code
displayItems Stripe.PaymentRequestItem[] An array of PaymentRequestItem objects. These objects 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.
label string | undefined A name that the browser shows the customer in the payment interface.
paymentIntent Stripe.PaymentIntent | null null Stripe PaymentIntent
paymentRequest Stripe.PaymentRequest | null null Stripe PaymentRequest
pending boolean false If you might change the payment amount later (for example, after you have calcluated shipping costs), set this to true. Note that browsers treat this as a hint for how to display things, and not necessarily as something that will prevent submission.
requestPayerEmail boolean | undefined See the requestPayerName option.
requestPayerName boolean | undefined By default, the browser‘s payment interface only asks the customer for actual payment information. A customer name can be collected by setting this option to true. This collected name will appears in the PaymentResponse object. We highly recommend you collect at least one of name, email, or phone as this also results in collection of billing address for Apple Pay. The billing address can be used to perform address verification and block fraudulent payments. For all other payment methods, the billing address is automatically collected when available.
requestPayerPhone boolean | undefined See the requestPayerName option.
requestShipping boolean | undefined Collect shipping address by setting this option to true. The address appears in the PaymentResponse. You must also 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 Stripe.PaymentRequestShippingOption[] An array of PaymentRequestShippingOption objects. The first shipping option listed appears in the browser payment interface as the default option.
buttonType StripePaymentRequestButtonType 'default'
buttonTheme StripePaymentRequestButtonTheme 'dark'
Methods
Name Privacy Description Parameters Return Inherited From
reset public void
Events
Name Type Description Inherited From
'unsupported' When the element detects that the user agent cannot make a payment
'fail' When a payment request fails
'cancel' When a payment request is cancelled
'shippingaddresschange' When the user chooses a different shipping address
'shippingoptionchange' When the user chooses a different shipping option
Attributes
Name Field Inherited From
amount amount
can-make-payment canMakePayment
country country
currency currency
displayItems displayItems
label label
payment-intent paymentIntent
payment-request paymentRequest
pending pending
request-payer-email requestPayerEmail
request-payer-name requestPayerName
request-payer-phone requestPayerPhone
request-shipping requestShipping
shippingOptions shippingOptions
button-type buttonType
button-theme buttonTheme
CSS Properties
Name Default Description
--stripe-payment-request-element-min-width `300px` min-width property of the container element
--stripe-payment-request-element-padding `8px 12px` padding property of the container element
--stripe-payment-request-element-background `white` background property of the container element
Private API
Fields
Name Privacy Type Default Description Inherited From
#displayItems private Stripe.PaymentRequestItem[] | undefined
#shippingOptions private Stripe.PaymentRequestShippingOption[] | undefined
complete private Completes the PaymentRequest.
Methods
Name Privacy Description Parameters Return Inherited From
getStripePaymentRequestOptions private Creates a PaymentRequestOptions object. Stripe.PaymentRequestOptions
initElement protected Initializes the PaymentRequest Object. Promise<void>
initPaymentRequest private Initialized the `PaymentRequest` object. Promise<void>
initPaymentRequestButton private Creates Stripe Payment Request Element. Promise<void>
initPaymentRequestListeners private Attaches listeners to the `PaymentRequest` object. Promise<void>
updatePaymentRequest private Updates the PaymentRequests's values
onCancel private Handle a `cancel` event void
onPaymentResponse private Handle a paymentResponse from Stripe event: StripePaymentRequestEvent Promise<void>
confirmPaymentIntent private When a PaymentIntent client secret is set, confirm the payment paymentResponse: Stripe.PaymentRequestPaymentMethodEvent Promise<void>
confirmCardPayment private Stripe confirmCardPayment method data: Stripe.ConfirmCardPaymentData, options: Stripe.ConfirmCardPaymentOptions Promise<Stripe.PaymentIntentResult>
onShippingaddresschange private originalEvent: Stripe.PaymentRequestShippingAddressEvent void
onShippingoptionchange private originalEvent: Stripe.PaymentRequestShippingOptionEvent void
parseDatasets private Parses an element's dataset number props from string to number selector: 'stripe-shipping-option' Stripe.PaymentRequestShippingOption[]
parseDatasets private selector: 'stripe-display-item' Stripe.PaymentRequestItem[]
parseDatasets private selector: 'stripe-display-item'|'stripe-shipping-option' (Stripe.PaymentRequestItem|Stripe.PaymentRequestShippingOption)[]

Functions

Name Description Parameters Return
isStripeDisplayItem el: Element el is StripeDisplayItem
isStripeShippingOption el: Element el is StripeShippingOption

Exports

Kind Name Declaration Module Package
js isStripeDisplayItem isStripeDisplayItem ./stripe-payment-request.js
js isStripeShippingOption isStripeShippingOption ./stripe-payment-request.js
js StripePaymentRequest StripePaymentRequest ./stripe-payment-request.js
custom-element-definition stripe-payment-request StripePaymentRequest ./stripe-payment-request.js

./index.js:

Exports

Kind Name Declaration Module Package
js StripeElements StripeElements ./stripe-elements.js
js StripePaymentRequest StripePaymentRequest ./stripe-payment-request.js