# 既存の顧客の支払い 顧客がオンセッションの間に既存の決済手段に請求する方法をご紹介します。 # Stripe がオンラインで提供するページ > This is a Stripe がオンラインで提供するページ for when platform is web and ui is stripe-hosted. View the full page at https://docs.stripe.com/payments/existing-customers?platform=web&ui=stripe-hosted. 決済セッションでは、買い手が各自の決済の詳細を入力できます。買い手が既存の顧客の場合、決済セッションを設定して、顧客の[保存済みカード](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=stripe-hosted)のいずれかを使って詳細に事前入力できます。決済セッションには、顧客が決済に使用できる最大 50 枚の保存済みカードが表示されます。 > #### Accounts v2 API を使用した顧客の表現 > > 導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。 ![1 枚のカードが保存された Checkout](https://b.stripecdn.com/docs-statics-srv/assets/saved-card.59d38df89f7892ff0a3669779ec30f0b.png) ## Checkout セッションを作成 [クライアント側] [サーバー側] サーバー側のエンドポイントを呼び出して Checkout セッションを作成する購入ボタンをウェブサイトに追加します。 ```html Checkout
``` Checkout は、`customer` [パラメータ](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) を使用して、既存の Customer オブジェクトの再利用に対応しています。既存顧客を再利用する場合、PaymentIntent やサブスクリプションなど、Checkout によって作成されたすべてのオブジェクトは、その Customer オブジェクトに関連付けられます。 `success_url` に `{CHECKOUT_SESSION_ID}` テンプレート変数を追加することで、顧客が Checkout セッションを正常に完了した後でセッション ID にアクセスできます。Checkout セッションを作成したら、レスポンスで返された [URL](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-url) に顧客をリダイレクトします。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "customer={{CUSTOMER_ID}}" \ --data-urlencode "success_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 追加の保存された支払い方法を表示する [サーバー側] > #### 法令遵守 > > 顧客の支払い情報を保存する際には、適用されるすべての法律、規制、ネットワークルールを遵守する責任を貴社が負うものとします。将来の購入時に過去の決済手段を顧客に表示する場合は、将来の購入に再利用するために決済手段の詳細を保存することの同意をあらかじめ得るようにしてください。 デフォルトでは、[always allow redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) に設定された支払い方法のみ表示されます。 Checkout セッション中に Apple Pay や Google Pay を再利用することはできないため、これらの支払い方法は保存済みオプションの一覧には表示されません。Checkout セッションが有効なたびに、Google Pay や Apple Pay の UI および Payment Request ボタンの UI を表示する必要があります。 Checkout セッションに他の再表示用の値を含めるか、支払い方法の `allow_redisplay` 設定を `always` に変更することで、他の保存済み支払い方法を表示できます。 - `allow_redisplay_filters` [パラメーター](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-allow_redisplay_filters)を使用して、Checkout に表示する保存済みの決済手段を指定します。パラメーターには、いずれかの有効な値 (`limited`、`unspecified`、`always`) を設定できます。 Checkout セッションで再表示フィルタリングを指定するとデフォルトの動作が上書きされるため、保存済みの決済手段を表示する場合は `always` 値を含める必要があります。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "customer={{CUSTOMER_ID}}" \ --data-urlencode "success_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ -d "saved_payment_method_options[allow_redisplay_filters][0]=always" \ -d "saved_payment_method_options[allow_redisplay_filters][1]=limited" \ -d "saved_payment_method_options[allow_redisplay_filters][2]=unspecified" ``` - [決済手段を更新](https://docs.stripe.com/api/payment_methods/update.md)して、各決済手段に `allow_redisplay` 値を設定します。 ```curl curl https://api.stripe.com/v1/payment_methods/{{PAYMENTMETHOD_ID}} \ -u "<>:" \ -d allow_redisplay=always ``` ## 支払いページのフィールドを事前入力 以下の条件がすべて当てはまる場合、Checkout では、顧客の保存されたクレジットカードの詳細を使用して、決済ページの**メール**、**名前**、**カード**、**請求先住所**の各フィールドに事前入力されます。 - Checkout が `payment` モードまたは `subscription` モードで使用されている (`setup` モードではフィールドの事前入力はサポートされていません)。 - 顧客がカードを保存している。カードの決済手段の事前入力のみ Checkout でサポートされている。 - 保存されているカードの `allow_redisplay` が `always` に設定されているか、[デフォルトの表示設定](https://docs.stripe.com/payments/existing-customers.md#display-additional-saved-payment-methods)が調整されている。 - 決済手段に、Checkout セッションの [`billing_address_collection`](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) 値に必要な [`billing_details`](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-billing_details) が含まれている。 - `auto` の場合、`email`、`name`、`address[country]` フィールドに値が必要です。アメリカ、カナダ、イギリスの請求先住所にも `address[postal_code]` が必要です。 - `required` の場合、`email`、`name`、`address` フィールドに値が必要です。 顧客に複数のカードが保存されている場合、Checkout では、以下の優先順位に一致するカードの詳細が事前入力されます。 - `payment` モードでは、Stripe は顧客の最新の保存されたクレジットカードを使用してフィールドに事前入力します。 - `サブスクリプション`モードでは、顧客のデフォルトの決済手段がクレジットカードの場合は Stripe が事前入力します。それ以外の場合は、Stripe は最後に保存されたクレジットカードを事前入力します。 Checkout が[配送先住所を収集](https://docs.stripe.com/payments/collect-addresses.md)する際に、顧客の配送先住所が Checkout セッションの[サポート対象国](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection-allowed_countries)のいずれかにある場合は、配送先住所フィールドが事前入力されます。 決済セッション中に顧客が保存したカードを削除できるようにするには、[save_payment_method_options[payment_method_remove]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_remove) を `enabled` に設定します。 > #### 事前入力のタイムアウト > > 事前入力された決済手段は、Checkout セッションの作成後 30 分間表示されます。有効期限が切れると、セキュリティ上の理由から、同じ Checkout セッションを読み込んでも決済手段が事前入力されなくなります。 ## 支払い後のイベントを処理 [サーバー側] 顧客が Checkout セッションの支払いを完了すると、Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか、[Webhook ガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信して処理します。これにより、次のアクションがトリガーされます。 - 顧客に注文確認メールを送信します。 - 取引をデータベースに記録します。 - 配送ワークフローを開始します。 顧客がリダイレクトされ、ウェブサイトに戻るのを待たずに、これらのイベントはリッスンできます。Checkout のランディングページからのみフルフィルメントをトリガーする場合、確実性に欠けます。非同期型のイベントをリッスンするようシステムを設定すると、1 回の実装で[異なるタイプの決済手段](https://stripe.com/payments/payment-methods-guide)を受け付けられるようになります。 詳しくは、[Checkout のフルフィルメントガイド](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 Checkout で支払いを回収する際には、以下のイベントを処理します。 | イベント | 説明 | アクション | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout セッションを正常に完了すると送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | ACH Direct Debt など、遅延型の決済手段による支払いが成功した場合に送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | ACH Direct Debt など、遅延型の決済手段による支払いが失敗した場合に送信されます。 | 顧客に失敗を通知して、顧客をオンセッションに戻し、支払いを再試行できるようにします。 | # 埋め込みフォーム > This is a 埋め込みフォーム for when platform is web and ui is embedded-form. View the full page at https://docs.stripe.com/payments/existing-customers?platform=web&ui=embedded-form. 決済セッションでは、買い手が各自の決済の詳細を入力できます。買い手が既存の顧客の場合、決済セッションを設定して、顧客の[保存済みカード](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=embedded-form)のいずれかを使って詳細に事前入力できます。決済セッションには、顧客が決済に使用できる最大 50 枚の保存済みカードが表示されます。 > #### Accounts v2 API を使用した顧客の表現 > > 導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。 ![1 枚のカードが保存された Checkout](https://b.stripecdn.com/docs-statics-srv/assets/saved-card.59d38df89f7892ff0a3669779ec30f0b.png) ## Checkout セッションを作成 [サーバー側] Checkout は、`customer` [parameter](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) で、既存の Customer オブジェクトの再利用に対応しています。既存顧客を再利用する場合、`PaymentIntents` や`Subscriptions` など、Checkout によって作成されたすべてのオブジェクトは、その`Customer` オブジェクトに関連付けられます。 サーバーで *Checkout セッション* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription)を作成します。 [ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) を `embedded_page` に設定します。 [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) パラメーターに、ウェブサイトでホストするカスタムページの URL を指定して、そのカスタムページに顧客を戻すようにします。URL に `{CHECKOUT_SESSION_ID}` テンプレート変数を含めて、戻り先ページでセッションのステータスを取得します。Checkout はこの変数を Checkout セッション ID に自動的に置き換えてからリダイレクトします。 [戻り先ページの設定](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=embedded-form#return-page)と、[リダイレクト動作をカスタマイズ](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form)するためのその他のオプションについて、詳細をご覧ください。 Checkout セッションの作成後、レスポンスで返される `client_secret` を使用して、[Checkout をマウント](https://docs.stripe.com/payments/existing-customers.md#mount-checkout)します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "customer={{CUSTOMER_ID}}" \ -d ui_mode=embedded_page \ --data-urlencode "return_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 追加の保存された支払い方法を表示する [サーバー側] > #### 法令遵守 > > 顧客の支払い情報を保存する際には、適用されるすべての法律、規制、ネットワークルールを遵守する責任を貴社が負うものとします。将来の購入時に過去の決済手段を顧客に表示する場合は、将来の購入に再利用するために決済手段の詳細を保存することの同意をあらかじめ得るようにしてください。 デフォルトでは、[always allow redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) に設定された支払い方法のみ表示されます。 Checkout セッション中に Apple Pay や Google Pay を再利用することはできないため、これらの支払い方法は保存済みオプションの一覧には表示されません。Checkout セッションが有効なたびに、Google Pay や Apple Pay の UI および Payment Request ボタンの UI を表示する必要があります。 Checkout セッションに他の再表示用の値を含めるか、支払い方法の `allow_redisplay` 設定を `always` に変更することで、他の保存済み支払い方法を表示できます。 - `allow_redisplay_filters` [パラメーター](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-allow_redisplay_filters)を使用して、Checkout に表示する保存済みの決済手段を指定します。パラメーターには、いずれかの有効な値 (`limited`、`unspecified`、`always`) を設定できます。 Checkout セッションで再表示フィルタリングを指定するとデフォルトの動作が上書きされるため、保存済みの決済手段を表示する場合は `always` 値を含める必要があります。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d ui_mode=embedded_page \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "customer={{CUSTOMER_ID}}" \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" \ -d "saved_payment_method_options[allow_redisplay_filters][0]=always" \ -d "saved_payment_method_options[allow_redisplay_filters][1]=limited" \ -d "saved_payment_method_options[allow_redisplay_filters][2]=unspecified" ``` - [決済手段を更新](https://docs.stripe.com/api/payment_methods/update.md)して、各決済手段に `allow_redisplay` 値を設定します。 ```curl curl https://api.stripe.com/v1/payment_methods/{{PAYMENTMETHOD_ID}} \ -u "<>:" \ -d allow_redisplay=always ``` ## Checkout をマウントする [クライアント側] #### HTML + JS Checkout は [Stripe.js](https://docs.stripe.com/js.md) の一部として利用できます。HTML ファイルのヘッダーに Stripe.js スクリプトを追加してページに含めます。次に、マウンティングに使用する空の DOM ノード (コンテナー) を作成します。 ```html
``` 公開可能な API キーで Stripe.js を初期化します。 Checkout セッションの作成、および client secret の取得をサーバーにリクエストする、非同期の `fetchClientSecret` 関数を作成します。 Checkout インスタンスを作成する際に、この関数を `options` に渡します。 ```javascript // Initialize Stripe.js const stripe = Stripe('<>'); initialize(); // Fetch Checkout Session and retrieve the client secret async function initialize() { const fetchClientSecret = async () => { const response = await fetch("/create-checkout-session", { method: "POST", }); const { clientSecret } = await response.json(); return clientSecret; }; // Initialize Checkout const checkout = await stripe.createEmbeddedCheckoutPage({ fetchClientSecret, }); // Mount Checkout checkout.mount('#checkout'); } ``` #### React npm から [react-stripe-js](https://docs.stripe.com/sdks/stripejs-react.md) と Stripe.js ローダーをインストールします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` 埋め込みの Checkout コンポーネントを使用するには、`EmbeddedCheckoutProvider` を作成します。公開可能 API キーを使用して `loadStripe` を呼び出し、返された `Promise` をプロバイダーに渡します。 Checkout セッションの作成、および client secret の取得をサーバーにリクエストする、非同期の `fetchClientSecret` 関数を作成します。この関数をプロバイダーで受け入れられる `options` プロパティに渡します。 ```jsx import * as React from 'react'; import {loadStripe} from '@stripe/stripe-js'; import { EmbeddedCheckoutProvider, EmbeddedCheckout } from '@stripe/react-stripe-js'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('pk_test_123'); const App = () => { const fetchClientSecret = React.useCallback(() => { // Create a Checkout Session return fetch("/create-checkout-session", { method: "POST", }) .then((res) => res.json()) .then((data) => data.clientSecret); }, []); const options = {fetchClientSecret}; return (
) } ``` Checkout は、HTTPS 接続を介して支払い情報をStripeに安全に送信する iframe でレンダリングされます。 > 一部の支払い方法では、別のページにリダイレクトして支払いを確定する必要があるため、Checkout は別の iframe 内に配置しないでください。 ### デザインをカスタマイズする アカウントの[ブランディング設定](https://dashboard.stripe.com/settings/branding)で、背景色、ボタンの色、枠線の角丸半径、フォントを設定して、サイトのデザインに合わせて Checkout をカスタマイズします。 デフォルトでは、Checkout は外側に余白やマージンが追加されずに表示されます。必要なマージンを適用するには (四方すべてに 16px など)、目的の余白を適用するコンテナー要素 (div など) を使用することをお勧めします。 ## 支払いページのフィールドを事前入力 以下の条件がすべて当てはまる場合、Checkout では、顧客の保存されたクレジットカードの詳細を使用して、決済ページの**メール**、**名前**、**カード**、**請求先住所**の各フィールドに事前入力されます。 - Checkout が `payment` モードまたは `subscription` モードで使用されている (`setup` モードではフィールドの事前入力はサポートされていません)。 - 顧客がカードを保存している。カードの決済手段の事前入力のみ Checkout でサポートされている。 - 保存されているカードの `allow_redisplay` が `always` に設定されているか、[デフォルトの表示設定](https://docs.stripe.com/payments/existing-customers.md#display-additional-saved-payment-methods)が調整されている。 - 決済手段に、Checkout セッションの [`billing_address_collection`](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) 値に必要な [`billing_details`](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-billing_details) が含まれている。 - `auto` の場合、`email`、`name`、`address[country]` フィールドに値が必要です。アメリカ、カナダ、イギリスの請求先住所にも `address[postal_code]` が必要です。 - `required` の場合、`email`、`name`、`address` フィールドに値が必要です。 顧客に複数のカードが保存されている場合、Checkout では、以下の優先順位に一致するカードの詳細が事前入力されます。 - `payment` モードでは、Stripe は顧客の最新の保存されたクレジットカードを使用してフィールドに事前入力します。 - `サブスクリプション`モードでは、顧客のデフォルトの決済手段がクレジットカードの場合は Stripe が事前入力します。それ以外の場合は、Stripe は最後に保存されたクレジットカードを事前入力します。 Checkout が[配送先住所を収集](https://docs.stripe.com/payments/collect-addresses.md)する際に、顧客の配送先住所が Checkout セッションの[サポート対象国](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection-allowed_countries)のいずれかにある場合は、配送先住所フィールドが事前入力されます。 決済セッション中に顧客が保存したカードを削除できるようにするには、[save_payment_method_options[payment_method_remove]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_remove) を `enabled` に設定します。 > #### 事前入力のタイムアウト > > 事前入力された決済手段は、Checkout セッションの作成後 30 分間表示されます。有効期限が切れると、セキュリティ上の理由から、同じ Checkout セッションを読み込んでも決済手段が事前入力されなくなります。 ## 支払い後のイベントを処理 [サーバー側] 顧客が Checkout セッションの支払いを完了すると、Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか、[Webhook ガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信して処理します。これにより、次のアクションがトリガーされます。 - 顧客に注文確認メールを送信します。 - 取引をデータベースに記録します。 - 配送ワークフローを開始します。 顧客がリダイレクトされ、ウェブサイトに戻るのを待たずに、これらのイベントはリッスンできます。Checkout のランディングページからのみフルフィルメントをトリガーする場合、確実性に欠けます。非同期型のイベントをリッスンするようシステムを設定すると、1 回の実装で[異なるタイプの決済手段](https://stripe.com/payments/payment-methods-guide)を受け付けられるようになります。 詳しくは、[Checkout のフルフィルメントガイド](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 Checkout で支払いを回収する際には、以下のイベントを処理します。 | イベント | 説明 | アクション | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout セッションを正常に完了すると送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | ACH Direct Debt など、遅延型の決済手段による支払いが成功した場合に送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | ACH Direct Debt など、遅延型の決済手段による支払いが失敗した場合に送信されます。 | 顧客に失敗を通知して、顧客をオンセッションに戻し、支払いを再試行できるようにします。 | # 埋め込みコンポーネント > This is a 埋め込みコンポーネント for when platform is web and ui is embedded-components. View the full page at https://docs.stripe.com/payments/existing-customers?platform=web&ui=embedded-components. 決済セッションでは、買い手が各自の決済の詳細を入力できます。買い手が既存の顧客の場合、決済セッションを設定して、顧客の[保存済みカード](https://docs.stripe.com/payments/checkout/save-during-payment.md?payment-ui=embedded-components)のいずれかを使って詳細に事前入力できます。決済セッションには、顧客が決済に使用できる最大 50 枚の保存済みカードが表示されます。 > #### Accounts v2 API を使用した顧客の表現 > > 導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。 ![1 枚のカードが保存された Payment Element](https://b.stripecdn.com/docs-statics-srv/assets/saved_card.9ae121fe039c6d963f3c9831eb92172f.png) ## Checkout セッションを作成 [クライアント側] [サーバー側] Checkout Sessions は、`customer` [parameter](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) を使用して、既存の`Customer` オブジェクトの再利用に対応しています。既存顧客を再利用する場合、`PaymentIntents` や`Subscriptions` など、Checkoutによって作成されたすべてのオブジェクトは、その`Customer` オブジェクトに関連付けられます。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d ui_mode=elements \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "customer={{CUSTOMER_ID}}" \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 追加の保存された支払い方法を表示する [サーバー側] > #### 法令遵守 > > 顧客の支払い情報を保存する際には、適用されるすべての法律、規制、ネットワークルールを遵守する責任を貴社が負うものとします。将来の購入時に過去の決済手段を顧客に表示する場合は、将来の購入に再利用するために決済手段の詳細を保存することの同意をあらかじめ得るようにしてください。 デフォルトでは、[always allow redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) に設定された支払い方法のみ表示されます。 Checkout セッション中に Apple Pay や Google Pay を再利用することはできないため、これらの支払い方法は保存済みオプションの一覧には表示されません。Checkout セッションが有効なたびに、Google Pay や Apple Pay の UI および Payment Request ボタンの UI を表示する必要があります。 Checkout セッションに他の再表示用の値を含めるか、支払い方法の `allow_redisplay` 設定を `always` に変更することで、他の保存済み支払い方法を表示できます。 - `allow_redisplay_filters` [パラメーター](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-allow_redisplay_filters)を使用して、Checkout に表示する保存済みの決済手段を指定します。パラメーターには、いずれかの有効な値 (`limited`、`unspecified`、`always`) を設定できます。 Checkout セッションで再表示フィルタリングを指定するとデフォルトの動作が上書きされるため、保存済みの決済手段を表示する場合は `always` 値を含める必要があります。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d mode=payment \ -d ui_mode=elements \ -d "line_items[0][price]={{PRICE_ID}}" \ -d "line_items[0][quantity]=1" \ -d "customer={{CUSTOMER_ID}}" \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" \ -d "saved_payment_method_options[allow_redisplay_filters][0]=always" \ -d "saved_payment_method_options[allow_redisplay_filters][1]=limited" \ -d "saved_payment_method_options[allow_redisplay_filters][2]=unspecified" ``` - [決済手段を更新](https://docs.stripe.com/api/payment_methods/update.md)して、各決済手段に `allow_redisplay` 値を設定します。 ```curl curl https://api.stripe.com/v1/payment_methods/{{PAYMENTMETHOD_ID}} \ -u "<>:" \ -d allow_redisplay=always ``` ## Payment Element を表示 [クライアント側] #### HTML + JS ### Stripe.js を設定 HTML ファイルの `head` に Stripe .js スクリプトを追加し、チェックアウトページに含めます。PCI への準拠を維持するために、常に js.stripe.com から Stripe.js を直接読み込んでください。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 ```html Checkout ``` 購入ページで次の JavaScript を使用して、Stripe のインスタンスを作成します。 ```javascript // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` ### Payment Element を支払いページに追加 Payment Element を決済ページに配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。 ```html
``` 前のステップから Checkout Session の `client_secret` を取得して、`Checkout` オブジェクトを初期化します。次に、Payment Element を作成してマウントします。 ```javascript const promise = fetch("/create-checkout-session", { method: "POST", headers: { "Content-Type": "application/json" }, }) .then((r) => r.json()) .then((r) => r.clientSecret); // Initialize Checkout const checkout = stripe.initCheckoutElementsSdk({ clientSecret: promise, }); // Create and mount the Payment Element const paymentElement = checkout.createPaymentElement(); paymentElement.mount('#payment-element'); ``` #### React ### Stripe.js を設定 次の npm パブリックレジストリから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### CheckoutElementsProvider を支払いページに追加して設定する 前のステップで取得した Checkout Session の `client_secret` を使用して [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) を初期化します。その後、支払いフォームを含む `CheckoutForm` コンポーネントをレンダリングします。 ```jsx import React, {useMemo} from 'react'; import ReactDOM from 'react-dom'; import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component's render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const promise = useMemo(() => { return fetch('/create-checkout-session', { method: 'POST', }) .then((res) => res.json()) .then((data) => data.clientSecret); }, []); return (
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Payment Element コンポーネントを追加 `PaymentElement` コンポーネントを使用して、決済フォームを表示します。 ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { return (
); }; export default CheckoutForm; ``` ## 支払いページのフィールドを事前入力 次の条件がすべて当てはまる場合、[Session オブジェクト](https://docs.stripe.com/js/custom_checkout/session_object)には、**メール**、**名前**、**クレジットカード**、**請求先住所**が含まれます。この情報には、顧客が保存したカードの詳細が含まれ、決済ページに表示できます。また、Payment Element には保存したカードが表示されます。 - Checkout が `payment` モードまたは `subscription` モードで使用されている (`setup` モードではフィールドの事前入力はサポートされていません)。 - 顧客がカードを保存している。カードの決済手段の事前入力のみ Checkout でサポートされている。 - 保存されているカードの `allow_redisplay` が `always` に設定されているか、[デフォルトの表示設定](https://docs.stripe.com/payments/existing-customers.md#display-additional-saved-payment-methods)が調整されている。 - 決済手段に、Checkout セッションの [`billing_address_collection`](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) 値に必要な [`billing_details`](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-billing_details) が含まれている。 - `auto` の場合、`email`、`name`、`address[country]` フィールドに値が必要です。アメリカ、カナダ、イギリスの請求先住所にも `address[postal_code]` が必要です。 - `required` の場合、`email`、`name`、`address` フィールドに値が必要です。 顧客に複数の保存されたカードがある場合、Payment Element は、以下の優先順位に一致する保存されたカードを表示します。 - `payment` モードでは、Stripe は顧客の最新の保存されたクレジットカードを使用してフィールドに事前入力します。 - `サブスクリプション`モードでは、顧客のデフォルトの決済手段がクレジットカードの場合は Stripe が事前入力します。それ以外の場合は、Stripe は最後に保存されたクレジットカードを事前入力します。 [配送先住所を徴収する](https://docs.stripe.com/payments/collect-addresses.md)際、顧客の[shipping.address](https://docs.stripe.com/api/customers/object.md#customer_object-shipping-address)がチェックアウトセッションの[サポート対象国](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection-allowed_countries)を満たす場合、[セッションオブジェクト](https://docs.stripe.com/js/custom_checkout/session_object)には配送先住所フィールドが含まれます。 決済セッション中に顧客が保存したカードを削除できるようにするには、[save_payment_method_options[payment_method_remove]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-saved_payment_method_options-payment_method_remove) を `enabled` に設定します。 > #### 事前入力のタイムアウト > > 事前入力された決済手段は、Checkout セッションの作成後 30 分間表示されます。有効期限が切れると、セキュリティ上の理由から、同じ Checkout セッションを読み込んでも決済手段が事前入力されなくなります。 ## Stripe に支払いを送信 [クライアント側] #### HTML + JS `Checkout` インスタンスから [確定](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出す**支払う** ボタンをレンダリングして、決済を送信します。 ```html
``` ```js const checkout = stripe.initCheckoutElementsSdk({clientSecret}); checkout.on('change', (session) => { document.getElementById('pay-button').disabled = !session.canConfirm; }); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const button = document.getElementById('pay-button'); const errors = document.getElementById('confirm-errors'); button.addEventListener('click', () => { // Clear any validation errors errors.textContent = ''; actions.confirm().then((result) => { if (result.type === 'error') { errors.textContent = result.error.message; } }); }); } ``` #### React [useCheckout](https://docs.stripe.com/js/react_stripe_js/checkout/use_checkout) から [confirm](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出して決済を送信する **Pay** ボタンをレンダリングします。 ```jsx import React from 'react'; import {useCheckout} from '@stripe/react-stripe-js/checkout'; const PayButton = () => { const checkoutState = useCheckout(); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); if (checkoutState.type !== "success") { return null; } const handleClick = () => { setLoading(true);checkoutState.checkout.confirm().then((result) => { if (result.type === 'error') { setError(result.error) } setLoading(false); }) }; return (
{error &&
{error.message}
}
) }; export default PayButton; ``` ## 支払い後のイベントを処理 [サーバー側] 顧客が Checkout セッションの支払いを完了すると、Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか、[Webhook ガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信して処理します。これにより、次のアクションがトリガーされます。 - 顧客に注文確認メールを送信します。 - 取引をデータベースに記録します。 - 配送ワークフローを開始します。 顧客がリダイレクトされ、ウェブサイトに戻るのを待たずに、これらのイベントはリッスンできます。Checkout のランディングページからのみフルフィルメントをトリガーする場合、確実性に欠けます。非同期型のイベントをリッスンするようシステムを設定すると、1 回の実装で[異なるタイプの決済手段](https://stripe.com/payments/payment-methods-guide)を受け付けられるようになります。 詳しくは、[Checkout のフルフィルメントガイド](https://docs.stripe.com/checkout/fulfillment.md)をご覧ください。 Checkout で支払いを回収する際には、以下のイベントを処理します。 | イベント | 説明 | アクション | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout セッションを正常に完了すると送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | ACH Direct Debt など、遅延型の決済手段による支払いが成功した場合に送信されます。 | 注文確認書を顧客に送信し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | ACH Direct Debt など、遅延型の決済手段による支払いが失敗した場合に送信されます。 | 顧客に失敗を通知して、顧客をオンセッションに戻し、支払いを再試行できるようにします。 | # カスタムフロー > This is a カスタムフロー for when platform is web and ui is elements. View the full page at https://docs.stripe.com/payments/existing-customers?platform=web&ui=elements. Payment Element を使用すると、買い手は各自の支払いの詳細を入力できます。買い手が既存の顧客の場合、Payment Element でカスタマーセッションを設定して、顧客の[既存の決済手段](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=elements)を設定できます。 > #### Accounts v2 API を使用した顧客の表現 > > 導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。 ![1 枚のカードが保存された Payment Element](https://b.stripecdn.com/docs-statics-srv/assets/saved_card.9ae121fe039c6d963f3c9831eb92172f.png) Payment Element は、次の保存済み決済手段タイプのみを表示できます。 - `card` - `link` - `us_bank_account` - `acss_debit` - `sepa_debit` - `bacs_debit` - `au_becs_debit` - `nz_bank_account` - `ideal` - `sofort` - `bancontact` ## Create PaymentIntent と CustomerSession を作成する [サーバー側] [PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md) と [CustomerSession](https://docs.stripe.com/api/customer_sessions/create.md) を作成します。必ず、既存の顧客 ID を渡して、`payment_method_redisplay` 機能を有効にしてください。 #### Accounts v2 #### Ruby ```ruby # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' post '/create-intent-and-customer-session' do intent = Stripe::PaymentIntent.create({ amount: 1099, currency: 'usd', automatic_payment_methods: {enabled: true}, customer_account: {{CUSTOMER_ACCOUNT_ID}}, }) customer_session = Stripe::CustomerSession.create({ customer_account: {{CUSTOMER_ACCOUNT_ID}}, components: { payment_element: { enabled: true, features: { payment_method_redisplay: 'enabled', }, }, }, }) { client_secret: intent.client_secret, customer_session_client_secret: customer_session.client_secret }.to_json end ``` #### Customers v1 #### Ruby ```ruby # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' post '/create-intent-and-customer-session' do intent = Stripe::PaymentIntent.create({ amount: 1099, currency: 'usd', # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. automatic_payment_methods: {enabled: true}, customer: {{CUSTOMER_ID}}, }) customer_session = Stripe::CustomerSession.create({ customer: {{CUSTOMER_ID}}, components: { payment_element: { enabled: true, features: { payment_method_redisplay: 'enabled', }, }, }, }) { client_secret: intent.client_secret, customer_session_client_secret: customer_session.client_secret }.to_json end ``` ## Optional: 追加の保存された支払い方法を表示する [サーバー側] > #### 法令遵守 > > 顧客の支払い情報を保存する際には、適用されるすべての法律、規制、ネットワークルールを遵守する責任を貴社が負うものとします。将来の購入時に過去の決済手段を顧客に表示する場合は、将来の購入に再利用するために決済手段の詳細を保存することの同意をあらかじめ得るようにしてください。 デフォルトでは、[always allow redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) に設定された支払い方法のみ表示されます。 Checkout セッション中に Apple Pay や Google Pay を再利用することはできないため、これらの支払い方法は保存済みオプションの一覧には表示されません。Checkout セッションが有効なたびに、Google Pay や Apple Pay の UI および Payment Request ボタンの UI を表示する必要があります。 Checkout セッションに他の再表示用の値を含めるか、支払い方法の `allow_redisplay` 設定を `always` に変更することで、他の保存済み支払い方法を表示できます。 - `payment_method_allow_redisplay_filters` [パラメーター](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components-payment_element-features-payment_method_allow_redisplay_filters)を使用して、Payment Element に表示する保存済みの決済手段を指定します。パラメーターには、いずれかの有効な値 (`limited`、`unspecified`、`always`) を設定できます。 ```curl curl https://api.stripe.com/v1/customer_sessions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "components[payment_element][enabled]=true" \ -d "components[payment_element][features][payment_method_redisplay]=enabled" \ -d "components[payment_element][features][payment_method_allow_redisplay_filters][]=always" \ -d "components[payment_element][features][payment_method_allow_redisplay_filters][]=limited" \ -d "components[payment_element][features][payment_method_allow_redisplay_filters][]=unspecified" ``` - [決済手段を更新](https://docs.stripe.com/api/payment_methods/update.md)して、各決済手段に `allow_redisplay` 値を設定します。 ```curl curl https://api.stripe.com/v1/payment_methods/{{PAYMENTMETHOD_ID}} \ -u "<>:" \ -d allow_redisplay=always ``` ## Payment Element を表示 [クライアント側] #### HTML + JS ### Stripe.js を設定 HTML ファイルの `head` に Stripe .js スクリプトを追加し、チェックアウトページに含めます。PCI への準拠を維持するために、常に js.stripe.com から Stripe.js を直接読み込んでください。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 ```html Checkout ``` 購入ページで次の JavaScript を使用して、Stripe のインスタンスを作成します。 ```javascript // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` ### Payment Element を支払いページに追加 Payment Element を決済ページに配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。 ```html
``` 前のステップで 2 つの `clients_secret` を取得して、Element を初期化します。次に、Payment Element を作成してマウントします。 ```javascript // Fetch the two `client_secret` const response = await fetch('/create-intent-and-customer-session', { method: "POST" }); const { client_secret, customer_session_client_secret } = await response.json(); // Initialize Elements const elements = stripe.elements({ clientSecret: client_secret, customerSessionClientSecret: customer_session_client_secret, }); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### React ### Stripe.js を設定 次の npm パブリックレジストリから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Elements プロバイダーを支払いページに追加して設定 前のステップで 2 つの `clients_secret` を取得して、[Elements プロバイダー](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider)を初期化します。次に、支払いフォームを含む CheckoutForm コンポーネントをレンダリングします。 ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component's render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const [clientSecret, setClientSecret] = useState(""); const [customerSessionClientSecret, setCustomerSessionClientSecret] = useState(""); // Fetch the two `client_secret` useEffect(() => { fetch("/create-intent-and-customer-session", { method: "POST" }) .then((res) => res.json()) .then((data) => { setClientSecret(data.client_secret); setCustomerSessionClientSecret(data.customer_session_client_secret); }); }, []); // Initialize the Element provider once we we received the two `client_secret` // And render the CheckoutForm return (
{clientSecret && customerSessionClientSecret && ( )}
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Payment Element コンポーネントを追加 `PaymentElement` コンポーネントを使用して、決済フォームを表示します。 ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { return (
); }; export default CheckoutForm; ``` ## Stripe に支払いを送信 [クライアント側] Payment Element からの詳細を指定して [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を使用し、支払いを完了します。ユーザーが支払いを完了した後に Stripe がユーザーをリダイレクトする場所を指定するには、この関数に [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を指定します。ユーザーはまず、銀行のオーソリページなどの中間サイトにリダイレクトされ、その後 `return_url` にリダイレクトされます。カード支払いでは、支払いが正常に完了するとすぐに `return_url` にリダイレクトします。 カード決済で支払いの完了後にリダイレクトを行わない場合は、[redirect](https://docs.stripe.com/js/payment_intents/confirm_payment#confirm_payment_intent-options-redirect) に `if_required` を設定できます。これで、リダイレクトベースの決済手段で購入する顧客のみがリダイレクトされます。 #### HTML + JS ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React 支払いフォームコンポーネントから [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を呼び出すには、[useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) フックと [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook) フックを使用します。 フックではなく従来のクラスコンポーネントを使用する場合は、代わりに [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) を使用します。 ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ); }; export default CheckoutForm; ``` `return_url` が、Web サイト上の支払いステータスを表示するページと対応していることを確認します。Stripe が顧客を `return_url` にリダイレクトするときは、以下の URL クエリーパラメーターが指定されます。 | パラメーター | 説明 | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | `PaymentIntent` の一意の識別子。 | | `payment_intent_client_secret` | `PaymentIntent` オブジェクトの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 | > 顧客のブラウザーセッションを追跡するツールを利用している場合、リファラー除外リストに `stripe.com` ドメインの追加が必要になる場合があります。リダイレクトを行うと、一部のツールでは新しいセッションが作成され、セッション全体の追跡ができなくなります。 クエリパラメーターのいずれか 1 つを使用して PaymentIntent を取得します。[PaymentIntent のステータス](https://docs.stripe.com/payments/paymentintents/lifecycle.md)を調べて、顧客に表示する内容を決定します。また、`return_url` を指定するときにカスタムのクエリパラメーターを追加することもできます。このパラメーターはリダイレクトプロセスの間維持されます。 #### HTML + JS ```javascript // Initialize Stripe.js using your publishable key const stripe = Stripe('<>'); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } }); ``` #### React ```jsx import React, {useState, useEffect} from 'react'; import {useStripe} from '@stripe/react-stripe-js'; const PaymentStatus = () => { const stripe = useStripe(); const [message, setMessage] = useState(null); useEffect(() => { if (!stripe) { return; } // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe .retrievePaymentIntent(clientSecret) .then(({paymentIntent}) => { // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': setMessage('Success! Payment received.'); break; case 'processing': setMessage("Payment processing. We'll update you when payment is received."); break; case 'requires_payment_method': // Redirect your user back to your payment page to attempt collecting // payment again setMessage('Payment failed. Please try another payment method.'); break; default: setMessage('Something went wrong.'); break; } }); }, [stripe]); return message; }; export default PaymentStatus; ``` ## 支払い後のイベントを処理 [サーバー側] 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか [Webhook のガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合、また悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう組み込みを設定すると、単一の組み込みで[複数の異なるタイプの支払い方法](https://stripe.com/payments/payment-methods-guide)を受け付けることができます。 Payment Element を使用して支払いを回収する場合は、`payment_intent.succeeded` イベントのほかにこれらのイベントを処理することをお勧めします。 | イベント | 説明 | アクション | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded) | 顧客が正常に支払いを完了したときに送信されます。 | 顧客に注文の確定を送信し、顧客の注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) | 顧客が正常に支払いを開始したが、支払いがまだ完了していない場合に送信されます。このイベントは、多くの場合、顧客が口座引き落としを開始するときに送信されます。その後、`payment_intent.succeeded` イベント、また、失敗の場合は `payment_intent.payment_failed` イベントが送信されます。 | 顧客に注文確認メールを送信し、支払いが保留中であることを示します。デジタル商品では、支払いの完了を待たずに注文のフルフィルメントを行うことが必要になる場合があります。 | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) | 顧客が支払いを試みたが、支払いに失敗する場合に送信されます。 | 支払いが `processing` から `payment_failed` に変わった場合は、顧客に再度支払いを試すように促します。 | # ダイレクト API > This is a ダイレクト API for when platform is web and ui is direct-api. View the full page at https://docs.stripe.com/payments/existing-customers?platform=web&ui=direct-api. 既存の決済手段の表示方法を完全に管理するには、ダイレクト APIの実装を使用してください。 > #### Accounts v2 API を使用した顧客の表現 > > 導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。 ## 決済手段を表示 [クライアント側] [サーバー側] `allow_redisplay` パラメーターを指定して [list Payment Method](https://docs.stripe.com/api/payment_methods/customer_list.md) エンドポイントを呼び出し、顧客の再利用可能な決済手段を取得します。 ```curl curl -G https://api.stripe.com/v1/customers/{{CUSTOMER_ID}}/payment_methods \ -u "<>:" \ -d allow_redisplay=always ``` API レスポンスデータを使用して、独自の UI に支払い方法を表示し、顧客が選択できるようにします。 ## Optional: 追加の保存された支払い方法を表示する [サーバー側] > #### 法令遵守 > > 顧客の支払い情報を保存する際には、適用されるすべての法律、規制、ネットワークルールを遵守する責任を貴社が負うものとします。将来の購入時に過去の決済手段を顧客に表示する場合は、将来の購入に再利用するために決済手段の詳細を保存することの同意をあらかじめ得るようにしてください。 デフォルトでは、[always allow redisplay](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-allow_redisplay) に設定された支払い方法のみ表示されます。 Checkout セッション中に Apple Pay や Google Pay を再利用することはできないため、これらの支払い方法は保存済みオプションの一覧には表示されません。Checkout セッションが有効なたびに、Google Pay や Apple Pay の UI および Payment Request ボタンの UI を表示する必要があります。 Checkout セッションに他の再表示用の値を含めるか、支払い方法の `allow_redisplay` 設定を `always` に変更することで、他の保存済み支払い方法を表示できます。 - `allow_redisplay` [パラメーター](https://docs.stripe.com/api/payment_methods/customer_list.md#list_customer_payment_methods-allow_redisplay)を使用して、顧客に表示する保存済みの決済手段を指定します。パラメーターには、いずれかの有効な値 (`limited`、`unspecified`、`always`) を設定できます。 ```curl curl -G https://api.stripe.com/v1/customers/{{CUSTOMER_ID}}/payment_methods \ -u "<>:" \ -d allow_redisplay=unspecified ``` - [決済手段を更新](https://docs.stripe.com/api/payment_methods/update.md)して、各決済手段に `allow_redisplay` 値を設定します。 ```curl curl https://api.stripe.com/v1/payment_methods/{{PAYMENTMETHOD_ID}} \ -u "<>:" \ -d allow_redisplay=always ``` ## PaymentIntent を作成 [サーバー側] [PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md) を作成して、顧客が選択した決済手段で請求を試みます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d customer={{CUSTOMER_ID}} \ -d payment_method={{PAYMENT_METHOD_ID}} \ -d confirm=true \ --data-urlencode "return_url=https://example.com/order/123/complete" ``` API コールが 402 レスポンスで失敗した場合は、支払いが拒否されたことを意味します。再試行するか、別の決済手段を試すように顧客に依頼します。 ## PaymentIntent ステータスを確認 [クライアント側] [サーバー側] PaymentIntent が正常に作成されたとして、`status` を確認します。 - `succeeded` は、顧客が想定どおりに請求されたことを示します。顧客に成功のメッセージを表示します。 - `requires_action` は、3D セキュアによる認証など、追加のアクションを求める必要があることを示します。フロントエンドで [`handleNextAction`](https://docs.stripe.com/js/payment_intents/handle_next_action) を呼び出し、顧客が実行する必要があるアクションをトリガーします。 ```javascript const { error, paymentIntent } = await stripe.handleNextAction({ clientSecret: "{{CLIENT_SECRET}}" }); if (error) { // Show error from Stripe.js } else { // Actions handled, show success message } ``` ## 支払い後のイベントを処理 [サーバー側] 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。[ダッシュボードの Webhook ツール](https://dashboard.stripe.com/webhooks)を使用するか [Webhook のガイド](https://docs.stripe.com/webhooks/quickstart.md)に従ってこれらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合、また悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう組み込みを設定すると、単一の組み込みで[複数の異なるタイプの支払い方法](https://stripe.com/payments/payment-methods-guide)を受け付けることができます。 Payment Element を使用して支払いを回収する場合は、`payment_intent.succeeded` イベントのほかにこれらのイベントを処理することをお勧めします。 | イベント | 説明 | アクション | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded) | 顧客が正常に支払いを完了したときに送信されます。 | 顧客に注文の確定を送信し、顧客の注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を実行します。 | | [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) | 顧客が正常に支払いを開始したが、支払いがまだ完了していない場合に送信されます。このイベントは、多くの場合、顧客が口座引き落としを開始するときに送信されます。その後、`payment_intent.succeeded` イベント、また、失敗の場合は `payment_intent.payment_failed` イベントが送信されます。 | 顧客に注文確認メールを送信し、支払いが保留中であることを示します。デジタル商品では、支払いの完了を待たずに注文のフルフィルメントを行うことが必要になる場合があります。 | | [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) | 顧客が支払いを試みたが、支払いに失敗する場合に送信されます。 | 支払いが `processing` から `payment_failed` に変わった場合は、顧客に再度支払いを試すように促します。 |