# ダイレクト支払いを作成する
連結アカウントで直接支払いを作成し、手数料を回収します。
顧客が連結アカウントと直接取引を行うときに「ダイレクト支払い」を作成すると、多くの場合、顧客はプラットフォームの存在に気付きません。ダイレクト支払いの特徴は以下のとおりです。
- 支払いはプラットフォームのアカウントではなく、連結アカウントに支払いとして表示されます。
- 連結アカウントの残高は、支払いのたびに増加します。
- アカウント残高は、支払いごとに発生するプラットフォーム手数料により増加します。
この支払いタイプは、SaaS (サービスとしてのソフトウェア) を提供するプラットフォームに最適です。たとえば、Shopify はオンラインストアフロントを構築するためのツールを提供し、Thinkific は教育者がオンラインコースを販売できるようにしています。
## プラットフォームの表示制限
ダイレクト支払いは、プラットフォームレベルでは表示が制限されます。ダイレクト支払いを作成すると、以下のようになります。
- `PaymentIntents` や `Charges` などの取引オブジェクトは、プラットフォームではなく連結アカウントに存在します。
- ダイレクト支払いデータにアクセスするには、[Stripe-Account ヘッダーの連結アカウント ID](https://docs.stripe.com/connect/authentication.md) を使用して Stripe API をクエリする必要があります。
このスコーピング動作は、Fivetran などのデータ同期サービスや、プラットフォームレベルの API クエリに依存するその他のサードパーティの組み込みに影響します。ダイレクト支払いデータを取得するには、プラットフォームではなく連結アカウントをクエリする必要があります。
> 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 "<>:" \
-H "Stripe-Account: {{CONNECTEDACCOUNT_ID}}" \
-d "line_items[0][price_data][currency]=usd" \
-d "line_items[0][price_data][product_data][name]=T-shirt" \
-d "line_items[0][price_data][unit_amount]=1000" \
-d "line_items[0][quantity]=1" \
-d "payment_intent_data[application_fee_amount]=123" \
-d mode=payment \
--data-urlencode "success_url=https://example.com/success?session_id={CHECKOUT_SESSION_ID}"
```
- `Stripe-Account`: このヘッダーは、連結アカウントのダイレクト支払いを示します。決済では連結アカウントの [ブランディング](https://docs.stripe.com/connect/direct-charges.md#branding) が使用されます。これにより、プラットフォームではなく連結アカウントと直接やり取りしているような印象を顧客に与えることができます。
- `line_items`: この属性は、顧客が購入しようとしているアイテムを表し、Stripe が提供する決済ページに表示されます。
- `payment_intent_data[application_fee_amount]`: この属性は、プラットフォームがプラットフォーム手数料として取引から差し引く金額を指定します。連結アカウントで支払いが処理された後、`application_fee_amount` がプラットフォームに送金されます。詳細については、[手数料の回収](https://docs.stripe.com/connect/direct-charges.md#collect-fees)をご覧ください。
- `success_url`: Stripe は、顧客が支払いを完了した後に成功時の URL にリダイレクトし、`{CHECKOUT_SESSION_ID}` の文字列を決済セッションの ID に置き換えます。この ID を使用してチェックアウトセッションを取得し、ステータスを確認して、顧客に表示する内容を決定してください。自社で使用するクエリパラメーターを追加することもできます。このパラメーターはリダイレクトプロセス全体にわたって存続します。詳細については、[Stripe が提供するウェブサイトでリダイレクトの動作をカスタマイズする](https://docs.stripe.com/payments/checkout/custom-success-page.md) をご覧ください。
連結アカウントで作成した決済を[決済リスト](https://dashboard.stripe.com/test/payments)で表示します。ダイレクト決済はエクスポートには表示されませんが、[レポート](https://docs.stripe.com/stripe-reports.md)、[Sigma](https://docs.stripe.com/stripe-data/sigma.md)、または API を使用して確認できます。
## 支払い後のイベントを処理する [サーバー側]
支払いが完了すると 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: その他の支払い方法を有効にする
ダッシュボードの[連結アカウントの支払い方法を管理する](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)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 |

支払い方法のオプション
支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。

保存ダイアログ
### 連結アカウントによる支払い方法の管理を許可する
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 ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。
このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。

アカウントのカスタマイズのチェックボックス
### 支払い方法ケイパビリティ
連結アカウントが追加の支払い方法を受け入れられるようにするには、`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` 配列にそれが含まれます。
## 手数料を回収する
プラットフォームでは、各取引の一部をプラットフォーム手数料という形で連結アカウントに請求できます。プラットフォーム手数料の料金体系は、以下の方法で設定できます。
- [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、料金設定ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。
- プラットフォーム手数料は [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接指定します。この方法で設定された手数料は、Platform Pricing Tool で指定された料金体系ロジックを上書きします。
プラットフォームは、以下の制限でプラットフォーム手数料を請求する場合があります。
- `application_fee_amount` の値は正の値で、支払い金額よりも小さくする必要があります。回収するプラットフォーム手数料は、支払い金額を上限とします。
- プラットフォーム手数料自体に追加の Stripe 手数料はありません。
- ブラジルの規制ならびに法令遵守の要件に従い、ブラジルの連結アカウントが含まれ、ブラジル国外を拠点とするプラットフォームは、Stripe を通じてプラットフォーム手数料を回収することはできません。
- `application_fee_amount` の通貨は、[複数の通貨](https://docs.stripe.com/connect/currencies.md)のいくつかの要素によって決まります。
結果として生じる決済の [BalanceTransaction](https://docs.stripe.com/api.md#balance_transaction_retrieve) には、Stripe 手数料とプラットフォーム手数料の両方の詳細な内訳が含まれます。レポート機能を向上させるために、手数料を回収すると [ApplicationFee](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが生成されます。`ApplicationFee` オブジェクトの `amount` プロパティを使用してレポートを作成します。
プラットフォーム手数料は、ダッシュボードの[手数料収入](https://dashboard.stripe.com/connect/application_fees)セクションで確認できます。
> デフォルトでは、ダイレクト支払いのプラットフォーム手数料は非同期で作成されます。支払い作成リクエストで `application_fee` オブジェクトを拡張すると、リクエストの一部としてプラットフォーム手数料が同期的に作成されます。`application_fee` オブジェクトを拡張するとリクエストの遅延が増加するため、必要な場合に拡張してください。
>
> 非同期で作成された `ApplicationFee` オブジェクトの通知を受信するには、[application_fee.created](https://docs.stripe.com/api/events/types.md#event_types-application_fee.created) Webhook イベントをリッスンします。
### 手数料を含む売上のフロー
決済に対するプラットフォーム手数料を指定すると、その手数料の金額がプラットフォームの Stripe アカウントに送金されます。連結アカウントで直接決済を処理する場合、Stripe 手数料とプラットフォーム手数料を差し引いた決済額が連結アカウントに入金されます。
たとえば、前の例のように、10 USD の決済を作成し、そのプラットフォーム手数料が 1.23 USD の場合、1.23 USD がプラットフォームアカウントに送金されます。8.18 USD (10 USD - 0.59 USD - 1.23 USD) が連結アカウントでの手取り額となります (標準的なアメリカの Stripe 手数料を想定した場合)。

複数の通貨で支払いを処理する場合は、Connect で[どのように通貨が処理されるか](https://docs.stripe.com/connect/currencies.md)についてもご覧ください。
## ブランディングをカスタマイズする
プラットフォームと連結アカウントでは、ダッシュボードの[ブランディング設定](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 "<>:" \
-H "Stripe-Account: {{CONNECTEDACCOUNT_ID}}" \
-d "line_items[0][price_data][currency]=usd" \
-d "line_items[0][price_data][product_data][name]=T-shirt" \
-d "line_items[0][price_data][unit_amount]=1000" \
-d "line_items[0][quantity]=1" \
-d "payment_intent_data[application_fee_amount]=123" \
-d mode=payment \
-d ui_mode=embedded_page \
--data-urlencode "return_url=https://example.com/checkout/return?session_id={CHECKOUT_SESSION_ID}"
```
- `Stripe-Account`: このヘッダーは、連結アカウントのダイレクト支払いを示します。決済では連結アカウントの [ブランディング](https://docs.stripe.com/connect/direct-charges.md#branding) が使用されます。これにより、プラットフォームではなく連結アカウントと直接やり取りしているような印象を顧客に与えることができます。
- `line_items`: この属性は、顧客が購入しようとしているアイテムを表し、オンライン決済フォームに表示されます。
- `payment_intent_data[application_fee_amount]`: この属性は、プラットフォームがプラットフォーム手数料として取引から差し引く金額を指定します。連結アカウントで支払いが処理された後、`application_fee_amount` がプラットフォームに送金されます。詳細については、[手数料の回収](https://docs.stripe.com/connect/direct-charges.md#collect-fees)をご覧ください。
- `return_url`: Stripe は、顧客が支払いを完了した後に戻り先 URL にリダイレクトし、`{CHECKOUT_SESSION_ID}` の文字列をチェックアウトセッション ID に置き換えます。この ID を使用してチェックアウトセッションを取得し、ステータスを確認して、顧客に表示する内容を決定します。戻り先 URL は、支払いのステータスが表示されるウェブサイト上のページと一致している必要があります。また、リダイレクトプロセス全体にわたって適用する、自社クエリパラメーターを追加することもできます。詳細については、[組み込みフォームでリダイレクトの動作をカスタマイズする](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=embedded-form) をご覧ください。
連結アカウントに直接作成した支払いは、そのアカウントと [Connect ダッシュボード](https://docs.stripe.com/connect/dashboard/understand-your-connect-business.md#supported-charges) でのみレポートされます。ダイレクト支払いの `PaymentIntents` や `Charges` などの取引オブジェクトをクエリするには、[Stripe-Account ヘッダーの連結アカウント ID](https://docs.stripe.com/connect/authentication.md) を使用して Stripe API をクエリする必要があります。
## Checkout をマウントする [クライアント側]
#### HTML + JS
Checkout は [Stripe.js](https://docs.stripe.com/js.md) の一部として利用できます。HTML ファイルのヘッダーに Stripe.js スクリプトを追加してページに含めます。次に、マウンティングに使用する空の DOM ノード (コンテナー) を作成します。
```html
```
公開可能な API キーと連結アカウント ID を使用して、Stripe.jp を初期化します。Checkout インスタンスを作成するときは、前のステップの `client_secret` を `options` に渡します。
```javascript
// Initialize Stripe.js
const stripe = Stripe('<>', {
stripeAccount: '{{CONNECTED_ACCOUNT_ID}}',
});
initialize();
// Fetch Checkout Session and retrieve the client secret
async function initialize() {
const fetchClientSecret = async () => {
const response = await fetch("/create-checkout-session", {
method: "POST",
});
const { clientSecret } = await response.json();
return clientSecret;
};
// Initialize Checkout
const checkout = await stripe.createEmbeddedCheckoutPage({
fetchClientSecret,
});
// Mount Checkout
checkout.mount('#checkout');
}
```
#### React
次の npm パブリックレジストリから [React Stripe.js](https://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
```
オンライン決済フォームコンポーネントを使用するには、`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('<>', {
stripeAccount: '{{CONNECTED_ACCOUNT_ID}}',
});
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: その他の支払い方法を有効にする
ダッシュボードの[連結アカウントの支払い方法を管理する](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)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 |

支払い方法のオプション
支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。

保存ダイアログ
### 連結アカウントによる支払い方法の管理を許可する
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 ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。
このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。

アカウントのカスタマイズのチェックボックス
### 支払い方法ケイパビリティ
連結アカウントが追加の支払い方法を受け入れられるようにするには、`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` 配列にそれが含まれます。
## 手数料を回収する
プラットフォームでは、各取引の一部をプラットフォーム手数料という形で連結アカウントに請求できます。プラットフォーム手数料の料金体系は、以下の方法で設定できます。
- [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、料金設定ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。
- プラットフォーム手数料は [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接指定します。この方法で設定された手数料は、Platform Pricing Tool で指定された料金体系ロジックを上書きします。
プラットフォームは、以下の制限でプラットフォーム手数料を請求する場合があります。
- `application_fee_amount` の値は正の値で、支払い金額よりも小さくする必要があります。回収するプラットフォーム手数料は、支払い金額を上限とします。
- プラットフォーム手数料自体に追加の Stripe 手数料はありません。
- ブラジルの規制ならびに法令遵守の要件に従い、ブラジルの連結アカウントが含まれ、ブラジル国外を拠点とするプラットフォームは、Stripe を通じてプラットフォーム手数料を回収することはできません。
- `application_fee_amount` の通貨は、[複数の通貨](https://docs.stripe.com/connect/currencies.md)のいくつかの要素によって決まります。
結果として生じる決済の [BalanceTransaction](https://docs.stripe.com/api.md#balance_transaction_retrieve) には、Stripe 手数料とプラットフォーム手数料の両方の詳細な内訳が含まれます。レポート機能を向上させるために、手数料を回収すると [ApplicationFee](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが生成されます。`ApplicationFee` オブジェクトの `amount` プロパティを使用してレポートを作成します。
プラットフォーム手数料は、ダッシュボードの[手数料収入](https://dashboard.stripe.com/connect/application_fees)セクションで確認できます。
> デフォルトでは、ダイレクト支払いのプラットフォーム手数料は非同期で作成されます。支払い作成リクエストで `application_fee` オブジェクトを拡張すると、リクエストの一部としてプラットフォーム手数料が同期的に作成されます。`application_fee` オブジェクトを拡張するとリクエストの遅延が増加するため、必要な場合に拡張してください。
>
> 非同期で作成された `ApplicationFee` オブジェクトの通知を受信するには、[application_fee.created](https://docs.stripe.com/api/events/types.md#event_types-application_fee.created) Webhook イベントをリッスンします。
## ブランディングをカスタマイズする
プラットフォームと連結アカウントでは、ダッシュボードの[ブランディング設定](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/direct-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 "<>:" \
-H "Stripe-Account: {{CONNECTEDACCOUNT_ID}}" \
-d amount=1000 \
-d currency=usd \
-d "automatic_payment_methods[enabled]=true" \
-d application_fee_amount=123
```
#### 支払い方法を手動で一覧表示する
```curl
curl https://api.stripe.com/v1/payment_intents \
-u "<>:" \
-H "Stripe-Account: {{CONNECTEDACCOUNT_ID}}" \
-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 "payment_method_types[]=sofort" \
-d application_fee_amount=123
```
PaymentIntent を作成する際は、特定のパラメーターを指定する必要があります。
- `amount`: 指定した金額でサーバー上に PaymentIntent を作成します。請求金額は、信頼できる環境であるサーバー側で常に決定するようにしてください。このアプローチによって、悪意のある顧客が価格を操作できないようにします。
- `currency`: 顧客に表示される決済手段は、PaymentIntent に含める通貨によって絞り込まれるため、提供する決済手段に基づいて選択します。たとえば、`eur` を渡し、ダッシュボードで OXXO を有効にしている場合、OXXO は `eur` での支払いに対応していないため、顧客に表示されません。一部の決済手段は、複数の通貨と国に対応しています。このガイドのサンプルコードでは、Bancontact、クレジットカード、EPS、iDEAL、Przelewy24、SEPA ダイレクトデビット、Sofort を使用します。
- `"payment_method_types[]"`: 対応しているすべての決済手段を手動で一覧表示します。
- (オプション) `payment_intent_data[application_fee_amount]`: この引数は、プラットフォームが取引から受け付ける予定の金額を指定します。Stripe の[プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、[ダッシュボード](https://dashboard.stripe.com/test/settings/connect/platform_pricing/payments)でプラットフォーム手数料の料金を管理している場合、設定された価格設定ロジックがツールによって上書きされるため、この引数は含めないようにしてください。連結アカウントで支払いが処理された後、`application_fee_amount` がプラットフォームに送金され、Stripe 手数料が連結アカウントの残高から差し引かれます。
> 各支払い方法は 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
// Initialize Stripe.js with the same connected account ID used when creating
// the PaymentIntent.
const stripe = Stripe('<>', {
stripeAccount: '{{CONNECTED_ACCOUNT_ID}}'
});
```
### Stripe Elements と Payment Element を決済ページに追加する
決済ページには Payment Element を配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。
```html
```
フォームが読み込まれたら、Payment Element のインスタンスを作成して、それを前のステップの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) とともに、コンテナーの DOM ノードにマウントします。[Elements](https://docs.stripe.com/js/elements_object/create) インスタンスの作成時に、オプションとしてこの値を渡します。
client secret は支払いを完了できるため、慎重に扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩したりすることがないようにしてください。
```javascript
const options = {
clientSecret: '{{CLIENT_SECRET}}',
// Fully customizable with the Appearance API
appearance: {/*...*/},
};
// Set up Stripe.js and Elements to use in checkout form using the client secret
const elements = stripe.elements(options);
// Create and mount the Payment Element
const paymentElement = elements.create("payment");
paymentElement.mount("#payment-element");
```
Payment Element によって動的なフォームが表示され、顧客が支払い方法を選択できるようになります。顧客が選択した支払い方法に必要なすべての支払い詳細が、フォームで自動的に収集されます。`Elements` オブジェクトを設定するときに、自社のサイトのデザインに合わせて [Payment Element のデザインをカスタマイズ](https://docs.stripe.com/elements/appearance-api.md)できます。
#### 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` と、前のステップの [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("<>", {
stripeAccount: '{{CONNECTED_ACCOUNT_ID}}'
});
function App() {
const options = {
// pass the client secret from the previous step
clientSecret: '{{CLIENT_SECRET}}',
// Fully customizable with the Appearance API
appearance: {/*...*/},
};
return (
);
};
ReactDOM.render(, document.getElementById('root'));
```
### PaymentElement コンポーネントを追加する
`PaymentElement` コンポーネントを使用して、フォームを構築します。
```jsx
import React from 'react';
import {PaymentElement} from '@stripe/react-stripe-js';
const CheckoutForm = () => {
return (
);
};
export default CheckoutForm;
```
Payment Element によって動的なフォームが表示され、顧客は支払い方法のタイプを選択できます。このフォームは、顧客が選択した支払い方法に必要なすべての支払い詳細を自動的に収集します。`Elements` プロバイダーを設定するときに、自社のサイトのデザインに合わせて [Payment Element のデザインをカスタマイズ](https://docs.stripe.com/elements/appearance-api.md)できます。
## 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 (
);
};
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: その他の支払い方法を有効にする
ダッシュボードの[連結アカウントの支払い方法を管理する](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)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 |

支払い方法のオプション
支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。

保存ダイアログ
### 連結アカウントによる支払い方法の管理を許可する
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 ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。
このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。

アカウントのカスタマイズのチェックボックス
### 支払い方法ケイパビリティ
連結アカウントが追加の支払い方法を受け入れられるようにするには、`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` 配列にそれが含まれます。
## 手数料を回収する
プラットフォームでは、各取引の一部をプラットフォーム手数料という形で連結アカウントに請求できます。プラットフォーム手数料の料金体系は、以下の方法で設定できます。
- [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、料金設定ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。
- プラットフォーム手数料は [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接指定します。この方法で設定された手数料は、Platform Pricing Tool で指定された料金体系ロジックを上書きします。
プラットフォームは、以下の制限でプラットフォーム手数料を請求する場合があります。
- `application_fee_amount` の値は正の値で、支払い金額よりも小さくする必要があります。回収するプラットフォーム手数料は、支払い金額を上限とします。
- プラットフォーム手数料自体に追加の Stripe 手数料はありません。
- ブラジルの規制ならびに法令遵守の要件に従い、ブラジルの連結アカウントが含まれ、ブラジル国外を拠点とするプラットフォームは、Stripe を通じてプラットフォーム手数料を回収することはできません。
- `application_fee_amount` の通貨は、[複数の通貨](https://docs.stripe.com/connect/currencies.md)のいくつかの要素によって決まります。
結果として生じる決済の [BalanceTransaction](https://docs.stripe.com/api.md#balance_transaction_retrieve) には、Stripe 手数料とプラットフォーム手数料の両方の詳細な内訳が含まれます。レポート機能を向上させるために、手数料を回収すると [ApplicationFee](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが生成されます。`ApplicationFee` オブジェクトの `amount` プロパティを使用してレポートを作成します。
プラットフォーム手数料は、ダッシュボードの[手数料収入](https://dashboard.stripe.com/connect/application_fees)セクションで確認できます。
> デフォルトでは、ダイレクト支払いのプラットフォーム手数料は非同期で作成されます。支払い作成リクエストで `application_fee` オブジェクトを拡張すると、リクエストの一部としてプラットフォーム手数料が同期的に作成されます。`application_fee` オブジェクトを拡張するとリクエストの遅延が増加するため、必要な場合に拡張してください。
>
> 非同期で作成された `ApplicationFee` オブジェクトの通知を受信するには、[application_fee.created](https://docs.stripe.com/api/events/types.md#event_types-application_fee.created) Webhook イベントをリッスンします。

[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)をご覧ください。
導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。
この接続方法では、以下の 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 <>: \
-H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"
-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" \
```
#### 支払い方法を手動で一覧表示する
#### 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 <>: \
-H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"
-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" \
```
> 各決済手段は 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) を初期化します。
次に、`STPAPIClient.shared.stripeAccount` を連結アカウントの ID に設定します。
#### 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 = publishableKeySTPAPIClient.shared.stripeAccount = ""{{CONNECTED_ACCOUNT_ID}}""// 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) を初期化します。
次に、`STPAPIClient.shared.stripeAccount` を連結アカウントの ID に設定します。
```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 = publishableKeySTPAPIClient.shared.stripeAccount = ""{{CONNECTED_ACCOUNT_ID}}""// 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
STPAPIClient.shared.stripeAccount = ""{{CONNECTED_ACCOUNT_ID}}""
// 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 を受け付けられるようになります。

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) オブジェクトで設定されます。
### デザイン
色やフォントなどをアプリの見た目や雰囲気に合わせてカスタマイズするには、[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 がレイアウトを自動で最適化するように設定することもできます。

#### 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 で支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。

アプリの 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: その他の支払い方法を有効にする
ダッシュボードの[連結アカウントの支払い方法を管理する](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)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 |

支払い方法のオプション
支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。

保存ダイアログ
### 連結アカウントによる支払い方法の管理を許可する
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 ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。
このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。

アカウントのカスタマイズのチェックボックス
### 支払い方法ケイパビリティ
連結アカウントが追加の支払い方法を受け入れられるようにするには、`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` 配列にそれが含まれます。
## 手数料を回収する
プラットフォームでは、各取引の一部をプラットフォーム手数料という形で連結アカウントに請求できます。プラットフォーム手数料の料金体系は、以下の方法で設定できます。
- [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、料金設定ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。
- プラットフォーム手数料は [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接指定します。この方法で設定された手数料は、Platform Pricing Tool で指定された料金体系ロジックを上書きします。
プラットフォームは、以下の制限でプラットフォーム手数料を請求する場合があります。
- `application_fee_amount` の値は正の値で、支払い金額よりも小さくする必要があります。回収するプラットフォーム手数料は、支払い金額を上限とします。
- プラットフォーム手数料自体に追加の Stripe 手数料はありません。
- ブラジルの規制ならびに法令遵守の要件に従い、ブラジルの連結アカウントが含まれ、ブラジル国外を拠点とするプラットフォームは、Stripe を通じてプラットフォーム手数料を回収することはできません。
- `application_fee_amount` の通貨は、[複数の通貨](https://docs.stripe.com/connect/currencies.md)のいくつかの要素によって決まります。
結果として生じる決済の [BalanceTransaction](https://docs.stripe.com/api.md#balance_transaction_retrieve) には、Stripe 手数料とプラットフォーム手数料の両方の詳細な内訳が含まれます。レポート機能を向上させるために、手数料を回収すると [ApplicationFee](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが生成されます。`ApplicationFee` オブジェクトの `amount` プロパティを使用してレポートを作成します。
プラットフォーム手数料は、ダッシュボードの[手数料収入](https://dashboard.stripe.com/connect/application_fees)セクションで確認できます。
> デフォルトでは、ダイレクト支払いのプラットフォーム手数料は非同期で作成されます。支払い作成リクエストで `application_fee` オブジェクトを拡張すると、リクエストの一部としてプラットフォーム手数料が同期的に作成されます。`application_fee` オブジェクトを拡張するとリクエストの遅延が増加するため、必要な場合に拡張してください。
>
> 非同期で作成された `ApplicationFee` オブジェクトの通知を受信するには、[application_fee.created](https://docs.stripe.com/api/events/types.md#event_types-application_fee.created) Webhook イベントをリッスンします。

[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.2.0")
// Include the financial connections SDK to support US bank account as a payment method
implementation("com.stripe:financial-connections:23.2.0")
}
```
> 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)をご覧ください。
導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。
この接続方法では、以下の 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 <>: \
-H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"
-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" \
```
#### 支払い方法を手動で一覧表示する
#### 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 <>: \
-H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"
-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" \
```
> 各決済手段は 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, ""{{CONNECTED_ACCOUNT_ID}}"")}
}
}
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, ""{{CONNECTED_ACCOUNT_ID}}"")
}
}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, ""{{CONNECTED_ACCOUNT_ID}}"")}
}
}
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) オブジェクトを使用して設定されます。
### デザイン
アプリの見た目や使い心地に合わせて、[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 がレイアウトを自動で最適化するように設定することもできます。

#### 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 に戻って支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。

> 導入サンプルは[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: その他の支払い方法を有効にする
ダッシュボードの[連結アカウントの支払い方法を管理する](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)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 |

支払い方法のオプション
支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。

保存ダイアログ
### 連結アカウントによる支払い方法の管理を許可する
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 ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。
このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。

アカウントのカスタマイズのチェックボックス
### 支払い方法ケイパビリティ
連結アカウントが追加の支払い方法を受け入れられるようにするには、`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` 配列にそれが含まれます。
## 手数料を回収する
プラットフォームでは、各取引の一部をプラットフォーム手数料という形で連結アカウントに請求できます。プラットフォーム手数料の料金体系は、以下の方法で設定できます。
- [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、料金設定ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。
- プラットフォーム手数料は [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接指定します。この方法で設定された手数料は、Platform Pricing Tool で指定された料金体系ロジックを上書きします。
プラットフォームは、以下の制限でプラットフォーム手数料を請求する場合があります。
- `application_fee_amount` の値は正の値で、支払い金額よりも小さくする必要があります。回収するプラットフォーム手数料は、支払い金額を上限とします。
- プラットフォーム手数料自体に追加の Stripe 手数料はありません。
- ブラジルの規制ならびに法令遵守の要件に従い、ブラジルの連結アカウントが含まれ、ブラジル国外を拠点とするプラットフォームは、Stripe を通じてプラットフォーム手数料を回収することはできません。
- `application_fee_amount` の通貨は、[複数の通貨](https://docs.stripe.com/connect/currencies.md)のいくつかの要素によって決まります。
結果として生じる決済の [BalanceTransaction](https://docs.stripe.com/api.md#balance_transaction_retrieve) には、Stripe 手数料とプラットフォーム手数料の両方の詳細な内訳が含まれます。レポート機能を向上させるために、手数料を回収すると [ApplicationFee](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが生成されます。`ApplicationFee` オブジェクトの `amount` プロパティを使用してレポートを作成します。
プラットフォーム手数料は、ダッシュボードの[手数料収入](https://dashboard.stripe.com/connect/application_fees)セクションで確認できます。
> デフォルトでは、ダイレクト支払いのプラットフォーム手数料は非同期で作成されます。支払い作成リクエストで `application_fee` オブジェクトを拡張すると、リクエストの一部としてプラットフォーム手数料が同期的に作成されます。`application_fee` オブジェクトを拡張するとリクエストの遅延が増加するため、必要な場合に拡張してください。
>
> 非同期で作成された `ApplicationFee` オブジェクトの通知を受信するには、[application_fee.created](https://docs.stripe.com/api/events/types.md#event_types-application_fee.created) Webhook イベントをリッスンします。

この統合は、決済の詳細収集や決済確認など、決済に必要なすべてのステップを一つのシートにまとめ、アプリ上部に表示されます。
## 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 の場合は、依存関係をインストールする必要はありません。
### Stripe の初期化
React Native アプリで Stripe を初期化するには、決済画面を `StripeProvider` コンポーネントでラップするか、`initStripe` 初期化メソッドを使用します。`publishableKey` の API [公開可能キー](https://docs.stripe.com/keys.md#obtain-api-keys)のみが必要です。次の例は、`StripeProvider` コンポーネントを使用して Stripe を初期化する方法を示しています。
```javascript
import { StripeProvider } from '@stripe/stripe-react-native';
function App() {
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)をご覧ください。
導入で [customer-configured Accounts](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) を使用している場合は、コード例内の `Customer` とイベント参照を、対応する Accounts v2 API リファレンスに置き換えてください。詳細については、[Account オブジェクトで顧客を表す](https://docs.stripe.com/connect/use-accounts-as-customers.md)をご覧ください。
この接続方法では、以下の 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 <>: \
-H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"
-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" \
```
#### 支払い方法を手動で一覧表示する
#### 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 <>: \
-H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"
-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" \
```
> 各決済手段は 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 (
);
}
```
顧客が**決済**ボタンをタップしたら、`presentPaymentSheet()` を呼び出して画面を表示します。顧客が支払いを完了すると、この画面は閉じ、オプションの `StripeError` とともに promise が解決されます。
```javascript
export default function CheckoutScreen() {
// continued from above
const openPaymentSheet = async () => {
const { error } = await presentPaymentSheet();
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
} else {
Alert.alert('Success', 'Your order is confirmed!');
}
};
return (
);
}
```
エラーがない場合は、ユーザーに完了したことを伝えます (注文確認画面を表示するなど)。
`allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。
## 戻り先 URL を設定する (iOS のみ) [クライアント側]
顧客はお客様のアプリから離れて、(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
}
}
}
}
}
```
さらに、[PaymentSheet.Configuration](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) オブジェクトの [returnURL](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV9returnURLSSSgvp) をアプリの URL に設定します。
```swift
var configuration = PaymentSheet.Configuration()
configuration.returnURL = "your-app://stripe-redirect"
```
## 支払い後のイベントを処理する
支払いが完了すると、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)をご覧ください。
## カードの読み取りを有効にする [クライアント側]
> Apple の iOS アプリの確認プロセスでは、カードのスキャン機能を有効にする必要があります。Android アプリの確認プロセスでは、カードのスキャン機能は必要ありませんが、Stripe ではこの機能を有効にすることを推奨しています。
### iOS
iOS をサポートするカードスキャン機能を有効にするには、アプリケーションの `Info.plist` の `NSCameraUsageDescription` (**プライバシー - カメラ利用の詳細**)を設定し、カメラにアクセスする理由を入力して下さい (例:「カードをスキャンするため」)。
### (任意) Android
カードスキャンサポートを有効にするには、[Google Pay & Wallet Console](https://pay.google.com/business/console?utm_source=devsite&utm_medium=devsite&utm_campaign=devsite) から Google Pay API への[本番アクセスをリクエスト](https://developers.google.com/pay/api/android/guides/test-and-deploy/request-prod-access)します。
- Google Pay を有効にしている場合、対象のデバイスの UI でカードスキャン機能が自動的に利用可能になります。対象のデバイスの詳細については、[Google Pay API の制約](https://developers.google.com/pay/payment-card-recognition/debit-credit-card-recognition)をご覧ください。
- **重要:** カードスキャン機能は、[Google Pay & Wallet Console](https://pay.google.com/business/console) に登録された同じ署名キーで署名されたビルドにのみ表示されます。異なる署名キーを使用したテストまたはデバッグビルド (Firebase App Tester を通じて配布されたビルドなど) では、 **カードをスキャン** オプションは表示されません。プレリリースビルドでカードスキャンをテストするには、以下のいずれかを行う必要があります。
- 本番環境の署名キーを使用してテストビルドに署名する
- Google Pay & Wallet Console にテスト署名キーのフィンガープリントを追加する
## Optional: Apple Pay を有効にする
### 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 を受け付けられるようになります。

Xcode で Apple Pay ケイパビリティを有効化する
### Apple Pay を追加する
#### 1 回限りの支払い
`StripeProvider` を作成する際に、加盟店 ID を渡します。
```javascript
import { StripeProvider } from '@stripe/stripe-react-native';
function App() {
return (
{/* Your app code here */}
);
}
```
`initPaymentSheet` を呼び出す際に、[ApplePayParams](https://stripe.dev/stripe-react-native/api-reference/modules/PaymentSheet.html#ApplePayParams) を渡します。
```javascript
await initPaymentSheet({
// ...
applePay: {
merchantCountryCode: 'US',
},
});
```
#### 継続支払い
`initPaymentSheet` を呼び出す際に、`merchantCountryCode` をビジネスの国コードに設定して、[ApplePayParams](https://stripe.dev/stripe-react-native/api-reference/modules/PaymentSheet.html#ApplePayParams) を渡します。
継続課金に関する [Apple のガイドライン](https://developer.apple.com/design/human-interface-guidelines/apple-pay#Supporting-subscriptions)に従い、決済予定の金額 (「月額 59.95 USD」など)を含む `cardItems` を設定し、その中に [RecurringCartSummaryItem](https://stripe.dev/stripe-react-native/api-reference/modules/ApplePay.html#RecurringCartSummaryItem) を含める必要があります。
`type` を `PaymentRequestType.Recurring` に設定して `request` を設定することで、[マーチャントトークン](https://developer.apple.com/apple-pay/merchant-tokens/)を導入することもできます。
Apple Pay で継続支払いを使用する方法について、詳細は [Apple の PassKit に関するドキュメント](https://developer.apple.com/documentation/passkit/pkpaymentrequest)をご覧ください。
#### iOS (React Native)
```javascript
const initializePaymentSheet = async () => {
const recurringSummaryItem = {
label: 'My Subscription',
amount: '59.99',
paymentType: 'Recurring',
intervalCount: 1,
intervalUnit: 'month',
// Payment starts today
startDate: new Date().getTime() / 1000,
// Payment ends in one year
endDate: new Date().getTime() / 1000 + 60 * 60 * 24 * 365,
};
const {error} = await initPaymentSheet({
// ...
applePay: {
merchantCountryCode: 'US',
cartItems: [recurringSummaryItem],
request: {
type: PaymentRequestType.Recurring,
description: 'Recurring',
managementUrl: 'https://my-backend.example.com/customer-portal',
billing: recurringSummaryItem,
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.'",
},
},
});
};
```
### 注文の追跡
iOS 16 以降で[注文の追跡](https://developer.apple.com/design/human-interface-guidelines/technologies/wallet/designing-order-tracking)情報を追加するには、`setOrderTracking` コールバック関数を設定します。Stripe は決済の完了後、iOS が Apple Pay 支払い画面を閉じる前にご使用の実装を呼び出します。
`setOrderTracking` コールバック関数の実装で、完了した注文の注文の詳細をサーバーから取得し、指定された `completion` 関数にその詳細を渡します。
注文の追跡の詳細については、[Apple のウォレットでの注文に関するドキュメント](https://developer.apple.com/documentation/walletorders)をご覧ください。
#### iOS (React Native)
```javascript
await initPaymentSheet({
// ...
applePay: {
// ...
setOrderTracking: async complete => {
const apiEndpoint =
Platform.OS === 'ios'
? 'http://localhost:4242'
: 'http://10.0.2.2:4567';
const response = await fetch(
`${apiEndpoint}/retrieve-order?orderId=${orderId}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
if (response.status === 200) {
const orderDetails = await response.json();
// orderDetails should include orderIdentifier, orderTypeIdentifier,
// authenticationToken and webServiceUrl
complete(orderDetails);
}
},
},
});
```
## 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 を追加する
`PaymentSheet` を初期化する際に、`merchantCountryCode` にビジネスの国コードを設定し、`googlePay` を true に設定します。
`testEnv` パラメーターを渡して、テスト環境を使用することもできます。Google Pay は、物理的な Android デバイスでのみテストできます。[React Native ドキュメント](https://reactnative.dev/docs/running-on-device)に従って、物理デバイスでアプリケーションをテストします。
```javascript
const { error, paymentOption } = await initPaymentSheet({
// ...
googlePay: {
merchantCountryCode: 'US',
testEnv: true, // use test environment
},
});
```
## Optional: 画面をカスタマイズする
カスタマイズはすべて `initPaymentSheet` を使用して設定されます。
### デザイン
色やフォントなどをアプリの見た目や雰囲気に合わせてカスタマイズするには、[Appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=react-native) を使用します。
### 加盟店の表示名
`merchantDisplayName` を設定し、顧客に対して表示するビジネス名を指定します。デフォルトはアプリ名です。
```javascript
await initPaymentSheet({
// ...
merchantDisplayName: 'Example Inc.',
});
```
### ダークモード
デフォルトで `PaymentSheet` は、ユーザーのシステム全体の表示設定 (ライト/ダークモード) に合わせて自動的に調整されます。これを変更するには、 iOS で `style` プロパティを `alwaysLight` モードまたは `alwaysDark` モードに設定します。
```javascript
await initPaymentSheet({
// ...
style: 'alwaysDark',
});
```
Android では、アプリでライトモードまたはダークモードに設定します。
```
// force dark
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
// force light
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
```
### デフォルトの請求詳細
PaymentSheet で収集される請求先情報のデフォルト値を設定するには、`defaultBillingDetails` プロパティを設定します。`PaymentSheet` の各フィールドに、指定した値が事前に読み込まれます。
```javascript
await initPaymentSheet({
// ...
defaultBillingDetails: {
email: 'foo@bar.com',
address: {
country: 'US',
},
},
});
```
### 請求詳細を収集する
`billingDetailsCollectionConfiguration` を使用して、PaymentSheet で請求先情報を収集する方法を指定します。
顧客の名前、メールアドレス、電話番号、住所を収集できます。
支払い方法に必要な値を収集しない場合は、以下を実行する必要があります。
1. `PaymentSheet` によって収集されない値を `defaultBillingDetails` プロパティに関連付けます。
1. `billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を `true` に設定します。
```javascript
await initPaymentSheet({
// ...
defaultBillingDetails: {
email: 'foo@bar.com',
},
billingDetailsCollectionConfiguration: {
name: PaymentSheet.CollectionMode.ALWAYS,
email: PaymentSheet.CollectionMode.NEVER,
address: PaymentSheet.AddressCollectionMode.FULL,
attachDefaultsToPaymentMethod: true
},
});
```
> 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。
## Optional: UI で支払いを完了する
支払い画面を表示して支払い方法の詳細のみを収集し、その後 `confirm` メソッドを呼び出して、アプリの UI で支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。

> サンプルの組み込みは、[Stripe の GitHub からご利用いただけます](https://github.com/stripe/stripe-react-native/blob/master/example/src/screens/PaymentsUICustomScreen.tsx)。
1. まず `initPaymentSheet` を呼び出し、`customFlow: true` を渡します。`initPaymentSheet` は、顧客の支払い方法を示す画像とラベルが格納された、最初の支払いオプションで解決されます。これらの詳細で UI を更新します。
```javascript
const {
initPaymentSheet,
presentPaymentSheet,
confirmPaymentSheetPayment,
} = useStripe()
const { error, paymentOption } = await initPaymentSheet({
customerId: customer,
customerEphemeralKeySecret: ephemeralKey,
paymentIntentClientSecret: paymentIntent,
customFlow: true,
merchantDisplayName: 'Example Inc.',
});
// Update your UI with paymentOption
```
1. `presentPaymentSheet` を使用して支払いの詳細を収集します。顧客が操作を完了すると、シートは自動的に閉じられ、promise が解決されます。UI は選択された支払い方法の詳細で更新されます。
```javascript
const { error, paymentOption } = await presentPaymentSheet();
```
1. `confirmPaymentSheetPayment` を使用し、支払いを確定します。これは、支払いの結果で解決されます。
```javascript
const { error } = await confirmPaymentSheetPayment();
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
} else {
Alert.alert(
'Success',
'Your order is confirmed!'
);
}
```
`allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。
## Optional: その他の支払い方法を有効にする
ダッシュボードの[連結アカウントの支払い方法を管理する](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)自身の支払い方法を管理することを許可していても、連結アカウントはこれを有効にできません。 |

支払い方法のオプション
支払い方法を変更した場合は、画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、連結アカウントを更新する必要があります。

保存ダイアログ
### 連結アカウントによる支払い方法の管理を許可する
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 ダッシュボードには、新規および既存のすべての連結アカウントに対して適用される支払い方法のデフォルトのセットが表示されます。連結アカウントは、お客様がブロックした支払い方法を除き、これらのデフォルトを上書きできます。
このオプションを有効にするには、**アカウントのカスタマイズ**チェックボックスを選択します。画面下部のバーにある**変更を確認**をクリックし、**保存して適用**をクリックして、この設定を更新する必要があります。

アカウントのカスタマイズのチェックボックス
### 支払い方法ケイパビリティ
連結アカウントが追加の支払い方法を受け入れられるようにするには、`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` 配列にそれが含まれます。
## 手数料を回収する
プラットフォームでは、各取引の一部をプラットフォーム手数料という形で連結アカウントに請求できます。プラットフォーム手数料の料金体系は、以下の方法で設定できます。
- [プラットフォームの料金設定ツール](https://docs.stripe.com/connect/platform-pricing-tools.md)を使用して、料金設定ルールを設定してテストします。この Stripe ダッシュボードのノーコード機能は、現時点では Stripe 手数料の支払い責任を負うプラットフォームでのみ利用できます。
- プラットフォーム手数料は [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) で直接指定します。この方法で設定された手数料は、Platform Pricing Tool で指定された料金体系ロジックを上書きします。
プラットフォームは、以下の制限でプラットフォーム手数料を請求する場合があります。
- `application_fee_amount` の値は正の値で、支払い金額よりも小さくする必要があります。回収するプラットフォーム手数料は、支払い金額を上限とします。
- プラットフォーム手数料自体に追加の Stripe 手数料はありません。
- ブラジルの規制ならびに法令遵守の要件に従い、ブラジルの連結アカウントが含まれ、ブラジル国外を拠点とするプラットフォームは、Stripe を通じてプラットフォーム手数料を回収することはできません。
- `application_fee_amount` の通貨は、[複数の通貨](https://docs.stripe.com/connect/currencies.md)のいくつかの要素によって決まります。
結果として生じる決済の [BalanceTransaction](https://docs.stripe.com/api.md#balance_transaction_retrieve) には、Stripe 手数料とプラットフォーム手数料の両方の詳細な内訳が含まれます。レポート機能を向上させるために、手数料を回収すると [ApplicationFee](https://docs.stripe.com/api/application_fees/object.md) オブジェクトが生成されます。`ApplicationFee` オブジェクトの `amount` プロパティを使用してレポートを作成します。
プラットフォーム手数料は、ダッシュボードの[手数料収入](https://dashboard.stripe.com/connect/application_fees)セクションで確認できます。
> デフォルトでは、ダイレクト支払いのプラットフォーム手数料は非同期で作成されます。支払い作成リクエストで `application_fee` オブジェクトを拡張すると、リクエストの一部としてプラットフォーム手数料が同期的に作成されます。`application_fee` オブジェクトを拡張するとリクエストの遅延が増加するため、必要な場合に拡張してください。
>
> 非同期で作成された `ApplicationFee` オブジェクトの通知を受信するには、[application_fee.created](https://docs.stripe.com/api/events/types.md#event_types-application_fee.created) Webhook イベントをリッスンします。
## 返金する
プラットフォームは連結アカウントに対して支払いを作成できるのと同様に、連結アカウントに対して支払いの返金を作成することもできます。連結アカウントとして[認証済み](https://docs.stripe.com/connect/authentication.md#stripe-account-header)の状態で、プラットフォームのシークレットキーを使用して[返金を作成](https://docs.stripe.com/api.md#create_refund)します。
返金する際に、プラットフォーム手数料は自動的に返金されません。プラットフォームはプラットフォーム手数料を明示的に返金する必要があります。そうしなければ、連結アカウント (決済が作成されたアカウント) はその金額を失うことになります。返金リクエストで、`refund_application_fee` 値を **true** として渡すことによって、プラットフォーム手数料を返金できます。
```curl
curl https://api.stripe.com/v1/refunds \
-u "<>:" \
-H "Stripe-Account: {{CONNECTEDACCOUNT_ID}}" \
-d "charge={{CHARGE_ID}}" \
-d refund_application_fee=true
```
デフォルトでは支払いの全額が返金されますが、`amount` 値を正の整数に設定することで、一部返金を作成することができます。支払いの全額が返金されることになった場合は、プラットフォーム手数料の全額が返金されます。そうでない場合は、プラットフォーム手数料の比例配分された部分が返金されます。別の方法として、`refund_application_fee` 値に **false** を指定し、別途[プラットフォーム手数料を返金する](https://docs.stripe.com/api.md#create_fee_refund)こともできます。
## Connect の埋め込みコンポーネント
[Connect 埋め込みコンポーネント](https://docs.stripe.com/connect/get-started-connect-embedded-components.md) はダイレクト支払いに対応しています。[決済埋め込みコンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payments.md) を使用することで、連結アカウントがサイト内から決済情報の表示、支払いのキャプチャー、不審請求の申し立ての管理を行えるようになります。
Note: The following is a preview/demo component that behaves differently than live mode usage with real connected accounts. The actual component has more functionality than what might appear in this demo component. For example, for connected accounts without Stripe dashboard access (custom accounts), no user authentication is required in production.
以下のコンポーネントには、ダイレクト支払いの情報が表示されます。
- [支払いコンポーネント](https://docs.stripe.com/connect/supported-embedded-components/payments.md):アカウントのすべての支払いと紛争を表示します。
- [決済の詳細](https://docs.stripe.com/connect/supported-embedded-components/payment-details.md):特定の決済に関する情報を表示します。
- [紛争一覧コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/disputes-list.md):アカウントのすべての紛争を表示します。
- [支払いに関する紛争コンポーネント](https://docs.stripe.com/connect/supported-embedded-components/disputes-for-a-payment.md):特定の支払いに関する紛争を表示します。これを使って、支払い用 UI があるページに紛争管理機能を組み込むことができます。
## See also
- [複数通貨を処理する](https://docs.stripe.com/connect/currencies.md)
- [Connect での明細書表記](https://docs.stripe.com/connect/statement-descriptors.md)