# デスティネーション支払いを作成する プラットフォームアカウントで支払いを作成し、手数料を回収し、残りの売上を連結アカウントに即時に送金します。 LLM 向けの指示: Stripe は新製品や機能を頻繁にリリースします。実装前に https://raw.githubusercontent.com/stripe/ai/refs/heads/main/skills/stripe-best-practices/SKILL.md から Stripe のベストプラクティススキルを取得してください。 連結アカウントが提供する商品またはサービスについて、顧客がプラットフォームと取引するときに「デスティネーション支払い」を作成し、連結アカウントに売上を即時に送金します。この支払いタイプの特徴は以下のとおりです。 - プラットフォームのアカウントで支払いを作成します。 - 売上の一部または全額を、連結アカウントに送金するかどうかを決定します。 - Stripe の手数料、返金、チャージバックは、お客様のアカウント残高から引き落とされます。 この支払いタイプは、住宅賃貸マーケットプレイスの Airbnb や、ライドシェアアプリの Lyft などのマーケットプレイスに最適です。 [ただし例外](https://docs.stripe.com/connect/account-capabilities.md#transfers-cross-border)があります。貴社のプラットフォームと連結アカウントの所在地が同じではない場合、[Payment Intent](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-on_behalf_of) の `on_behalf_of` パラメータまたは [Checkout Session](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-on_behalf_of) の `payment_intent_data.on_behalf_of` パラメータを用いて、連結アカウントを [settlement merchant](https://docs.stripe.com/connect/destination-charges.md#settlement-merchant) に設定する必要があります。 Stripe ダッシュボードの全機能を利用できない連結アカウントの場合には、デスティネーション支払いを使用することをお勧めします。 [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) を使用して、Stripe がオンラインで提供する決済ページにリダイレクトします。この実装と、[Stripe の他の実装タイプとの比較](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 #### 導入作業 Complexity: 2/5 #### 接続方法のタイプ Stripe がオンラインで提供する決済ページにリダイレクトする #### UI のカスタマイズ 限定的なカスタマイズ - 20 種類の事前設定されたフォント - 3 種類の事前設定された角丸の半径 - カスタムの背景色と枠線の色 - カスタムロゴ [試してみる](https://checkout.stripe.dev/) まず、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 (Checkout セッション)](https://docs.stripe.com/api/checkout/sessions.md) は、ラインアイテム、注文金額と通貨、受け付け可能な支払い方法など、支払いフォームで顧客に表示される内容を制御します。サーバー側のエンドポイントを呼び出して Checkout セッションを作成する購入ボタンをウェブサイトに追加します。 ```html Checkout
``` #### 支払い先 サーバー側で 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 "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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ --data-urlencode success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` | パラメーター | 説明 | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [payment_intent_data[transfer_data][destination]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-transfer_data-destination) | デスティネーション支払いであることを示しています。デスティネーション支払いでは、支払いがプラットフォームで処理され、売上が即時かつ自動的に連結アカウントの保留中の残高に送金されます。 | | [line_items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) | 顧客が購入しようとしているアイテムを表します。このアイテムは埋め込みの支払いフォームに表示されます。 | | [success_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-success_url) | 顧客が支払いを完了した後にリダイレクトされる URL。値 `{CHECKOUT_SESSION_ID}` を使用して Checkout セッションを取得し、そのステータスを調べて顧客に表示する内容を決定します。[Custom クエリパラメーター](https://docs.stripe.com/payments/checkout/custom-success-page.md) を追加することもできます。これはリダイレクト プロセス全体にわたって存続します。 | | [payment_intent_data[application_fee_amount]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-application_fee_amount) | プラットフォームが取引で受け取る予定の金額。支払いがキャプチャーされると、プラットフォームから、`transfer_data[destination]` で指定された連結アカウントに支払い金額の全額が即時送金されます。その後 `application_fee_amount` がプラットフォームに返金され、プラットフォームの金額から Stripe 手数料が差し引かれます。 | (See full diagram at https://docs.stripe.com/connect/destination-charges) デスティネーション支払いを処理する場合、Checkout ではプラットフォームアカウントのブランド設定を使用します。詳細については、[ブランディングをカスタマイズする](https://docs.stripe.com/connect/destination-charges.md#branding)をご覧ください。 #### 以下の代理として `on_behalf_of` パラメータを連結アカウント ID に設定して、デスティネーション支払いを作成します。`on_behalf_of` パラメータは、[売上処理加盟店](https://docs.stripe.com/connect/destination-charges.md#settlement-merchant)を決定します。デフォルトではプラットフォームアカウントに設定されます。これは、以下に影響を与えます。 - 顧客に表示する明細書表記 - 顧客に表示する住所と電話番号 - 支払いの売上処理通貨 - 顧客に表示する [Checkout ページのブランディング](https://docs.stripe.com/connect/destination-charges.md#branding) サーバー側で 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 "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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[on_behalf_of]"="{{CONNECTEDACCOUNT_ID}}" \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ --data-urlencode success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` | パラメーター | 説明 | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [payment_intent_data[on_behalf_of]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-on_behalf_of) | 売上処理加盟店。パラメーターが存在しない場合は、デフォルトでプラットフォームに設定されます。 | | [payment_intent_data[transfer_data][destination]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-transfer_data-destination) | デスティネーション支払いであることを示しています。デスティネーション支払いでは、支払いがプラットフォームで処理され、売上が即時かつ自動的に連結アカウントの保留中の残高に送金されます。 | | [line_items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) | 顧客が購入しようとしているアイテムを表します。このアイテムは Stripe がホストする Checkout ページに表示されます。 | | [success_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-success_url) | 顧客が支払いを完了した後にリダイレクトされる URL。値 `{CHECKOUT_SESSION_ID}` を使用して Checkout セッションを取得し、そのステータスを調べて顧客に表示する内容を決定します。[Custom クエリパラメーター](https://docs.stripe.com/payments/checkout/custom-success-page.md) を追加することもできます。これはリダイレクト プロセス全体にわたって存続します。 | | [payment_intent_data[application_fee_amount]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-application_fee_amount) | プラットフォームが取引で受け取る予定の金額。支払いがキャプチャーされると、プラットフォームから、`transfer_data[destination]` で指定された連結アカウントに支払い金額の全額が即時送金されます。その後 `application_fee_amount` がプラットフォームに返金され、プラットフォームの金額から Stripe 手数料が差し引かれます。 | (See full diagram at https://docs.stripe.com/connect/destination-charges) ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[Webhook を使用してこのイベントを受信](https://docs.stripe.com/webhooks/quickstart.md)し、顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアント側では、コールバックの実行前に顧客がブラウザーのウィンドウを閉じたり、アプリケーションを終了したりする可能性があります。また、支払い方法によっては支払いの確定までに 2 ~ 14 日かかることがあります。自社の構築済みのシステムで非同期イベントをリッスンするように設定すると、一度の導入で複数の[支払い方法](https://stripe.com/payments/payment-methods-guide)に対応できるようになります。 Checkout で支払いを回収するときは、以下のすべてのイベントを処理することをお勧めします。 | イベント | 説明 | 次のステップ | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ---------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout フォームを送信して、決済を正常に承認しました。 | 決済の成功または失敗の結果を待ちます。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | 顧客の決済が成功しました。 | 購入された商品やサービスのフルフィルメントを行います。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | 何らかの理由により決済が拒否されたか、失敗しました。 | 顧客にメールで連絡して、新たに注文するように依頼します。 | これらのイベントのすべてに、[Checkout Session (Checkout セッション)](https://docs.stripe.com/api/checkout/sessions.md) オブジェクトが含まれています。決済が成功すると、基となる *PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) の[ステータス](https://docs.stripe.com/payments/paymentintents/lifecycle.md)が `processing` から `succeeded` または失敗のステータスに変わります。 ## 実装内容をテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: その他の支払い方法を有効にする #### 支払い先 Stripe ダッシュボードの[支払い方法ページ](https://dashboard.stripe.com/settings/payment_methods)から、アカウントの支払い方法を設定します。カード支払い、Google Pay、Apple Pay はデフォルトで有効になっていますが、必要に応じて支払い方法を有効にしたり無効にしたりできます。連結アカウントは自身の支払い方法をカスタマイズできません。 顧客に決済フォームを表示する前に、Stripe は通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストを決定します。決済フォームでは、購入完了率の向上につながり、顧客の通貨と所在地に最も適した決済手段が優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューの下に隠れた状態になります。 #### 以下の代理として ダッシュボードの[連結アカウントの支払い方法を管理する](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)に移動して、連結アカウントで対応する支払い方法を設定します。デフォルトの設定に対する変更は、新規および既存のすべての連結アカウントに適用されます。 支払い方法の情報に関する次のリソースをご覧ください。 - [支払い方法ガイド](https://stripe.com/payments/payment-methods-guide#choosing-the-right-payment-methods-for-your-business)は、プラットフォームに適した支払い方法の選択に役立ちます。 - [アカウントのケイパビリティ](https://docs.stripe.com/connect/account-capabilities.md) を使用して、選択した決済手段が連結アカウントで機能することを確認します。 - Stripe プロダクトおよび決済フローに適した決済手段を選択できるよう、[決済手段とサポート対象のプロダクト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#product-support)に関する表をご確認ください。 支払い方法ごとに、次のいずれかのドロップダウンオプションを選択できます。 | | | | | **デフォルトで有効にする** | 連結アカウントは、決済フローでこの支払い方法に対応します。一部の支払い方法は、無効またはブロックされている可能性があります。これは、*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントが、設定ページで有効化する必要があるためです。 | | **デフォルトで無効にする** | 連結アカウントは、決済フローでこの支払い方法に対応しません。*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントに、自身の支払い方法を管理することを許可している場合、連結アカウントはこれを有効にすることができます。 | | **ブロック済み** | 連結アカウントは、決済フローでこの支払い方法に対応しません。連結アカウントに *Stripe ダッシュボードにアクセスして* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 | ![支払い方法のドロップダウンオプション。支払い方法ごとに選択可能なオプション (ブロック済み、デフォルトで有効にする、デフォルトで無効にする) を示します。](https://b.stripecdn.com/docs-statics-srv/assets/dropdowns.ef651d721d5939d81521dd34dde4577f.png) 支払い方法のオプション 支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。 ![保存ボタンをクリックした後に表示される、ユーザーが変更した内容のリストを含むダイアログ](https://b.stripecdn.com/docs-statics-srv/assets/dialog.a56ea7716f60db9778706790320d13be.png) 保存ダイアログ ### 連結アカウントによる支払い方法の管理を許可する Stripe では、連結アカウントが自身の支払い方法をカスタマイズできるようにすることをお勧めしています。このオプションを有効にすると、*Stripe ダッシュボードにアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)できる各連結アカウントは、[支払い方法](https://dashboard.stripe.com/settings/payment_methods)ページを表示および更新できるようになります。Stripe ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。 このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。 ![連結アカウントの所有者に支払い方法のカスタマイズを許可する際に選択するチェックボックスのスクリーンショット](https://b.stripecdn.com/docs-statics-srv/assets/checkbox.275bd35d2a025272f03af029a144e577.png) アカウントのカスタマイズのチェックボックス ### 支払い方法ケイパビリティ 連結アカウントが追加の支払い方法を受け入れられるようにするには、`Accounts` にアクティブな支払い方法のケイパビリティが必要です。 [連結アカウントの決済手段の管理](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)で決済手段に「デフォルトで有効にする」オプションを選択した場合、新規および既存の連結アカウントが確認要件を満たしていれば、Stripe は自動的に必要なケイパビリティをリクエストします。連結アカウントが要件を満たしていない場合、または直接制御したい場合は、ダッシュボードまたは API でケイパビリティを手動でリクエストできます。 ほとんどの決済手段の確認要件は `card_payments` ケイパビリティと同じですが、いくつかの制限と例外があります。[決済手段ケイパビリティ表](https://docs.stripe.com/connect/account-capabilities.md#payment-methods)には、追加の確認が必要な決済手段が一覧表示されます。 #### ダッシュボード ダッシュボードで[連結アカウントを見つけ](https://docs.stripe.com/connect/dashboard/managing-individual-accounts.md#finding-accounts)て、ケイパビリティを編集し、未対応の確認要件を確認します。 #### API 既存の連結アカウントについては、既存のケイパビリティを[リスト](https://docs.stripe.com/api/capabilities/list.md) して、追加のケイパビリティをリクエストする必要があるかどうかを判断できます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities \ -u "<>:" ``` 各連結アカウントのケイパビリティを[更新](https://docs.stripe.com/api/capabilities/update.md)して、追加のケイパビリティをリクエストします。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities/us_bank_account_ach_payments \ -u "<>:" \ -d requested=true ``` リクエストされたケイパビリティが有効になるまでに時間がかかる場合があります。ケイパビリティに有効化の要件がある場合は、レスポンスの `requirements` 配列にそれが含まれます。 ## 手数料を回収する 支払いが処理される際に、取引の全額を連結アカウントに送金するのではなく、プラットフォームが取引金額の一部を手数料という形で受け取ることを決定できます。手数料の料金体系は、次の 2 つの方法で設定できます。 - [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、プラットフォーム手数料の料金体系ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。 - 社内で料金体系ルールを設定し、[application_fee_amount](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-application_fee_amount) または [transfer_data[amount]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-transfer_data-amount) パラメーターを使用して、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接手数料を指定します。この方法で設定された手数料は、プラットフォーム料金設定ツールで指定された料金体系ロジックを上書きします。 #### application_fee_amount `application_fee_amount` を指定して支払いを作成すると、支払いのキャプチャー後に、支払いの総額が即座にプラットフォームから `transfer_data[destination]` アカウントに送金されます。その後、`application_fee_amount` (上限は支払い総額) がプラットフォームに送金されます。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ --data-urlencode success_url="https://example.com/success" ``` プラットフォーム手数料が回収されると、[プラットフォーム手数料](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが作成されます。[ダッシュボード](https://dashboard.stripe.com/connect/application_fees)、[アプリケーション手数料](https://docs.stripe.com/api/application_fees/list.md)、または [Sigma](https://docs.stripe.com/stripe-data/how-sigma-works.md) でアプリケーション手数料のリストを表示できます。プラットフォーム手数料オブジェクトの `amount` プロパティを使用して、項目別の手数料レポートを作成することもできます。 `application_fee_amount` を使用する際には、以下の点に留意します。 - `application_fee_amount` は合計取引額が上限です。 - `application_fee_amount` は常に取引と同じ通貨で計算されます。 - プラットフォーム手数料は、連結アカウントの売上処理通貨と同じ通貨で *売上として処理* (When funds are available in your Stripe balance)されます。越境デスティネーション支払いの場合は、[プラットフォームの売上処理通貨と異なる](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)通貨になる場合があります。 - `application_fee_amount` がお客様のアカウントに送金された後に、お客様のプラットフォームが Stripe 手数料を支払います。 - 金額には追加の Stripe 手数料は適用されません。 - プラットフォームは埋め込みのプラットフォーム手数料レポートを使用して、[回収した手数料](https://dashboard.stripe.com/connect/application_fees)を照合できます。 - Stripe がオンラインで提供するダッシュボードや、[支払い詳細コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payment-details.md) などのコンポーネントでは、連結アカウントは合計金額とプラットフォーム手数料のどちらの金額も表示できます。 ### デスティネーション支払いでの資金のフロー 上記のコードでは、支払いの全額 (10.00 USD) が連結アカウントの保留残高に追加されます。`application_fee_amount` (1.23 USD) はその支払い金額から差し引かれ、お客様のプラットフォームに送金されます。 次に Stripe 手数料 (0.59 USD) がプラットフォームアカウントの残高から差し引かれます。プラットフォーム手数料から Stripe 手数料を差し引いた金額 (1.23 USD - 0.59 USD = 0.64 USD) は、プラットフォームアカウントの残高に残ります。 ![デスティネーション支払いの売上のフロー](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_app_fee.c9ef81298155b38f986df02d0efa9167.png) 通常の Stripe 支払いからの売上と同様に、プラットフォームアカウントの通常の送金スケジュールで `application_fee_amount` が利用可能になります。 #### transfer_data[amount] `transfer_data[amount]` は `transfer_data[destination]` に送金される支払い金額を示す正の整数です。支払い金額からプラットフォームの手数料を差し引き、その計算結果を `transfer_data[amount]` として渡します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[transfer_data][amount]"=877 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ --data-urlencode success_url="https://example.com/success" ``` `transfer_data[amount]` を使用する際には、以下が適用されます。 - 金額は合計取引額が上限です。 - 金額は、常に取引と同じ通貨で計算されます。 - 金額は[プラットフォームの売上処理通貨と同じ通貨](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)で*売上として処理* (When funds are available in your Stripe balance)されます。 - 連結アカウントは、Stripe 上のオンラインダッシュボード (Stripe ダッシュボードや Express ダッシュボードなど) で支払いの合計額を確認することはできません。表示されるのは送金済みの金額のみです。 - プラットフォームが、支払いの Stripe 手数料を別途支払います。 - 金額には追加の Stripe 手数料は適用されません。 - 支払いの作成後に、レポート作成などの目的で[手数料を計算する](https://docs.stripe.com/stripe-data/query-all-fees-data.md#fees-paid-by-connected-accounts)場合、[PaymentIntent を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)して PaymentIntent の `amount` から `transfer_data[amount]` を差し引きます。 [プラットフォーム手数料額](https://docs.stripe.com/connect/destination-charges.md#application-fee)を使用して、支払いに関連付けられた明示的なプラットフォーム手数料を作成し、レポート作成を効率化することを検討してください。 ### 売上のフロー 上記のコードでは、支払い `amount` (10.00 USD) がプラットフォームアカウントの残高に追加されます。`transfer_data[amount]` (8.77 USD) がプラットフォームアカウントの残高から差し引かれ、連結アカウントの保留中の残高に追加されます。支払い `amount` (10.00 USD) から `transfer_data[amount]` (8.77 USD) と Stripe 手数料 (支払い `amount` に対する) を差し引いた正味金額 0.64 USD が、プラットフォームアカウントの保留中の残高に残ります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_amount.46cd59f6496607d68020b546aa1af85f.png) 通常の Stripe 支払いからの売上と同様に、連結アカウントの通常送金スケジュールで `transfer_data[amount]` が利用可能になます。 プラットフォームは、残高履歴エクスポートのデスティネーションプラットフォーム手数料列を調べることで `transfer_data[amount]` 支払いから確保する金額を追跡できます。 ## ブランディングをカスタマイズする プラットフォームと連結アカウントでは、ダッシュボードの[ブランディング設定](https://dashboard.stripe.com/account/branding)を使用して、支払いページのブランディングをカスタマイズできます。ダイレクト支払いの場合、Checkout は連結アカウントのブランド設定を使用します。 API を使用して[ブランディング設定を更新](https://docs.stripe.com/api/accounts/update.md#update_account-settings-branding)することもできます。 - `icon`: Checkout ページのヘッダーにあるビジネス名の横に表示されます。 - `logo`: Checkout ページのヘッダーで、アイコンとビジネス名の代わりに使用されます。 - `primary_color`: Checkout ページの背景色として使用されます。 - `secondary_color`: Checkout ページのボタンの色として使用されます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}} \ -u "<>:" \ -d "settings[branding][icon]"="{{FILE_ID}}" \ -d "settings[branding][logo]"="{{FILE_ID}}" \ --data-urlencode "settings[branding][primary_color]"="#663399" \ --data-urlencode "settings[branding][secondary_color]"="#4BB543" ``` [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) を使用して、事前構築した決済フォームをサイトに埋め込みます。この実装と、[Stripe の他の実装タイプとの比較](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 #### 導入作業 Complexity: 2/5 #### 接続方法のタイプ サイトに構築済みの決済フォームを埋め込む #### UI のカスタマイズ 限定的なカスタマイズ - 20 種類の事前設定されたフォント - 3 種類の事前設定された角丸の半径 - カスタムの背景色と枠線の色 - カスタムロゴ まず、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 (Checkout セッション)](https://docs.stripe.com/api/checkout/sessions.md) は、ラインアイテム、注文金額、注文通貨など、オンライン支払いフォームで顧客に表示される内容を制御します。サーバー側のエンドポイントで Checkout セッションを作成します (例: `/create-checkout-session`)。レスポンスには、次のステップで Checkout のマウントに使用される `client_secret` が含まれています。 #### 支払い先 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/checkout/return?session_id={CHECKOUT_SESSION_ID}" ``` | パラメーター | 説明 | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [payment_intent_data[transfer_data][destination]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-transfer_data-destination) | デスティネーション支払いであることを示しています。デスティネーション支払いでは、支払いがプラットフォームで処理され、売上が即時かつ自動的に連結アカウントの保留中の残高に送金されます。 | | [line_items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) | 顧客が購入しようとしているアイテムを表します。このアイテムは Stripe がホストする Checkout ページに表示されます。 | | [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) | 顧客が支払いを完了した後にリダイレクトされる URL。値 `{CHECKOUT_SESSION_ID}` を使用して Checkout セッションを取得し、ステータスを調べて顧客に表示する内容を決定します。戻り URL が支払いのステータスを提供する Web サイト上のページに対応していることを確認してください。[カスタムクエリパラメーター](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form) を追加することもできます。これはリダイレクトプロセス全体にわたって存続します。 | | [payment_intent_data[application_fee_amount]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-application_fee_amount) | プラットフォームが取引で受け取る予定の金額。支払いがキャプチャーされると、プラットフォームから、`transfer_data[destination]` で指定された連結アカウントに支払い金額の全額が即時送金されます。その後 `application_fee_amount` がプラットフォームに返金され、プラットフォームの金額から Stripe 手数料が差し引かれます。 | (See full diagram at https://docs.stripe.com/connect/destination-charges) デスティネーション支払いを実行する場合、Checkout ではプラットフォームアカウントのブランド設定を使用します。詳細については、[ブランディングをカスタマイズする](https://docs.stripe.com/connect/destination-charges.md#branding)をご覧ください。 #### 以下の代理として `on_behalf_of` パラメーターに連結アカウントの ID (デフォルトではプラットフォーム) を設定して、デスティネーション支払いを作成します。`on_behalf_of` パラメーターは、[売上処理加盟店](https://docs.stripe.com/connect/destination-charges.md#settlement-merchant)を決定し、これは次の項目に影響します。 - 顧客に表示する明細書表記 - 顧客に表示する住所と電話番号 - 支払いの売上処理通貨 - 顧客に表示する [Checkout ページのブランディング](https://docs.stripe.com/connect/destination-charges.md#branding) ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[on_behalf_of]"="{{CONNECTEDACCOUNT_ID}}" \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode return_url="https://example.com/return?session_id={CHECKOUT_SESSION_ID}" ``` | パラメーター | 説明 | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [payment_intent_data[on_behalf_of]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-on_behalf_of) | このパラメーターにより、売上処理加盟店を決定します。パラメーターが渡されない場合、デフォルトではプラットフォームになります。 | | [payment_intent_data[transfer_data][destination]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-transfer_data-destination) | デスティネーション支払いであることを示しています。デスティネーション支払いでは、支払いがプラットフォームで処理され、売上が即時かつ自動的に連結アカウントの保留中の残高に送金されます。 | | [line_items](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items) | 顧客が購入しようとしているアイテムを表します。このアイテムは Stripe がホストする決済ページに表示されます。 | | [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) | 顧客が支払いを完了した後にリダイレクトされる URL。値 `{CHECKOUT_SESSION_ID}` を使用して Checkout セッションを取得し、ステータスを調べて顧客に表示する内容を決定します。戻り URL が支払いのステータスを提供する Web サイト上のページに対応していることを確認してください。[カスタムクエリパラメーター](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form) を追加することもできます。これはリダイレクトプロセス全体にわたって存続します。 | | [payment_intent_data[application_fee_amount]](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_intent_data-application_fee_amount) | プラットフォームが取引で受け取る予定の金額。支払いがキャプチャーされると、プラットフォームから、`transfer_data[destination]` で指定された連結アカウントに支払い金額の全額が即時送金されます。その後 `application_fee_amount` がプラットフォームに返金され、プラットフォームの金額から Stripe 手数料が差し引かれます。 | (See full diagram at https://docs.stripe.com/connect/destination-charges) ## Checkout をマウントする [クライアント側] #### HTML + JS Checkout は [Stripe.js](https://docs.stripe.com/js.md) の一部として利用できます。HTML ファイルのヘッダーに Stripe.js スクリプトを追加してページに含めます。次に、マウンティングに使用する空の DOM ノード (コンテナー) を作成します。 ```html
``` 公開可能な API キーを使用して Stripe.js を初期化します。Checkout インスタンスを作成するときに、前のステップの `client_secret` を `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.initEmbeddedCheckout({ fetchClientSecret, }); // Mount Checkout checkout.mount('#checkout'); } ``` #### React Connect.js と React Connect.js のライブラリを [npm のパブリックレジストリー](https://www.npmjs.com/package/@stripe/react-connect-js)からインストールします。 ```bash npm install --save @stripe/connect-js @stripe/react-connect-js ``` オンライン決済フォームコンポーネントを使用するには、`EmbeddedCheckoutProvider` を作成します。公開可能な API キーを使用して `loadStripe` を呼び出し、返された `Promise` をプロバイダーに渡します。プロバイダーによって承認された `options` プロパティを使用して、前のステップの `client_secret` を渡します。 ```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('<>'); const App = ({clientSecret}) => { const options = {clientSecret}; return ( ) } ``` Checkout は、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe に表示されます。一部の支払い方法では、支払いを確定するために別のページにリダイレクトする必要があるため、Checkout を別の iframe 内に配置しないでください。 ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると Stripe は [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) イベントを送信します。[Webhook を使用してこのイベントを受信](https://docs.stripe.com/webhooks/quickstart.md)し、顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアント側では、コールバックの実行前に顧客がブラウザーのウィンドウを閉じたり、アプリケーションを終了したりする可能性があります。また、支払い方法によっては支払いの確定までに 2 ~ 14 日かかることがあります。自社の構築済みのシステムで非同期イベントをリッスンするように設定すると、一度の導入で複数の[支払い方法](https://stripe.com/payments/payment-methods-guide)に対応できるようになります。 Checkout で支払いを回収するときは、以下のすべてのイベントを処理することをお勧めします。 | イベント | 説明 | 次のステップ | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | ---------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout フォームを送信して、決済を正常に承認しました。 | 決済の成功または失敗の結果を待ちます。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | 顧客の決済が成功しました。 | 購入された商品やサービスのフルフィルメントを行います。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | 何らかの理由により決済が拒否されたか、失敗しました。 | 顧客にメールで連絡して、新たに注文するように依頼します。 | これらのイベントのすべてに、[Checkout Session (Checkout セッション)](https://docs.stripe.com/api/checkout/sessions.md) オブジェクトが含まれています。決済が成功すると、基となる *PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) の[ステータス](https://docs.stripe.com/payments/paymentintents/lifecycle.md)が `processing` から `succeeded` または失敗のステータスに変わります。 ## 実装内容をテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: その他の支払い方法を有効にする #### 支払い先 Stripe ダッシュボードの[支払い方法ページ](https://dashboard.stripe.com/settings/payment_methods)から、アカウントの支払い方法を設定します。カード支払い、Google Pay、Apple Pay はデフォルトで有効になっていますが、必要に応じて支払い方法を有効にしたり無効にしたりできます。連結アカウントは自身の支払い方法をカスタマイズできません。 顧客に決済フォームを表示する前に、Stripe は通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストを決定します。決済フォームでは、購入完了率の向上につながり、顧客の通貨と所在地に最も適した決済手段が優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューの下に隠れた状態になります。 #### 以下の代理として ダッシュボードの[連結アカウントの支払い方法を管理する](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)に移動して、連結アカウントで対応する支払い方法を設定します。デフォルトの設定に対する変更は、新規および既存のすべての連結アカウントに適用されます。 支払い方法の情報に関する次のリソースをご覧ください。 - [支払い方法ガイド](https://stripe.com/payments/payment-methods-guide#choosing-the-right-payment-methods-for-your-business)は、プラットフォームに適した支払い方法の選択に役立ちます。 - [アカウントのケイパビリティ](https://docs.stripe.com/connect/account-capabilities.md) を使用して、選択した決済手段が連結アカウントで機能することを確認します。 - Stripe プロダクトおよび決済フローに適した決済手段を選択できるよう、[決済手段とサポート対象のプロダクト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#product-support)に関する表をご確認ください。 支払い方法ごとに、次のいずれかのドロップダウンオプションを選択できます。 | | | | | **デフォルトで有効にする** | 連結アカウントは、決済フローでこの支払い方法に対応します。一部の支払い方法は、無効またはブロックされている可能性があります。これは、*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントが、設定ページで有効化する必要があるためです。 | | **デフォルトで無効にする** | 連結アカウントは、決済フローでこの支払い方法に対応しません。*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントに、自身の支払い方法を管理することを許可している場合、連結アカウントはこれを有効にすることができます。 | | **ブロック済み** | 連結アカウントは、決済フローでこの支払い方法に対応しません。連結アカウントに *Stripe ダッシュボードにアクセスして* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 | ![支払い方法のドロップダウンオプション。支払い方法ごとに選択可能なオプション (ブロック済み、デフォルトで有効にする、デフォルトで無効にする) を示します。](https://b.stripecdn.com/docs-statics-srv/assets/dropdowns.ef651d721d5939d81521dd34dde4577f.png) 支払い方法のオプション 支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。 ![保存ボタンをクリックした後に表示される、ユーザーが変更した内容のリストを含むダイアログ](https://b.stripecdn.com/docs-statics-srv/assets/dialog.a56ea7716f60db9778706790320d13be.png) 保存ダイアログ ### 連結アカウントによる支払い方法の管理を許可する Stripe では、連結アカウントが自身の支払い方法をカスタマイズできるようにすることをお勧めしています。このオプションを有効にすると、*Stripe ダッシュボードにアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)できる各連結アカウントは、[支払い方法](https://dashboard.stripe.com/settings/payment_methods)ページを表示および更新できるようになります。Stripe ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。 このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。 ![連結アカウントの所有者に支払い方法のカスタマイズを許可する際に選択するチェックボックスのスクリーンショット](https://b.stripecdn.com/docs-statics-srv/assets/checkbox.275bd35d2a025272f03af029a144e577.png) アカウントのカスタマイズのチェックボックス ### 支払い方法ケイパビリティ 連結アカウントが追加の支払い方法を受け入れられるようにするには、`Accounts` にアクティブな支払い方法のケイパビリティが必要です。 [連結アカウントの決済手段の管理](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)で決済手段に「デフォルトで有効にする」オプションを選択した場合、新規および既存の連結アカウントが確認要件を満たしていれば、Stripe は自動的に必要なケイパビリティをリクエストします。連結アカウントが要件を満たしていない場合、または直接制御したい場合は、ダッシュボードまたは API でケイパビリティを手動でリクエストできます。 ほとんどの決済手段の確認要件は `card_payments` ケイパビリティと同じですが、いくつかの制限と例外があります。[決済手段ケイパビリティ表](https://docs.stripe.com/connect/account-capabilities.md#payment-methods)には、追加の確認が必要な決済手段が一覧表示されます。 #### ダッシュボード ダッシュボードで[連結アカウントを見つけ](https://docs.stripe.com/connect/dashboard/managing-individual-accounts.md#finding-accounts)て、ケイパビリティを編集し、未対応の確認要件を確認します。 #### API 既存の連結アカウントについては、既存のケイパビリティを[リスト](https://docs.stripe.com/api/capabilities/list.md) して、追加のケイパビリティをリクエストする必要があるかどうかを判断できます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities \ -u "<>:" ``` 各連結アカウントのケイパビリティを[更新](https://docs.stripe.com/api/capabilities/update.md)して、追加のケイパビリティをリクエストします。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities/us_bank_account_ach_payments \ -u "<>:" \ -d requested=true ``` リクエストされたケイパビリティが有効になるまでに時間がかかる場合があります。ケイパビリティに有効化の要件がある場合は、レスポンスの `requirements` 配列にそれが含まれます。 ## 手数料を回収する 支払いが処理される際に、取引の全額を連結アカウントに送金するのではなく、プラットフォームが取引金額の一部を手数料という形で受け取ることを決定できます。手数料の料金体系は、次の 2 つの方法で設定できます。 - [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、プラットフォーム手数料の料金体系ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。 - 社内で料金体系ルールを設定し、[application_fee_amount](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-application_fee_amount) または [transfer_data[amount]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-transfer_data-amount) パラメーターを使用して、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接手数料を指定します。この方法で設定された手数料は、プラットフォーム料金設定ツールで指定された料金体系ロジックを上書きします。 #### application_fee_amount `application_fee_amount` を指定して支払いを作成すると、支払いのキャプチャー後に、支払いの総額が即座にプラットフォームから `transfer_data[destination]` アカウントに送金されます。その後、`application_fee_amount` (上限は支払い総額) がプラットフォームに送金されます。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[application_fee_amount]"=123 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode success_url="https://example.com/success" ``` プラットフォーム手数料が回収されると、[プラットフォーム手数料](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが作成されます。[ダッシュボード](https://dashboard.stripe.com/connect/application_fees)、[アプリケーション手数料](https://docs.stripe.com/api/application_fees/list.md)、または [Sigma](https://docs.stripe.com/stripe-data/how-sigma-works.md) でアプリケーション手数料のリストを表示できます。プラットフォーム手数料オブジェクトの `amount` プロパティを使用して、項目別の手数料レポートを作成することもできます。 `application_fee_amount` を使用する際には、以下の点に留意します。 - `application_fee_amount` は合計取引額が上限です。 - `application_fee_amount` は常に取引と同じ通貨で計算されます。 - プラットフォーム手数料は、連結アカウントの売上処理通貨と同じ通貨で *売上として処理* (When funds are available in your Stripe balance)されます。越境デスティネーション支払いの場合は、[プラットフォームの売上処理通貨と異なる](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)通貨になる場合があります。 - `application_fee_amount` がお客様のアカウントに送金された後に、お客様のプラットフォームが Stripe 手数料を支払います。 - 金額には追加の Stripe 手数料は適用されません。 - プラットフォームは埋め込みのプラットフォーム手数料レポートを使用して、[回収した手数料](https://dashboard.stripe.com/connect/application_fees)を照合できます。 - Stripe がオンラインで提供するダッシュボードや、[支払い詳細コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payment-details.md) などのコンポーネントでは、連結アカウントは合計金額とプラットフォーム手数料のどちらの金額も表示できます。 ### デスティネーション支払いでの資金のフロー 上記のコードでは、支払いの全額 (10.00 USD) が連結アカウントの保留残高に追加されます。`application_fee_amount` (1.23 USD) はその支払い金額から差し引かれ、お客様のプラットフォームに送金されます。 次に Stripe 手数料 (0.59 USD) がプラットフォームアカウントの残高から差し引かれます。プラットフォーム手数料から Stripe 手数料を差し引いた金額 (1.23 USD - 0.59 USD = 0.64 USD) は、プラットフォームアカウントの残高に残ります。 ![デスティネーション支払いの売上のフロー](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_app_fee.c9ef81298155b38f986df02d0efa9167.png) 通常の Stripe 支払いからの売上と同様に、プラットフォームアカウントの通常の送金スケジュールで `application_fee_amount` が利用可能になります。 #### transfer_data[amount] `transfer_data[amount]` は `transfer_data[destination]` に送金される支払い金額を示す正の整数です。支払い金額からプラットフォームの手数料を差し引き、その計算結果を `transfer_data[amount]` として渡します。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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]"=1000 \ -d "line_items[0][quantity]"=1 \ -d "payment_intent_data[transfer_data][amount]"=877 \ -d "payment_intent_data[transfer_data][destination]"="{{CONNECTEDACCOUNT_ID}}" \ -d mode=payment \ -d ui_mode=embedded \ --data-urlencode success_url="https://example.com/success" ``` `transfer_data[amount]` を使用する際には、以下が適用されます。 - 金額は合計取引額が上限です。 - 金額は、常に取引と同じ通貨で計算されます。 - 金額は[プラットフォームの売上処理通貨と同じ通貨](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)で*売上として処理* (When funds are available in your Stripe balance)されます。 - 連結アカウントは、Stripe 上のオンラインダッシュボード (Stripe ダッシュボードや Express ダッシュボードなど) で支払いの合計額を確認することはできません。表示されるのは送金済みの金額のみです。 - プラットフォームが、支払いの Stripe 手数料を別途支払います。 - 金額には追加の Stripe 手数料は適用されません。 - 支払いの作成後に、レポート作成などの目的で[手数料を計算する](https://docs.stripe.com/stripe-data/query-all-fees-data.md#fees-paid-by-connected-accounts)場合、[PaymentIntent を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)して PaymentIntent の `amount` から `transfer_data[amount]` を差し引きます。 [プラットフォーム手数料額](https://docs.stripe.com/connect/destination-charges.md#application-fee)を使用して、支払いに関連付けられた明示的なプラットフォーム手数料を作成し、レポート作成を効率化することを検討してください。 ### 売上のフロー 上記のコードでは、支払い `amount` (10.00 USD) がプラットフォームアカウントの残高に追加されます。`transfer_data[amount]` (8.77 USD) がプラットフォームアカウントの残高から差し引かれ、連結アカウントの保留中の残高に追加されます。支払い `amount` (10.00 USD) から `transfer_data[amount]` (8.77 USD) と Stripe 手数料 (支払い `amount` に対する) を差し引いた正味金額 0.64 USD が、プラットフォームアカウントの保留中の残高に残ります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_amount.46cd59f6496607d68020b546aa1af85f.png) 通常の Stripe 支払いからの売上と同様に、連結アカウントの通常送金スケジュールで `transfer_data[amount]` が利用可能になます。 プラットフォームは、残高履歴エクスポートのデスティネーションプラットフォーム手数料列を調べることで `transfer_data[amount]` 支払いから確保する金額を追跡できます。 ## ブランディングをカスタマイズする プラットフォームと連結アカウントでは、ダッシュボードの[ブランディング設定](https://dashboard.stripe.com/account/branding)を使用して、支払いページのブランディングをカスタマイズできます。ダイレクト支払いの場合、Checkout は連結アカウントのブランド設定を使用します。 API を使用して[ブランディング設定を更新](https://docs.stripe.com/api/accounts/update.md#update_account-settings-branding)することもできます。 - `icon`: Checkout ページのヘッダーにあるビジネス名の横に表示されます。 - `logo`: Checkout ページのヘッダーで、アイコンとビジネス名の代わりに使用されます。 - `primary_color`: Checkout ページの背景色として使用されます。 - `secondary_color`: Checkout ページのボタンの色として使用されます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}} \ -u "<>:" \ -d "settings[branding][icon]"="{{FILE_ID}}" \ -d "settings[branding][logo]"="{{FILE_ID}}" \ --data-urlencode "settings[branding][primary_color]"="#663399" \ --data-urlencode "settings[branding][secondary_color]"="#4BB543" ``` [Stripe Elements](https://docs.stripe.com/payments/elements.md) を使用して、サイトに UI コンポーネントを埋め込むことでカスタムの決済システムを構築します。クライアント側とサーバー側のコードでさまざまな支払い方法を受け付ける決済フォームを構築します。この実装と、[Stripe のその他の実装タイプとの比較](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)をご覧ください。 #### 導入作業 Complexity: 3/5 #### 接続方法のタイプ カスタムの決済フローに UI コンポーネントを組み合わせる #### UI のカスタマイズ [Appearance API](https://docs.stripe.com/elements/appearance-api.md) による CSS レベルのカスタマイズ まず、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' ``` ## PaymentIntent を作成する [サーバー側] Stripe は [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md) オブジェクトを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して請求の実施と支払い状態の変化を追跡します。 このドキュメントで説明される決済の組み込みの概要。 (See full diagram at https://docs.stripe.com/connect/destination-charges) 購入プロセスで顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe によってダッシュボードの設定から支払い方法を自動的に取得することも、手動でリスト化することもできます。 貴社の構築済みのシステムで、決済手段の提供にコードベースのオプションを必要とする場合を除き、決済手段を手動でリスト化しないでください。Stripe は通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストを決定します。購入完了率の上昇につながり、使用通貨と顧客の所在地に最も適した決済手段が、優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューに隠された状態になります。 #### ダッシュボードで支払い方法を管理する サーバーで金額と通貨を有効にして PaymentIntent を作成します。最新バージョンの API では、Stripe はデフォルトで機能を有効にしているため、`automatic_payment_methods` パラメーターの指定は必要ありません。支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は、取引の金額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` #### 支払い方法を手動で一覧表示する サーバーで金額、通貨、支払い方法のタイプのリストを指定して PaymentIntent を作成します。決済金額は、クライアント側ではなく、常に信頼できる環境のサーバー側で指定してください。これにより、悪意のある顧客が金額を恣意的に選択できないようにします。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=eur \ -d "payment_method_types[]"=bancontact \ -d "payment_method_types[]"=card \ -d "payment_method_types[]"=eps \ -d "payment_method_types[]"=ideal \ -d "payment_method_types[]"=p24 \ -d "payment_method_types[]"=sepa_debit \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` 提供する決済手段に応じて通貨を選択します。一部の決済手段は複数の通貨と国に対応します。この例では、Bancontact、クレジットカード、EPS、iDEAL、Przelewy24、SEPA ダイレクトデビットを使用します。 > 各支払い方法は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各支払い方法を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[支払い方法の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)をご覧ください。 ### client secret を取得する PaymentIntent には、*client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) が含まれています。これは、支払いプロセスを安全に完了するためにクライアント側で使用されます。client secret をクライアント側に渡す際は、いくつかの方法を使用できます。 #### 1 ページのアプリケーション ブラウザーの `fetch` 関数を使用して、サーバーのエンドポイントから client secret を取得します。この方法は、クライアント側が 1 ページのアプリケーションで、特に React などの最新のフロントエンドフレームワークで構築されている場合に最適です。client secret を処理するサーバーのエンドポイントを作成します。 #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` その後、クライアント側で JavaScript を使用して client secret を取得します。 ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### サーバ側のレンダリング サーバーからクライアントに client secret を渡します。この方法は、アプリケーションがブラウザーへの送信前に静的なコンテンツをサーバーで生成する場合に最適です。 決済フォームに [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を追加します。サーバー側のコードで、PaymentIntent から client secret を取得します。 #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## 支払いの詳細を収集する [クライアント側] [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用してクライアント側で支払い詳細を収集します。Payment Element は事前構築された UI コンポーネントであり、さまざまな決済手段の詳細の収集をシンプルにします。 Payment Element には、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe が含まれています。一部の支払い方法では、支払いを確定するために別のページにリダイレクトする必要があるため、Payment Element を別の iframe 内に配置しないでください。 iframe を使用して Apple Pay または Google Pay を受け付けたい場合は、iframe の [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) 属性を `"payment *"` と等しく設定する必要があります。 構築済みのシステムを機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。HTTPS を使用しなくてもシステムをテストできますが、本番環境で決済を受け付ける準備が整ったら、必ず、HTTPS を[有効](https://docs.stripe.com/security/guide.md#tls)にしてください。 #### HTML + JS ### Stripe.js を設定する Payment Element は Stripe.js の機能として自動的に使用できるようになります。決済ページに Stripe.js スクリプトを含めるには、HTML ファイルの `head` にスクリプトを追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI 準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 ```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
``` 前のフォームが読み込まれたら、Payment Element のインスタンスを作成して、それをコンテナーの DOM ノードにマウントします。[Elements](https://docs.stripe.com/js/elements_object/create) インスタンスを作成する際に、前のステップからの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を `options` に渡します。 client secret は支払いを完了できるため、慎重に取り扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩することがないようにしてください。 ```javascript const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options); // 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 プロバイダーを支払いページに追加して設定する Payment Element コンポーネントを使用するには、決済ページコンポーネントを [Elements プロバイダー](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider)でラップします。公開キーを使用して `loadStripe` を呼び出し、返された `Promise` を `Elements` プロバイダーに渡します。加えて、前のステップの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を `options` にして `Elements` プロバイダーに渡します。 ```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 options = { // passing the client secret obtained in step 3 clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; 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 Elements は、ドロップイン UI コンポーネントのコレクションです。フォームをさらにカスタマイズしたり、その他の顧客情報を収集したりする場合は、[Elements のドキュメント](https://docs.stripe.com/payments/elements.md)をご覧ください。 Payment Element によって動的なフォームが表示され、顧客はここで支払い方法を選択できます。支払い方法ごとに、フォームでは、必要な支払いの詳細のすべてを入力するように顧客に自動的に求めます。 ### デザインをカスタマイズする `Elements` プロバイダーを作成する際に、[Appearance (デザイン) オブジェクト](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-appearance)を `options` に渡すことで、サイトのデザインに合わせて Payment Element をカスタマイズできます。 ### 住所を収集 デフォルトでは、Payment Element は必要な請求住所の詳細のみを収集します。[税金の計算](https://docs.stripe.com/api/tax/calculations/create.md)、配送先情報を入力するなどの一部の動作では、顧客の完全な住所が必要です。次のように対応できます。 - [Address Element](https://docs.stripe.com/elements/address-element.md) を使用して、オートコンプリートとローカリゼーションの機能を利用して、顧客の完全な住所を収集します。これにより、最も正確な税金計算が可能になります。 - 独自のカスタムフォームを使用して住所の詳細を収集する。 ### Apple Pay マーチャントトークンをリクエストする 連携機能を [Apple Pay 決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=checkout)ように設定している場合は、加盟店が開始する取引 (MIT) を有効にするために、Apple Pay インターフェイスがマーチャントトークンを返すように設定することをお勧めします。Payment Element で[関連するマーチャントトークンのタイプをリクエスト](https://docs.stripe.com/apple-pay/merchant-tokens.md?pay-element=web-pe)してください。 ## 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` に変わった場合は、顧客に再度支払いを試すように促します。 | ## 実装内容をテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### ウォレット | 決済手段 | シナリオ | テスト方法 | | ------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Alipay | 顧客はリダイレクトベースの[即時通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | BECS ダイレクトデビット | 顧客が BECS ダイレクトデビットによる支払いに成功しました。 | アカウント番号 `900123456` と BSB `000000` を使用して、フォームに入力します。確定された PaymentIntent のステータスは、まず `processing` に移行し、3 分後に `succeeded` ステータスに移行します。 | | BECS ダイレクトデビット | 顧客の支払いが `account_closed` エラーコードで失敗します。 | アカウント番号 `111111113`と BSB `000000`を使用して、フォームに入力します。 | | Bancontact、EPS、iDEAL、Przelewy24 | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | #### 店舗支払い | 決済手段 | シナリオ | テスト方法 | | ----------- | ------------------------------------- | ------------------------------------------------------------- | | Boleto、OXXO | 顧客が Boleto または OXXO で取引の詳細を使用して支払います。 | 支払い方法として Boleto または OXXO を選択し、支払いを送信します。ダイアログが表示されたら、それを閉じます。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: その他の支払い方法を有効にする #### 支払い先 Stripe ダッシュボードの[支払い方法ページ](https://dashboard.stripe.com/settings/payment_methods)から、アカウントの支払い方法を設定します。カード支払い、Google Pay、Apple Pay はデフォルトで有効になっていますが、必要に応じて支払い方法を有効にしたり無効にしたりできます。連結アカウントは自身の支払い方法をカスタマイズできません。 顧客に決済フォームを表示する前に、Stripe は通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストを決定します。決済フォームでは、購入完了率の向上につながり、顧客の通貨と所在地に最も適した決済手段が優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューの下に隠れた状態になります。 #### 以下の代理として ダッシュボードの[連結アカウントの支払い方法を管理する](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)に移動して、連結アカウントで対応する支払い方法を設定します。デフォルトの設定に対する変更は、新規および既存のすべての連結アカウントに適用されます。 支払い方法の情報に関する次のリソースをご覧ください。 - [支払い方法ガイド](https://stripe.com/payments/payment-methods-guide#choosing-the-right-payment-methods-for-your-business)は、プラットフォームに適した支払い方法の選択に役立ちます。 - [アカウントのケイパビリティ](https://docs.stripe.com/connect/account-capabilities.md) を使用して、選択した決済手段が連結アカウントで機能することを確認します。 - Stripe プロダクトおよび決済フローに適した決済手段を選択できるよう、[決済手段とサポート対象のプロダクト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#product-support)に関する表をご確認ください。 支払い方法ごとに、次のいずれかのドロップダウンオプションを選択できます。 | | | | | **デフォルトで有効にする** | 連結アカウントは、決済フローでこの支払い方法に対応します。一部の支払い方法は、無効またはブロックされている可能性があります。これは、*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントが、設定ページで有効化する必要があるためです。 | | **デフォルトで無効にする** | 連結アカウントは、決済フローでこの支払い方法に対応しません。*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントに、自身の支払い方法を管理することを許可している場合、連結アカウントはこれを有効にすることができます。 | | **ブロック済み** | 連結アカウントは、決済フローでこの支払い方法に対応しません。連結アカウントに *Stripe ダッシュボードにアクセスして* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 | ![支払い方法のドロップダウンオプション。支払い方法ごとに選択可能なオプション (ブロック済み、デフォルトで有効にする、デフォルトで無効にする) を示します。](https://b.stripecdn.com/docs-statics-srv/assets/dropdowns.ef651d721d5939d81521dd34dde4577f.png) 支払い方法のオプション 支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。 ![保存ボタンをクリックした後に表示される、ユーザーが変更した内容のリストを含むダイアログ](https://b.stripecdn.com/docs-statics-srv/assets/dialog.a56ea7716f60db9778706790320d13be.png) 保存ダイアログ ### 連結アカウントによる支払い方法の管理を許可する Stripe では、連結アカウントが自身の支払い方法をカスタマイズできるようにすることをお勧めしています。このオプションを有効にすると、*Stripe ダッシュボードにアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)できる各連結アカウントは、[支払い方法](https://dashboard.stripe.com/settings/payment_methods)ページを表示および更新できるようになります。Stripe ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。 このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。 ![連結アカウントの所有者に支払い方法のカスタマイズを許可する際に選択するチェックボックスのスクリーンショット](https://b.stripecdn.com/docs-statics-srv/assets/checkbox.275bd35d2a025272f03af029a144e577.png) アカウントのカスタマイズのチェックボックス ### 支払い方法ケイパビリティ 連結アカウントが追加の支払い方法を受け入れられるようにするには、`Accounts` にアクティブな支払い方法のケイパビリティが必要です。 [連結アカウントの決済手段の管理](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)で決済手段に「デフォルトで有効にする」オプションを選択した場合、新規および既存の連結アカウントが確認要件を満たしていれば、Stripe は自動的に必要なケイパビリティをリクエストします。連結アカウントが要件を満たしていない場合、または直接制御したい場合は、ダッシュボードまたは API でケイパビリティを手動でリクエストできます。 ほとんどの決済手段の確認要件は `card_payments` ケイパビリティと同じですが、いくつかの制限と例外があります。[決済手段ケイパビリティ表](https://docs.stripe.com/connect/account-capabilities.md#payment-methods)には、追加の確認が必要な決済手段が一覧表示されます。 #### ダッシュボード ダッシュボードで[連結アカウントを見つけ](https://docs.stripe.com/connect/dashboard/managing-individual-accounts.md#finding-accounts)て、ケイパビリティを編集し、未対応の確認要件を確認します。 #### API 既存の連結アカウントについては、既存のケイパビリティを[リスト](https://docs.stripe.com/api/capabilities/list.md) して、追加のケイパビリティをリクエストする必要があるかどうかを判断できます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities \ -u "<>:" ``` 各連結アカウントのケイパビリティを[更新](https://docs.stripe.com/api/capabilities/update.md)して、追加のケイパビリティをリクエストします。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities/us_bank_account_ach_payments \ -u "<>:" \ -d requested=true ``` リクエストされたケイパビリティが有効になるまでに時間がかかる場合があります。ケイパビリティに有効化の要件がある場合は、レスポンスの `requirements` 配列にそれが含まれます。 ## 手数料を回収する 支払いが処理される際に、取引の全額を連結アカウントに送金するのではなく、プラットフォームが取引金額の一部を手数料という形で受け取ることを決定できます。手数料の料金体系は、次の 2 つの方法で設定できます。 - [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、プラットフォーム手数料の料金体系ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。 - 社内で料金体系ルールを設定し、[application_fee_amount](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-application_fee_amount) または [transfer_data[amount]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-transfer_data-amount) パラメーターを使用して、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接手数料を指定します。この方法で設定された手数料は、プラットフォーム料金設定ツールで指定された料金体系ロジックを上書きします。 #### application_fee_amount `application_fee_amount` を指定して支払いを作成すると、支払いのキャプチャー後に、支払いの総額が即座にプラットフォームから `transfer_data[destination]` アカウントに送金されます。その後、`application_fee_amount` (上限は支払い総額) がプラットフォームに送金されます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` プラットフォーム手数料が回収されると、[プラットフォーム手数料](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが作成されます。[ダッシュボード](https://dashboard.stripe.com/connect/application_fees)、[アプリケーション手数料](https://docs.stripe.com/api/application_fees/list.md)、または [Sigma](https://docs.stripe.com/stripe-data/how-sigma-works.md) でアプリケーション手数料のリストを表示できます。プラットフォーム手数料オブジェクトの `amount` プロパティを使用して、項目別の手数料レポートを作成することもできます。 `application_fee_amount` を使用する際には、以下の点に留意します。 - `application_fee_amount` は合計取引額が上限です。 - `application_fee_amount` は常に取引と同じ通貨で計算されます。 - プラットフォーム手数料は、連結アカウントの売上処理通貨と同じ通貨で *売上として処理* (When funds are available in your Stripe balance)されます。越境デスティネーション支払いの場合は、[プラットフォームの売上処理通貨と異なる](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)通貨になる場合があります。 - `application_fee_amount` がお客様のアカウントに送金された後に、お客様のプラットフォームが Stripe 手数料を支払います。 - 金額には追加の Stripe 手数料は適用されません。 - プラットフォームは埋め込みのプラットフォーム手数料レポートを使用して、[回収した手数料](https://dashboard.stripe.com/connect/application_fees)を照合できます。 - Stripe がオンラインで提供するダッシュボードや、[支払い詳細コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payment-details.md) などのコンポーネントでは、連結アカウントは合計金額とプラットフォーム手数料のどちらの金額も表示できます。 ### デスティネーション支払いでの資金のフロー 上記のコードでは、支払いの全額 (10.00 USD) が連結アカウントの保留残高に追加されます。`application_fee_amount` (1.23 USD) はその支払い金額から差し引かれ、お客様のプラットフォームに送金されます。 次に Stripe 手数料 (0.59 USD) がプラットフォームアカウントの残高から差し引かれます。プラットフォーム手数料から Stripe 手数料を差し引いた金額 (1.23 USD - 0.59 USD = 0.64 USD) は、プラットフォームアカウントの残高に残ります。 ![デスティネーション支払いの売上のフロー](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_app_fee.c9ef81298155b38f986df02d0efa9167.png) 通常の Stripe 支払いからの売上と同様に、プラットフォームアカウントの通常の送金スケジュールで `application_fee_amount` が利用可能になります。 #### transfer_data[amount] `transfer_data[amount]` は `transfer_data[destination]` に送金される支払い金額を示す正の整数です。支払い金額からプラットフォームの手数料を差し引き、その計算結果を `transfer_data[amount]` として渡します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d "transfer_data[amount]"=877 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` `transfer_data[amount]` を使用する際には、以下が適用されます。 - 金額は合計取引額が上限です。 - 金額は、常に取引と同じ通貨で計算されます。 - 金額は[プラットフォームの売上処理通貨と同じ通貨](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)で*売上として処理* (When funds are available in your Stripe balance)されます。 - 連結アカウントは、Stripe 上のオンラインダッシュボード (Stripe ダッシュボードや Express ダッシュボードなど) で支払いの合計額を確認することはできません。表示されるのは送金済みの金額のみです。 - プラットフォームが、支払いの Stripe 手数料を別途支払います。 - 金額には追加の Stripe 手数料は適用されません。 - 支払いの作成後に、レポート作成などの目的で[手数料を計算する](https://docs.stripe.com/stripe-data/query-all-fees-data.md#fees-paid-by-connected-accounts)場合、[PaymentIntent を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)して PaymentIntent の `amount` から `transfer_data[amount]` を差し引きます。 [プラットフォーム手数料額](https://docs.stripe.com/connect/destination-charges.md#application-fee)を使用して、支払いに関連付けられた明示的なプラットフォーム手数料を作成し、レポート作成を効率化することを検討してください。 ### 売上のフロー 上記のコードでは、支払い `amount` (10.00 USD) がプラットフォームアカウントの残高に追加されます。`transfer_data[amount]` (8.77 USD) がプラットフォームアカウントの残高から差し引かれ、連結アカウントの保留中の残高に追加されます。支払い `amount` (10.00 USD) から `transfer_data[amount]` (8.77 USD) と Stripe 手数料 (支払い `amount` に対する) を差し引いた正味金額 0.64 USD が、プラットフォームアカウントの保留中の残高に残ります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_amount.46cd59f6496607d68020b546aa1af85f.png) 通常の Stripe 支払いからの売上と同様に、連結アカウントの通常送金スケジュールで `transfer_data[amount]` が利用可能になます。 プラットフォームは、残高履歴エクスポートのデスティネーションプラットフォーム手数料列を調べることで `transfer_data[amount]` 支払いから確保する金額を追跡できます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-overview.9e0d68d009dc005f73a6f5df69e00458.png) [PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) クラスを使用して、Stripe の構築済み決済 UI を iOS アプリの決済フローに組み込みます。[GitHub](https://github.com/stripe/stripe-ios/tree/master/Example/PaymentSheet%20Example) のサンプル実装をご覧ください。 ## Stripe を設定する [サーバー側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録してください](https://dashboard.stripe.com/register)。 ### サーバー側 この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから 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' ``` ### クライアント側 [Stripe iOS SDK](https://github.com/stripe/stripe-ios) はオープンソースです。[詳細なドキュメントが提供されており](https://stripe.dev/stripe-ios/index.html)、iOS 13 以降をサポートするアプリと互換性があります。 #### Swift Package Manager SDK をインストールするには、以下のステップに従います。 1. Xcode で、**File (ファイル)** > **Add Package Dependencies… (パッケージ依存関係を追加)** を選択し、リポジトリー URL として `https://github.com/stripe/stripe-ios-spm` を入力します。 1. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。 1. **StripePaymentSheet** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。 #### CocoaPods 1. まだインストールしていない場合は、[CocoaPods](https://guides.cocoapods.org/using/getting-started.html) の最新バージョンをインストールします。 1. 既存の [Podfile](https://guides.cocoapods.org/syntax/podfile.html) がない場合は、以下のコマンドを実行して作成します。 ```bash pod init ``` 1. この行を `Podfile` に追加します。 ```podfile pod 'StripePaymentSheet' ``` 1. 以下のコマンドを実行します。 ```bash pod install ``` 1. これ以降は、Xcode でプロジェクトを開く際に、`.xcodeproj` ファイルではなく、必ず `.xcworkspace` ファイルを使用するということを忘れないでください。 1. 今後、SDK の最新バージョンに更新するには、以下を実行します。 ```bash pod update StripePaymentSheet ``` #### Carthage 1. まだインストールしていない場合は、[Carthage](https://github.com/Carthage/Carthage#installing-carthage) の最新バージョンをインストールします。 1. この行を `Cartfile` に追加します。 ```cartfile github "stripe/stripe-ios" ``` 1. [Carthage のインストール手順](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos)に従います。必ず、[こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentSheet/README.md#manual-linking)にリストされている必要なフレームワークのすべてを埋め込んでください。 1. 今後、SDK の最新バージョンに更新するには、以下のコマンドを実行します。 ```bash carthage update stripe-ios --platform ios ``` #### 手動のフレームワーク 1. Stripe の [GitHub リリースページ](https://github.com/stripe/stripe-ios/releases/latest)に移動して、**Stripe.xcframework.zip** をダウンロードして解凍します。 1. **StripePaymentSheet.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。 1. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentSheet/README.md#manual-linking)にリストされている必要なフレームワークのすべてに対して、ステップ 2 を繰り返します。 1. 今後、Stripe の SDK の最新バージョンに更新するには、ステップ 1 から 3 を繰り返します。 > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases (リリース)](https://github.com/stripe/stripe-ios/releases) ページをご覧ください。リポジトリの[リリースをウォッチ](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository)して、新しいリリースの公開時に通知を受け取ることも可能です。 アプリの起動時に Stripe [公開可能キー](https://dashboard.stripe.com/test/apikeys)を使用して SDK を設定します。これにより、アプリが Stripe API にリクエストを送信できるようになります。 #### Swift ```swift import UIKitimportStripePaymentSheet @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {StripeAPI.defaultPublishableKey = "<>" // do any other necessary launch configuration return true } } ``` > テストおよび開発時には[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 ## エンドポイントを追加する [サーバー側] > #### 注 > > PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。 1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。 1. (オプション) [Customer (顧客)](https://docs.stripe.com/api/customers.md): 今後の支払いに備えて決済手段を設定するには、決済手段を*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付ける必要があります。Customer オブジェクトは、顧客がビジネスでアカウントを作成するときに作成します。顧客がゲストとして支払いを行う場合は、支払いの前に Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントを表す内部表現に関連付けることができます。 1. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): Customer オブジェクトの情報は機密情報であるため、アプリから直接取得することはできません。CustomerSession により、SDK に Customer への範囲を設定した一時的なアクセス権が付与され、また追加の設定オプションが提供されます。すべての[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)のリストをご覧ください。 > Customer にカードを保存したことがなく、リピート顧客に保存されたカードの再利用を許可しない場合は、実装で Customer オブジェクトおよび CustomerSession オブジェクトを省略できます。 セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。 1. Customer を取得するか、新規作成する。 1. 顧客の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。 1. [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount)、[currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency)、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を指定して PaymentIntent を作成します。 1. PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer))、CustomerSession の `client_secret`、Customer の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id)、および貴社の[公開可能キー](https://dashboard.stripe.com/apikeys)をアプリに返します。 決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。 構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。 #### ダッシュボードで支払い方法を管理する 支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。PaymentIntent は、ダッシュボードで設定された支払い方法を使用して作成されます。ダッシュボードを使用しない場合や、支払い方法を手動で指定する場合は、`payment_method_types` 属性を使用して支払い方法を一覧表示することができます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount="123" \ -d "transfer_data[destination]"="{{CONNECTED_ACCOUNT_ID}}" \ ``` #### 支払い方法を手動で一覧表示する #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "payment_method_types[]"="bancontact" \ -d "payment_method_types[]"="card" \ -d "payment_method_types[]"="ideal" \ -d "payment_method_types[]"="klarna" \ -d "payment_method_types[]"="sepa_debit" \ -d application_fee_amount="123" \ -d "transfer_data[destination]"="{{CONNECTED_ACCOUNT_ID}}" \ ``` > 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。 ## 決済画面を導入する [クライアント側] 決済画面に Mobile Payment Element を表示するには、必ず以下を行ってください。 - 顧客が購入している商品を合計金額とともに表示する - [Address Element](https://docs.stripe.com/elements/address-element.md?platform=ios) を使用して、必要な配送先情報を顧客から収集する - Stripe の UI を表示する購入ボタンを追加する #### UIKit アプリの Checkout 画面で、前のステップで作成したエンドポイントから PaymentIntent の client Secret、CustomerSession の client Secret、顧客 ID、公開可能キーを取得します。`STPAPIClient.shared` を使用して公開可能キーを設定し、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) を初期化します。 #### iOS (Swift) ```swift import UIKit@_spi(CustomerSessionBetaAccess) import StripePaymentSheet class CheckoutViewController: UIViewController { @IBOutlet weak var checkoutButton: UIButton! var paymentSheet: PaymentSheet? let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint override func viewDidLoad() { super.viewDidLoad() checkoutButton.addTarget(self, action: #selector(didTapCheckoutButton), for: .touchUpInside) checkoutButton.isEnabled = false // MARK: Fetch the PaymentIntent client secret, CustomerSession client secret, Customer ID, and publishable key var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerId = json["customer"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, let paymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey// MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. configuration.allowsDelayedPaymentMethods = true self.paymentSheet = PaymentSheet(paymentIntentClientSecret:paymentIntentClientSecret, configuration: configuration) DispatchQueue.main.async { self.checkoutButton.isEnabled = true } }) task.resume() } } ``` 顧客が**購入**ボタンをタップしたら、`present` を呼び出して PaymentSheet を表示します。顧客が支払いを完了したら、Stripe は PaymentSheet を閉じ、[PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) とともに完了ブロックを呼び出します。 #### iOS (Swift) ```swift @objc func didTapCheckoutButton() { // MARK: Start the checkout process paymentSheet?.present(from: self) { paymentResult in // MARK: Handle the payment result switch paymentResult { case .completed: print("Your order is confirmed") case .canceled: print("Canceled!") case .failed(let error): print("Payment failed: \(error)") } } } ``` #### SwiftUI 決済画面用の `ObservableObject` モデルを作成します。このモデルは、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) と [PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) を公開します。 ```swift import StripePaymentSheet import SwiftUI class CheckoutViewModel: ObservableObject { let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint @Published var paymentSheet: PaymentSheet? @Published var paymentResult: PaymentSheetResult? } ``` 前のステップで作成したエンドポイントから PaymentIntent の client secret、CustomerSession の client secret、顧客 ID、公開可能キーを取得します。`STPAPIClient.shared` を使用して公開可能キーを設定し、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) を初期化します。 ```swift @_spi(CustomerSessionBetaAccess) import StripePaymentSheet import SwiftUI class CheckoutViewModel: ObservableObject { let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint @Published var paymentSheet: PaymentSheet? @Published var paymentResult: PaymentSheetResult? func preparePaymentSheet() { // MARK: Fetch thePaymentIntent and Customer information from the backend var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerId = json["customer"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, letpaymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey// MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. configuration.allowsDelayedPaymentMethods = true DispatchQueue.main.async { self.paymentSheet = PaymentSheet(paymentIntentClientSecret:paymentIntentClientSecret, configuration: configuration) } }) task.resume() } } struct CheckoutView: View { @ObservedObject var model = CheckoutViewModel() var body: some View { VStack { if model.paymentSheet != nil { Text("Ready to pay.") } else { Text("Loading…") } }.onAppear { model.preparePaymentSheet() } } } ``` [PaymentSheet.PaymentButton](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/PaymentButton.html) を `View` に追加します。これは、SwiftUI の `Button` と同様に動作し、`View` を追加することでカスタマイズされます。ボタンをタップすると PaymentSheet が表示されます。支払いが完了すると、Stripe は PaymentSheet を閉じ、[PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) オブジェクトとともに `onCompletion` ハンドラが呼び出されます。 ```swift @_spi(CustomerSessionBetaAccess) import StripePaymentSheet import SwiftUI class CheckoutViewModel: ObservableObject { let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint @Published var paymentSheet: PaymentSheet? @Published var paymentResult: PaymentSheetResult? func preparePaymentSheet() { // MARK: Fetch the PaymentIntent and Customer information from the backend var request = URLRequest(url: backendCheckoutUrl) request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let customerId = json["customer"] as? String, let customerSessionClientSecret = json["customerSessionClientSecret"] as? String, let paymentIntentClientSecret = json["paymentIntent"] as? String, let publishableKey = json["publishableKey"] as? String, let self = self else { // Handle error return } STPAPIClient.shared.publishableKey = publishableKey // MARK: Create a PaymentSheet instance var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) // Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods // that complete payment after a delay, like SEPA Debit and Sofort. configuration.allowsDelayedPaymentMethods = true DispatchQueue.main.async { self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) } }) task.resume() } func onPaymentCompletion(result: PaymentSheetResult) { self.paymentResult = result } } struct CheckoutView: View { @ObservedObject var model = CheckoutViewModel() var body: some View { VStack {if let paymentSheet = model.paymentSheet { PaymentSheet.PaymentButton( paymentSheet: paymentSheet, onCompletion: model.onPaymentCompletion ) { Text("Buy") } } else { Text("Loading…") }if let result = model.paymentResult { switch result { case .completed: Text("Payment complete") case .failed(let error): Text("Payment failed: \(error.localizedDescription)") case .canceled: Text("Payment canceled.") } } }.onAppear { model.preparePaymentSheet() } } } ``` `PaymentSheetResult` が `.completed` の場合は、ユーザーに通知します (注文確認画面を表示するなど)。 `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## 戻り先 URL を設定する [クライアント側] 顧客はお客様のアプリから離れて、(Safari やバンキングアプリなどで) 認証する場合があります。ユーザーが認証後にアプリに自動的に戻れるようにするには、[カスタム URL スキームを構成](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)し、URL を SDK に転送するようにアプリのデリゲートを設定します。Stripe は[ユニバーサルリンク](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content)には対応していません。 #### SceneDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } let stripeHandled = StripeAPI.handleURLCallback(with: url) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } ``` #### AppDelegate #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } return false } ``` #### SwiftUI #### Swift ```swift @main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!").onOpenURL { incomingURL in let stripeHandled = StripeAPI.handleURLCallback(with: incomingURL) if (!stripeHandled) { // This was not a Stripe url – handle the URL normally as you would } } } } } ``` ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると、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` に変わった場合は、顧客に再度支払いを試すように促します。 | ## 実装内容をテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ---------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Bancontact、iDEAL | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## カードの読み取りを有効にする iOS をサポートするカードスキャン機能を有効にするには、アプリケーションの `Info.plist` の `NSCameraUsageDescription` (**プライバシー - カメラ利用の詳細**)を設定し、カメラにアクセスする理由を入力して下さい (例:「カードをスキャンするため」)。 ## Optional: Apple Pay を有効にする > 決済画面に専用の **Apple Pay** ボタンがある場合は、[Apple Pay ガイド](https://docs.stripe.com/apple-pay.md#present-payment-sheet)に従い、`ApplePayContext` を使用して Apple Pay ボタンからの支払いを回収します。その他の種類の支払い方法を処理するには、`PaymentSheet` を使用できます。 ### Apple 加盟店 ID を登録する Apple Developer Web サイトで [新規 ID を登録](https://developer.apple.com/account/resources/identifiers/add/merchant) して、Apple 加盟店 ID を取得します。 フォームに説明と ID を入力します。説明はお客様の記録用であり、後で変更できます。アプリの名前を ID として使用することをお勧めします (`merchant.com.{{YOUR_APP_NAME}}` など)。 ### 新しい Apple Pay 証明書を作成する 支払いデータを暗号化するためのアプリの証明書を作成します。 ダッシュボードの [iOS certificate settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、**新規アプリケーションを追加**をクリックし、表示されるガイドに従います。 証明書署名リクエスト (CSR) ファイルをダウンロードして、Apple Pay の利用を可能にする安全な証明書を Apple から取得します。 1 つの CSR ファイルを使用して証明書を 1 つだけ発行する必要があります。Apple 加盟店 ID を切り替えた場合、ダッシュボードの [iOS Certificate Settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、新しい CSR と証明書を取得する必要があります。 ### Xcode を使用して組み込む Apple Pay ケイパビリティをアプリに追加します。Xcode でプロジェクト設定を開き、**Signing & Capabilities (署名およびケイパビリティ)** タブを選択して、**Apple Pay** ケイパビリティを追加します。この段階で開発者アカウントへのログインを要求される場合があります。前の手順で作成した加盟店 ID を選択すると、アプリで Apple Pay を受け付けられるようになります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/xcode.a701d4c1922d19985e9c614a6f105bf1.png) Xcode で Apple Pay ケイパビリティを有効化する ### Apple Pay を追加する #### 1 回限りの支払い Apple Pay を PaymentSheet に追加するには、Apple 加盟店 ID と[お客様のビジネスの国コード](https://dashboard.stripe.com/settings/account)で `PaymentSheet.Configuration` を初期化してから、[applePay](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV8applePayAC05ApplefD0VSgvp) を設定します。 #### iOS (Swift) ```swift var configuration = PaymentSheet.Configuration() configuration.applePay = .init( merchantId: "merchant.com.your_app_name", merchantCountryCode: "US" ) ``` #### 継続支払い Apple Pay を PaymentSheet に追加するには、Apple 加盟店 ID と[お客様のビジネスの国コード](https://dashboard.stripe.com/settings/account)で `PaymentSheet.Configuration` を初期化してから、[applePay](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV8applePayAC05ApplefD0VSgvp) を設定します。 継続支払いに関する [Apple のガイドライン](https://developer.apple.com/design/human-interface-guidelines/apple-pay#Supporting-subscriptions)に従い、`PKPaymentRequest` で追加の属性を設定する必要もあります。[ApplePayConfiguration.paymentRequestHandlers](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/applepayconfiguration/handlers/paymentrequesthandler) にハンドラーを追加して、請求する予定の金額 (たとえば月額 9.95 USD) を指定して [PKPaymentRequest.paymentSummaryItems](https://developer.apple.com/documentation/passkit/pkpaymentrequest/1619231-paymentsummaryitems) を設定します。 `PKPaymentRequest` で `recurringPaymentRequest` または `automaticReloadPaymentRequest` プロパティを設定することで、[加盟店トークン](https://developer.apple.com/apple-pay/merchant-tokens/)を導入することもできます。 Apple Pay で継続支払いを使用する方法の詳細については、[Apple の PassKit に関するドキュメント](https://developer.apple.com/documentation/passkit/pkpaymentrequest)をご覧ください。 #### iOS (Swift) ```swift let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( paymentRequestHandler: { request in // PKRecurringPaymentSummaryItem is available on iOS 15 or later if #available(iOS 15.0, *) { let billing = PKRecurringPaymentSummaryItem(label: "My Subscription", amount: NSDecimalNumber(string: "59.99")) // Payment starts today billing.startDate = Date() // Payment ends in one year billing.endDate = Date().addingTimeInterval(60 * 60 * 24 * 365) // Pay once a month. billing.intervalUnit = .month billing.intervalCount = 1 // recurringPaymentRequest is only available on iOS 16 or later if #available(iOS 16.0, *) { request.recurringPaymentRequest = PKRecurringPaymentRequest(paymentDescription: "Recurring", regularBilling: billing, managementURL: URL(string: "https://my-backend.example.com/customer-portal")!) request.recurringPaymentRequest?.billingAgreement = "You'll be billed $59.99 every month for the next 12 months. To cancel at any time, go to Account and click 'Cancel Membership.'" } request.paymentSummaryItems = [billing] request.currencyCode = "USD" } else { // On older iOS versions, set alternative summary items. request.paymentSummaryItems = [PKPaymentSummaryItem(label: "Monthly plan starting July 1, 2022", amount: NSDecimalNumber(string: "59.99"), type: .final)] } return request } ) var configuration = PaymentSheet.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers) ``` ### 注文の追跡 iOS 16 以降で[注文の追跡](https://developer.apple.com/design/human-interface-guidelines/technologies/wallet/designing-order-tracking)情報を追加するには、`PaymentSheet.ApplePayConfiguration.Handlers` で [authorizationResultHandler](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/applepayconfiguration/handlers/authorizationresulthandler) を設定します。支払いの完了後、Stripe は iOS が Apple Pay の決済画面を閉じる前に実装を呼び出します。 `authorizationResultHandler` の実装で、完了した注文の注文の詳細をサーバーから取得します。提供された [PKPaymentAuthorizationResult](https://developer.apple.com/documentation/passkit/pkpaymentauthorizationresult) に詳細を追加し、変更された結果を返します。 注文の追跡の詳細については、[Apple のウォレットでの注文に関するドキュメント](https://developer.apple.com/documentation/walletorders)をご覧ください。 #### iOS (Swift) ```swift let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( authorizationResultHandler: { result in do { // Fetch the order details from your service let myOrderDetails = try await MyAPIClient.shared.fetchOrderDetails(orderID: orderID) result.orderDetails = PKPaymentOrderDetails( orderTypeIdentifier: myOrderDetails.orderTypeIdentifier, // "com.myapp.order" orderIdentifier: myOrderDetails.orderIdentifier, // "ABC123-AAAA-1111" webServiceURL: myOrderDetails.webServiceURL, // "https://my-backend.example.com/apple-order-tracking-backend" authenticationToken: myOrderDetails.authenticationToken) // "abc123" // Return your modified PKPaymentAuthorizationResult return result } catch { return PKPaymentAuthorizationResult(status: .failure, errors: [error]) } } ) var configuration = PaymentSheet.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers) ``` ## Optional: 画面をカスタマイズする カスタマイズはすべて、[PaymentSheet.Configuration](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) オブジェクトで設定されます。 ### デザイン Customize colors, fonts, and so on to match the look and feel of your app by using the [appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=ios). ### 決済手段のレイアウト [paymentMethodLayout](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/configuration-swift.struct/paymentmethodlayout) を使用して、画面上の決済手段のレイアウトを設定します。横や縦に表示することも、Stripe がレイアウトを自動で最適化するように設定することもできます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-mpe-payment-method-layouts.9d0513e2fcec5660378ba1824d952054.png) #### Swift ```swift var configuration = PaymentSheet.Configuration() configuration.paymentMethodLayout = .automatic ``` ### ユーザーの住所を収集する [Address Element](https://docs.stripe.com/elements/address-element.md?platform=ios) を使用して、顧客から国内および国外の配送先住所や請求先住所を収集します。 ### 加盟店の表示名 [merchantDisplayName](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:18StripePaymentSheet0bC0C13ConfigurationV19merchantDisplayNameSSvp) を設定し、顧客に表示するビジネス名を指定します。デフォルトではアプリ名になります。 #### Swift ```swift var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "My app, Inc." ``` ### ダークモード `PaymentSheet` は、ユーザーのシステム全体の表示設定 (ライト / ダークモード) に合わせて自動的に調整されます。アプリがダークモードに対応していない場合は、[style](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:18StripePaymentSheet0bC0C13ConfigurationV5styleAC18UserInterfaceStyleOvp) を `alwaysLight` または `alwaysDark` モードに設定できます。 ```swift var configuration = PaymentSheet.Configuration() configuration.style = .alwaysLight ``` ### デフォルトの請求詳細 支払い画面で収集される請求詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティーを設定します。`PaymentSheet` の各フィールドに、指定したそれらの値が事前に読み込まれます。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.address.country = "US" configuration.defaultBillingDetails.email = "foo@bar.com" ``` ### 請求の詳細の収集 `billingDetailsCollectionConfiguration` を使用して、決済画面で請求の詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 支払い方法で必須の請求詳細のみを収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を true に設定します。その場合、`PaymentSheet.Configuration.defaultBillingDetails` が支払い方法の[請求詳細](https://docs.stripe.com/api/payment_methods/object.md?lang=node#payment_method_object-billing_details)として設定されます。 支払い方法で必ずしも必須ではない追加の請求詳細を収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を false に設定します。 その場合、`PaymentSheet` で収集した請求詳細が支払い方法の請求詳細として設定されます。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.email = "foo@bar.com" configuration.billingDetailsCollectionConfiguration.name = .always configuration.billingDetailsCollectionConfiguration.email = .never configuration.billingDetailsCollectionConfiguration.address = .full configuration.billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod = true ``` > 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。 ## Optional: UI で支払いを完了する 支払い方法の詳細を収集するためにのみ支払い画面を表示して、後で `confirm` メソッドを呼び出して、アプリの UI で支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-multi-step.cd631ea4f1cd8cf3f39b6b9e1e92b6c5.png) アプリの UI で支払いを完了する #### UIKit 以下のステップでは、アプリの UI で支払いを完了する方法を説明します。[GitHub](https://github.com/stripe/stripe-ios/blob/master/Example/PaymentSheet%20Example/PaymentSheet%20Example/ExampleCustomCheckoutViewController.swift) でサンプルの実装をご覧下さい。 1. 最初に、`PaymentSheet` ではなく、[PaymentSheet.FlowController](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller) を初期化し、その `paymentOption` プロパティで UI を更新します。このプロパティには、顧客が最初に選択したデフォルトの支払い方法を表す画像とラベルが含まれています。 ```swift PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in switch result { case .failure(let error): print(error) case .success(let paymentSheetFlowController): self?.paymentSheetFlowController = paymentSheetFlowController // Update your UI using paymentSheetFlowController.paymentOption } } ``` 1. 次に、`presentPaymentOptions` を呼び出し、支払いの詳細を収集します。完了したら、`paymentOption` プロパティで再度 UI を更新します。 ```swift paymentSheetFlowController.presentPaymentOptions(from: self) { // Update your UI using paymentSheetFlowController.paymentOption } ``` 1. 最後に、`confirm` を呼び出します。 ```swift paymentSheetFlowController.confirm(from: self) { paymentResult in // MARK: Handle the payment result switch paymentResult { case .completed: print("Payment complete!") case .canceled: print("Canceled!") case .failed(let error): print(error) } } ``` #### SwiftUI 以下のステップでは、アプリの UI で支払いを完了する方法を説明します。[GitHub](https://github.com/stripe/stripe-ios/blob/master/Example/PaymentSheet%20Example/PaymentSheet%20Example/ExampleSwiftUICustomPaymentFlow.swift) でサンプルの実装をご覧下さい。 1. 最初に、`PaymentSheet` ではなく、[PaymentSheet.FlowController](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller) を初期化します。その `paymentOption` プロパティには、顧客が現在選択している支払い方法を表す画像とラベルが含まれており、これを UI で使用することができます。 ```swift PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in switch result { case .failure(let error): print(error) case .success(let paymentSheetFlowController): self?.paymentSheetFlowController = paymentSheetFlowController // Use the paymentSheetFlowController.paymentOption properties in your UI myPaymentMethodLabel = paymentSheetFlowController.paymentOption?.label ?? "Select a payment method" myPaymentMethodImage = paymentSheetFlowController.paymentOption?.image ?? UIImage(systemName: "square.and.pencil")! } } ``` 1. [PaymentSheet.FlowController.PaymentOptionsButton](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/paymentoptionsbutton) を使用して、支払いの詳細を収集するための画面を表示するボタンをラップします。`PaymentSheet.FlowController` が `onSheetDismissed` 引数を呼び出すと、`PaymentSheet.FlowController` インスタンスの `paymentOption` に現在選択されている支払い方法が反映されます。 ```swift PaymentSheet.FlowController.PaymentOptionsButton( paymentSheetFlowController: paymentSheetFlowController, onSheetDismissed: { myPaymentMethodLabel = paymentSheetFlowController.paymentOption?.label ?? "Select a payment method" myPaymentMethodImage = paymentSheetFlowController.paymentOption?.image ?? UIImage(systemName: "square.and.pencil")! }, content: { /* An example button */ HStack { Text(myPaymentMethodLabel) Image(uiImage: myPaymentMethodImage) } } ) ``` 1. [PaymentSheet.FlowController.PaymentOptionsButton](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/paymentoptionsbutton) を使用して、支払いを確定するボタンをラップします。 ```swift PaymentSheet.FlowController.ConfirmButton( paymentSheetFlowController: paymentSheetFlowController, onCompletion: { result in // MARK: Handle the payment result switch result { case .completed: print("Payment complete!") case .canceled: print("Canceled!") case .failed(let error): print(error) } }, content: { /* An example button */ Text("Pay") } ) ``` `PaymentSheetResult` が `.completed` の場合は、ユーザーに通知します (注文確認画面を表示するなど)。 `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## Optional: その他の支払い方法を有効にする #### 支払い先 Stripe ダッシュボードの[支払い方法ページ](https://dashboard.stripe.com/settings/payment_methods)から、アカウントの支払い方法を設定します。カード支払い、Google Pay、Apple Pay はデフォルトで有効になっていますが、必要に応じて支払い方法を有効にしたり無効にしたりできます。連結アカウントは自身の支払い方法をカスタマイズできません。 顧客に決済フォームを表示する前に、Stripe は通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストを決定します。決済フォームでは、購入完了率の向上につながり、顧客の通貨と所在地に最も適した決済手段が優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューの下に隠れた状態になります。 #### 以下の代理として ダッシュボードの[連結アカウントの支払い方法を管理する](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)に移動して、連結アカウントで対応する支払い方法を設定します。デフォルトの設定に対する変更は、新規および既存のすべての連結アカウントに適用されます。 支払い方法の情報に関する次のリソースをご覧ください。 - [支払い方法ガイド](https://stripe.com/payments/payment-methods-guide#choosing-the-right-payment-methods-for-your-business)は、プラットフォームに適した支払い方法の選択に役立ちます。 - [アカウントのケイパビリティ](https://docs.stripe.com/connect/account-capabilities.md) を使用して、選択した決済手段が連結アカウントで機能することを確認します。 - Stripe プロダクトおよび決済フローに適した決済手段を選択できるよう、[決済手段とサポート対象のプロダクト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#product-support)に関する表をご確認ください。 支払い方法ごとに、次のいずれかのドロップダウンオプションを選択できます。 | | | | | **デフォルトで有効にする** | 連結アカウントは、決済フローでこの支払い方法に対応します。一部の支払い方法は、無効またはブロックされている可能性があります。これは、*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントが、設定ページで有効化する必要があるためです。 | | **デフォルトで無効にする** | 連結アカウントは、決済フローでこの支払い方法に対応しません。*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントに、自身の支払い方法を管理することを許可している場合、連結アカウントはこれを有効にすることができます。 | | **ブロック済み** | 連結アカウントは、決済フローでこの支払い方法に対応しません。連結アカウントに *Stripe ダッシュボードにアクセスして* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 | ![支払い方法のドロップダウンオプション。支払い方法ごとに選択可能なオプション (ブロック済み、デフォルトで有効にする、デフォルトで無効にする) を示します。](https://b.stripecdn.com/docs-statics-srv/assets/dropdowns.ef651d721d5939d81521dd34dde4577f.png) 支払い方法のオプション 支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。 ![保存ボタンをクリックした後に表示される、ユーザーが変更した内容のリストを含むダイアログ](https://b.stripecdn.com/docs-statics-srv/assets/dialog.a56ea7716f60db9778706790320d13be.png) 保存ダイアログ ### 連結アカウントによる支払い方法の管理を許可する Stripe では、連結アカウントが自身の支払い方法をカスタマイズできるようにすることをお勧めしています。このオプションを有効にすると、*Stripe ダッシュボードにアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)できる各連結アカウントは、[支払い方法](https://dashboard.stripe.com/settings/payment_methods)ページを表示および更新できるようになります。Stripe ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。 このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。 ![連結アカウントの所有者に支払い方法のカスタマイズを許可する際に選択するチェックボックスのスクリーンショット](https://b.stripecdn.com/docs-statics-srv/assets/checkbox.275bd35d2a025272f03af029a144e577.png) アカウントのカスタマイズのチェックボックス ### 支払い方法ケイパビリティ 連結アカウントが追加の支払い方法を受け入れられるようにするには、`Accounts` にアクティブな支払い方法のケイパビリティが必要です。 [連結アカウントの決済手段の管理](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)で決済手段に「デフォルトで有効にする」オプションを選択した場合、新規および既存の連結アカウントが確認要件を満たしていれば、Stripe は自動的に必要なケイパビリティをリクエストします。連結アカウントが要件を満たしていない場合、または直接制御したい場合は、ダッシュボードまたは API でケイパビリティを手動でリクエストできます。 ほとんどの決済手段の確認要件は `card_payments` ケイパビリティと同じですが、いくつかの制限と例外があります。[決済手段ケイパビリティ表](https://docs.stripe.com/connect/account-capabilities.md#payment-methods)には、追加の確認が必要な決済手段が一覧表示されます。 #### ダッシュボード ダッシュボードで[連結アカウントを見つけ](https://docs.stripe.com/connect/dashboard/managing-individual-accounts.md#finding-accounts)て、ケイパビリティを編集し、未対応の確認要件を確認します。 #### API 既存の連結アカウントについては、既存のケイパビリティを[リスト](https://docs.stripe.com/api/capabilities/list.md) して、追加のケイパビリティをリクエストする必要があるかどうかを判断できます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities \ -u "<>:" ``` 各連結アカウントのケイパビリティを[更新](https://docs.stripe.com/api/capabilities/update.md)して、追加のケイパビリティをリクエストします。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities/us_bank_account_ach_payments \ -u "<>:" \ -d requested=true ``` リクエストされたケイパビリティが有効になるまでに時間がかかる場合があります。ケイパビリティに有効化の要件がある場合は、レスポンスの `requirements` 配列にそれが含まれます。 ## 手数料を回収する 支払いが処理される際に、取引の全額を連結アカウントに送金するのではなく、プラットフォームが取引金額の一部を手数料という形で受け取ることを決定できます。手数料の料金体系は、次の 2 つの方法で設定できます。 - [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、プラットフォーム手数料の料金体系ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。 - 社内で料金体系ルールを設定し、[application_fee_amount](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-application_fee_amount) または [transfer_data[amount]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-transfer_data-amount) パラメーターを使用して、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接手数料を指定します。この方法で設定された手数料は、プラットフォーム料金設定ツールで指定された料金体系ロジックを上書きします。 #### application_fee_amount `application_fee_amount` を指定して支払いを作成すると、支払いのキャプチャー後に、支払いの総額が即座にプラットフォームから `transfer_data[destination]` アカウントに送金されます。その後、`application_fee_amount` (上限は支払い総額) がプラットフォームに送金されます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` プラットフォーム手数料が回収されると、[プラットフォーム手数料](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが作成されます。[ダッシュボード](https://dashboard.stripe.com/connect/application_fees)、[アプリケーション手数料](https://docs.stripe.com/api/application_fees/list.md)、または [Sigma](https://docs.stripe.com/stripe-data/how-sigma-works.md) でアプリケーション手数料のリストを表示できます。プラットフォーム手数料オブジェクトの `amount` プロパティを使用して、項目別の手数料レポートを作成することもできます。 `application_fee_amount` を使用する際には、以下の点に留意します。 - `application_fee_amount` は合計取引額が上限です。 - `application_fee_amount` は常に取引と同じ通貨で計算されます。 - プラットフォーム手数料は、連結アカウントの売上処理通貨と同じ通貨で *売上として処理* (When funds are available in your Stripe balance)されます。越境デスティネーション支払いの場合は、[プラットフォームの売上処理通貨と異なる](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)通貨になる場合があります。 - `application_fee_amount` がお客様のアカウントに送金された後に、お客様のプラットフォームが Stripe 手数料を支払います。 - 金額には追加の Stripe 手数料は適用されません。 - プラットフォームは埋め込みのプラットフォーム手数料レポートを使用して、[回収した手数料](https://dashboard.stripe.com/connect/application_fees)を照合できます。 - Stripe がオンラインで提供するダッシュボードや、[支払い詳細コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payment-details.md) などのコンポーネントでは、連結アカウントは合計金額とプラットフォーム手数料のどちらの金額も表示できます。 ### デスティネーション支払いでの資金のフロー 上記のコードでは、支払いの全額 (10.00 USD) が連結アカウントの保留残高に追加されます。`application_fee_amount` (1.23 USD) はその支払い金額から差し引かれ、お客様のプラットフォームに送金されます。 次に Stripe 手数料 (0.59 USD) がプラットフォームアカウントの残高から差し引かれます。プラットフォーム手数料から Stripe 手数料を差し引いた金額 (1.23 USD - 0.59 USD = 0.64 USD) は、プラットフォームアカウントの残高に残ります。 ![デスティネーション支払いの売上のフロー](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_app_fee.c9ef81298155b38f986df02d0efa9167.png) 通常の Stripe 支払いからの売上と同様に、プラットフォームアカウントの通常の送金スケジュールで `application_fee_amount` が利用可能になります。 #### transfer_data[amount] `transfer_data[amount]` は `transfer_data[destination]` に送金される支払い金額を示す正の整数です。支払い金額からプラットフォームの手数料を差し引き、その計算結果を `transfer_data[amount]` として渡します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d "transfer_data[amount]"=877 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` `transfer_data[amount]` を使用する際には、以下が適用されます。 - 金額は合計取引額が上限です。 - 金額は、常に取引と同じ通貨で計算されます。 - 金額は[プラットフォームの売上処理通貨と同じ通貨](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)で*売上として処理* (When funds are available in your Stripe balance)されます。 - 連結アカウントは、Stripe 上のオンラインダッシュボード (Stripe ダッシュボードや Express ダッシュボードなど) で支払いの合計額を確認することはできません。表示されるのは送金済みの金額のみです。 - プラットフォームが、支払いの Stripe 手数料を別途支払います。 - 金額には追加の Stripe 手数料は適用されません。 - 支払いの作成後に、レポート作成などの目的で[手数料を計算する](https://docs.stripe.com/stripe-data/query-all-fees-data.md#fees-paid-by-connected-accounts)場合、[PaymentIntent を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)して PaymentIntent の `amount` から `transfer_data[amount]` を差し引きます。 [プラットフォーム手数料額](https://docs.stripe.com/connect/destination-charges.md#application-fee)を使用して、支払いに関連付けられた明示的なプラットフォーム手数料を作成し、レポート作成を効率化することを検討してください。 ### 売上のフロー 上記のコードでは、支払い `amount` (10.00 USD) がプラットフォームアカウントの残高に追加されます。`transfer_data[amount]` (8.77 USD) がプラットフォームアカウントの残高から差し引かれ、連結アカウントの保留中の残高に追加されます。支払い `amount` (10.00 USD) から `transfer_data[amount]` (8.77 USD) と Stripe 手数料 (支払い `amount` に対する) を差し引いた正味金額 0.64 USD が、プラットフォームアカウントの保留中の残高に残ります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_amount.46cd59f6496607d68020b546aa1af85f.png) 通常の Stripe 支払いからの売上と同様に、連結アカウントの通常送金スケジュールで `transfer_data[amount]` が利用可能になます。 プラットフォームは、残高履歴エクスポートのデスティネーションプラットフォーム手数料列を調べることで `transfer_data[amount]` 支払いから確保する金額を追跡できます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/android-overview.471eaf89a760f5b6a757fd96b6bb9b60.png) [PaymentSheet](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html) クラスを使用して、Stripe の構築済み決済 UI を Android アプリの決済フローに組み込みます。 ## Stripe を設定する [サーバー側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録してください](https://dashboard.stripe.com/register)。 ### サーバー側 この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから 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' ``` ### クライアント側 [Stripe Android SDK](https://github.com/stripe/stripe-android) はオープンソースであり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-android/)。 SDK をインストールするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `stripe-android` を追加します。 #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Stripe Android SDK implementation("com.stripe:stripe-android:23.0.2") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.0.2") } ``` > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。 Stripe の[公開可能キー](https://dashboard.stripe.com/apikeys)を使用して SDK を設定し、 `Application` サブクラスなどで、Stripe API へのリクエストを実行できるようにします。 #### Kotlin ```kotlin import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "<>" ) } } ``` > テストおよび開発時には[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 ## エンドポイントを追加する [サーバー側] > #### 注 > > PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。 1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。 1. (オプション) [Customer (顧客)](https://docs.stripe.com/api/customers.md): 今後の支払いに備えて決済手段を設定するには、決済手段を*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付ける必要があります。Customer オブジェクトは、顧客がビジネスでアカウントを作成するときに作成します。顧客がゲストとして支払いを行う場合は、支払いの前に Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントを表す内部表現に関連付けることができます。 1. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): Customer オブジェクトの情報は機密情報であるため、アプリから直接取得することはできません。CustomerSession により、SDK に Customer への範囲を設定した一時的なアクセス権が付与され、また追加の設定オプションが提供されます。すべての[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)のリストをご覧ください。 > Customer にカードを保存したことがなく、リピート顧客に保存されたカードの再利用を許可しない場合は、実装で Customer オブジェクトおよび CustomerSession オブジェクトを省略できます。 セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。 1. Customer を取得するか、新規作成する。 1. 顧客の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。 1. [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount)、[currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency)、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を指定して PaymentIntent を作成します。 1. PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer))、CustomerSession の `client_secret`、Customer の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id)、および貴社の[公開可能キー](https://dashboard.stripe.com/apikeys)をアプリに返します。 決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。 構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。 #### ダッシュボードで支払い方法を管理する 支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。PaymentIntent は、ダッシュボードで設定された支払い方法を使用して作成されます。ダッシュボードを使用しない場合や、支払い方法を手動で指定する場合は、`payment_method_types` 属性を使用して支払い方法を一覧表示することができます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount="123" \ -d "transfer_data[destination]"="{{CONNECTED_ACCOUNT_ID}}" \ ``` #### 支払い方法を手動で一覧表示する #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "payment_method_types[]"="bancontact" \ -d "payment_method_types[]"="card" \ -d "payment_method_types[]"="ideal" \ -d "payment_method_types[]"="klarna" \ -d "payment_method_types[]"="sepa_debit" \ -d application_fee_amount="123" \ -d "transfer_data[destination]"="{{CONNECTED_ACCOUNT_ID}}" \ ``` > 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。 ## 決済画面を導入する [クライアント側] 決済ページでは、Mobile Payment Element を表示する前に以下を実行する必要があります。 - 購入商品と合計金額を表示する - [Address Element](https://docs.stripe.com/elements/address-element.md?platform=android) を使用して必要な配送先情報を収集する - Stripe の UI を表示する決済ボタンを含める #### Jetpack Compose 決済アクティビティーの `onCreate` 内で `PaymentSheet` インスタンスを[初期化](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-builder/index.html)して、結果を処理するメソッドを渡します。 ```kotlin import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult @Composable fun App() { val paymentSheet = remember { PaymentSheet.Builder(::onPaymentSheetResult) }.build() } private fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } ``` 次に、前のステップで作成したエンドポイントから、PaymentIntent のClient Secret、顧客 SessionのClient Secret、顧客 ID、公開可能キーを取得します。公開可能キーは `PaymentConfiguration` を使用して設定し、その他は保存して、PaymentSheet を表示するときに使用します。 ```kotlin import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberimport androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult @Composable fun App() { val paymentSheet = remember { PaymentSheet.Builder(::onPaymentSheetResult) }.build()val context = LocalContext.current var customerConfig by remember { mutableStateOf(null) } varpaymentIntentClientSecret by remember { mutableStateOf(null) } LaunchedEffect(context) { // Make a request to your own server and retrieve payment configurations val networkResult = ... if (networkResult.isSuccess) {paymentIntentClientSecret = networkResult.paymentIntent customerConfig = PaymentSheet.CustomerConfiguration.createWithCustomerSession( id = networkResult.customer, clientSecret = networkResult.customerSessionClientSecret )PaymentConfiguration.init(context, networkResult.publishableKey)} } } private fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } ``` 顧客が決済ボタンをタップしたら、[presentWithPaymentIntent](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html#1814490530%2FFunctions%2F2002900378) を呼び出して支払い画面を表示します。顧客が決済を完了すると、画面が閉じ、[PaymentSheetResult](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result/index.html) とともに [PaymentSheetResultCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result-callback/index.html) が呼び出されます。 ```kotlin import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult @Composable fun App() { val paymentSheet = remember { PaymentSheet.Builder(::onPaymentSheetResult) }.build() val context = LocalContext.current var customerConfig by remember { mutableStateOf(null) } var paymentIntentClientSecret by remember { mutableStateOf(null) } LaunchedEffect(context) { // Make a request to your own server and retrieve payment configurations val networkResult = ... if (networkResult.isSuccess) { paymentIntentClientSecret = networkResult.paymentIntent customerConfig = PaymentSheet.CustomerConfiguration.createWithCustomerSession( id = networkResult.customer, clientSecret = networkResult.customerSessionClientSecret ) PaymentConfiguration.init(context, networkResult.publishableKey) } }Button( onClick = { val currentConfig = customerConfig val currentClientSecret =paymentIntentClientSecret if (currentConfig != null && currentClientSecret != null) { presentPaymentSheet(paymentSheet, currentConfig, currentClientSecret) } } ) { Text("Checkout") } }private fun presentPaymentSheet( paymentSheet: PaymentSheet, customerConfig: PaymentSheet.CustomerConfiguration,paymentIntentClientSecret: String ) { paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, PaymentSheet.Configuration.Builder(merchantDisplayName = "My merchant name") .customer(customerConfig) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. .allowsDelayedPaymentMethods(true) .build() ) } private fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) {when(paymentSheetResult) { is PaymentSheetResult.Canceled -> { print("Canceled") } is PaymentSheetResult.Failed -> { print("Error: ${paymentSheetResult.error}") } is PaymentSheetResult.Completed -> { // Display for example, an order confirmation screen print("Completed") } } } ``` #### ビュー (クラシック) 決済アクティビティーの `onCreate` 内で、結果を処理するメソッドを渡して、`PaymentSheet` インスタンスを[初期化](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html#-394860221%2FConstructors%2F2002900378)します。 #### Kotlin ```kotlin import com.stripe.android.paymentsheet.PaymentSheet class CheckoutActivity : AppCompatActivity() { lateinit var paymentSheet: PaymentSheet override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) paymentSheet = PaymentSheet.Builder(::onPaymentSheetResult).build(this) } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } } ``` 次に、前のステップで作成したエンドポイントから、PaymentIntent のClient Secret、顧客 SessionのClient Secret、顧客 ID、公開可能キーを取得します。公開可能キーは `PaymentConfiguration` を使用して設定し、その他は保存して、PaymentSheet を表示するときに使用します。 #### Kotlin ```kotlin import com.stripe.android.paymentsheet.PaymentSheet class CheckoutActivity : AppCompatActivity() { lateinit var paymentSheet: PaymentSheetlateinit var customerConfig: PaymentSheet.CustomerConfiguration lateinit varpaymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) paymentSheet = PaymentSheet.Builder(::onPaymentSheetResult).build(this)lifecycleScope.launch { // Make a request to your own server and retrieve payment configurations val networkResult = MyBackend.getPaymentConfig() if (networkResult.isSuccess) {paymentIntentClientSecret = networkResult.paymentIntent customerConfig = PaymentSheet.CustomerConfiguration.createWithCustomerSession( id = networkResult.customer, clientSecret = networkResult.customerSessionClientSecret )PaymentConfiguration.init(context, networkResult.publishableKey)} } } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { // implemented in the next steps } } ``` 顧客が決済ボタンをタップしたら、[presentWithPaymentIntent](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/index.html#1814490530%2FFunctions%2F2002900378) を呼び出して支払い画面を表示します。顧客が決済を完了すると、画面が閉じ、[PaymentSheetResult](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result/index.html) とともに [PaymentSheetResultCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result-callback/index.html) が呼び出されます。 #### Kotlin ```kotlin // ... class CheckoutActivity : AppCompatActivity() { lateinit var paymentSheet: PaymentSheet lateinit var customerConfig: PaymentSheet.CustomerConfiguration lateinit var paymentIntentClientSecret: String // ...fun presentPaymentSheet() { paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, PaymentSheet.Configuration.Builder(merchantDisplayName = "My merchant name") .customer(customerConfig) // Set `allowsDelayedPaymentMethods` to true if your business handles // delayed notification payment methods like US bank accounts. .allowsDelayedPaymentMethods(true) .build() ) } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) {when(paymentSheetResult) { is PaymentSheetResult.Canceled -> { print("Canceled") } is PaymentSheetResult.Failed -> { print("Error: ${paymentSheetResult.error}") } is PaymentSheetResult.Completed -> { // Display for example, an order confirmation screen print("Completed") } } } } ``` `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## 支払い後のイベントを処理する [サーバー側] 支払いが完了すると、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` に変わった場合は、顧客に再度支払いを試すように促します。 | ## 実装内容をテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 4242424242424242 | カード支払いは成功し、認証は必要とされません。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000002500003155 | カード支払いには*認証* (Strong Customer Authentication (SCA) is a regulatory requirement in effect as of September 14, 2019, that impacts many European online payments. It requires customers to use two-factor authentication like 3D Secure to verify their purchase)が必要です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 4000000000009995 | カードは、`insufficient_funds` などの拒否コードで拒否されます。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | | 6205500000000000004 | UnionPay カードは、13 ~ 19 桁の可変長です。 | クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。 | #### 銀行へのリダイレクト | 決済手段 | シナリオ | テスト方法 | | ---------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Bancontact、iDEAL | 顧客は、リダイレクトベースの即時通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | リダイレクトベースの任意の支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。 | | Pay by Bank | 顧客はリダイレクトベースの、[遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法で支払いに成功します。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Complete test payment (テスト支払い完了)** をクリックします。 | | Pay by Bank | 顧客は、リダイレクトベースの遅延通知型の支払い方法のリダイレクトページで、認証に失敗しました。 | 支払い方法を選択し、必要な情報を入力して、支払いを確定します。その後、リダイレクトページで **Fail test payment (テスト支払いを失敗させる)** をクリックします。 | | BLIK | BLIK による支払いはさまざまな理由で失敗します。即時の失敗 (コードの有効期限切れや無効など)、遅延型のエラー (銀行による拒否など)、またはタイムアウト (顧客が時間内に応答しなかったなど) などがあります。 | メールパターンを使用して[さまざまな失敗をシミュレーションします。](https://docs.stripe.com/payments/blik/accept-a-payment.md#simulate-failures) | #### 口座引き落とし | 決済手段 | シナリオ | テスト方法 | | -------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | SEPA ダイレクトデビット | 顧客が SEPA ダイレクトデビットによる支払いに成功しました。 | 口座番号 `AT321904300235473204` を使用して、フォームに入力します。確定された PaymentIntent のステータスはまず、processing に移行し、3 分後に succeeded ステータスに移行します。 | | SEPA ダイレクトデビット | 顧客の Payment Intent のステータスが、`processing` から `requires_payment_method` に移行します。 | 口座番号 `AT861904300235473202` を使用して、フォームに入力します。 | 実装内容をテストするためのその他の情報については、[テスト](https://docs.stripe.com/testing.md)をご覧ください。 ## Optional: Google Pay を有効にする ### 実装方法を設定する Google Pay を使用するには、まず以下を **AndroidManifest.xml** の `` に追加し、Google Pay API を有効化します。 ```xml ... ``` 詳細は、Google Pay の Android 向け [Google Pay API を設定する](https://developers.google.com/pay/api/android/guides/setup) を参照してください。 ### Google Pay を追加する 組み込みに Google Pay を追加するには、[PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) を初期化する際に、お客様の Google Pay 環境 (本番またはテスト) と[ビジネスの国コード](https://dashboard.stripe.com/settings/account)を指定して [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) を渡します。 #### Kotlin ```kotlin val googlePayConfiguration = PaymentSheet.GooglePayConfiguration( environment = PaymentSheet.GooglePayConfiguration.Environment.Test, countryCode = "US", currencyCode = "USD" // Required for Setup Intents, optional for Payment Intents ) val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "My merchant name") .googlePay(googlePayConfiguration) .build() ``` ### Google Pay をテストする Google では、[テストクレジットカードスイート](https://developers.google.com/pay/api/android/guides/resources/test-card-suite) を使用してテスト決済を行うことができます。Stripe [テストカード](https://docs.stripe.com/testing.md) をテストスイートと併用できます。 Google Pay がサポートされている国では、シミュレーションされたデバイスではなく、物理的な Android デバイスを使用して Google Pay をテストする必要があります。Google ウォレットに保存した実際のクレジットカードを使用して、テスト用デバイスの Google アカウントにログインします。 ## Optional: 画面をカスタマイズする すべてのカスタマイズは、[PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) オブジェクトを使用して設定されます。 ### デザイン Customize colors, fonts, and more to match the look and feel of your app by using the [appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=android). ### 決済手段のレイアウト [paymentMethodLayout](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/-builder/index.html#2123253356%2FFunctions%2F2002900378) を使用して、画面上の決済手段のレイアウトを設定します。横や縦に表示することも、Stripe がレイアウトを自動で最適化するように設定することもできます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/android-mpe-payment-method-layouts.3bcfe828ceaad1a94e0572a22d91733f.png) #### Kotlin ```kotlin PaymentSheet.Configuration.Builder("Example, Inc.") .paymentMethodLayout(PaymentSheet.PaymentMethodLayout.Automatic) .build() ``` ### ユーザーの住所を収集する [Address Element](https://docs.stripe.com/elements/address-element.md?platform=android) を使用して、顧客から国内および国外の配送先住所や請求先住所を収集します。 ### ビジネス表示名 [merchantDisplayName](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html#-191101533%2FProperties%2F2002900378) を設定し、顧客に表示するビジネス名を指定します。デフォルトではアプリ名になります。 #### Kotlin ```kotlin PaymentSheet.Configuration.Builder( merchantDisplayName = "My app, Inc." ).build() ``` ### ダークモード `PaymentSheet` は、ユーザーのシステム全体の表示設定 (ライト/ダークモード) に合わせてデフォルトで自動的に調整されます。これを変更するには、アプリでライトモードまたはダークモードを設定します。 #### Kotlin ```kotlin // force dark AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) // force light AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) ``` ### デフォルトの請求詳細 支払い画面で収集される請求詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティーを設定します。`PaymentSheet` の各フィールドに、指定したそれらの値が事前に読み込まれます。 #### Kotlin ```kotlin val address = PaymentSheet.Address(country = "US") val billingDetails = PaymentSheet.BillingDetails( address = address, email = "foo@bar.com" ) val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Merchant, Inc.") .defaultBillingDetails(billingDetails) .build() ``` ### 請求先情報の収集を設定する `BillingDetailsCollectionConfiguration` を使用して、PaymentSheet で請求詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 UI でデフォルトの請求詳細が収集されない場合でも、それらの詳細を PaymentMethod オブジェクトに関連付けるには、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を `true` に設定します。 #### Kotlin ```kotlin val billingDetails = PaymentSheet.BillingDetails( email = "foo@bar.com" ) val billingDetailsCollectionConfiguration = BillingDetailsCollectionConfiguration( attachDefaultsToPaymentMethod = true, name = BillingDetailsCollectionConfiguration.CollectionMode.Always, email = BillingDetailsCollectionConfiguration.CollectionMode.Never, address = BillingDetailsCollectionConfiguration.AddressCollectionMode.Full, ) val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Merchant, Inc.") .defaultBillingDetails(billingDetails) .billingDetailsCollectionConfiguration(billingDetailsCollectionConfiguration) .build() ``` > 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。 ## Optional: UI で支払いを完了する 支払い画面を表示して支払い方法の詳細のみを収集し、アプリの UI に戻って支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。 ![](https://b.stripecdn.com/docs-statics-srv/assets/android-multi-step.84d8a0a44b1baa596bda491322b6d9fd.png) > 導入サンプルは[GitHubで入手できます](https://github.com/stripe/stripe-android/blob/master/paymentsheet-example/src/main/java/com/stripe/android/paymentsheet/example/samples/ui/paymentsheet/custom_flow/CustomFlowActivity.kt)。 1. 最初に、[Builder](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/-builder/index.html) メソッドのいずれかを使用して、`PaymentSheet` ではなく [PaymentSheet.FlowController](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html) を初期化します。 #### Android (Kotlin) ```kotlin class CheckoutActivity : AppCompatActivity() { private lateinit var flowController: PaymentSheet.FlowController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val flowController = PaymentSheet.FlowController.Builder( resultCallback = ::onPaymentSheetResult, paymentOptionResultCallback = ::onPaymentOption, ).build(this) } } ``` 1. 次に、バックエンドから取得した Stripe オブジェクトキーで `configureWithPaymentIntent` を呼び出し、[getPaymentOption()](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html#-2091462043%2FFunctions%2F2002900378) を使用してコールバックで UI を更新します。ここには、顧客が現在選択している決済手段を表す画像とラベルが含まれています。 #### Android (Kotlin) ```kotlin flowController.configureWithPaymentIntent( paymentIntentClientSecret = paymentIntentClientSecret, configuration = PaymentSheet.Configuration.Builder("Example, Inc.") .customer(PaymentSheet.CustomerConfiguration( id = customerId, ephemeralKeySecret = ephemeralKeySecret )) .build() ) { isReady, error -> if (isReady) { // Update your UI using `flowController.getPaymentOption()` } else { // handle FlowController configuration failure } } ``` 1. 次に、[presentPaymentOptions](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html#449924733%2FFunctions%2F2002900378) を呼び出して、決済の詳細を収集します。顧客が操作を完了すると、画面は閉じ、すでに `create` で渡されている [paymentOptionCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-option-callback/index.html) が呼び出されます。このメソッドを実装し、返された `paymentOption` で UI を更新します。 #### Android (Kotlin) ```kotlin // ... flowController.presentPaymentOptions() // ... private fun onPaymentOption(paymentOptionResult: PaymentOptionResult) { val paymentOption = paymentOptionResult.paymentOption if (paymentOption != null) { paymentMethodButton.text = paymentOption.label paymentMethodButton.setCompoundDrawablesRelativeWithIntrinsicBounds( paymentOption.drawableResourceId, 0, 0, 0 ) } else { paymentMethodButton.text = "Select" paymentMethodButton.setCompoundDrawablesRelativeWithIntrinsicBounds( null, null, null, null ) } } ``` 1. 最後に、[confirm](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-flow-controller/index.html#-479056656%2FFunctions%2F2002900378) を呼び出して支払いを完了します。顧客が操作を完了すると、画面は閉じ、すでに `create` で渡されている [paymentResultCallback](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet-result-callback/index.html#237248767%2FFunctions%2F2002900378) が呼び出されます。 #### Android (Kotlin) ```kotlin // ... flowController.confirmPayment() // ... private fun onPaymentSheetResult( paymentSheetResult: PaymentSheetResult ) { when (paymentSheetResult) { is PaymentSheetResult.Canceled -> { // Payment canceled } is PaymentSheetResult.Failed -> { // Payment Failed. See logcat for details or inspect paymentSheetResult.error } is PaymentSheetResult.Completed -> { // Payment Complete } } } ``` `allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。 ## Optional: その他の支払い方法を有効にする #### 支払い先 Stripe ダッシュボードの[支払い方法ページ](https://dashboard.stripe.com/settings/payment_methods)から、アカウントの支払い方法を設定します。カード支払い、Google Pay、Apple Pay はデフォルトで有効になっていますが、必要に応じて支払い方法を有効にしたり無効にしたりできます。連結アカウントは自身の支払い方法をカスタマイズできません。 顧客に決済フォームを表示する前に、Stripe は通貨、決済手段の制約、その他のパラメーターを評価し、対応可能な決済手段のリストを決定します。決済フォームでは、購入完了率の向上につながり、顧客の通貨と所在地に最も適した決済手段が優先的に表示されます。優先度の低い決済手段は、オーバーフローメニューの下に隠れた状態になります。 #### 以下の代理として ダッシュボードの[連結アカウントの支払い方法を管理する](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)に移動して、連結アカウントで対応する支払い方法を設定します。デフォルトの設定に対する変更は、新規および既存のすべての連結アカウントに適用されます。 支払い方法の情報に関する次のリソースをご覧ください。 - [支払い方法ガイド](https://stripe.com/payments/payment-methods-guide#choosing-the-right-payment-methods-for-your-business)は、プラットフォームに適した支払い方法の選択に役立ちます。 - [アカウントのケイパビリティ](https://docs.stripe.com/connect/account-capabilities.md) を使用して、選択した決済手段が連結アカウントで機能することを確認します。 - Stripe プロダクトおよび決済フローに適した決済手段を選択できるよう、[決済手段とサポート対象のプロダクト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#product-support)に関する表をご確認ください。 支払い方法ごとに、次のいずれかのドロップダウンオプションを選択できます。 | | | | | **デフォルトで有効にする** | 連結アカウントは、決済フローでこの支払い方法に対応します。一部の支払い方法は、無効またはブロックされている可能性があります。これは、*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントが、設定ページで有効化する必要があるためです。 | | **デフォルトで無効にする** | 連結アカウントは、決済フローでこの支払い方法に対応しません。*Stripe ダッシュボードへのアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)が許可された連結アカウントに、自身の支払い方法を管理することを許可している場合、連結アカウントはこれを有効にすることができます。 | | **ブロック済み** | 連結アカウントは、決済フローでこの支払い方法に対応しません。連結アカウントに *Stripe ダッシュボードにアクセスして* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 | ![支払い方法のドロップダウンオプション。支払い方法ごとに選択可能なオプション (ブロック済み、デフォルトで有効にする、デフォルトで無効にする) を示します。](https://b.stripecdn.com/docs-statics-srv/assets/dropdowns.ef651d721d5939d81521dd34dde4577f.png) 支払い方法のオプション 支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。 ![保存ボタンをクリックした後に表示される、ユーザーが変更した内容のリストを含むダイアログ](https://b.stripecdn.com/docs-statics-srv/assets/dialog.a56ea7716f60db9778706790320d13be.png) 保存ダイアログ ### 連結アカウントによる支払い方法の管理を許可する Stripe では、連結アカウントが自身の支払い方法をカスタマイズできるようにすることをお勧めしています。このオプションを有効にすると、*Stripe ダッシュボードにアクセス* (Platforms can provide connected accounts with access to the full Stripe Dashboard or the Express Dashboard. Otherwise, platforms build an interface for connected accounts using embedded components or the Stripe API)できる各連結アカウントは、[支払い方法](https://dashboard.stripe.com/settings/payment_methods)ページを表示および更新できるようになります。Stripe ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。 このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。 ![連結アカウントの所有者に支払い方法のカスタマイズを許可する際に選択するチェックボックスのスクリーンショット](https://b.stripecdn.com/docs-statics-srv/assets/checkbox.275bd35d2a025272f03af029a144e577.png) アカウントのカスタマイズのチェックボックス ### 支払い方法ケイパビリティ 連結アカウントが追加の支払い方法を受け入れられるようにするには、`Accounts` にアクティブな支払い方法のケイパビリティが必要です。 [連結アカウントの決済手段の管理](https://dashboard.stripe.com/settings/payment_methods/connected_accounts)で決済手段に「デフォルトで有効にする」オプションを選択した場合、新規および既存の連結アカウントが確認要件を満たしていれば、Stripe は自動的に必要なケイパビリティをリクエストします。連結アカウントが要件を満たしていない場合、または直接制御したい場合は、ダッシュボードまたは API でケイパビリティを手動でリクエストできます。 ほとんどの決済手段の確認要件は `card_payments` ケイパビリティと同じですが、いくつかの制限と例外があります。[決済手段ケイパビリティ表](https://docs.stripe.com/connect/account-capabilities.md#payment-methods)には、追加の確認が必要な決済手段が一覧表示されます。 #### ダッシュボード ダッシュボードで[連結アカウントを見つけ](https://docs.stripe.com/connect/dashboard/managing-individual-accounts.md#finding-accounts)て、ケイパビリティを編集し、未対応の確認要件を確認します。 #### API 既存の連結アカウントについては、既存のケイパビリティを[リスト](https://docs.stripe.com/api/capabilities/list.md) して、追加のケイパビリティをリクエストする必要があるかどうかを判断できます。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities \ -u "<>:" ``` 各連結アカウントのケイパビリティを[更新](https://docs.stripe.com/api/capabilities/update.md)して、追加のケイパビリティをリクエストします。 ```curl curl https://api.stripe.com/v1/accounts/{{CONNECTEDACCOUNT_ID}}/capabilities/us_bank_account_ach_payments \ -u "<>:" \ -d requested=true ``` リクエストされたケイパビリティが有効になるまでに時間がかかる場合があります。ケイパビリティに有効化の要件がある場合は、レスポンスの `requirements` 配列にそれが含まれます。 ## 手数料を回収する 支払いが処理される際に、取引の全額を連結アカウントに送金するのではなく、プラットフォームが取引金額の一部を手数料という形で受け取ることを決定できます。手数料の料金体系は、次の 2 つの方法で設定できます。 - [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、プラットフォーム手数料の料金体系ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。 - 社内で料金体系ルールを設定し、[application_fee_amount](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-application_fee_amount) または [transfer_data[amount]](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-transfer_data-amount) パラメーターを使用して、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接手数料を指定します。この方法で設定された手数料は、プラットフォーム料金設定ツールで指定された料金体系ロジックを上書きします。 #### application_fee_amount `application_fee_amount` を指定して支払いを作成すると、支払いのキャプチャー後に、支払いの総額が即座にプラットフォームから `transfer_data[destination]` アカウントに送金されます。その後、`application_fee_amount` (上限は支払い総額) がプラットフォームに送金されます。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount=123 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` プラットフォーム手数料が回収されると、[プラットフォーム手数料](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが作成されます。[ダッシュボード](https://dashboard.stripe.com/connect/application_fees)、[アプリケーション手数料](https://docs.stripe.com/api/application_fees/list.md)、または [Sigma](https://docs.stripe.com/stripe-data/how-sigma-works.md) でアプリケーション手数料のリストを表示できます。プラットフォーム手数料オブジェクトの `amount` プロパティを使用して、項目別の手数料レポートを作成することもできます。 `application_fee_amount` を使用する際には、以下の点に留意します。 - `application_fee_amount` は合計取引額が上限です。 - `application_fee_amount` は常に取引と同じ通貨で計算されます。 - プラットフォーム手数料は、連結アカウントの売上処理通貨と同じ通貨で *売上として処理* (When funds are available in your Stripe balance)されます。越境デスティネーション支払いの場合は、[プラットフォームの売上処理通貨と異なる](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)通貨になる場合があります。 - `application_fee_amount` がお客様のアカウントに送金された後に、お客様のプラットフォームが Stripe 手数料を支払います。 - 金額には追加の Stripe 手数料は適用されません。 - プラットフォームは埋め込みのプラットフォーム手数料レポートを使用して、[回収した手数料](https://dashboard.stripe.com/connect/application_fees)を照合できます。 - Stripe がオンラインで提供するダッシュボードや、[支払い詳細コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payment-details.md) などのコンポーネントでは、連結アカウントは合計金額とプラットフォーム手数料のどちらの金額も表示できます。 ### デスティネーション支払いでの資金のフロー 上記のコードでは、支払いの全額 (10.00 USD) が連結アカウントの保留残高に追加されます。`application_fee_amount` (1.23 USD) はその支払い金額から差し引かれ、お客様のプラットフォームに送金されます。 次に Stripe 手数料 (0.59 USD) がプラットフォームアカウントの残高から差し引かれます。プラットフォーム手数料から Stripe 手数料を差し引いた金額 (1.23 USD - 0.59 USD = 0.64 USD) は、プラットフォームアカウントの残高に残ります。 ![デスティネーション支払いの売上のフロー](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_app_fee.c9ef81298155b38f986df02d0efa9167.png) 通常の Stripe 支払いからの売上と同様に、プラットフォームアカウントの通常の送金スケジュールで `application_fee_amount` が利用可能になります。 #### transfer_data[amount] `transfer_data[amount]` は `transfer_data[destination]` に送金される支払い金額を示す正の整数です。支払い金額からプラットフォームの手数料を差し引き、その計算結果を `transfer_data[amount]` として渡します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1000 \ -d currency=usd \ -d "automatic_payment_methods[enabled]"=true \ -d "transfer_data[amount]"=877 \ -d "transfer_data[destination]"="{{CONNECTEDACCOUNT_ID}}" ``` `transfer_data[amount]` を使用する際には、以下が適用されます。 - 金額は合計取引額が上限です。 - 金額は、常に取引と同じ通貨で計算されます。 - 金額は[プラットフォームの売上処理通貨と同じ通貨](https://docs.stripe.com/connect/currencies/fx-quotes-api.md#application-fees-for-destination-charges-and-converting-balances)で*売上として処理* (When funds are available in your Stripe balance)されます。 - 連結アカウントは、Stripe 上のオンラインダッシュボード (Stripe ダッシュボードや Express ダッシュボードなど) で支払いの合計額を確認することはできません。表示されるのは送金済みの金額のみです。 - プラットフォームが、支払いの Stripe 手数料を別途支払います。 - 金額には追加の Stripe 手数料は適用されません。 - 支払いの作成後に、レポート作成などの目的で[手数料を計算する](https://docs.stripe.com/stripe-data/query-all-fees-data.md#fees-paid-by-connected-accounts)場合、[PaymentIntent を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)して PaymentIntent の `amount` から `transfer_data[amount]` を差し引きます。 [プラットフォーム手数料額](https://docs.stripe.com/connect/destination-charges.md#application-fee)を使用して、支払いに関連付けられた明示的なプラットフォーム手数料を作成し、レポート作成を効率化することを検討してください。 ### 売上のフロー 上記のコードでは、支払い `amount` (10.00 USD) がプラットフォームアカウントの残高に追加されます。`transfer_data[amount]` (8.77 USD) がプラットフォームアカウントの残高から差し引かれ、連結アカウントの保留中の残高に追加されます。支払い `amount` (10.00 USD) から `transfer_data[amount]` (8.77 USD) と Stripe 手数料 (支払い `amount` に対する) を差し引いた正味金額 0.64 USD が、プラットフォームアカウントの保留中の残高に残ります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/destination_charge_amount.46cd59f6496607d68020b546aa1af85f.png) 通常の Stripe 支払いからの売上と同様に、連結アカウントの通常送金スケジュールで `transfer_data[amount]` が利用可能になます。 プラットフォームは、残高履歴エクスポートのデスティネーションプラットフォーム手数料列を調べることで `transfer_data[amount]` 支払いから確保する金額を追跡できます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-overview.9e0d68d009dc005f73a6f5df69e00458.png) この統合は、決済の詳細収集や決済確認など、決済に必要なすべてのステップを一つのシートにまとめ、アプリ上部に表示されます。 ## Stripe を設定する [サーバー側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録してください](https://dashboard.stripe.com/register)。 ### サーバー側 この接続方法では、Stripe API と通信するエンドポイントがサーバー上に必要です。サーバーから 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' ``` ### クライアント側 [React Native SDK](https://github.com/stripe/stripe-react-native) はオープンソースであり、詳細なドキュメントが提供されています。内部では、[ネイティブの iOS](https://github.com/stripe/stripe-ios) および [Android](https://github.com/stripe/stripe-android) の SDK を使用します。Stripe の React Native SDK をインストールするには、プロジェクトのディレクトリーで (使用するパッケージマネージャーによって異なる) 次のいずれかのコマンドを実行します。 #### yarn ```bash yarn add @stripe/stripe-react-native ``` #### npm ```bash npm install @stripe/stripe-react-native ``` 次に、その他の必要な依存関係をインストールします。 - iOS の場合は、**ios** ディレクトリに移動して `pod install` を実行し、必要なネイティブ依存関係もインストールします。 - Android の場合は、依存関係をインストールする必要はありません。 > [公式の TypeScript ガイド](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project)に従って TypeScript のサポートを追加することをお勧めします。 ### Stripe の初期化 React Native アプリで Stripe を初期化するには、決済画面を `StripeProvider` コンポーネントでラップするか、`initStripe` 初期化メソッドを使用します。`publishableKey` の API [公開可能キー](https://docs.stripe.com/keys.md#obtain-api-keys)のみが必要です。次の例は、`StripeProvider` コンポーネントを使用して Stripe を初期化する方法を示しています。 ```jsx import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( {/* Your app code here */} ); } ``` > テストおよび開発時には API の[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 ## エンドポイントを追加する [サーバー側] > #### 注 > > PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。 Connect プラットフォームが [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、Stripe の [ガイド](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご確認の上、コード内の `Customer` およびイベント参照を同等の Accounts v2 API リファレンスに置き換えてください。 この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。 1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。 1. (オプション) [Customer (顧客)](https://docs.stripe.com/api/customers.md): 今後の支払いに備えて決済手段を設定するには、決済手段を*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付ける必要があります。Customer オブジェクトは、顧客がビジネスでアカウントを作成するときに作成します。顧客がゲストとして支払いを行う場合は、支払いの前に Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントを表す内部表現に関連付けることができます。 1. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): Customer オブジェクトの情報は機密情報であるため、アプリから直接取得することはできません。CustomerSession により、SDK に Customer への範囲を設定した一時的なアクセス権が付与され、また追加の設定オプションが提供されます。すべての[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)のリストをご覧ください。 > Customer にカードを保存したことがなく、リピート顧客に保存されたカードの再利用を許可しない場合は、実装で Customer オブジェクトおよび CustomerSession オブジェクトを省略できます。 セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。 1. Customer を取得するか、新規作成する。 1. 顧客の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。 1. [amount](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-amount)、[currency](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-currency)、[customer](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer) を指定して PaymentIntent を作成します。 1. PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer))、CustomerSession の `client_secret`、Customer の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id)、および貴社の[公開可能キー](https://dashboard.stripe.com/apikeys)をアプリに返します。 決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。 構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。 #### ダッシュボードで支払い方法を管理する 支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。PaymentIntent は、ダッシュボードで設定された支払い方法を使用して作成されます。ダッシュボードを使用しない場合や、支払い方法を手動で指定する場合は、`payment_method_types` 属性を使用して支払い方法を一覧表示することができます。 #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ # In the latest version of the API, specifying the `automatic_payment_methods` parameter # is optional because Stripe enables its functionality by default. -d "automatic_payment_methods[enabled]"=true \ -d application_fee_amount="123" \ -d "transfer_data[destination]"="{{CONNECTED_ACCOUNT_ID}}" \ ``` #### 支払い方法を手動で一覧表示する #### curl ```bash # Create a Customer (use an existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" \ -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}" # Create an CustomerSession for the Customer curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[mobile_payment_element][enabled]"=true \ -d "components[mobile_payment_element][features][payment_method_save]"=enabled \ -d "components[mobile_payment_element][features][payment_method_redisplay]"=enabled \ -d "components[mobile_payment_element][features][payment_method_remove]"=enabled # Create a PaymentIntent curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "amount"=1099 \ -d "currency"="eur" \ -d "payment_method_types[]"="bancontact" \ -d "payment_method_types[]"="card" \ -d "payment_method_types[]"="ideal" \ -d "payment_method_types[]"="klarna" \ -d "payment_method_types[]"="sepa_debit" \ -d application_fee_amount="123" \ -d "transfer_data[destination]"="{{CONNECTED_ACCOUNT_ID}}" \ ``` > 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。 ## 決済画面を導入する [クライアント側] 決済ページでは、モバイル決済 Element を表示する前に以下を実行する必要があります。 - 購入商品と合計金額を表示する - 必要な配送先情報を収集する - Stripe の UI を表示する決済ボタンを含める アプリの決済フローで、前のステップで作成したバックエンドのエンドポイントにネットワークリクエストを送信し、`useStripe` フックから `initPaymentSheet` を呼び出します。 ```javascript export default function CheckoutScreen() { const { initPaymentSheet, presentPaymentSheet } = useStripe(); const [loading, setLoading] = useState(false); const fetchPaymentSheetParams = async () => { const response = await fetch(`${API_URL}/payment-sheet`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); const { paymentIntent, ephemeralKey, customer } = await response.json(); return { paymentIntent, ephemeralKey, customer, }; }; const initializePaymentSheet = async () => { const { paymentIntent, ephemeralKey, customer, } = await fetchPaymentSheetParams(); const { error } = await initPaymentSheet({ merchantDisplayName: "Example, Inc.", customerId: customer, customerEphemeralKeySecret: ephemeralKey, paymentIntentClientSecret: paymentIntent, // Set `allowsDelayedPaymentMethods` to true if your business can handle payment //methods that complete payment after a delay, like SEPA Debit and Sofort. allowsDelayedPaymentMethods: true, defaultBillingDetails: { name: 'Jane Doe', } }); if (!error) { setLoading(true); } }; const openPaymentSheet = async () => { // see below }; useEffect(() => { initializePaymentSheet(); }, []); return (