# 設定で支払い方法を管理する 支払い方法設定シートを使用して、顧客がアプリの設定ページで支払い方法を管理できるようにします。 > Payment Method Settings Sheet は、アプリの設定ページで使用することを想定しています。決済処理には、決済手段の保存と表示にも対応し、Payment Method Settings Sheet よりも多くの決済手段をサポートする[アプリ内決済](https://docs.stripe.com/payments/mobile.md)を使用してください。 > コードでは、このコンポーネントは歴史的な理由から `CustomerSheet` として参照されます。ドキュメント全体を通して、コード例で `CustomerSheet` と記載されている場合、これは Payment Method Settings Sheet を指します。 Payment Method Settings Sheet は、顧客が保存した決済手段を管理できるようにする組み込み済みの UI コンポーネントです。決済フローの外側で Payment Method Settings Sheet の UI を使用でき、外観とスタイルはアプリの外観と美観に合わせてカスタマイズ可能です。顧客は決済手段の追加と削除ができます。決済手段は`Customer`オブジェクトに保存され、顧客はデバイスにローカル保存されるデフォルトの決済手段を設定できます。アプリ内決済と Payment Method Settings Sheet の両方を使用することで、保存された決済手段に関する一貫したエンドツーエンドのソリューションを顧客に提供できます。 > #### Accounts v2 API サポート > > Payment Method Settings Sheet は*顧客設定のアカウント* (Account configurations represent role-based functionality that you can enable for accounts, such as merchant, customer, or recipient)をサポートしていません。`Customer`オブジェクトのみをサポートしています。 ![iOS アプリに保存された複数の支払い方法を提示する支払い方法設定シートのスクリーンショット。](https://b.stripecdn.com/docs-statics-srv/assets/ios-landing.6c4969968fd6efe3d39fe673628f8284.png) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) オブジェクトは、SDK に `Customer` への一時的なアクセス権を付与し、追加の設定オプションを提供します。これらの設定オプションにより、CustomerSheet の動作をカスタマイズできます。CustomerSession で公開される機能の一覧は、[API ドキュメント](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)に記載されています。 ## Stripe を設定する まず、Stripe アカウントが必要です。[今すぐご登録ください](https://dashboard.stripe.com/register)。 [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)キーを使用します。 ## 支払い方法を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。 多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。 > CustomerSheet は、カード、アメリカの銀行口座、SEPA ダイレクトデビットのみに対応しています。 ## 顧客エンドポイントを追加 [サーバー側] サーバー側で、CustomerSession の client secret を取得するエンドポイントと、新しい決済手段を [Customer](https://docs.stripe.com/api/customers.md) に保存する [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を作成するエンドポイントの 2 つのエンドポイントを作成します。 1. [Customer](https://docs.stripe.com/api/customers.md) ID と [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) の client secret を返すエンドポイントを作成します。 #### curl ```bash # Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[customer_sheet][enabled]"=true \ -d "components[customer_sheet][features][payment_method_remove]"=enabled ``` > レガシーの顧客の一時キーを使用した実装では、保存された決済手段の `allow_redisplay` 値が `unspecified` になります。Customer Sessions の使用時に保存した決済手段に加えて、これらの決済手段を表示するには、`payment_method_allow_redisplay_filters` を `["unspecified", "always"]` に設定します。詳細については、[CustomerSessions](https://docs.stripe.com/api/customer_sessions.md) をご覧ください。 1. [Customer](https://docs.stripe.com/api/customers.md) ID を指定して設定された [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を返すエンドポイントを作成します。 #### curl ```bash # Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" curl https://api.stripe.com/v1/setup_intents \ -u <>: \ -d "customer"="{{CUSTOMER_ID}}" \ ``` 今後の支払いで、顧客が決済フローでオンセッション時にのみ決済手段を使用する場合、[usage](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-usage) パラメーターを *on\_session* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) に設定して、オーソリ率を改善します。 ## 画面を設定する 次に、`IntentConfiguration`、`CustomerSessionClientSecretProvider`、[CustomerSheet.Configuration](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/customersheet/configuration/) を持つ`CustomerSheet` クラスを使用して支払い方法設定シートを構成します。 ```swift var configuration = CustomerSheet.Configuration() // Configure settings for the CustomerSheet here. For example: configuration.headerTextForSelectionScreen = "Manage your payment method" let intentConfiguration = CustomerSheet.IntentConfiguration(setupIntentClientSecretProvider: { let json = try await myBackend.createSetupIntent() return json["setupIntentClientSecret"]! }) let customerSheet = CustomerSheet( configuration: configuration, intentConfiguration: intentConfiguration, customerSessionClientSecretProvider: { let json = try await myBackend.createCustomerSessionClientSecret() return .init(customerId: json["customerId"]!, clientSecret: json["customerSessionClientSecret"]!) }) ``` ## 支払い画面を表示する #### UIKit `CustomerSheet` を使用して支払い方法設定シートを提示します。顧客がシートを閉じると、`CustomerSheet` は`CustomerSheet.SheetResult` で完了ブロックを呼び出します。 #### iOS (Swift) ```swift import StripePaymentSheet customerSheet.present(from: self, completion: { result in switch result { case .canceled(let paymentOption), .selected(let paymentOption): // Configure your UI based on the payment option self.paymentLabel.text = paymentOption?.displayData().label ?? "None" // Optional: Send the selected payment method ID to your back end for advanced use cases // like charging a customer when not present in your app if let paymentOption = paymentOption { switch paymentOption { case .paymentMethod(let paymentMethod, let paymentOptionDisplayData): MyBackend.setDefaultPaymentMethod(paymentMethod.stripeId) case .applePay(paymentOptionDisplayData: let paymentOptionDisplayData): MyBackend.setDefaultPaymentMethodIsApplePay() } } case .error(let error): // Show the error in your UI } }) ``` - 顧客が決済手段を選択する場合、その結果は `.selected(PaymentOptionSelection?)` になります。関連付けられる値は、選択した [PaymentOptionSelection](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/customersheet/paymentoptionselection) になり、ユーザーが過去に選択した決済手段を削除した場合は `nil` になります。決済手段の詳細は、PaymentOptionSelection の `paymentMethod` の関連値で確認できます。 - ユーザーが画面をキャンセルした場合、その結果は `.canceled` になります。関連付けられる値は、Customer Sheet を開く前に選択された元の決済手段です (その決済手段がまだ利用可能な場合)。 - エラーが発生した場合、その結果は `.error(Error)` になります。 Apple Pay を有効にする方法は[こちら](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-apple-pay)をご覧ください。 #### SwiftUI 支払い方法設定シートを表示する画面用の`ObservableObject` モデルを作成します。このモデルは、[CustomerSheet](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/customersheet) のインスタンスを保持します。 ```swift import StripePaymentSheet import SwiftUI class YourAccountViewModel: ObservableObject { var customerSheet: CustomerSheet } ``` `.customerSheet` ViewModifier を使用して、支払い方法設定シートを表示します。 ```swift struct YourAccountView: View { @State private var showingCustomerSheet = false @ObservedObject var model = YourAccountViewModel() var body: some View { VStack { Button(action: { showingCustomerSheet = true }) { Text("Present Customer Sheet") }.customerSheet( isPresented: $showingCustomerSheet, customerSheet: model.customerSheet, onCompletion: model.onCompletion) } } } ``` `customerSheetResult` を追加し、支払い方法設定シートを提示した結果を`ObservableObject` に保存します。 ```swift class YourAccountViewModel: ObservableObject { var customerSheet: CustomerSheet @Published var customerSheetResult: CustomerSheet.CustomerSheetResult? func onCompletion(result: CustomerSheet.CustomerSheetResult) { self.customerSheetResult = result } } ``` `customerSheetResult` を使用して、選択された支払い方法を UI に表示します。 ```swift struct YourAccountView: View { @State private var showingCustomerSheet = false @ObservedObject var model = MyBackendCustomerSheetModel() var body: some View { VStack { Button(action: { showingCustomerSheet = true }) { Text("Present Customer Sheet") }.customerSheet( isPresented: $showingCustomerSheet, customerSheet: model.customerSheet, onCompletion: model.onCompletion)if let customerSheetResult = model.customerSheetResult { ExampleCustomerSheetPaymentMethodView(customerSheetResult: customerSheetResult) } } } } ``` - 顧客が決済手段を選択する場合、その結果は `.selected(PaymentOptionSelection?)` になります。関連付けられる値は、選択した [PaymentOptionSelection](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/customersheet/paymentoptionselection) になり、ユーザーが過去に選択した決済手段を削除した場合は `nil` になります。決済手段の詳細は、PaymentOptionSelection の `paymentMethod` の関連値で確認できます。 - ユーザーが画面をキャンセルした場合、その結果は `.canceled` になります。選択された支払い方法は変更されていません。 - エラーが発生した場合、その結果は `.error(Error)` になります。 Apple Pay を有効にする方法は[こちら](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-apple-pay)をご覧ください。 ## Optional: ACH 決済を有効にする ACH デビット支払いを有効にするには、以下を行います。 1. アプリの依存関係として `StripeFinancialConnections` を含めます。 1. [ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)の設定セクションで、支払い方法としてアメリカの銀行口座を有効化します。 ## Optional: 選択した支払い方法を取得する 支払い方法設定シートを表示せずにデフォルトの支払い方法を取得するには、`CustomerSheet` で`retrievePaymentOptionSelection()` を呼び出します。 ```swift let paymentMethodOption = try await customerSheet.retrievePaymentOptionSelection() // Configure your UI based on the payment option self.paymentLabel.text = paymentMethodOption?.displayData().label ?? "None" // Send the selected payment method ID to your back end switch paymentMethodOption { case .paymentMethod(paymentMethod: let paymentMethod, paymentOptionDisplayData: let paymentOptionDisplayData): try await MyBackend.setDefaultPaymentMethod(paymentMethod.stripeId) case .applePay(paymentOptionDisplayData: let paymentOptionDisplayData): try await MyBackend.setDefaultPaymentMethodIsApplePay() } ``` ## Optional: 画面をカスタマイズする ### デザイン [Appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=ios) を使用して、アプリのデザインに合わせて色、フォント、その他の外観の属性をカスタマイズします。 > `fetchPaymentMethods` は、保存された決済手段を除外して表示しないようにできますが、追加可能な決済手段のタイプには影響しません。 ### デフォルトの請求詳細 支払い画面で収集される請求詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティを設定します。`CustomerSheet` の各フィールドに、指定した値が事前に読み込まれます。 ```swift var configuration = CustomerSheet.Configuration() configuration.defaultBillingDetails.address.country = "US" configuration.defaultBillingDetails.email = "foo@bar.com" ``` ### 請求詳細の収集 `billingDetailsCollectionConfiguration` を使用して、決済画面で請求詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 `CustomerSheet` によって収集されない値を関連付けるには、`defaultBillingDetails` プロパティに値を追加し、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を `true` に設定します。決済手段が必要とする値を収集する予定がない場合は、必ずこの手順を実行してください。 ```swift var configuration = CustomerSheet.Configuration() configuration.defaultBillingDetails.email = "foo@bar.com" configuration.billingDetailsCollectionConfiguration.name = .always configuration.billingDetailsCollectionConfiguration.email = .never configuration.billingDetailsCollectionConfiguration.address = .full configuration.billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod = true ``` > 情報の収集に適用される法律については、法務チームに相談してください。電話番号は、取引に必要な場合にのみ収集してください。 > Payment Method Settings Sheet は、アプリの設定ページで使用することを想定しています。決済処理には、決済手段の保存と表示にも対応し、Payment Method Settings Sheet よりも多くの決済手段をサポートする[アプリ内決済](https://docs.stripe.com/payments/mobile.md)を使用してください。 > コードでは、このコンポーネントは歴史的な理由から `CustomerSheet` として参照されます。ドキュメント全体を通して、コード例で `CustomerSheet` と記載されている場合、これは Payment Method Settings Sheet を指します。 Payment Method Settings Sheet は、顧客が保存した決済手段を管理できるようにする組み込み済みの UI コンポーネントです。決済フローの外側で Payment Method Settings Sheet の UI を使用でき、外観とスタイルはアプリの外観と美観に合わせてカスタマイズ可能です。顧客は決済手段の追加と削除ができます。決済手段は`Customer`オブジェクトに保存され、顧客はデバイスにローカル保存されるデフォルトの決済手段を設定できます。アプリ内決済と Payment Method Settings Sheet の両方を使用することで、保存された決済手段に関する一貫したエンドツーエンドのソリューションを顧客に提供できます。 > #### Accounts v2 API サポート > > Payment Method Settings Sheet は*顧客設定のアカウント* (Account configurations represent role-based functionality that you can enable for accounts, such as merchant, customer, or recipient)をサポートしていません。`Customer`オブジェクトのみをサポートしています。 ![Android アプリに保存された複数の支払い方法を提示する支払い方法設定シートのスクリーンショット。](https://b.stripecdn.com/docs-statics-srv/assets/ios-landing.6c4969968fd6efe3d39fe673628f8284.png) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) オブジェクトは、SDK に `Customer` または顧客設定の `Account` への一時的なアクセス権を付与し、追加の設定オプションを提供します。これらの設定オプションにより、`CustomerSheet` の動作をカスタマイズできます。`CustomerSession` で公開される機能の一覧は、[API ドキュメント](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)に記載されています。 ## Stripe を設定する まず、Stripe アカウントが必要です。[今すぐ登録してください](https://dashboard.stripe.com/register)。 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.9.1") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.9.1") } ``` > 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)キーを使用します。 ## 決済手段を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。 多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。 > 支払い方法設定シートは、現時点ではクレジットカードとアメリカの銀行口座にのみ対応しています。 ## 顧客エンドポイントを追加 [サーバー側] サーバー側で、CustomerSession の client secret を取得するエンドポイントと、新しい決済手段を [Customer](https://docs.stripe.com/api/customers.md) に保存する [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を作成するエンドポイントの 2 つのエンドポイントを作成します。 1. [Customer](https://docs.stripe.com/api/customers.md) ID と [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) の client secret を返すエンドポイントを作成します。 #### curl ```bash # Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[customer_sheet][enabled]"=true \ -d "components[customer_sheet][features][payment_method_remove]"=enabled ``` > レガシーの顧客の一時キーを使用した実装では、保存された決済手段の `allow_redisplay` 値が `unspecified` になります。Customer Sessions の使用時に保存した決済手段に加えて、これらの決済手段を表示するには、`payment_method_allow_redisplay_filters` を `["unspecified", "always"]` に設定します。詳細については、[CustomerSessions](https://docs.stripe.com/api/customer_sessions.md) をご覧ください。 1. [Customer](https://docs.stripe.com/api/customers.md) ID を指定して設定された [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を返すエンドポイントを作成します。 #### curl ```bash # Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" curl https://api.stripe.com/v1/setup_intents \ -u <>: \ -d "customer"="{{CUSTOMER_ID}}" \ ``` 今後の支払いで、顧客が決済フローでオンセッション時にのみ決済手段を使用する場合、[usage](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-usage) パラメーターを *on\_session* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) に設定して、オーソリ率を改善します。 ## Customer Session プロバイダーを作成 [クライアント側] `CustomerSessionProvider` は、[CustomerSession](https://docs.stripe.com/api/customer_sessions.md) オブジェクトを通じて `CustomerSheet` を Stripe と通信できるようにします。クライアント側で `CustomerSessionProvider` を作成します。これにより、サーバーで `CustomerSession` client secret と `SetupIntent` client secret を作成できるようになります。 ```kotlin import com.stripe.android.customersheet.CustomerSheet import com.stripe.android.customersheet.ExperimentalCustomerSheetApi @OptIn(ExperimentalCustomerSheetApi::class) class MyCustomerSessionProvider : CustomerSheet.CustomerSessionProvider() { val myBackend = // .... override suspend fun providesCustomerSessionClientSecret(): Result { return myBackend.getCustomerSessionClientSecret().fold( onSuccess = { response -> Result.success( CustomerSessionClientSecret.create( customerId = response.customerId, clientSecret = response.customerSessionClientSecret, ) ) }, onFailure = { exception -> Result.failure(exception) } ) } override suspend fun provideSetupIntentClientSecret(customerId: String): Result { return myBackend.getSetupIntentClientSecret(customerId).fold( onSuccess = { response -> Result.success(response.setupIntentClientSecret) }, onFailure = { exception -> Result.failure(exception) } ) } } ``` ```kotlin import android.app.Application import androidx.lifecycle.AndroidViewModel class CheckoutViewModel( application: Application ) : AndroidViewModel(application) { val customerSessionProvider = MyCustomerSessionProvider() } ``` ## 画面を設定する 次に、`CustomerSheet` クラスと`CustomerSessionProvider` を使用して支払い方法設定シートを初期化し、[CustomerSheet.Configuration](https://github.com/stripe/stripe-android/blob/master/paymentsheet/src/main/java/com/stripe/android/customersheet/CustomerSheet.kt) を使用して`configure` を呼び出します。`present` および`retrievePaymentOptionSelection` を呼び出す前に、必ず`configure` を呼び出してください。 ```kotlin import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import com.stripe.android.customersheet.CustomerSheet import com.stripe.android.customersheet.ExperimentalCustomerSheetApi import com.stripe.android.customersheet.rememberCustomerSheet @OptIn(ExperimentalCustomerSheetApi::class) class CheckoutActivity : ComponentActivity() { private val viewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val configuration = CustomerSheet.Configuration.builder(merchantDisplayName = "{{YOUR BUSINESS NAME}}") .build() setContent { val customerSheet = rememberCustomerSheet( customerSessionProvider = viewModel.customerSessionProvider, callback = viewModel::handleResult // Implemented in next step ) LaunchedEffect(customerSheet) { customerSheet.configure(configuration = configuration) } } } } ``` ## 画面を表示する `CustomerSheet` を使用して支払い方法設定シートを提示します。顧客がシートを終了すると、`CustomerSheet` は完了ブロックを呼び出し、`CustomerSheetResult` を渡します。 ```kotlin import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModelsimport androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.stripe.android.customersheet.CustomerSheet import com.stripe.android.customersheet.ExperimentalCustomerSheetApi import com.stripe.android.customersheet.rememberCustomerSheetimport com.stripe.android.uicore.image.rememberDrawablePainter @OptIn(ExperimentalCustomerSheetApi::class) class CheckoutActivity : ComponentActivity() {private val viewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val configuration = CustomerSheet.Configuration.builder(merchantDisplayName = "{{YOUR BUSINESS NAME}}") .headerTextForSelectionScreen("Manage your payment method") .build() setContent { val customerSheet = rememberCustomerSheet( customerSessionProvider = viewModel.customerSessionProvider, callback = viewModel::handleResult ) LaunchedEffect(customerSheet) { customerSheet.configure(configuration = configuration)viewModel.handleResult(customerSheet.retrievePaymentOptionSelection()) }val paymentOption by viewModel.paymentOption.collectAsState() Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { val icon = paymentOption?.icon() if (icon != null) { Image( painter = rememberDrawablePainter( drawable = icon ), contentDescription = "Payment Method Icon", modifier = Modifier.height(32.dp) ) } TextButton( onClick = { customerSheet.present() } ) { Text( text = paymentOption?.label ?: "Select" ) } } } } } ``` ```kotlin import android.app.Application import androidx.lifecycle.AndroidViewModel import com.stripe.android.customersheet.ExperimentalCustomerSheetApiimport com.stripe.android.paymentsheet.model.PaymentOption import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update @OptIn(ExperimentalCustomerSheetApi::class) class CheckoutViewModel( application: Application ) : AndroidViewModel(application) { val customerSessionProvider = // ... private val _paymentOption = MutableStateFlow(null) val paymentOption: StateFlow = _paymentOption fun handleResult(result: CustomerSheetResult) { when (result) { is CustomerSheetResult.Selected -> { // Configure your UI based on the payment option _paymentOption.update { result.selection?.paymentOption } } is CustomerSheetResult.Canceled -> { // Configure your UI based on the payment option _paymentOption.update { result.selection?.paymentOption } } is CustomerSheetResult.Failed -> { // Show the error in your UI } } } } ``` - 顧客が支払い方法を選択する場合、その結果は、`CustomerSheetResult.Selected` になります。関連付けられる値は、選択された `PaymentOptionSelection` になるか、ユーザーが過去に選択した支払い方法を削除した場合は null になります。支払い方法の詳細は、`PaymentOptionSelection` の `paymentMethod` 値で確認できます。 - 顧客が画面をキャンセルした場合、その結果は `CustomerSheetResult.Canceled` になります。関連付けられる値は、顧客の元の `PaymentOptionSelection` であるか、顧客が以前に決済手段を選択していない場合や、最初に選択した決済手段を削除している場合は null になります。 - エラーが発生した場合、その結果は `CustomerSheetResult.Failed` になります。 ## 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 を追加するには、[CustomerSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.customersheet/-customer-sheet/-configuration/index.html) を [CustomerSheet.Configuration.Builder](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.customersheet/-customer-sheet/-configuration/-builder/index.html) で初期化する際に、[googlePayEnabled](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.customersheet/-customer-sheet/-configuration/-builder/google-pay-enabled.html) に `true` を渡します。 #### Kotlin ```kotlin val configuration = CustomerSheet.Configuration.Builder() .googlePayEnabled(true) .build() ``` ## Optional: ACH 決済を有効にする ACH デビット決済を有効にするには、アプリの依存関係として Financial Connections を指定します。 [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` ブロックに `financial-connections` を追加します。 #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Financial Connections Android SDK implementation("com.stripe:financial-connections:23.9.1") } ``` > 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)してください。 ## Optional: 選択した支払い方法を取得する 支払い方法設定シートを表示せずにデフォルトの支払い方法を取得するには、`CustomerSheet` で`retrievePaymentOptionSelection()` を呼び出します。 ```kotlin class CheckoutActivity : ComponentActivity() { private val viewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val configuration = ... setContent { val customerSheet = ... LaunchedEffect(Unit) { customerSheet.configure(configuration = configuration) val result = customerSheet.retrievePaymentOptionSelection() viewModel.handleResult(result) } ... } } } ``` ## Optional: 画面をカスタマイズする ### デザイン [Appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=android) を使用して、アプリのデザインに合わせて色、フォント、その他の外観の属性をカスタマイズします。 > `retrievePaymentMethods` は、保存された決済手段を除外して表示しないようにできますが、追加可能な決済手段のタイプには影響しません。 ### デフォルトの請求詳細 Customer sheet で収集される請求詳細のデフォルト値を設定するには、[defaultBillingDetails](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.customersheet/-customer-sheet/-configuration/-builder/index.html#-1446247975%2FFunctions%2F2002900378) プロパティを設定します。`CustomerSheet` の各フィールドに、指定した値が事前に読み込まれます。 ```kotlin val configuration = CustomerSheet.Configuration.Builder() .defaultBillingDetails( PaymentSheet.BillingDetails( address = PaymentSheet.Address( country = "US" ), email = "foo@bar.com" ) ) .build() ``` ### 請求詳細の収集 [billingDetailsCollectionConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.customersheet/-customer-sheet/-configuration/-builder/index.html#1512634376%2FFunctions%2F2002900378) を使用して、決済画面で請求詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 `CustomerSheet` によって収集されない値を関連付けるには、[defaultBillingDetails](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.customersheet/-customer-sheet/-configuration/-builder/index.html#-1446247975%2FFunctions%2F2002900378) プロパティに値を追加し、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を `true` に設定します。決済手段が必要とする値を収集する予定がない場合は、必ずこの手順を実行してください。 ```kotlin val configuration = CustomerSheet.Configuration.Builder() .defaultBillingDetails( PaymentSheet.BillingDetails( email = "foo@bar.com" ) ) .billingDetailsCollectionConfiguration( PaymentSheet.BillingDetailsCollectionConfiguration( name = PaymentSheet.BillingDetailsCollectionConfiguration.AddressCollectionMode.Always, email = PaymentSheet.BillingDetailsCollectionConfiguration.AddressCollectionMode.Never, address = PaymentSheet.BillingDetailsCollectionConfiguration.AddressCollectionMode.Full, attachDefaultsToPaymentMethod = true, ) ) .build() ``` > 情報の収集に適用される法律については、法務チームに相談してください。電話番号は、取引に必要な場合にのみ収集してください。 > Payment Method Settings Sheet は、アプリの設定ページで使用することを想定しています。決済処理には、決済手段の保存と表示にも対応し、Payment Method Settings Sheet よりも多くの決済手段をサポートする[アプリ内決済](https://docs.stripe.com/payments/mobile.md)を使用してください。 > コードでは、このコンポーネントは歴史的な理由から `CustomerSheet` として参照されます。ドキュメント全体を通して、コード例で `CustomerSheet` と記載されている場合、これは Payment Method Settings Sheet を指します。 Payment Method Settings Sheet は、顧客が保存した決済手段を管理できるようにする組み込み済みの UI コンポーネントです。決済フローの外側で Payment Method Settings Sheet の UI を使用でき、外観とスタイルはアプリの外観と美観に合わせてカスタマイズ可能です。顧客は決済手段の追加と削除ができます。決済手段は`Customer`オブジェクトに保存され、顧客はデバイスにローカル保存されるデフォルトの決済手段を設定できます。アプリ内決済と Payment Method Settings Sheet の両方を使用することで、保存された決済手段に関する一貫したエンドツーエンドのソリューションを顧客に提供できます。 > #### Accounts v2 API サポート > > Payment Method Settings Sheet は*顧客設定のアカウント* (Account configurations represent role-based functionality that you can enable for accounts, such as merchant, customer, or recipient)をサポートしていません。`Customer`オブジェクトのみをサポートしています。 ![iOS アプリに保存された複数の支払い方法を提示する支払い方法設定シートのスクリーンショット。](https://b.stripecdn.com/docs-statics-srv/assets/ios-landing.6c4969968fd6efe3d39fe673628f8284.png) ## Stripe をセットアップする まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 [React Native SDK](https://github.com/stripe/stripe-react-native) はオープンソースであり、詳細なドキュメントが提供されています。内部では、[ネイティブの iOS](https://github.com/stripe/stripe-ios) および [Android](https://github.com/stripe/stripe-android) の SDK を使用します。Stripe の React Native SDK をインストールするには、プロジェクトのディレクトリーで (使用するパッケージマネージャーによって異なる) 次のいずれかのコマンドを実行します。 #### yarn ```bash yarn add @stripe/stripe-react-native ``` #### npm ```bash npm install @stripe/stripe-react-native ``` 次に、その他の必要な依存関係をインストールします。 - iOS の場合は、**ios** ディレクトリに移動して `pod install` を実行し、必要なネイティブ依存関係もインストールします。 - Android の場合は、依存関係をインストールする必要はありません。 > [公式の TypeScript ガイド](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project)に従って TypeScript のサポートを追加することをお勧めします。 ### Stripe の初期化 React Native アプリで Stripe を初期化するには、決済画面を `StripeProvider` コンポーネントでラップするか、`initStripe` 初期化メソッドを使用します。`publishableKey` の API [公開可能キー](https://docs.stripe.com/keys.md#obtain-api-keys)のみが必要です。次の例は、`StripeProvider` コンポーネントを使用して Stripe を初期化する方法を示しています。 ```jsx import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( {/* Your app code here */} ); } ``` > テストおよび開発時には API の[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 ## 決済手段を有効にする [支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*SetupIntent* (The Setup Intents API lets you build dynamic flows for collecting payment method details for future payments. It tracks the lifecycle of a payment setup flow and can trigger additional authentication steps if required by law or by the payment method) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。 多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。 > CustomerSheet はカードとアメリカの銀行口座にのみ対応しています。 ## 顧客エンドポイントを追加 [サーバー側] サーバー側で、CustomerSession の client secret を取得するエンドポイントと、新しい決済手段を [Customer](https://docs.stripe.com/api/customers.md) に保存する [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を作成するエンドポイントの 2 つのエンドポイントを作成します。 1. [Customer](https://docs.stripe.com/api/customers.md) ID と [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) の client secret を返すエンドポイントを作成します。 #### curl ```bash # Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" curl https://api.stripe.com/v1/customer_sessions \ -u <>: \ -X "POST" \ -d "customer"="{{CUSTOMER_ID}}" \ -d "components[customer_sheet][enabled]"=true \ -d "components[customer_sheet][features][payment_method_remove]"=enabled ``` > レガシーの顧客の一時キーを使用した実装では、保存された決済手段の `allow_redisplay` 値が `unspecified` になります。Customer Sessions の使用時に保存した決済手段に加えて、これらの決済手段を表示するには、`payment_method_allow_redisplay_filters` を `["unspecified", "always"]` に設定します。詳細については、[CustomerSessions](https://docs.stripe.com/api/customer_sessions.md) をご覧ください。 1. [Customer](https://docs.stripe.com/api/customers.md) ID を指定して設定された [SetupIntent](https://docs.stripe.com/api/setup_intents.md) を返すエンドポイントを作成します。 #### curl ```bash # Create a Customer (skip this and get the existing Customer ID if this is a returning customer) curl https://api.stripe.com/v1/customers \ -u <>: \ -X "POST" curl https://api.stripe.com/v1/setup_intents \ -u <>: \ -d "customer"="{{CUSTOMER_ID}}" \ ``` 今後の支払いで、顧客が決済フローでオンセッション時にのみ決済手段を使用する場合、[usage](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-usage) パラメーターを *on\_session* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) に設定して、オーソリ率を改善します。 ## 画面を初期化する 2 つのメソッドを実装する `ClientSecretProvider` オブジェクトを作成します。`CustomerSheet は`、`CustomerSession` オブジェクトと前に作成されたエンドポイントを使用して Stripe と通信するために、ClientSecretProvider を必要とします。 ```jsx import {ClientSecretProvider, CustomerSessionClientSecret} from '@stripe/stripe-react-native'; const clientSecretProvider: ClientSecretProvider = { // Must return an object with customerId and clientSecret async provideCustomerSessionClientSecret(): Promise { const result = await MyBackend.createCustomerSession(); return { customerId: result.customer, clientSecret: result.customerSessionClientSecret, }; }, // Must return a string async provideSetupIntentClientSecret(): Promise { const result = await MyBackend.createSetupIntent(); return result.setupIntent; } }; ``` 次に、Payment Method Settings Sheet を設定します。これは `CustomerSheet` クラスを使用して、`CustomerSheet.initialize` に希望の設定を提供することで設定できます。 ```jsx import {CustomerSheet} from '@stripe/stripe-react-native'; const {error} = await CustomerSheet.initialize({ // You must provide intentConfiguration and clientSecretProvider intentConfiguration: { paymentMethodTypes: ['card'], }, clientSecretProvider: clientSecretProvider, headerTextForSelectionScreen: 'Manage your payment method', returnURL: 'my-return-url://', }); ``` ## 支払い画面を表示する #### 機能性 `CustomerSheet` を使用して Payment Method Settings Sheet を提示します。顧客がシートを破棄すると、プロミスは `CustomerSheetResult` で解決します。 #### 関数を直接使用する ```jsx import {CustomerSheet} from '@stripe/stripe-react-native'; const {error, paymentOption, paymentMethod} = await CustomerSheet.present(); if (error) { if (error.code === CustomerSheetError.Canceled) { // Customer dismissed the sheet without changing their payment option } else { // Show the error in your UI } } else { if (paymentOption) { // Configure your UI based on the payment option MyBackend.setDefaultPaymentMethod(paymentMethod.id); } if (paymentMethod) { console.log(JSON.stringify(paymentMethod, null, 2)); } } ``` - 顧客が決済手段を選択した場合、結果には `paymentOption` が含まれます。関連付けられた値は、選択された [PaymentOption](https://stripe.dev/stripe-react-native/api-reference/interfaces/PaymentSheet.PaymentOption.html)、または、顧客が以前に選択した決済手段を削除した場合は `nil` となります。決済手段の詳細は、`paymentMethod` プロパティで確認できます。 - 顧客がシートをキャンセルした場合、その結果には `error.code === CustomerSheetError.Canceled` の `error` が含まれます。選択された決済手段は変更されません。 - エラーが発生した場合、詳細は `error` に含まれます。 Apple Pay を有効にする方法は[こちら](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-apple-pay)をご覧ください。 #### コンポーネント 支払い方法設定シート (`CustomerSheet`) の表示を制御する状態変数を作成します。 ```jsx import {CustomerSheet, ClientSecretProvider, CustomerSessionClientSecret} from '@stripe/stripe-react-native'; export default function MyScreen() { const [customerSheetVisible, setCustomerSheetVisible] = React.useState(false); const clientSecretProvider: ClientSecretProvider = { async provideCustomerSessionClientSecret(): Promise { const result = await MyBackend.createCustomerSession(); return { customerId: result.customer, clientSecret: result.customerSessionClientSecret, }; }, async provideSetupIntentClientSecret(): Promise { const result = await MyBackend.createSetupIntent(); return result.setupIntent; } }; return (