# 将来の支払いを設定する Checkout セッションで支払い情報を保存し、後で顧客に請求する方法をご紹介します。 # ホスト型ページ > This is a ホスト型ページ for when payment-ui is stripe-hosted. View the full page at https://docs.stripe.com/payments/checkout/save-and-reuse?payment-ui=stripe-hosted. Checkout の設定モードを使用すると、顧客の支払い情報を収集して、今後の決済時に再利用できます。設定モードは、[Setup Intents API](https://docs.stripe.com/api/setup_intents.md) を使用して [Payment Methods](https://docs.stripe.com/api/payment_methods.md) を作成します。 [GitHub の実用サンプル](https://github.com/stripe-samples/checkout-remember-me-with-twilio-verify)をご覧ください。 ## Stripe を設定する [サーバ側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 アプリケーションから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。 #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Checkout セッションを作成する [クライアント側] [サーバ側] ウェブサイトに決済ボタンを追加し、サーバー側のエンドポイントを呼び出して Checkout セッションを作成します。 ```html Checkout
``` 設定モードのセッションを作成するには、セッションの作成時に `setup` の値を指定して `mode` パラメーターを使用します。オプションで [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) パラメーターを指定して、作成した決済手段を既存の顧客に自動的に関連付けることもできます。Checkout ではデフォルトで[動的決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)が使用されるため、`setup` モードを使用するときに [currency](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-currency) パラメーターを渡す必要があります。 `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=setup \ -d currency=usd \ -d "customer={{CUSTOMER_ID}}" \ --data-urlencode "success_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` ### 決済手段 デフォルトでは、カードとその他の一般的な決済手段が有効になっています。[Stripe ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で個々の決済手段をオンまたはオフにできます。Checkout では、Stripe は通貨と制限事項を評価して、対応している決済手段を顧客に動的に提示します。 決済手段が顧客にどのように表示されるか確認するには、ダッシュボードで取引 ID を入力するか、または注文金額と通貨を設定します。 [決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)では Apple Pay と Google Pay を有効にすることができます。デフォルトでは、Apple Pay は有効で、Google Pay は無効になっています。ただし、有効になっていても Stripe が除外する場合があります。配送先住所を収集せずに[税金の自動計算を有効にした](https://docs.stripe.com/tax/checkout.md)場合、Google Pay は除外されます。 Checkout の Stripe 上のオンラインページでは、Apple Pay や Google Pay を有効にするために実装内容を変更する必要はありません。Stripe は、これらの決済を他のカード決済と同じように処理します。 ## Checkout セッションを取得する [サーバ側] 顧客が Checkout セッションを正常に完了した後に、お客様は Session オブジェクトを取得する必要があります。これは、以下の 2 つの方法で実行できます。 - **非同期**: Session オブジェクトを含む `checkout.session.completed` *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) を処理します。[Webhook の設定](https://docs.stripe.com/webhooks.md)の詳細をご覧ください。 - **同期:** ユーザーがサイトにリダイレクトされるときに `success_url` からセッション ID を取得します。セッション ID を使用して、Session オブジェクトを[取得](https://docs.stripe.com/api/checkout/sessions/retrieve.md)します。 ```curl curl https://api.stripe.com/v1/checkout/sessions/cs_test_MlZAaTXUMHjWZ7DcXjusJnDU4MxPalbtL5eYrmS2GKxqscDtpJq8QM0k \ -u "<>:" ``` 顧客が支払いの成功後に必ず `success_url` に到達するとは限らないため、ドロップオフの許容度に応じて適切な判断をする必要があります。リダイレクトが発生する前に顧客がブラウザータブを閉じることもあります。Webhook を処理することで、システムがこのようなドロップオフの影響を受けずに済みます。 Session オブジェクトの取得後、Checkout セッションの際に作成された SetupIntent の ID である `setup_intent` キーの値を入手します。[SetupIntent](https://docs.stripe.com/payments/setup-intents.md) は、今後の支払いに備えて顧客の銀行口座情報を設定するために使用されるオブジェクトです。 以下に `checkout.session.completed` ペイロードの例を示します。 ```json { "id": "evt_1Ep24XHssDVaQm2PpwS19Yt0", "object": "event", "api_version": "2019-03-14", "created": 1561420781, "data": { "object": { "id": "cs_test_MlZAaTXUMHjWZ7DcXjusJnDU4MxPalbtL5eYrmS2GKxqscDtpJq8QM0k", "object": "checkout.session", "billing_address_collection": null, "client_reference_id": null, "customer": "", "customer_email": null, "display_items": [], "mode": "setup","setup_intent": "seti_1EzVO3HssDVaQm2PJjXHmLlM", "submit_type": null, "subscription": null, "success_url": "https://example.com/success" } }, "livemode": false, "pending_webhooks": 1, "request": { "id": null, "idempotency_key": null }, "type": "checkout.session.completed" } ``` 次のステップに備えて `setup_intent` ID を書き留めておきます。 ## SetupIntent を取得する [サーバ側] `setup_intent` ID を使用し、SetupIntent オブジェクトを[取得](https://docs.stripe.com/api/setup_intents/retrieve.md)します。返されるオブジェクトには `payment_method` ID が含まれ、これを次のステップで顧客に関連付けることができます。 ```curl curl https://api.stripe.com/v1/setup_intents/seti_1EzVO3HssDVaQm2PJjXHmLlM \ -u "<>:" ``` > この情報を (Webhook の処理とは異なり) Stripe API から同期的にリクエストする場合は、/v1/checkout/session エンドポイントに対するリクエスト内の SetupIntent オブジェクトを[拡張](https://docs.stripe.com/api/expanding_objects.md)することで、前のステップとこのステップを結合できます。このようにすることで、新しく作成された PaymentMethod ID にアクセスするためのネットワークリクエストを二重に作成する必要がなくなります。 ## 後で決済手段に請求する [サーバ側] 既存の顧客を指定して Checkout セッションを作成しなかった場合は、PaymentMethod の ID を使用して、*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) を *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。PaymentMethod を顧客に関連付けた後、[PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method) を使用して、*オフセッション* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information)の支払いを行うことができます。 - [customer](https://docs.stripe.com/api.md#create_payment_intent-customer) を 顧客の ID に、[payment_method](https://docs.stripe.com/api.md#create_payment_intent-payment_method) を PaymentMethod の ID に設定します。 - [off_session](https://docs.stripe.com/api/payment_intents/confirm.md#confirm_payment_intent-off_session) が `true` の場合、支払いの試行時に顧客が決済フローを実行中でなく、カード発行会社、銀行、その他の決済機関といった提携機関からの認証リクエストに対応できないことを示します。決済フロー中に提携機関から認証をリクエストされた場合、Stripe は以前の*オンセッション* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method)取引の顧客情報を使用して免除をリクエストします。免除の条件が満たされていない場合、PaymentIntent はエラーを返す可能性があります。 - PaymentIntent の [confirm](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-confirm) プロパティの値を `true` に設定します。これにより、PaymentIntent が作成されると直ちに確定が行われます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "customer={{CUSTOMER_ID}}" \ -d "payment_method={{PAYMENTMETHOD_ID}}" \ -d off_session=true \ -d confirm=true ``` 支払いが失敗すると、リクエストも 402 HTTP ステータスコードで失敗し、PaymentIntent のステータスが *requires\_payment\_method* (This status appears as "requires_source" in API versions before 2019-02-11) になります。アプリケーションに戻って支払いを完了するよう (メールやアプリ内通知を送信するなどして) 顧客に通知し、顧客を新しい Checkout セッションに誘導して別の決済手段を選択するよう促します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=1099" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ --data-urlencode "success_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` # 埋め込みページ > This is a 埋め込みページ for when payment-ui is embedded-form. View the full page at https://docs.stripe.com/payments/checkout/save-and-reuse?payment-ui=embedded-form. 顧客の支払い情報を収集して、今後の決済時に再利用できるようにするには、Checkout の設定モードを使用します。設定モードは、[Setup Intents API](https://docs.stripe.com/api/setup_intents.md) を使用して [PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods.md) を作成します。 ## Stripe を設定する [サーバー側] まず、Stripe アカウントが必要です。[今すぐご登録ください](https://dashboard.stripe.com/register)。 アプリケーションから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。 #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## Checkout セッションを作成する [サーバー側] サーバーから、*Checkout Session* (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` に設定します。setup モードの Checkout Session を作成するには、[mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-mode) を `setup` に設定します。 自社サイトでホストされているカスタムページに顧客を戻すには、そのページの URL を [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_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)するためのその他のオプションについて、詳細をご覧ください。 必要に応じて、[customer パラメーター](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer)を指定して、作成した決済手段を既存の顧客に自動的に関連付けることが可能です。 Checkout セッションの作成後、レスポンスで返される `client_secret` を使用して、[Checkout をマウント](https://docs.stripe.com/payments/checkout/save-and-reuse.md#mount-checkout)します。 #### Ruby ```ruby # This example sets up an endpoint using the Sinatra framework. require 'json' require 'sinatra' require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. client = Stripe::StripeClient.new('<>') post '/create-checkout-session' do session = client.v1.checkout.sessions.create({ currency: 'usd', mode: 'setup', ui_mode: 'embedded_page', return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }) {clientSecret: session.client_secret}.to_json end ``` ### 決済手段 デフォルトでは、カードとその他の一般的な決済手段が有効になっています。[Stripe ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で個々の決済手段をオンまたはオフにできます。Checkout では、Stripe は通貨と制限事項を評価して、対応している決済手段を顧客に動的に提示します。 決済手段が顧客にどのように表示されるか確認するには、ダッシュボードで取引 ID を入力するか、または注文金額と通貨を設定します。 [決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)では Apple Pay と Google Pay を有効にすることができます。デフォルトでは、Apple Pay は有効で、Google Pay は無効になっています。ただし、有効になっていても Stripe が除外する場合があります。配送先住所を収集せずに[税金の自動計算を有効にした](https://docs.stripe.com/tax/checkout.md)場合、Google Pay は除外されます。 Checkout の Stripe 上のオンラインページでは、Apple Pay や Google Pay を有効にするために実装内容を変更する必要はありません。Stripe は、これらの決済を他のカード決済と同じように処理します。 ## 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 セッションを正常に完了した後に、お客様は Session オブジェクトを取得する必要があります。これは、以下の 2 つの方法で実行できます。 - **非同期**: Session オブジェクトを含む `checkout.session.completed` *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) を処理します。[Webhook の設定](https://docs.stripe.com/webhooks.md)の詳細をご覧ください。 - **同期:** ユーザーがサイトにリダイレクトされるときに `return_url` からセッション ID を取得します。セッション ID を使用して、Session オブジェクトを[取得](https://docs.stripe.com/api/checkout/sessions/retrieve.md)します。 ```curl curl https://api.stripe.com/v1/checkout/sessions/cs_test_MlZAaTXUMHjWZ7DcXjusJnDU4MxPalbtL5eYrmS2GKxqscDtpJq8QM0k \ -u "<>:" ``` 顧客が支払いの成功後に必ず `return_url` に到達するとは限らないため、ドロップオフの許容度に応じて適切な判断をする必要があります。リダイレクトが発生する前に顧客がブラウザータブを閉じることもあります。Webhook を処理することで、システムがこのようなドロップオフの影響を受けずに済みます。 Session オブジェクトの取得後、Checkout セッションの際に作成された SetupIntent の ID である `setup_intent` キーの値を入手します。[SetupIntent](https://docs.stripe.com/payments/setup-intents.md) は、今後の支払いに備えて顧客の銀行口座情報を設定するために使用されるオブジェクトです。 以下に `checkout.session.completed` ペイロードの例を示します。 ```json { "id": "evt_1Ep24XHssDVaQm2PpwS19Yt0", "object": "event", "api_version": "2019-03-14", "created": 1561420781, "data": { "object": { "id": "cs_test_MlZAaTXUMHjWZ7DcXjusJnDU4MxPalbtL5eYrmS2GKxqscDtpJq8QM0k", "object": "checkout.session", "billing_address_collection": null, "client_reference_id": null, "customer": "", "customer_email": null, "display_items": [], "mode": "setup","setup_intent": "seti_1EzVO3HssDVaQm2PJjXHmLlM", "submit_type": null, "subscription": null, "success_url": "https://example.com/success" } }, "livemode": false, "pending_webhooks": 1, "request": { "id": null, "idempotency_key": null }, "type": "checkout.session.completed" } ``` 次のステップに備えて `setup_intent` ID を書き留めておきます。 ## SetupIntent を取得する [サーバー側] SetupIntent ID を使用し、SetupIntent オブジェクトを[取得](https://docs.stripe.com/api/setup_intents/retrieve.md)します。返されるオブジェクトには、次のステップで顧客に関連付けることができる `payment_method` ID が含まれています。 ```curl curl https://api.stripe.com/v1/setup_intents/seti_1EzVO3HssDVaQm2PJjXHmLlM \ -u "<>:" ``` > この情報を (Webhook の処理とは異なり) Stripe API から同期的にリクエストする場合は、/v1/checkout/session エンドポイントに対するリクエスト内の SetupIntent オブジェクトを[拡張](https://docs.stripe.com/api/expanding_objects.md)することで、前のステップとこのステップを結合できます。このようにすることで、新しく作成された PaymentMethod ID にアクセスするためのネットワークリクエストを二重に作成する必要がなくなります。 ## 後で決済手段に請求する [サーバー側] 既存の顧客を指定して Checkout セッションを作成しなかった場合は、PaymentMethod の ID を使用して、*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) を *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。PaymentMethod を顧客に関連付けた後、[PaymentIntent](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method) を使用して、*オフセッション* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information)の支払いを行うことができます。 - [customer](https://docs.stripe.com/api.md#create_payment_intent-customer) を 顧客の ID に、[payment_method](https://docs.stripe.com/api.md#create_payment_intent-payment_method) を PaymentMethod の ID に設定します。 - [off_session](https://docs.stripe.com/api/payment_intents/confirm.md#confirm_payment_intent-off_session) が `true` の場合、支払いの試行時に顧客が決済フローを実行中でなく、カード発行会社、銀行、その他の決済機関といった提携機関からの認証リクエストに対応できないことを示します。決済フロー中に提携機関から認証をリクエストされた場合、Stripe は以前の*オンセッション* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method)取引の顧客情報を使用して免除をリクエストします。免除の条件が満たされていない場合、PaymentIntent はエラーを返す可能性があります。 - PaymentIntent の [confirm](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-confirm) プロパティの値を `true` に設定します。これにより、PaymentIntent が作成されると直ちに確定が行われます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "customer={{CUSTOMER_ID}}" \ -d "payment_method={{PAYMENTMETHOD_ID}}" \ -d off_session=true \ -d confirm=true ``` 支払いが失敗すると、リクエストも 402 HTTP ステータスコードで失敗し、PaymentIntent のステータスが *requires\_payment\_method* (This status appears as "requires_source" in API versions before 2019-02-11) になります。アプリケーションに戻って支払いを完了するよう (メールやアプリ内通知を送信するなどして) 顧客に通知し、顧客を新しい Checkout セッションに誘導して別の決済手段を選択するよう促します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "line_items[0][price_data][currency]=usd" \ -d "line_items[0][price_data][product_data][name]=T-shirt" \ -d "line_items[0][price_data][unit_amount]=1099" \ -d "line_items[0][quantity]=1" \ -d mode=payment \ -d ui_mode=embedded_page \ --data-urlencode "return_url=https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ```