# 設定で支払い方法を管理する 支払い方法設定シートを使用して、顧客がアプリの設定ページで支払い方法を管理できるようにします。 > 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.2") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.9.2") } ``` > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。 Stripe の[公開可能キー](https://dashboard.stripe.com/apikeys)を使用して SDK を設定し、 `Application` サブクラスなどで、Stripe API へのリクエストを実行できるようにします。 #### Kotlin ```kotlin import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "<>" ) } } ``` > テストおよび開発時には[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 ## 決済手段を有効にする [支払い方法の設定](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.2") } ``` > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。 ## 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() ``` > 情報の収集に適用される法律については、法務チームに相談してください。電話番号は、取引に必要な場合にのみ収集してください。