This is the abridged developer documentation for stripe-pwa-elements # stripe-pwa-elements > Stripe の決済UIを Web Components として提供します。 ## はじめに [Section titled “はじめに”](#はじめに) [導入](/guides/getting-started/)インストール手順と最小の利用例を確認します。 [ガイド](/guides/)PaymentIntent/SetupIntent、イベント、i18n、スタイリングをまとめます。 [コンポーネントAPI](/components/)各コンポーネントの Props / Events / Methods を参照できます。 # Components > 各 Web Component の API リファレンス。 このセクションは `src/components/**/readme.md`(Stencil の `docs-readme` 出力)を取り込み、Starlight 用のページとして整形したものです。 ## コンポーネント選択ガイド [Section titled “コンポーネント選択ガイド”](#コンポーネント選択ガイド) 用途に応じて最適なコンポーネントを選択してください。詳しいフロー図は [決済フロー](/guides/payment-flows/) ガイドを参照してください。 | コンポーネント | ユースケース | | --------------------------------------------------------------------------------------- | --------------------------------------- | | [`stripe-card-element`](/components/stripe-card-element/) | カード決済のみ(カード番号・有効期限・CVC を個別表示) | | [`stripe-card-element-modal`](/components/stripe-card-element-modal/) | カード決済をモーダルで表示 | | [`stripe-payment-element`](/components/stripe-payment-element/) | 複数の決済手段を統合表示(カード・銀行振込・ウォレットなど) | | [`stripe-express-checkout-element`](/components/stripe-express-checkout-element/) | Apple Pay / Google Pay / Link のワンクリック決済 | | [`stripe-link-authentication-element`](/components/stripe-link-authentication-element/) | Stripe Link によるメール認証 | | [`stripe-address-element`](/components/stripe-address-element/) | 住所の収集 | | [`stripe-currency-selector`](/components/stripe-currency-selector/) | Adaptive Pricing の通貨選択 | | [`stripe-modal`](/components/stripe-modal/) | 決済コンポーネントのモーダルラッパー | | [`stripe-payment-request-button`](/components/stripe-payment-request-button/) | Payment Request API ボタン(Beta) | # > Component API reference. > このページは `src/components/stripe-address-element/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### initStripe [Section titled “initStripe”](#initstripe) Get Stripe.js, and initialize elements ```js const stripeElement = document.createElement('stripe-address-element'); customElements .whenDefined('stripe-address-element') .then(() => { stripeElement.initStripe('pk_test_XXXXXXXXX') }) ``` ### updateProgress [Section titled “updateProgress”](#updateprogress) Update the form submit progress ```js const stripeElement = document.createElement('stripe-address-element'); customElements .whenDefined('stripe-address-element') .then(() => { stripeElement.addEventListener('formSubmit', async props => { const { detail: { address } } = props; console.log('Address:', address); stripeElement.updateProgress('success') }); }) ``` ### setErrorMessage [Section titled “setErrorMessage”](#seterrormessage) Set error message ```js const stripeElement = document.createElement('stripe-address-element'); customElements .whenDefined('stripe-address-element') .then(() => { stripeElement.addEventListener('formSubmit', async props => { try { throw new Error('debug') } catch (e) { stripeElement.setErrorMessage(`Error: ${e.message}`) stripeElement.updateProgress('failure') } }); }) ``` ### getValue [Section titled “getValue”](#getvalue) Get the current address value ```js const stripeElement = document.querySelector('stripe-address-element'); const addressValue = await stripeElement.getValue(); console.log('Address:', addressValue); ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js const stripeElement = document.createElement('stripe-address-element'); customElements .whenDefined('stripe-address-element') .then(() => { stripeElement .addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { console.log('Stripe loaded:', stripe); }); }) ``` ### formSubmit [Section titled “formSubmit”](#formsubmit) Form submit event ```js const stripeElement = document.createElement('stripe-address-element'); customElements .whenDefined('stripe-address-element') .then(() => { stripeElement .addEventListener('formSubmit', async props => { const { detail: { address } } = props; console.log('Address submitted:', address); }) }) ``` [![Edit in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/p/devbox/github/hideokamoto/stripe-pwa-elements/tree/main/examples/codesandbox) — Try it first: open the live demo (Stripe test mode, `address.html`) in CodeSandbox. ## Known console error [Section titled “Known console error”](#known-console-error) When this component is used on its own, the browser console shows: ```plaintext Unable to select session. Make sure Elements is initialized with clientSecret or use the nullableSessionSelector() instead. ``` The form still works: it renders, accepts input, and `formSubmit` is emitted with the entered address. The message is logged by an iframe that Stripe.js adds when an Address Element is mounted (`elements-inner-easel`), not by the address form itself. Stripe.js logs it when the Elements group was created without a PaymentIntent / SetupIntent client secret or a `mode` / `currency`. This component creates its Elements group without them, because a standalone address form has no payment to describe, so the message cannot be avoided here and can be ignored. This was observed with the Stripe.js version loaded by `@stripe/stripe-js` 9.x. ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ------------------ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------- | | `allowedCountries` | – | Allowed countries (array of country codes) | `string[]` | `undefined` | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `buttonLabel` | `button-label` | Submit button label By default we recommended to use these string - ‘Save’ or ‘Continue’ These strings will translated automatically by this library. | `string` | `'Save'` | | `defaultCountry` | `default-country` | Default country code (e.g., ‘US’, ‘JP’, ‘GB’) | `string` | `undefined` | | `handleSubmit` | – | Form submit event handler | `(event: Event, props: AddressSubmitEvent) => Promise` | `undefined` | | `mode` | `mode` | Address mode: ‘shipping’ or ‘billing’ | `"billing" \| "shipping"` | `'billing'` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `sheetTitle` | `sheet-title` | Form title By default we recommended to use these string - ‘Shipping address’ for shipping mode - ‘Billing address’ for billing mode These strings will translated automatically by this library. | `string` | `'Billing address'` | | `showLabel` | `show-label` | Show the form label | `boolean` | `false` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | -------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `formSubmit` | Form submit event | `CustomEvent<{ address: { value: { name: string; firstName?: string; lastName?: string; address: { line1: string; line2: string; city: string; state: string; postal_code: string; country: string; }; phone?: string; }; complete: boolean; }; }>` | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `getValue() => Promise<{ value: import("@stripe/stripe-js").StripeAddressElementChangeEvent["value"]; complete: boolean; }>` [Section titled “getValue() => Promise<{ value: import("@stripe/stripe-js").StripeAddressElementChangeEvent\["value"\]; complete: boolean; }>”](#getvalue--promise-value-importstripestripe-jsstripeaddresselementchangeeventvalue-complete-boolean-) Get the current address value #### Returns [Section titled “Returns”](#returns) Type: `Promise<{ value: { name: string; firstName?: string; lastName?: string; address: { line1: string; line2: string; city: string; state: string; postal_code: string; country: string; }; phone?: string; }; complete: boolean; }>` Promise resolving to the address value ### `initStripe(publishableKey: string, options?: InitStripeOptions) => Promise` [Section titled “initStripe(publishableKey: string, options?: InitStripeOptions) => Promise\”](#initstripepublishablekey-string-options-initstripeoptions--promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | ----------------------------- | ----------- | | `publishableKey` | `string` | | | `options` | `{ stripeAccount?: string; }` | | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `setErrorMessage(errorMessage: string) => Promise` [Section titled “setErrorMessage(errorMessage: string) => Promise\”](#seterrormessageerrormessage-string--promisethis) Set error message #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | -------------- | -------- | ----------- | | `errorMessage` | `string` | string | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `updateProgress(progress: ProgressStatus) => Promise` [Section titled “updateProgress(progress: ProgressStatus) => Promise\”](#updateprogressprogress-progressstatus--promisethis) Update the form submit progress #### Parameters [Section titled “Parameters”](#parameters-2) | Name | Type | Description | | ---------- | ------------------------------------------- | ----------- | | `progress` | `"" \| "loading" \| "success" \| "failure"` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-card-element/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### initStripe [Section titled “initStripe”](#initstripe) Get Stripe.js, and initialize elements ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { stripeElement.initStripe('pk_test_XXXXXXXXX') }) ``` ### updateProgress [Section titled “updateProgress”](#updateprogress) Update the form submit progress ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { // You must set the attributes to stop running default form submit action when you want to listen the 'formSubmit' event. stripeElement.setAttribute('should-use-default-form-submit-action', false) stripeElement.addEventListener('formSubmit', async props => { const { detail: { stripe, cardNumber, event }, } = props; const result = await stripe.createPaymentMethod({ type: 'card', card: cardNumber, }); console.log(result); stripeElement.updateProgress('success') }); }) ``` ### setErrorMessage [Section titled “setErrorMessage”](#seterrormessage) Set error message ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { // You must set the attributes to stop running default form submit action when you want to listen the 'formSubmit' event. stripeElement.setAttribute('should-use-default-form-submit-action', false) stripeElement.addEventListener('formSubmit', async props => { try { throw new Error('debug') } catch (e) { stripeElement.setErrorMessage(`Error: ${e.message}`) stripeElement.updateProgress('failure') } }); }) ``` ### intentClientSecret [Section titled “intentClientSecret”](#intentclientsecret) The client secret from paymentIntent.create response ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { stripeElement.setAttribute('intent-client-secret', 'dummy') }) ``` ```html ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { stripeElement .addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { 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 }); }); }) ``` ### formSubmit [Section titled “formSubmit”](#formsubmit) Form submit event ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { stripeElement .addEventListener('formSubmit', async props => { const { detail: { stripe, cardNumber, event }, } = props; const result = await stripe.createPaymentMethod({ type: 'card', card: cardNumber, }); console.log(result); }) }) ``` ### defaultFormSubmitResult [Section titled “defaultFormSubmitResult”](#defaultformsubmitresult) Recieve the result of defaultFormSubmit event ```js const stripeElement = document.createElement('stripe-card-element'); customElements .whenDefined('stripe-card-element') .then(() => { stripeElement.addEventListener('defaultFormSubmitResult', async ({detail}) => { if (detail instanceof Error) { console.error(detail) } else { console.log(detail) } }) }) ``` [![Edit in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/p/devbox/github/hideokamoto/stripe-pwa-elements/tree/main/examples/codesandbox) — Try it first: open the live demo (Stripe test mode, `card.html`) in CodeSandbox. ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ---------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | -------------------------------- | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `buttonLabel` | `button-label` | Submit button label By default we recommended to use these string - ‘Pay’ -> PaymentSheet - ‘Add’ -> PaymentFlow(Android) - ‘Add card’ -> PaymentFlow(iOS) - ‘Add a card’ -> PaymentFlow(iOS) These strings will translated automatically by this library. | `string` | `'Pay'` | | `handleSubmit` | – | Form submit event handler | `(event: Event, props: FormSubmitEvent) => Promise` | `undefined` | | `intentClientSecret` | `intent-client-secret` | The client secret from paymentIntent.create response | `string` | `undefined` | | `intentType` | `intent-type` | Default submit handle type. If you want to use `setupIntent`, should update this attribute. | `"payment" \| "setup"` | `'payment'` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `sheetTitle` | `sheet-title` | Payment sheet title By default we recommended to use these string - ‘Add your payment information’ -> PaymentSheet / PaymentFlow(Android) - ‘Add a card’ -> PaymentFlow(iOS) These strings will translated automatically by this library. | `string` | `'Add your payment information'` | | `shouldUseDefaultFormSubmitAction` | `should-use-default-form-submit-action` | The component will confirm the intent for you: `stripe.confirmCardPayment` when `intentType` is `'payment'`, `stripe.confirmCardSetup` when it is `'setup'`. If you want to customize the behavior, should set false. And listen the ‘formSubmit’ event on the element | `boolean` | `true` | | `showLabel` | `show-label` | Show the form label | `boolean` | `false` | | `showPaymentRequestButton` | `show-payment-request-button` | If show PaymentRequest Button, should put true | `boolean` | `undefined` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | | `zip` | `zip` | If true, show zip code field | `boolean` | `true` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | ------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `defaultFormSubmitResult` | Recieve the result of defaultFormSubmit event | `CustomEvent` | | `formSubmit` | Form submit event | `CustomEvent<{ stripe: Stripe; cardNumberElement: StripeCardNumberElement; cardExpiryElement: StripeCardExpiryElement; cardCVCElement: StripeCardCvcElement; intentClientSecret?: string; zipCode?: string; }>` | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `initStripe(publishableKey: string, options?: InitStripeOptions) => Promise` [Section titled “initStripe(publishableKey: string, options?: InitStripeOptions) => Promise\”](#initstripepublishablekey-string-options-initstripeoptions--promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | ----------------------------- | ----------- | | `publishableKey` | `string` | | | `options` | `{ stripeAccount?: string; }` | | #### Returns [Section titled “Returns”](#returns) Type: `Promise` ### `setErrorMessage(errorMessage: string) => Promise` [Section titled “setErrorMessage(errorMessage: string) => Promise\”](#seterrormessageerrormessage-string--promisethis) Set error message #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | -------------- | -------- | ----------- | | `errorMessage` | `string` | string | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `setPaymentRequestOption(option: PaymentRequestButtonOption) => Promise` [Section titled “setPaymentRequestOption(option: PaymentRequestButtonOption) => Promise\”](#setpaymentrequestoptionoption-paymentrequestbuttonoption--promisethis) #### Parameters [Section titled “Parameters”](#parameters-2) | Name | Type | Description | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `option` | `PaymentRequestOptions & { paymentRequestPaymentMethodHandler?: PaymentRequestPaymentMethodEventHandler; paymentRequestShippingAddressChangeHandler?: PaymentRequestShippingAddressEventHandler; paymentRequestShippingOptionChangeHandler?: PaymentRequestShippingOptionEventHandler; }` | | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `updateProgress(progress: ProgressStatus) => Promise` [Section titled “updateProgress(progress: ProgressStatus) => Promise\”](#updateprogressprogress-progressstatus--promisethis) Update the form submit progress #### Parameters [Section titled “Parameters”](#parameters-3) | Name | Type | Description | | ---------- | ------------------------------------------- | ----------- | | `progress` | `"" \| "loading" \| "success" \| "failure"` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` ## Dependencies [Section titled “Dependencies”](#dependencies) ### Used by [Section titled “Used by”](#used-by) * [stripe-card-element-modal](../stripe-card-element-modal) ### Depends on [Section titled “Depends on”](#depends-on) * [stripe-payment-request-button](../stripe-payment-request-button) ### Graph [Section titled “Graph”](#graph) ``` graph TD; stripe-card-element --> stripe-payment-request-button stripe-card-element-modal --> stripe-card-element ``` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-card-element-modal/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### intentClientSecret [Section titled “intentClientSecret”](#intentclientsecret) The client secret from paymentIntent.create response ```js const stripeElement = document.createElement('stripe-card-element-modal'); customElements .whenDefined('stripe-card-element-modal') .then(() => { stripeElement.setAttribute('intent-client-secret', 'dummy') }) ``` ```html ``` ### intentType [Section titled “intentType”](#intenttype) Default submit handle type. ```html ``` ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ---------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | ----------- | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `undefined` | | `buttonLabel` | `button-label` | Submit button label By default we recommended to use these string - ‘Pay’ -> PaymentSheet - ‘Add’ -> PaymentFlow(Android) - ‘Add card’ -> PaymentFlow(iOS) - ‘Add a card’ -> PaymentFlow(iOS) These strings will translated automatically by this library. | `string` | `undefined` | | `handleSubmit` | – | Form submit event handler | `(event: Event, props: FormSubmitEvent) => Promise` | `undefined` | | `intentClientSecret` | `intent-client-secret` | The client secret from paymentIntent.create response | `string` | `undefined` | | `intentType` | `intent-type` | Default submit handle type. If you want to use `setupIntent`, should update this attribute. | `"payment" \| "setup"` | `'payment'` | | `open` | `open` | Modal state. If true, the modal will open | `boolean` | `false` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `sheetTitle` | `sheet-title` | Payment sheet title By default we recommended to use these string - ‘Add your payment information’ -> PaymentSheet / PaymentFlow(Android) - ‘Add a card’ -> PaymentFlow(iOS) These strings will translated automatically by this library. | `string` | `undefined` | | `shouldUseDefaultFormSubmitAction` | `should-use-default-form-submit-action` | The component will confirm the intent for you: `stripe.confirmCardPayment` when `intentType` is `'payment'`, `stripe.confirmCardSetup` when it is `'setup'`. If you want to customize the behavior, should set false. And listen the ‘formSubmit’ event on the element | `boolean` | `true` | | `showCloseButton` | `show-close-button` | If true, the modal display close button | `boolean` | `true` | | `showLabel` | `show-label` | Show the form label | `boolean` | `false` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | | `zip` | `zip` | If true, show zip code field | `boolean` | `true` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | -------- | ----------- | ------------------ | | `closed` | | `CustomEvent` | ## Methods [Section titled “Methods”](#methods) ### `destroy() => Promise` [Section titled “destroy() => Promise\”](#destroy--promisevoid) Remove the modal #### Returns [Section titled “Returns”](#returns) Type: `Promise` ### `getStripeCardElementElement() => Promise` [Section titled “getStripeCardElementElement() => Promise\”](#getstripecardelementelement--promisehtmlstripecardelementelement) Get the inner component #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `present() => Promise` [Section titled “present() => Promise\”](#present--promiseunknown) open modal #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `setPaymentRequestButton(options: PaymentRequestButtonOption) => Promise` [Section titled “setPaymentRequestButton(options: PaymentRequestButtonOption) => Promise\”](#setpaymentrequestbuttonoptions-paymentrequestbuttonoption--promisevoid) Add payment request button #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `options` | `PaymentRequestOptions & { paymentRequestPaymentMethodHandler?: PaymentRequestPaymentMethodEventHandler; paymentRequestShippingAddressChangeHandler?: PaymentRequestShippingAddressEventHandler; paymentRequestShippingOptionChangeHandler?: PaymentRequestShippingOptionEventHandler; }` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` ### `updateProgress(progress: ProgressStatus) => Promise` [Section titled “updateProgress(progress: ProgressStatus) => Promise\”](#updateprogressprogress-progressstatus--promisehtmlstripecardelementelement) Update Stripe client loading process #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | ---------- | ------------------------------------------- | ----------- | | `progress` | `"" \| "loading" \| "success" \| "failure"` | | #### Returns [Section titled “Returns”](#returns-4) Type: `Promise` ## Dependencies [Section titled “Dependencies”](#dependencies) ### Depends on [Section titled “Depends on”](#depends-on) * [stripe-modal](../stripe-modal) * [stripe-card-element](../stripe-card-element) ### Graph [Section titled “Graph”](#graph) ``` graph TD; stripe-card-element-modal --> stripe-modal stripe-card-element-modal --> stripe-card-element stripe-modal --> ion-icon stripe-card-element --> stripe-payment-request-button ``` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-currency-selector/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### initStripe [Section titled “initStripe”](#initstripe) Get Stripe.js, and initialize elements ```js const stripeCurrencySelector = document.createElement('stripe-currency-selector'); customElements .whenDefined('stripe-currency-selector') .then(() => { stripeCurrencySelector.initStripe('pk_test_XXXXXXXXX') }) ``` ### setErrorMessage [Section titled “setErrorMessage”](#seterrormessage) Set error message ```js const stripeCurrencySelector = document.createElement('stripe-currency-selector'); customElements .whenDefined('stripe-currency-selector') .then(() => { stripeCurrencySelector.setErrorMessage('Invalid currency selected'); }); ``` ### getSelectedCurrency [Section titled “getSelectedCurrency”](#getselectedcurrency) Get the selected currency ```js const stripeCurrencySelector = document.querySelector('stripe-currency-selector'); const currency = await stripeCurrencySelector.getSelectedCurrency(); console.log('Selected currency:', currency); ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js const stripeCurrencySelector = document.createElement('stripe-currency-selector'); customElements .whenDefined('stripe-currency-selector') .then(() => { stripeCurrencySelector .addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { console.log('Stripe loaded:', stripe); }); }) ``` ### currencyChange [Section titled “currencyChange”](#currencychange) Currency change event ```js const stripeCurrencySelector = document.createElement('stripe-currency-selector'); customElements .whenDefined('stripe-currency-selector') .then(() => { stripeCurrencySelector .addEventListener('currencyChange', async props => { const { detail: { currency } } = props; console.log('Currency changed:', currency); }) }) ``` ## Overview [Section titled “Overview”](#overview) Stripe Currency Selector Element Allows customers to select their preferred currency for Adaptive Pricing ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ---------------------- | ------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------- | ----------------------- | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `clientSecret` | `client-secret` | The client secret from Checkout Session Required for Currency Selector Element | `string` | `undefined` | | `handleCurrencyChange` | – | Currency change event handler | `(props: CurrencySelectorChangeEvent) => Promise` | `undefined` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | ---------------- | -------------------------- | ------------------------------------ | | `currencyChange` | Currency change event | `CustomEvent<{ currency: string; }>` | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `getSelectedCurrency() => Promise` [Section titled “getSelectedCurrency() => Promise\”](#getselectedcurrency--promisestring--undefined) Get the selected currency #### Returns [Section titled “Returns”](#returns) Type: `Promise` Promise resolving to the selected currency code (e.g., ‘USD’, ‘EUR’) ### `initStripe(publishableKey: string, options?: InitStripeOptions) => Promise` [Section titled “initStripe(publishableKey: string, options?: InitStripeOptions) => Promise\”](#initstripepublishablekey-string-options-initstripeoptions--promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | ----------------------------- | ------------------------------------------------------- | | `publishableKey` | `string` | - Your Stripe publishable API key | | `options` | `{ stripeAccount?: string; }` | - Optional initialization options (e.g., stripeAccount) | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `setErrorMessage(errorMessage: string) => Promise` [Section titled “setErrorMessage(errorMessage: string) => Promise\”](#seterrormessageerrormessage-string--promisethis) Set error message #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | -------------- | -------- | ------------------------------ | | `errorMessage` | `string` | - The error message to display | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` Promise resolving to this instance for method chaining *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-express-checkout-element/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ```html ``` ### clientSecret [Section titled “clientSecret”](#clientsecret) The client secret from paymentIntent.create or setupIntent.create response ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.setAttribute('client-secret', 'pi_xxx_secret_xxx') }) ``` ### updateProgress [Section titled “updateProgress”](#updateprogress) Update the progress status ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.updateProgress('success') }) ``` ### setErrorMessage [Section titled “setErrorMessage”](#seterrormessage) Set error message ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.setErrorMessage('Payment failed') }) ``` ### initStripe [Section titled “initStripe”](#initstripe) Get Stripe.js, and initialize elements ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.initStripe('pk_test_XXXXXXXXX') }) ``` ### updateElementOptions [Section titled “updateElementOptions”](#updateelementoptions) Update element options dynamically ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(async () => { await element.initStripe('pk_test_xxx') element.updateElementOptions({ amount: 2000 }) }) ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { console.log('Stripe loaded', stripe) }); }) ``` ### confirm [Section titled “confirm”](#confirm) Express Checkout confirm event ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.addEventListener('confirm', async ({ detail }) => { console.log('Payment confirmed', detail) }) }) ``` ### expressCheckoutClick [Section titled “expressCheckoutClick”](#expresscheckoutclick) Express Checkout click event ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.addEventListener('expressCheckoutClick', async ({ detail }) => { console.log('Button clicked', detail) }) }) ``` ### defaultConfirmResult [Section titled “defaultConfirmResult”](#defaultconfirmresult) Receive the result of default confirm action ```js const element = document.createElement('stripe-express-checkout-element'); customElements .whenDefined('stripe-express-checkout-element') .then(() => { element.addEventListener('defaultConfirmResult', async ({detail}) => { if (detail instanceof Error) { console.error(detail) } else { console.log(detail) } }) }) ``` [![Edit in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/p/devbox/github/hideokamoto/stripe-pwa-elements/tree/main/examples/codesandbox) — Try it first: open the live demo (Stripe test mode, `express-checkout.html`) in CodeSandbox. ## Overview [Section titled “Overview”](#overview) Express Checkout Element Component Provides one-click payment methods (Apple Pay, Google Pay, Link, PayPal, etc.) ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | ----------------------- | | `amount` | `amount` | Payment amount in cents (e.g., 1099 for $10.99) | `number` | `undefined` | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `buttonHeight` | `button-height` | Button height in pixels (e.g., ‘48px’) | `string` | `undefined` | | `clientSecret` | `client-secret` | The client secret from paymentIntent.create or setupIntent.create response | `string` | `undefined` | | `currency` | `currency` | Three-letter ISO currency code (e.g., ‘usd’, ‘eur’) | `string` | `undefined` | | `intentType` | `intent-type` | Default submit handle type. If you want to use `setupIntent`, should update this attribute. | `"payment" \| "setup"` | `'payment'` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `shouldUseDefaultConfirmAction` | `should-use-default-confirm-action` | The component will provide a function to call the confirmation API. If you want to customize the behavior, should set false. And listen the ‘confirm’ event on the element | `boolean` | `true` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | ---------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `cancel` | Express Checkout cancel event Fired when user cancels the express checkout flow | `CustomEvent` | | `confirm` | Express Checkout confirm event Fired when user completes the express checkout flow | `CustomEvent` | | `defaultConfirmResult` | Receive the result of default confirm action | `CustomEvent` | | `expressCheckoutClick` | Express Checkout click event Fired when user clicks on an express checkout button | `CustomEvent` | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `initStripe(publishableKey: string, options?: InitStripeOptions) => Promise` [Section titled “initStripe(publishableKey: string, options?: InitStripeOptions) => Promise\”](#initstripepublishablekey-string-options-initstripeoptions--promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | ----------------------------- | ----------- | | `publishableKey` | `string` | | | `options` | `{ stripeAccount?: string; }` | | #### Returns [Section titled “Returns”](#returns) Type: `Promise` ### `setErrorMessage(errorMessage: string) => Promise` [Section titled “setErrorMessage(errorMessage: string) => Promise\”](#seterrormessageerrormessage-string--promisethis) Set error message #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | -------------- | -------- | ----------- | | `errorMessage` | `string` | string | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `updateElementOptions(options: Partial) => Promise` [Section titled “updateElementOptions(options: Partial\) => Promise\”](#updateelementoptionsoptions-partialexpresscheckoutelementoptions--promisethis) Update element options dynamically #### Parameters [Section titled “Parameters”](#parameters-2) | Name | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | | `options` | `{ mode?: "setup" \| "payment" \| "subscription"; amount?: number; currency?: string; paymentMethods?: { applePay?: "never" \| "always" \| "auto"; googlePay?: "never" \| "always" \| "auto"; link?: "never" \| "always" \| "auto"; paypal?: "never" \| "always" \| "auto"; amazonPay?: "never" \| "always" \| "auto"; }; buttonType?: { applePay?: "buy" \| "donate" \| "plain" \| "book" \| "check-out" \| "subscribe"; googlePay?: "checkout" \| "buy" \| "donate" \| "plain" \| "book" \| "subscribe" \| "order" \| "pay"; }; buttonTheme?: { applePay?: "black" \| "white" \| "white-outline"; googlePay?: "black" \| "white"; }; buttonHeight?: string \| number; layout?: { maxColumns?: number; maxRows?: number; overflow?: "never" \| "auto"; }; }` | - Partial options to update | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `updateProgress(progress: ProgressStatus) => Promise` [Section titled “updateProgress(progress: ProgressStatus) => Promise\”](#updateprogressprogress-progressstatus--promisethis) Update the progress status #### Parameters [Section titled “Parameters”](#parameters-3) | Name | Type | Description | | ---------- | ------------------------------------------- | ----------- | | `progress` | `"" \| "loading" \| "success" \| "failure"` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-link-authentication-element/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### initStripe [Section titled “initStripe”](#initstripe) Get Stripe.js, and initialize elements ```js const stripeElement = document.createElement('stripe-link-authentication-element'); customElements .whenDefined('stripe-link-authentication-element') .then(() => { stripeElement.initStripe('pk_test_XXXXXXXXX') }) ``` ### updateProgress [Section titled “updateProgress”](#updateprogress) Update the progress status ```js const stripeElement = document.createElement('stripe-link-authentication-element'); customElements .whenDefined('stripe-link-authentication-element') .then(() => { stripeElement.updateProgress('success') }) ``` ### setErrorMessage [Section titled “setErrorMessage”](#seterrormessage) Set error message ```js const stripeElement = document.createElement('stripe-link-authentication-element'); customElements .whenDefined('stripe-link-authentication-element') .then(() => { stripeElement.setErrorMessage('Invalid email address') }) ``` ### getEmail [Section titled “getEmail”](#getemail) Get the current email value from the element ```js const stripeElement = document.createElement('stripe-link-authentication-element'); customElements .whenDefined('stripe-link-authentication-element') .then(async () => { const email = await stripeElement.getEmail(); console.log(email); }) ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js const stripeElement = document.createElement('stripe-link-authentication-element'); customElements .whenDefined('stripe-link-authentication-element') .then(() => { stripeElement .addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { console.log('Stripe loaded:', stripe); }); }) ``` ### linkAuthenticationChange [Section titled “linkAuthenticationChange”](#linkauthenticationchange) Link Authentication Element change event ```js const stripeElement = document.createElement('stripe-link-authentication-element'); customElements .whenDefined('stripe-link-authentication-element') .then(() => { stripeElement .addEventListener('linkAuthenticationChange', async ({ detail }) => { console.log('Email changed:', detail.email); }) }) ``` ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ----------------- | ------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ----------------------- | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `defaultEmail` | `default-email` | Default email value to prefill the element | `string` | `undefined` | | `handleChange` | – | Link Authentication Element change handler | `(event: LinkAuthenticationElementChangeEvent) => void \| Promise` | `undefined` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | -------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `linkAuthenticationChange` | Link Authentication Element change event Emitted when the email value changes | `CustomEvent<{ stripe: Stripe; linkAuthenticationElement: StripeLinkAuthenticationElement; email?: string; }>` | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `getEmail() => Promise` [Section titled “getEmail() => Promise\”](#getemail--promisestring--undefined) Get the current email value from the element #### Returns [Section titled “Returns”](#returns) Type: `Promise` The current email value or undefined ### `initStripe(publishableKey: string, options?: InitStripeOptions) => Promise` [Section titled “initStripe(publishableKey: string, options?: InitStripeOptions) => Promise\”](#initstripepublishablekey-string-options-initstripeoptions--promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | ----------------------------- | ----------- | | `publishableKey` | `string` | | | `options` | `{ stripeAccount?: string; }` | | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `setErrorMessage(errorMessage: string) => Promise` [Section titled “setErrorMessage(errorMessage: string) => Promise\”](#seterrormessageerrormessage-string--promisethis) Set error message #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | -------------- | -------- | ----------- | | `errorMessage` | `string` | string | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `updateProgress(progress: ProgressStatus) => Promise` [Section titled “updateProgress(progress: ProgressStatus) => Promise\”](#updateprogressprogress-progressstatus--promisethis) Update the progress status #### Parameters [Section titled “Parameters”](#parameters-2) | Name | Type | Description | | ---------- | ------------------------------------------- | ----------- | | `progress` | `"" \| "loading" \| "success" \| "failure"` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-modal/readme.md` から自動生成されています。 ## Accessibility [Section titled “Accessibility”](#accessibility) While open, the modal behaves as a modal dialog: * The host element gets `role="dialog"` and `aria-modal="true"`. * Focus moves into the modal (the close button, or the first focusable element) and returns to the previously focused element when it closes. * `Tab` / `Shift+Tab` cycle through the focusable elements inside the modal. * Pressing `Escape` closes the modal and emits the `close` event. Give the dialog an accessible name with `aria-label` or `aria-labelledby` on the host element: ```html

Add your payment information

``` Note: key presses inside cross-origin iframes (for example Stripe Elements fields) are not visible to the modal, so `Escape` pressed while such a field has focus does not close it. ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ----------------- | ------------------- | ----------------------------------------- | --------- | ------- | | `open` | `open` | Modal state. If true, the modal will open | `boolean` | `false` | | `showCloseButton` | `show-close-button` | If true, the modal display close button | `boolean` | `true` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | ------- | ----------- | ------------------ | | `close` | | `CustomEvent` | ## Methods [Section titled “Methods”](#methods) ### `closeModal() => Promise` [Section titled “closeModal() => Promise\”](#closemodal--promisevoid) Close the modal #### Returns [Section titled “Returns”](#returns) Type: `Promise` ### `openModal() => Promise` [Section titled “openModal() => Promise\”](#openmodal--promisevoid) Open the modal #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `toggleModal() => Promise` [Section titled “toggleModal() => Promise\”](#togglemodal--promisevoid) Toggle modal state #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ## Dependencies [Section titled “Dependencies”](#dependencies) ### Used by [Section titled “Used by”](#used-by) * [stripe-card-element-modal](../stripe-card-element-modal) * [stripe-payment-sheet](../stripe-payment-sheet) ### Depends on [Section titled “Depends on”](#depends-on) * ion-icon ### Graph [Section titled “Graph”](#graph) ``` graph TD; stripe-modal --> ion-icon stripe-card-element-modal --> stripe-modal stripe-payment-sheet --> stripe-modal ``` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-payment-element/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### initStripe [Section titled “initStripe”](#initstripe) Get Stripe.js, and initialize elements ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.initStripe('pk_test_XXXXXXXXX') }) ``` ### initStripeWithCheckoutSession [Section titled “initStripeWithCheckoutSession”](#initstripewithcheckoutsession) Get Stripe.js and initialize with Checkout Session mode ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.initStripeWithCheckoutSession( 'pk_test_XXXXXXXXX', 'cs_xxx_secret_xxx' ) }) ``` ### updateProgress [Section titled “updateProgress”](#updateprogress) Update the form submit progress ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.updateProgress('success') }) ``` ### setErrorMessage [Section titled “setErrorMessage”](#seterrormessage) Set error message ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.setErrorMessage('Payment failed') }) ``` ### intentClientSecret [Section titled “intentClientSecret”](#intentclientsecret) The client secret from paymentIntent.create or setupIntent.create response ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.setAttribute('intent-client-secret', 'pi_xxx_secret_xxx') }) ``` ```html ``` ### checkoutSessionClientSecret [Section titled “checkoutSessionClientSecret”](#checkoutsessionclientsecret) The client secret from checkout session response ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.initStripeWithCheckoutSession('pk_test_xxx', 'cs_xxx_secret_xxx') }) ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement .addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { console.log('Stripe loaded:', stripe); }); }) ``` ### formSubmit [Section titled “formSubmit”](#formsubmit) Form submit event ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement .addEventListener('formSubmit', async props => { const { detail: { stripe, elements } } = props; console.log('Form submitted', stripe, elements); }) }) ``` ### defaultFormSubmitResult [Section titled “defaultFormSubmitResult”](#defaultformsubmitresult) Receive the result of defaultFormSubmit event ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.addEventListener('defaultFormSubmitResult', async ({detail}) => { if (detail instanceof Error) { console.error(detail) } else { console.log(detail) } }) }) ``` ### checkoutSessionConfirmResult [Section titled “checkoutSessionConfirmResult”](#checkoutsessionconfirmresult) Receive the result of checkout session confirm ```js const stripeElement = document.createElement('stripe-payment-element'); customElements .whenDefined('stripe-payment-element') .then(() => { stripeElement.addEventListener('checkoutSessionConfirmResult', async ({detail}) => { if (detail instanceof Error) { console.error(detail) } else if (detail.type === 'success') { console.log('Payment successful:', detail.session) } else { console.error('Payment failed:', detail.error) } }) }) ``` ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ---------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | -------------------------------- | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `buttonLabel` | `button-label` | Submit button label By default we recommended to use these string - ‘Pay’ -> PaymentSheet - ‘Add’ -> PaymentFlow(Android) - ‘Add card’ -> PaymentFlow(iOS) - ‘Add a card’ -> PaymentFlow(iOS) These strings will translated automatically by this library. | `string` | `'Pay'` | | `checkoutSessionClientSecret` | `checkout-session-client-secret` | The client secret from checkout session response Use this for Checkout Session mode instead of intentClientSecret When this prop is set, the component will use Checkout Session API | `string` | `undefined` | | `handleSubmit` | – | Form submit event handler | `(event: Event, props: PaymentElementSubmitEvent) => Promise` | `undefined` | | `intentClientSecret` | `intent-client-secret` | The client secret from paymentIntent.create or setupIntent.create response Use this for Payment Intent / Setup Intent mode | `string` | `undefined` | | `intentType` | `intent-type` | Default submit handle type. If you want to use `setupIntent`, should update this attribute. | `"payment" \| "setup"` | `'payment'` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `sheetTitle` | `sheet-title` | Payment sheet title By default we recommended to use these string - ‘Add your payment information’ -> PaymentSheet / PaymentFlow(Android) - ‘Add a card’ -> PaymentFlow(iOS) These strings will translated automatically by this library. | `string` | `'Add your payment information'` | | `shouldUseDefaultFormSubmitAction` | `should-use-default-form-submit-action` | The component will provide a function to call the `stripe.confirmPayment` API. If you want to customize the behavior, should set false. And listen the ‘formSubmit’ event on the element | `boolean` | `true` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `checkoutSessionConfirmResult` | Receive the result of checkout session confirm This event is emitted when using Checkout Session mode | `CustomEvent` | | `defaultFormSubmitResult` | Receive the result of defaultFormSubmit event This event is emitted when using Payment Intent / Setup Intent mode | `CustomEvent` | | `formSubmit` | Form submit event | `CustomEvent<{ stripe: Stripe; elements?: StripeElements; intentClientSecret?: string; checkout?: StripeCheckoutElementsSdk; checkoutSessionClientSecret?: string; }>` | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `initStripe(publishableKey: string, options?: InitStripeOptions) => Promise` [Section titled “initStripe(publishableKey: string, options?: InitStripeOptions) => Promise\”](#initstripepublishablekey-string-options-initstripeoptions--promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | ----------------------------- | ----------- | | `publishableKey` | `string` | | | `options` | `{ stripeAccount?: string; }` | | #### Returns [Section titled “Returns”](#returns) Type: `Promise` ### `initStripeWithCheckoutSession(publishableKey: string, checkoutSessionClientSecret: string, options?: InitCheckoutSessionOptions) => Promise` [Section titled “initStripeWithCheckoutSession(publishableKey: string, checkoutSessionClientSecret: string, options?: InitCheckoutSessionOptions) => Promise\”](#initstripewithcheckoutsessionpublishablekey-string-checkoutsessionclientsecret-string-options-initcheckoutsessionoptions--promisevoid) Get Stripe.js and initialize with Checkout Session mode Use this method when you have a Checkout Session client secret instead of Payment/Setup Intent #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | ----------------------------- | -------------------------------------------- | ----------------------------------------- | | `publishableKey` | `string` | - Your Stripe publishable API key | | `checkoutSessionClientSecret` | `string` | - The client secret from Checkout Session | | `options` | `InitStripeOptions & CheckoutSessionOptions` | - Optional configuration | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `setErrorMessage(errorMessage: string) => Promise` [Section titled “setErrorMessage(errorMessage: string) => Promise\”](#seterrormessageerrormessage-string--promisethis) Set error message #### Parameters [Section titled “Parameters”](#parameters-2) | Name | Type | Description | | -------------- | -------- | ----------- | | `errorMessage` | `string` | string | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `updateProgress(progress: ProgressStatus) => Promise` [Section titled “updateProgress(progress: ProgressStatus) => Promise\”](#updateprogressprogress-progressstatus--promisethis) Update the form submit progress #### Parameters [Section titled “Parameters”](#parameters-3) | Name | Type | Description | | ---------- | ------------------------------------------- | ----------- | | `progress` | `"" \| "loading" \| "success" \| "failure"` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-payment-request-button/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### paymentMethodEventHandler [Section titled “paymentMethodEventHandler”](#paymentmethodeventhandler) Set handler of the `paymentRequest.on('paymentmethod'` event. ```js element.setPaymentMethodEventHandler(async (event, stripe) => { // Confirm the PaymentIntent with the payment method returned from the payment request. const {error} = await stripe.confirmCardPayment( paymentIntent.client_secret, { payment_method: event.paymentMethod.id, shipping: { name: event.shippingAddress.recipient, phone: event.shippingAddress.phone, address: { line1: event.shippingAddress.addressLine[0], city: event.shippingAddress.city, postal_code: event.shippingAddress.postalCode, state: event.shippingAddress.region, country: event.shippingAddress.country, }, }, }, {handleActions: false} ); ``` ### shippingOptionEventHandler [Section titled “shippingOptionEventHandler”](#shippingoptioneventhandler) Set handler of the `paymentRequest.on('shippingoptionchange')` event ```js element.setPaymentRequestShippingOptionEventHandler(async (event, stripe) => { event.updateWith({status: 'success'}); }) ``` ### shippingAddressEventHandler [Section titled “shippingAddressEventHandler”](#shippingaddresseventhandler) Set handler of the `paymentRequest.on('shippingaddresschange')` event ```js element.setPaymentRequestShippingAddressEventHandler(async (event, stripe) => { const response = await store.updatePaymentIntentWithShippingCost( paymentIntent.id, store.getLineItems(), event.shippingOption ); }) ``` ### stripeLoaded [Section titled “stripeLoaded”](#stripeloaded) Stripe Client loaded event ```js stripeElement .addEventListener('stripeLoaded', async ({ detail: {stripe} }) => { 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 }); }); ``` > **⚠️ DEPRECATED:** This component is deprecated. `stripe.paymentRequest()` is being removed in Stripe.js 9.x (deprecated 2025-09-30 / removed 2026-03-25). Please migrate to [``](../stripe-express-checkout-element/) which supports Apple Pay, Google Pay, Link, PayPal, and more. See the [migration guide](../../docs/guides/migrate-payment-request-button-to-express-checkout.md). > **\[DEPRECATED]** `stripe-payment-request-button` is deprecated and will be removed in a future release. `stripe.paymentRequest()` is being removed in Stripe.js 9.x (deprecated as of 2025-09-30 / 2026-03-25). Please migrate to `` which supports Apple Pay, Google Pay, Link, PayPal, and more via the modern Express Checkout Element API. Migration guide: ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ----------------------------- | ------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ----------------------- | | `applicationName` | `application-name` | Overwrite the application name that registered For wrapper library (like Capacitor) | `string` | `'stripe-pwa-elements'` | | `paymentMethodEventHandler` | – | Set handler of the `paymentRequest.on('paymentmethod'` event. | `(event: PaymentRequestPaymentMethodEvent, stripe: Stripe) => Promise` | `undefined` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `shippingAddressEventHandler` | – | Set handler of the `paymentRequest.on('shippingaddresschange')` event | `(event: PaymentRequestShippingAddressEvent, stripe: Stripe) => Promise` | `undefined` | | `shippingOptionEventHandler` | – | Set handler of the `paymentRequest.on('shippingoptionchange')` event | `(event: PaymentRequestShippingOptionEvent, stripe: Stripe) => Promise` | `undefined` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | | `stripeDidLoaded` | – | Stripe.js class loaded handler | `(event: StripeLoadedEvent) => Promise` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | -------------- | -------------------------- | ---------------------------------- | | `stripeLoaded` | Stripe Client loaded event | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `initStripe(publishableKey: string, options?: { showButton?: boolean; stripeAccount?: string; }) => Promise` [Section titled “initStripe(publishableKey: string, options?: { showButton?: boolean; stripeAccount?: string; }) => Promise\”](#initstripepublishablekey-string-options--showbutton-boolean-stripeaccount-string---promisevoid) Get Stripe.js, and initialize elements #### Parameters [Section titled “Parameters”](#parameters) | Name | Type | Description | | ---------------- | --------------------------------------------------- | ----------- | | `publishableKey` | `string` | | | `options` | `{ showButton?: boolean; stripeAccount?: string; }` | | #### Returns [Section titled “Returns”](#returns) Type: `Promise` ### `isAvailable(type: "applePay" | "googlePay") => Promise` [Section titled “isAvailable(type: "applePay" | "googlePay") => Promise\”](#isavailabletype-applepay--googlepay--promisevoid) Check isAvailable ApplePay or GooglePay. If you run this method, you should run before initStripe. #### Parameters [Section titled “Parameters”](#parameters-1) | Name | Type | Description | | ------ | --------------------------- | ----------- | | `type` | `"applePay" \| "googlePay"` | | #### Returns [Section titled “Returns”](#returns-1) Type: `Promise` ### `setPaymentMethodEventHandler(handler: PaymentRequestPaymentMethodEventHandler) => Promise` [Section titled “setPaymentMethodEventHandler(handler: PaymentRequestPaymentMethodEventHandler) => Promise\”](#setpaymentmethodeventhandlerhandler-paymentrequestpaymentmethodeventhandler--promisevoid) Register event handler for `paymentRequest.on('paymentmethod'` event. #### Parameters [Section titled “Parameters”](#parameters-2) | Name | Type | Description | | --------- | ---------------------------------------------------------------------------- | ----------- | | `handler` | `(event: PaymentRequestPaymentMethodEvent, stripe: Stripe) => Promise` | | #### Returns [Section titled “Returns”](#returns-2) Type: `Promise` ### `setPaymentRequestOption(option: PaymentRequestOptions) => Promise` [Section titled “setPaymentRequestOption(option: PaymentRequestOptions) => Promise\”](#setpaymentrequestoptionoption-paymentrequestoptions--promisethis) #### Parameters [Section titled “Parameters”](#parameters-3) | Name | Type | Description | | -------- | ----------------------- | ----------- | | `option` | `PaymentRequestOptions` | | #### Returns [Section titled “Returns”](#returns-3) Type: `Promise` ### `setPaymentRequestShippingAddressEventHandler(handler: PaymentRequestShippingAddressEventHandler) => Promise` [Section titled “setPaymentRequestShippingAddressEventHandler(handler: PaymentRequestShippingAddressEventHandler) => Promise\”](#setpaymentrequestshippingaddresseventhandlerhandler-paymentrequestshippingaddresseventhandler--promisevoid) Register event handler for `paymentRequest.on('shippingaddresschange'` event. #### Parameters [Section titled “Parameters”](#parameters-4) | Name | Type | Description | | --------- | ------------------------------------------------------------------------------ | ----------- | | `handler` | `(event: PaymentRequestShippingAddressEvent, stripe: Stripe) => Promise` | | #### Returns [Section titled “Returns”](#returns-4) Type: `Promise` ### `setPaymentRequestShippingOptionEventHandler(handler: PaymentRequestShippingOptionEventHandler) => Promise` [Section titled “setPaymentRequestShippingOptionEventHandler(handler: PaymentRequestShippingOptionEventHandler) => Promise\”](#setpaymentrequestshippingoptioneventhandlerhandler-paymentrequestshippingoptioneventhandler--promisevoid) Register event handler for `paymentRequest.on('shippingoptionchange'` event. #### Parameters [Section titled “Parameters”](#parameters-5) | Name | Type | Description | | --------- | ----------------------------------------------------------------------------- | ----------- | | `handler` | `(event: PaymentRequestShippingOptionEvent, stripe: Stripe) => Promise` | | #### Returns [Section titled “Returns”](#returns-5) Type: `Promise` ## Dependencies [Section titled “Dependencies”](#dependencies) ### Used by [Section titled “Used by”](#used-by) * [stripe-card-element](../stripe-card-element) ### Graph [Section titled “Graph”](#graph) ``` graph TD; stripe-card-element --> stripe-payment-request-button ``` *** *Built with [StencilJS](https://stenciljs.com/)* # > Component API reference. > このページは `src/components/stripe-payment-sheet/readme.md` から自動生成されています。 ## 使用例 [Section titled “使用例”](#使用例) ### present [Section titled “present”](#present) Show the sheet and wait for its result. ```js const sheet = document.querySelector('stripe-payment-sheet'); const { paymentResult } = await sheet.present(); ``` ## Overview [Section titled “Overview”](#overview) A payment sheet: the Payment Element in a modal, with the same events and results as the native PaymentSheet of `@capacitor-community/stripe`. PaymentIntent and SetupIntent are told apart by the client secret prefix; a Checkout Session is used when `checkout-session-client-secret` is set. ## Properties [Section titled “Properties”](#properties) | Property | Attribute | Description | Type | Default | | ----------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | | `applicationName` | `application-name` | Application name registered to Stripe.js, for wrapper libraries such as `@capacitor-community/stripe`. | `string` | `'stripe-pwa-elements'` | | `buttonLabel` | `button-label` | Submit button label. Translated automatically by this library. | `string` | `'Pay'` | | `checkoutSessionClientSecret` | `checkout-session-client-secret` | The client secret of a Checkout Session created with `ui_mode: 'elements'` (named `custom` in older Stripe API versions). Its format is not inspected. When it is set, it is used instead of `intent-client-secret` (the same rule as `stripe-payment-element`). Create the session with `customer_email` or `customer`, or pass `options.defaultBillingDetails.email`, because the sheet has no email field. | `string` | `undefined` | | `intentClientSecret` | `intent-client-secret` | The client secret of a PaymentIntent (`pi_..._secret_...`) or a SetupIntent (`seti_..._secret_...`). The prefix decides whether `confirmPayment` or `confirmSetup` is used. | `string` | `undefined` | | `open` | `open` | Whether the sheet is shown. Setting it to false closes the sheet as canceled. | `boolean` | `false` | | `options` | – | Options with the same keys as `CreatePaymentSheetOption` of `@capacitor-community/stripe`. JavaScript property only. | `{ merchantDisplayName?: string; paymentMethodLayout?: "horizontal" \| "vertical" \| "automatic"; defaultBillingDetails?: { email?: string; name?: string; phone?: string; address?: PaymentSheetAddress; }; returnURL?: string; style?: "alwaysLight" \| "alwaysDark"; billingDetailsCollectionConfiguration?: { email?: "never" \| "always" \| "automatic"; name?: "never" \| "always" \| "automatic"; phone?: "never" \| "always" \| "automatic"; address?: "never" \| "automatic" \| "full"; }; shippingDetails?: { name?: string; phone?: string; address?: PaymentSheetAddress; }; enableApplePay?: boolean; enableGooglePay?: boolean; customerId?: string; customerEphemeralKeySecret?: string; applePayMerchantId?: string; GooglePayIsTesting?: boolean; countryCode?: string; currencyCode?: string; withZipCode?: boolean; allowsDelayedPaymentMethods?: boolean; }` | `undefined` | | `publishableKey` | `publishable-key` | Your Stripe publishable API key. | `string` | `undefined` | | `sheetTitle` | `sheet-title` | Sheet title. Translated automatically by this library. | `string` | `'Add your payment information'` | | `stripeAccount` | `stripe-account` | Optional. Making API calls for connected accounts | `string` | `undefined` | ## Events [Section titled “Events”](#events) | Event | Description | Type | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `paymentSheetCanceled` | The customer closed the sheet | `CustomEvent` | | `paymentSheetCompleted` | The payment or setup succeeded. In Checkout Session mode the detail is the result of `confirm` (`{ type: 'success', session }`) | `CustomEvent<{ paymentIntent: PaymentIntent; error?: undefined; } \| { paymentIntent?: undefined; error: StripeError; } \| { setupIntent: SetupIntent; error?: undefined; } \| { setupIntent?: undefined; error: StripeError; } \| { type: "error"; error: ConfirmError; } \| { type: "success"; session: StripeCheckoutSession; }>` | | `paymentSheetFailed` | The confirmation failed with an error the customer cannot fix in the sheet | `CustomEvent` | | `paymentSheetFailedToLoad` | Stripe.js or the Payment Element failed to load, or the client secret format is unknown | `CustomEvent` | | `paymentSheetLoaded` | Stripe.js and the Payment Element are ready | `CustomEvent<{ stripe: Stripe; }>` | ## Methods [Section titled “Methods”](#methods) ### `present() => Promise` [Section titled “present() => Promise\”](#present--promisepaymentsheetpresentresult) Show the sheet and wait for its result. Calling it again while a result is pending returns the same promise. #### Returns [Section titled “Returns”](#returns) Type: `Promise` `{ paymentResult }`, where `paymentResult` is `paymentSheetCompleted`, `paymentSheetCanceled` or `paymentSheetFailed` ## Dependencies [Section titled “Dependencies”](#dependencies) ### Depends on [Section titled “Depends on”](#depends-on) * [stripe-modal](../stripe-modal) ### Graph [Section titled “Graph”](#graph) ``` graph TD; stripe-payment-sheet --> stripe-modal stripe-modal --> ion-icon ``` *** *Built with [StencilJS](https://stenciljs.com/)* # Guides > 使い方のガイド。 ## Guides [Section titled “Guides”](#guides) * [Getting Started](/guides/getting-started/) * [決済フロー](/guides/payment-flows/) * [バンドラ統合(Vite / webpack / Capacitor)](/guides/bundler-integration/) * [stripe-payment-request-button から stripe-express-checkout-element への移行](/guides/migrate-payment-request-button-to-express-checkout/) * [AI コーディングエージェントで使う](/guides/ai-agents/) # AI コーディングエージェントで使う > Agent Skill と llms.txt で、コーディングエージェントに stripe-pwa-elements の正しい使い方を渡す。 このリポジトリは、コーディングエージェント向けの [Agent Skill](https://agentskills.io/specification) を配布しています。 スキルには、用途に合うコンポーネントの選び方、publishable key と client secret の渡し方、送信・確定の流れ、 そして Stripe アカウントに変更を加える操作の前に利用者の承認を取るといった安全ルールが書かれています。 ## インストール [Section titled “インストール”](#インストール) [`skills`](https://www.npmjs.com/package/skills) CLI でプロジェクトに入れます。 ```bash npx skills add hideokamoto/stripe-pwa-elements ``` Claude Code ではプラグインとして入れることもできます。 ```text /plugin marketplace add hideokamoto/stripe-pwa-elements /plugin install stripe-pwa-elements@stripe-pwa-elements ``` ## HTTP で取得する [Section titled “HTTP で取得する”](#http-で取得する) このサイトは、リポジトリの `plugins/stripe-pwa-elements/skills/stripe-pwa-elements/SKILL.md` をビルド時に読み込んで配信しています。 | URL | 内容 | | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | [`/skill.md`](/skill.md) | スキル本体(SKILL.md) | | [`/.well-known/agent-skills/index.json`](/.well-known/agent-skills/index.json) | [Agent Skills Discovery RFC](https://github.com/cloudflare/agent-skills-discovery-rfc)(草案 v0.2.0)形式の一覧。各スキルの SHA-256 ダイジェスト付き | | [`/.well-known/agent-skills/stripe-pwa-elements/SKILL.md`](/.well-known/agent-skills/stripe-pwa-elements/SKILL.md) | スキル本体。検出用一覧(index.json)が指す場所です | ## llms.txt [Section titled “llms.txt”](#llmstxt) ドキュメント全体は [`/llms.txt`](/llms.txt)、[`/llms-full.txt`](/llms-full.txt)、[`/llms-small.txt`](/llms-small.txt) で取得できます。 `/llms.txt` にはスキルの URL とインストール方法も載せています。 各ページの `` には `` があり、どのページからでも `/llms.txt` を見つけられます。 ## コンポーネントを変えたら [Section titled “コンポーネントを変えたら”](#コンポーネントを変えたら) コンポーネントの追加・名前変更・削除や、props・イベント・メソッド・読み込み方法を変えたときは、 同じプルリクエストでスキルも更新してください。 スキルに書いたタグ名・CDN のパス・i18n の言語がコードと合わなくなると、`src/agent-skill.unit.spec.ts` が失敗します。 # バンドラ統合(Vite / webpack / Capacitor) > custom-elements ビルドから直接 import して実行時の動的 import 失敗を回避する。 Vite・webpack・Rollup などのバンドラを使う場合(Capacitor アプリを含む)は、 遅延ローダー `defineCustomElements()` ではなく **custom-elements ビルドからの直接 import** を推奨します。 ## 遅延ローダーの問題 [Section titled “遅延ローダーの問題”](#遅延ローダーの問題) 通常のインストール手順では、遅延ローダー経由ですべてのコンポーネントを登録します。 ```javascript import { defineCustomElements } from 'stripe-pwa-elements/loader'; defineCustomElements(); ``` このローダーは各コンポーネントを実行時に動的 `import()` で別チャンクとして取得します。 バンドラ環境ではチャンク URL がパッケージ自身の ESM 出力を基準に解決されるため、 バンドラが正しく配信できないことがあります。Vite(および Vite ベースの Capacitor プロジェクト)では、 次のエラーとして現れることがよくあります。 ```text TypeError: Failed to fetch dynamically imported module ``` ## 解決策: custom-elements ビルドから import する [Section titled “解決策: custom-elements ビルドから import する”](#解決策-custom-elements-ビルドから-import-する) 必要なコンポーネントを `dist/components` から直接 import します。 各モジュールは import 時にカスタム要素を自動登録するため、import するだけで利用できます。 なお、この import 方法は`stripe-pwa-elements@4.0.1`以降を使ってください。v4.0.0 ではコンポーネントの外枠だけが描画され、内部の Stripe Element がマウントされない不具合がありました。4.0.0 を使う場合は、代わりに全部入りバンドルを import してください。 ```javascript import 'stripe-pwa-elements/dist/stripe-elements/stripe-elements.esm.js'; ``` ```javascript // を登録 — defineCustomElements() は不要 import 'stripe-pwa-elements/dist/components/stripe-payment-element'; ``` import が静的になるため、バンドラがコンポーネントをアプリのバンドルに含めます。 実行時の動的 `import()` が発生しないので、“Failed to fetch dynamically imported module” エラーは起こりません。 実際に使うコンポーネントだけを import してください(それぞれ tree-shaking 可能です)。 ```javascript import 'stripe-pwa-elements/dist/components/stripe-payment-element'; import 'stripe-pwa-elements/dist/components/stripe-express-checkout-element'; ``` 要素のタグ名は変わらないため、マークアップはそのままです。 ```html ``` TypeScript の型は `dist/components` からではなく、引き続きパッケージルートから import します。 ```ts import type { DefaultFormSubmitResult, IntentType } from 'stripe-pwa-elements'; ``` ## バンドラ別のセットアップ [Section titled “バンドラ別のセットアップ”](#バンドラ別のセットアップ) ### Vite [Section titled “Vite”](#vite) 特別な設定は不要で、上記の静的 import がそのまま動作します。 アプリのエントリポイント(例: `main.ts`)付近で一度 import してください。 main.ts ```javascript import 'stripe-pwa-elements/dist/components/stripe-payment-element'; ``` 以前 `defineCustomElements()` を呼んでいた場合は、二重登録を避けるため削除してください。 ### webpack [Section titled “webpack”](#webpack) webpack は静的 import を直接解決するため、追加のローダー設定は不要です。 エントリモジュールからコンポーネントを import します。 index.js ```javascript import 'stripe-pwa-elements/dist/components/stripe-payment-element'; ``` ### Rollup [Section titled “Rollup”](#rollup) Rollup はインポートしたコンポーネントを静的にバンドルします。 パッケージパスを解決できるよう `@rollup/plugin-node-resolve` を有効にしてください。 rollup.config.mjs ```javascript import { nodeResolve } from '@rollup/plugin-node-resolve'; export default { plugins: [nodeResolve()], // ... }; ``` index.js ```javascript import 'stripe-pwa-elements/dist/components/stripe-payment-element'; ``` ## Capacitor + Vite(推奨セットアップ) [Section titled “Capacitor + Vite(推奨セットアップ)”](#capacitor--vite推奨セットアップ) Capacitor の Web レイヤーは通常 Vite でビルドされるため、遅延ローダーでは上記の 動的 import エラーに遭遇することがあります。代わりに直接 import を使ってください。 src/main.ts ```javascript import 'stripe-pwa-elements/dist/components/stripe-payment-element'; // 利用する他のコンポーネントも追加 ``` これは Capacitor アプリおよび [`@capacitor-community/stripe`](https://github.com/capacitor-community/stripe) の Web 実装で推奨されるセットアップです。 ## どちらを使うか [Section titled “どちらを使うか”](#どちらを使うか) | 環境 | 推奨 import | | ----------------------------------- | ------------------------------------------- | | 素の HTML / ビルドなし | CDN ` ``` ### 4. src/main.ts を書き換える [Section titled “4. src/main.ts を書き換える”](#4-srcmaints-を書き換える) 使うコンポーネントを`dist/components`から import します。import するだけでカスタム要素が登録されます。 ```ts import 'stripe-pwa-elements/dist/components/stripe-card-element'; const API = 'https://stripe-pwa-elements-docs.wp-kyoto.workers.dev/api'; const log = (message: string, detail?: unknown) => { const out = document.querySelector('#log')!; out.textContent += detail === undefined ? `${message}\n` : `${message}\n${JSON.stringify(detail, null, 2)}\n`; }; // デモ API から公開可能キーと clientSecret を取得 const { publishableKey } = await (await fetch(`${API}/config`)).json(); const { clientSecret } = await ( await fetch(`${API}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ currency: 'jpy' }), }) ).json(); // 要素を生成して属性をセット const el = document.createElement('stripe-card-element'); el.setAttribute('publishable-key', publishableKey); el.setAttribute('intent-client-secret', clientSecret); el.setAttribute('button-label', 'Pay now'); // イベントを購読 el.addEventListener('stripeLoaded', () => log('event: stripeLoaded')); el.addEventListener('formSubmit', () => log('event: formSubmit')); el.addEventListener('defaultFormSubmitResult', event => { const detail = (event as CustomEvent).detail; if (detail instanceof Error) { log('payment failed', { message: detail.message }); } else { log('payment result', detail); } }); document.querySelector('#checkout')!.appendChild(el); ``` ### 5. 起動して決済する [Section titled “5. 起動して決済する”](#5-起動して決済する) ```bash npm run dev ``` `http://localhost:5173`を開くとカードフォームが表示されます。カード番号`4242 4242 4242 4242`、未来の有効期限、任意の CVC を入力して **Pay now** を押してください。ログの`payment result`に`status: succeeded`が出れば完了です。 * HonoX HonoX では hono/jsx ラッパーの[`hono-stripe-elements`](https://www.npmjs.com/package/hono-stripe-elements)を使います。カスタム要素の登録をクライアント側で遅延実行してくれるため、アイランド(island)内でそのまま JSX として描画できます。`document.createElement`や動的 import を自分で書く必要はありません。 ### 1. HonoX プロジェクトを作成する [Section titled “1. HonoX プロジェクトを作成する”](#1-honox-プロジェクトを作成する) ```bash npm create hono@latest stripe-honox -- --template x-basic --install --pm npm cd stripe-honox ``` ### 2. hono-stripe-elements を追加する [Section titled “2. hono-stripe-elements を追加する”](#2-hono-stripe-elements-を追加する) ```bash npm i hono-stripe-elements stripe-pwa-elements ``` `stripe-pwa-elements`は peer dependency なので一緒にインストールします。 ### 3. アイランドを作成する [Section titled “3. アイランドを作成する”](#3-アイランドを作成する) `app/islands/payment-form.tsx`を新規作成します。 ```tsx import { useEffect, useState } from 'hono/jsx'; import { StripeCardElement } from 'hono-stripe-elements'; const API = 'https://stripe-pwa-elements-docs.wp-kyoto.workers.dev/api'; export default function PaymentForm() { const [intent, setIntent] = useState<{ publishableKey: string; clientSecret: string } | null>(null); const [logs, setLogs] = useState([]); const appendLog = (message: string) => setLogs(prev => [...prev, message]); useEffect(() => { let cancelled = false; (async () => { const { publishableKey } = await (await fetch(`${API}/config`)).json(); const { clientSecret } = await ( await fetch(`${API}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ currency: 'jpy' }), }) ).json(); if (!cancelled) setIntent({ publishableKey, clientSecret }); })(); return () => { cancelled = true; }; }, []); return (
{intent ? ( カードフォームを読み込み中…

} onStripeLoaded={() => appendLog('event: stripeLoaded')} onFormSubmit={() => appendLog('event: formSubmit')} onDefaultFormSubmitResult={event => { const detail = event.detail; if (detail instanceof Error) { appendLog(`payment failed: ${detail.message}`); } else { const intent = 'paymentIntent' in detail ? detail.paymentIntent : 'setupIntent' in detail ? detail.setupIntent : undefined; appendLog(`payment status: ${intent?.status}`); } }} /> ) : (

決済を準備中…

)}
{logs.join('\n')}
); } ``` `onXxx` props は camelCase のカスタムイベントを購読します(`onFormSubmit` → `formSubmit`)。`fallback`はクライアント側で Web Component の準備ができるまで描画されます。 ### 4. ルートに配置する [Section titled “4. ルートに配置する”](#4-ルートに配置する) `app/routes/index.tsx`を書き換えます。 ```tsx import { createRoute } from 'honox/factory'; import PaymentForm from '../islands/payment-form'; export default createRoute(c => { return c.render(
stripe-pwa-elements × HonoX

Card demo

, ); }); ``` ### 5. 起動して決済する [Section titled “5. 起動して決済する”](#5-起動して決済する-1) ```bash npm run dev ``` `http://localhost:5173`を開き、カード番号`4242 4242 4242 4242`、未来の有効期限、任意の CVC を入力して **Pay now** を押してください。ログに`payment status: succeeded`が出れば完了です。 * ビルドなし(CDN) npm やバンドラを使わずに、unpkg の CDN から全部入りバンドルを読み込みます。`stripe-elements.esm.js`はパッケージの`unpkg`フィールドが指す自己登録型のファイルで、読み込むだけですべてのコンポーネントが使えます。 ### 1. index.html を作る [Section titled “1. index.html を作る”](#1-indexhtml-を作る) `index.html`を新規作成します。 ```html stripe-pwa-elements demo

Card demo


      
    
  
  ```
 ### 2. 静的サーバーで配信する [Section titled “2. 静的サーバーで配信する”](#2-静的サーバーで配信する) 
  ```bash
  python3 -m http.server 4321
  ```
 `http://localhost:4321`を開き、カード番号`4242 4242 4242 4242`、未来の有効期限、任意の CVC を入力して **Pay now** を押してください。なお`file://`で直接開いてもデモ API の CORS に阻まれるため、許可された`localhost`のオリジンで配信してください。 ## うまくいかないとき [Section titled “うまくいかないとき”](#うまくいかないとき) * `Origin is not allowed`が返るときは、デモ API の CORS で許可されたポートで起動しているか確認してください(`3000`/`4321`/`5173`)。 * `Failed to fetch dynamically imported module`が出るときは、`stripe-pwa-elements/loader`の遅延ローダーを使っていないか確認してください。バンドラ環境では[バンドラ統合](/guides/bundler-integration/)に従って`dist/components`からの静的 import に切り替えます。 * コンポーネントの外枠だけが出てカード入力が表示されないときは、バージョンを確認してください。v4.0.0 では`dist/components`の個別 import で内部の Stripe Element がマウントされない不具合がありました。`stripe-pwa-elements@4.0.1`以降で解消しています。 * ウォレットボタンが表示されないときは、端末がその決済手段に対応しているか確認してください。``は Apple Pay や Google Pay、Link など対応する端末があるときだけボタンを描画します。 ## 次に読む [Section titled “次に読む”](#次に読む) * Payment Intent など各フローの流れと本番用 API の考え方は[決済フロー](/guides/payment-flows/)を参照してください * webpack や Rollup、Capacitor などの環境での import 方法は[バンドラ統合](/guides/bundler-integration/)にまとめています * 各コンポーネントの Props/Events/Methods は[Components](/components/)で確認できます

# stripe-payment-request-button から stripe-express-checkout-element への移行

> stripe.paymentRequest() の廃止に伴う移行ガイド。

## なぜ移行が必要か [Section titled “なぜ移行が必要か”](#なぜ移行が必要か) Stripe は `stripe.paymentRequest()` API を **Stripe.js 9.x で削除予定**です(2025-09-30 非推奨宣言 / 2026-03-25 削除予定)。 `` はこの API に依存しているため、**非推奨(deprecated)** となりました。 代替として、`` を使用してください。こちらはモダンな Express Checkout Element API を使用し、Apple Pay・Google Pay・Link・PayPal・Amazon Pay など多数の決済手段をサポートします。 ## 移行前後のコード比較 [Section titled “移行前後のコード比較”](#移行前後のコード比較) ### Before: `` [Section titled “Before: \”](#before-stripe-payment-request-button) 
```html

```
 
```js
const element = document.querySelector('stripe-payment-request-button');


// PaymentRequest オプションを設定
await element.setPaymentRequestOption({
  country: 'US',
  currency: 'usd',
  total: {
    label: 'Total',
    amount: 1099,
  },
  requestPayerName: true,
  requestPayerEmail: true,
});


// Stripe を初期化
await element.initStripe('pk_test_xxxxx');


// 決済メソッドイベントを処理
await element.setPaymentMethodEventHandler(async (event, stripe) => {
  const { error } = await stripe.confirmCardPayment(
    paymentIntent.client_secret,
    {
      payment_method: event.paymentMethod.id,
    },
    { handleActions: false },
  );


  if (error) {
    event.complete('fail');
  } else {
    event.complete('success');
  }
});
```
 ### After: `` [Section titled “After: \”](#after-stripe-express-checkout-element) 
```html

```
 
```js
const element = document.querySelector('stripe-express-checkout-element');


// Stripe を初期化
await element.initStripe('pk_test_xxxxx');


// 決済確定イベントを処理(カスタム動作が必要な場合)
element.addEventListener('confirm', async ({ detail }) => {
  const { error } = await detail.stripe.confirmPayment({
    elements: detail.elements,
    confirmParams: {
      return_url: 'https://example.com/success',
    },
  });


  if (error) {
    console.error(error);
  }
});


// デフォルトの確定動作を使用する場合(推奨)
// should-use-default-confirm-action="true"(デフォルト)のまま
// defaultConfirmResult イベントで結果を受け取る
element.addEventListener('defaultConfirmResult', ({ detail }) => {
  if (detail instanceof Error) {
    console.error(detail);
  } else {
    console.log('Success:', detail);
  }
});
```
 ## Props / Events マッピング [Section titled “Props / Events マッピング”](#props--events-マッピング) ### Props [Section titled “Props”](#props) | stripe-payment-request-button | stripe-express-checkout-element | 備考 | | ------------------------------------------ | ---------------------------------------------------------- | ---------------------- | | `publishable-key` | `publishable-key` | 同じ | | `stripe-account` | `stripe-account` | 同じ | | `application-name` | `application-name` | 同じ | | `stripeDidLoaded` | `stripeDidLoaded` | 同じ(JS プロパティ) | | *(PaymentRequestOptions の `total.amount`)* | `amount` | 属性として直接指定 | | *(PaymentRequestOptions の `currency`)* | `currency` | 属性として直接指定 | | *(PaymentRequestOptions の `country`)* | *(Elements に自動設定)* | `client-secret` から自動推定 | | `paymentMethodEventHandler` | *(`confirm` イベントで代替)* | イベントリスナーに移行 | | `shippingAddressEventHandler` | *(Express Checkout Element の `shippingaddresschange` で代替)* | Stripe.js 直接利用 | | `shippingOptionEventHandler` | *(Express Checkout Element の `shippingoptionchange` で代替)* | Stripe.js 直接利用 | ### Events [Section titled “Events”](#events) | stripe-payment-request-button | stripe-express-checkout-element | 備考 | | ----------------------------- | ------------------------------- | ----------------------- | | `stripeLoaded` | `stripeLoaded` | 同じ | | *(paymentmethod コールバック)* | `confirm` | Express Checkout 確定時に発火 | | *(なし)* | `expressCheckoutClick` | ボタンクリック時に発火 | | *(なし)* | `defaultConfirmResult` | デフォルト確定動作の結果 | | *(なし)* | `cancel` | ユーザーがキャンセルした場合 | ### Methods [Section titled “Methods”](#methods) | stripe-payment-request-button | stripe-express-checkout-element | 備考 | | -------------------------------------------------- | ---------------------------------- | ------------- | | `initStripe(key, options)` | `initStripe(key, options)` | ほぼ同じ | | `setPaymentRequestOption(options)` | *(属性 `amount`, `currency` で代替)* | 移行先では属性で指定 | | `setPaymentMethodEventHandler(fn)` | *(`confirm` イベントで代替)* | イベントリスナーに移行 | | `setPaymentRequestShippingOptionEventHandler(fn)` | *(Stripe Elements API で代替)* | より柔軟な API を使用 | | `setPaymentRequestShippingAddressEventHandler(fn)` | *(Stripe Elements API で代替)* | より柔軟な API を使用 | | `isAvailable(type)` | *(Express Checkout は自動的にボタンを表示制御)* | 明示的な確認不要 | | *(なし)* | `updateProgress(status)` | ローディング状態の制御 | | *(なし)* | `setErrorMessage(msg)` | エラーメッセージの表示 | | *(なし)* | `updateElementOptions(options)` | 動的なオプション更新 | ## 関連リンク [Section titled “関連リンク”](#関連リンク) * [`` コンポーネントリファレンス](/components/stripe-express-checkout-element/) * [Stripe Express Checkout Element ドキュメント](https://stripe.com/docs/elements/express-checkout-element) * [Stripe.js 移行ガイド(英語)](https://stripe.com/docs/js/appendix/payment_request) ## 次に読む [Section titled “次に読む”](#次に読む) * [決済フロー](/guides/payment-flows/) * [Getting Started](/guides/getting-started/)

# 決済フロー

> PaymentIntent・SetupIntent・Checkout Session の各フローを図解します。

このガイドでは、stripe-pwa-elements で使用する主要な決済フローを説明します。 ## PaymentIntent フロー [Section titled “PaymentIntent フロー”](#paymentintent-フロー) 即時決済を行う場合に使用します。`` または `` で利用できます。 
```
sequenceDiagram
    participant Server as サーバー
    participant Client as ブラウザ
    participant Stripe

    Server->>Stripe: PaymentIntent 作成
    Stripe-->>Server: client_secret を返却
    Server-->>Client: client_secret をフロントへ渡す
    Client->>Client: Web Component に client_secret をセット
    Client->>Client: ユーザーがカード情報を入力
    Client->>Stripe: stripe.confirmCardPayment / confirmPayment
    Stripe-->>Client: 結果(成功 or エラー)
    Client->>Server: 結果を通知(Webhook 推奨)
```
 ### コード例 [Section titled “コード例”](#コード例) 
```html

```
 
```js
const el = document.querySelector('stripe-payment-element');
el.addEventListener('defaultFormSubmitResult', ({ detail }) => {
  if (detail instanceof Error) {
    console.error(detail);
  } else {
    console.log('Success:', detail);
  }
});
```
 ## SetupIntent フロー [Section titled “SetupIntent フロー”](#setupintent-フロー) 将来の決済のためにカード情報を保存する場合に使用します。`intent-type="setup"` を指定します。 
```
sequenceDiagram
    participant Server as サーバー
    participant Client as ブラウザ
    participant Stripe

    Server->>Stripe: SetupIntent 作成
    Stripe-->>Server: client_secret を返却
    Server-->>Client: client_secret をフロントへ渡す
    Client->>Client: Web Component に client_secret + intent-type="setup" をセット
    Client->>Client: ユーザーがカード情報を入力
    Client->>Stripe: stripe.confirmCardSetup / confirmSetup
    Stripe-->>Client: 結果(成功 or エラー)
    Client->>Server: 結果を通知(Webhook 推奨)
```
 ### コード例 [Section titled “コード例”](#コード例-1) 
```html

```
 ## Checkout Session フロー [Section titled “Checkout Session フロー”](#checkout-session-フロー) Stripe Checkout を使用した統合型の決済フローです。`` で `initCheckoutSession` メソッドを使用します。 
```
sequenceDiagram
    participant Server as サーバー
    participant Client as ブラウザ
    participant Stripe

    Server->>Stripe: Checkout Session 作成
    Stripe-->>Server: client_secret を返却
    Server-->>Client: client_secret をフロントへ渡す
    Client->>Client: initCheckoutSession(publishableKey, options)
    Client->>Client: ユーザーが支払い情報を入力
    Client->>Stripe: checkout.confirm()
    Stripe-->>Client: リダイレクト or 結果
```
 ### コード例 [Section titled “コード例”](#コード例-2) 
```js
const el = document.querySelector('stripe-payment-element');
await customElements.whenDefined('stripe-payment-element');
await el.initCheckoutSession('pk_test_xxxxx', {
  checkoutSessionClientSecret: 'cs_xxxxx_secret_xxxxx',
});
```
 ## コンポーネント選択ガイド [Section titled “コンポーネント選択ガイド”](#コンポーネント選択ガイド) 用途に応じて最適なコンポーネントを選択してください。 
```
flowchart TD
    Start[決済を受け付けたい] --> Q1{Apple Pay / Google Pay
のみ?} Q1 -->|はい| Express[stripe-express-checkout-element] Q1 -->|いいえ| Q2{カード決済のみ?} Q2 -->|はい| Q3{モーダル表示?} Q3 -->|はい| CardModal[stripe-card-element-modal] Q3 -->|いいえ| Card[stripe-card-element] Q2 -->|いいえ| Q4{複数の決済手段?} Q4 -->|はい| Payment[stripe-payment-element] Q4 -->|いいえ| Q5{Stripe Link?} Q5 -->|はい| Link[stripe-link-authentication-element
+ stripe-payment-element] Q5 -->|いいえ| Payment ``` | コンポーネント | ユースケース | | ------------------------------------ | --------------------------------------- | | `stripe-card-element` | カード決済のみ(カード番号・有効期限・CVC を個別表示) | | `stripe-card-element-modal` | カード決済をモーダルで表示 | | `stripe-payment-element` | 複数の決済手段を統合表示(カード・銀行振込・ウォレットなど) | | `stripe-express-checkout-element` | Apple Pay / Google Pay / Link のワンクリック決済 | | `stripe-link-authentication-element` | Stripe Link によるメール認証 | | `stripe-address-element` | 住所の収集 | | `stripe-currency-selector` | Adaptive Pricing の通貨選択 | ## 次に読む [Section titled “次に読む”](#次に読む) * 各コンポーネントの詳細は [Components](/components/) を参照 * 基本的なセットアップは [Getting Started](/guides/getting-started/) を参照