# アプリ内決済を受け付ける Payment Sheet を使用して、iOS、Android、または React Native アプリにカスタムの決済システムを構築します。 Payment Sheet はカスタマイズ可能なコンポーネントであり、アプリ内でボトムシートを使用して決済手段リストを表示し、支払い情報を収集します。 > #### Accounts v2 API に対応する > > Payment Sheet は*顧客設定のアカウント* (Account configurations represent role-based functionality that you can enable for accounts, such as merchant, customer, or recipient)をサポートしていません。`Customer`オブジェクトのみをサポートしています。 # 決済手段を収集して保存する SetupIntent フローを使用する場合、請求を作成することなく、将来の支払いに備えて決済手段を保存できます。この実装では、アプリに Payment Sheet をレンダリングし、*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) を作成して決済手段を保存します。 ## Stripe を設定する [サーバー側] [クライアント側] ### サーバー側 この組み込みは、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` を入力します。 2. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。 3. **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) の最新バージョンをインストールします。 2. 既存の [Podfile](https://guides.cocoapods.org/syntax/podfile.html) がない場合は、以下のコマンドを実行して作成します。 ```bash pod init ``` 3. この行を `Podfile` に追加します。 ```podfile pod 'StripePaymentSheet' ``` 4. 以下のコマンドを実行します。 ```bash pod install ``` 5. これ以降は、Xcode でプロジェクトを開く際に、`.xcodeproj` ファイルではなく、必ず `.xcworkspace` ファイルを使用するということを忘れないでください。 6. 今後、SDK の最新バージョンに更新するには、以下を実行します。 ```bash pod update StripePaymentSheet ``` #### Carthage 1. まだインストールしていない場合は、[Carthage](https://github.com/Carthage/Carthage#installing-carthage) の最新バージョンをインストールします。 2. この行を `Cartfile` に追加します。 ```cartfile github "stripe/stripe-ios" ``` 3. [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)にリストされている必要なフレームワークのすべてを埋め込んでください。 4. 今後、SDK の最新バージョンに更新するには、以下のコマンドを実行します。 ```bash carthage update stripe-ios --platform ios ``` #### 手動のフレームワーク 1. Stripe の [GitHub リリースページ](https://github.com/stripe/stripe-ios/releases/latest)に移動して、**Stripe.xcframework.zip** をダウンロードして解凍します。 2. **StripePaymentSheet.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。 3. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentSheet/README.md#manual-linking)にリストされている必要なフレームワークのすべてに対して、ステップ 2 を繰り返します。 4. 今後、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)して、新しいリリースの公開時に通知を受け取ることも可能です。 また、SDK が Stripe への API コールを実行できるように、[公開可能キー](https://dashboard.stripe.com/apikeys)を設定する必要もあります。開始するには、導入中にクライアント側で公開可能キーをハードコード化できますが、本番環境ではサーバーから公開可能キーを取得します。 ```swift // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys STPAPIClient.shared.publishableKey = "<>" ``` ## 支払い方法を有効にする [支払い方法の設定](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)をご覧ください。 ## 戻り先 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 } } } } } ``` さらに、[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" ``` ## 顧客を作成する [サーバー側] 以降の決済のために決済手段を設定するには、顧客を表すオブジェクトに関連付ける必要があります。顧客がアカウントを作成するか、ビジネスと最初の取引を行うときに、[Customer](https://docs.stripe.com/api/customers/create.md) オブジェクトを作成します。 ```curl curl -X POST https://api.stripe.com/v1/customers \ -u "<>:" ``` ## 支払いの詳細を収集する [クライアント側] 実装には 2 つのスタイルを利用できます。いずれかを選択して、続行してください。 | PaymentSheet | PaymentSheet.FlowController | | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | ![PaymentSheet](https://b.stripecdn.com/docs-statics-srv/assets/ios-overview.9e0d68d009dc005f73a6f5df69e00458.png) | ![PaymentSheet.FlowController](https://b.stripecdn.com/docs-statics-srv/assets/ios-multi-step.cd631ea4f1cd8cf3f39b6b9e1e92b6c5.png) | | 支払い情報を収集して設定を完了する画面を表示します。画面に**設定**というボタンが表示され、支払い方法が設定されます。 | 支払い情報の収集のみを行う画面を表示します。画面に**続行する**というボタンが表示され、購入者はアプリに戻されて、そのアプリ内のお客様の自社設定のボタンで設定が完了します。 | #### PaymentSheet ### PaymentSheet を初期化する 決済手段を設定する 準備ができたら (顧客が決済ボタンをタップしたときなど)、`PaymentSheet.Configuration` と [PaymentSheet.IntentConfiguration](https://github.com/stripe/stripe-ios/blob/master/StripePaymentSheet/StripePaymentSheet/Source/PaymentSheet/PaymentSheetIntentConfiguration.swift) を使用して PaymentSheet を初期化します。[Configuration](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/configuration-swift.struct) オブジェクトには、通常、`returnURL` など、支払い間で変更されない PaymentSheet の一般的な設定が含まれます。[IntentConfiguration](https://github.com/stripe/stripe-ios/blob/master/StripePaymentSheet/StripePaymentSheet/Source/PaymentSheet/PaymentSheetIntentConfiguration.swift) オブジェクトには、 決済 (金額や通貨など) ```swift import StripePaymentSheet class MyCheckoutVC: UIViewController { func didTapCheckoutButton() {let intentConfig = PaymentSheet.IntentConfiguration(mode: .setup(currency: "USD")) { [weak self] confirmationToken in try await self?.handleConfirmationToken(confirmationToken) } var configuration = PaymentSheet.Configuration() configuration.returnURL = "your-app://stripe-redirect" // Use the return url you set up in the previous step let paymentSheet = PaymentSheet(intentConfiguration: intentConfig, configuration: configuration) } func handleConfirmationToken(_ confirmationToken: STPConfirmationToken) async throws -> String { // ...explained later } } ``` ### PaymentSheet を提示する 次に、PaymentSheet を提示します。`present` メソッドは、顧客が決済手段の設定を完了して画面が非表示になったときに呼び出される完了ブロックを使用します。結果を処理する完了ブロックを実装します (たとえば、`.completed` のケースで確認画面を表示するなど)。 ```swift class MyCheckoutVC: UIViewController { func didTapCheckoutButton() { // ...paymentSheet.present(from: self) { result in switch result { case .completed: //Setupcompleted - show a confirmation screen. case .failed(let error): print(error) // PaymentSheet encountered an unrecoverable error. You can display the error to the user, log it, and so on case .canceled: // Customer canceled - you should probably do nothing. } } } } ``` ### 支払い情報を確定する 顧客が PaymentSheet で Setup をタップすると、`PaymentSheet.IntentConfiguration` に渡されたコールバックが、顧客の支払い詳細と設定を表す [STPConfirmationToken](https://stripe.dev/stripe-ios/stripepayments/documentation/stripepayments/stpconfirmationtoken) オブジェクトで呼び出されます。 このコールバックを実装して、サーバーにリクエストを送信します。サーバーは SetupIntent を作成 リクエストが返されたら、サーバー応答のClient Secretを返すか、エラーをスローします。PaymentSheet confirms the SetupIntentを完了するために必要な次のアクションを完了するか、ローカライズされたエラーメッセージをUIに表示します ([errorDescription](https://developer.apple.com/documentation/foundation/localizederror/2946895-errordescription) または [localizedDescription](https://developer.apple.com/documentation/foundation/nserror/1414418-localizeddescription))。 ```swift class MyCheckoutVC: UIViewController { // ... func handleConfirmationToken(_ confirmationToken: STPConfirmationToken) async throws -> String { // Make a request to your own server. Pass confirmationToken.stripeId if using server-side confirmation. // Return the client secret or throw an error. return try await MyAPIClient.shared.createIntent(confirmationTokenId: confirmationToken.stripeId) } } ``` #### PaymentSheet.FlowController この実装では、決済画面に支払い情報を収集する PaymentSheet に対応する「**支払い方法**」ボタンと、設定を完了する「**購入**」ボタンが配置されていると想定しています。 ### PaymentSheet.FlowController を初期化する Checkout 画面が読み込まれたら、`PaymentSheet.Configuration` と `PaymentSheet.IntentConfiguration` を使用して `PaymentSheet.FlowController` を初期化します。[Configuration](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/configuration-swift.struct) オブジェクトには、`returnURL` など、通常は支払い間で変更されない PaymentSheet の汎用的な設定が含まれます。[IntentConfiguration](https://github.com/stripe/stripe-ios/blob/master/StripePaymentSheet/StripePaymentSheet/Source/PaymentSheet/PaymentSheetIntentConfiguration.swift) オブジェクトには、金額や通貨設定 (通貨など) などの特定の `PaymentSheet.FlowController` が初期化されたら、`paymentOption` を指定して「**支払い方法**」ボタンを更新します。このプロパティには、顧客が最初に選択したデフォルトの支払い方法を表す画像とラベルが含まれています。 ```swift class MyCheckoutVC: UIViewController { func loadCheckout() {let intentConfig = PaymentSheet.IntentConfiguration(mode: .setup(currency: "USD")) { [weak self] confirmationToken in try await self?.handleConfirmationToken(confirmationToken) } var configuration = PaymentSheet.Configuration() configuration.returnURL = "your-app://stripe-redirect" // Use the return url you set up in the previous step PaymentSheet.FlowController.create( intentConfiguration: intentConfig, configuration: configuration ) { [weak self] result in switch result { case .failure(let error): print(error) case .success(let paymentSheetFlowController): self?.paymentSheetFlowController = paymentSheetFlowController // Update your UI paymentSheetFlowController.paymentOption.image and paymentSheetFlowController.paymentOption.label } } } func handleConfirmationToken(_ confirmationToken: STPConfirmationToken) async throws -> String { // ...explained later } } ``` ### PaymentSheet を表示する 顧客が「**支払い方法**」ボタンをタップしたら、`presentPaymentOptions` を呼び出して、支払い情報を収集します。完了したら、`paymentOption` プロパティで UI を再び更新します。 ```swift paymentSheetFlowController.presentPaymentOptions(from: self) { // Update your UI using paymentSheetFlowController.paymentOption } ``` ### (任意)支払いの詳細を更新する 顧客が支払い情報を変更するアクション (割引コードの適用やカートの編集など) を実行したら、新しい値を指定して PaymentSheet.FlowController インスタンスを更新します。こうすると、UI に正確な値が表示され ( **Pay** ボタンや Apple Pay UI など)、適切な決済手段などを表示できます。PaymentSheet.FlowController を再初期化するのではなく、インスタンスを更新することで、決済画面に顧客の支払い情報が保存されます。 更新された IntentConfiguration オブジェクトを指定して `update` メソッドを呼び出します。更新の進行中は、PaymentSheet.FlowController で `present` または `confirm` を呼び出さないでください (たとえば、「**購入**」ボタンと「**支払い方法**」ボタンを無効にするなど)。 更新が完了したら、顧客が以前に選択した支払い方法が使用できなくなっている場合には、`paymentOption` プロパティを指定して UI を更新します。更新が失敗した場合は、再試行してください。 ```swift // Create an updated IntentConfiguration var updatedIntentConfig = oldIntentConfig updatedIntentConfig.amount = 999 // Disable your "Buy" and "Payment method" buttons and call `update` paymentSheetFlowController.update(intentConfiguration: updatedIntentConfig) { [weak self] error in if error != nil { // You must retry - until the update succeeds, the customer can't pay or select a payment method. // For example, you can automatically retry the update with an exponential back-off, or present the user with an alert that retries the update. } else { // Re-enable your "Buy" and "Payment method" buttons // Update your UI using paymentSheetFlowController.paymentOption.image and paymentSheetFlowController.paymentOption.label } } ``` ### 支払い情報を確定する 顧客が **購入** ボタンをタップしたら、[paymentSheetFlowController.confirm](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/confirm(from:completion:) を呼び出します)。これにより、顧客の支払いの詳細と設定を表す [STPConfirmationToken](https://stripe.dev/stripe-ios/stripepayments/documentation/stripepayments/stpconfirmationtoken) オブジェクトを使用して、`PaymentSheet.IntentConfiguration` に渡した `confirmationTokenConfirmHandler` コールバックが呼び出されます。 このコールバックを実装して、サーバーにリクエストを送信します。サーバーは SetupIntent を作成 リクエストが返されるときに、サーバーレスポンスの client secret またはエラーをスローします。PaymentSheet は、client secret を使用して SetupIntent を確定 するために必要な次のアクションを実行します。 ```swift class MyCheckoutVC: UIViewController { // ...func didTapBuyButton() { paymentSheetFlowController.confirm(from: self) { paymentResult in switch paymentResult { case .completed: //Setupcompleted - show a confirmation screen. case .failed(let error): // PaymentSheet encountered an unrecoverable error. You can display the error to the user, log it, and so on print(error) case .canceled: // Customer canceled - you should probably do nothing. } } } func handleConfirmationToken(_ confirmationToken: STPConfirmationToken) async throws -> String { // Make a request to your own server. Pass confirmationToken.stripeId if using server-side confirmation. return try await fetchIntentClientSecret(...) } } ``` サーバーコードについては以下のステップで説明します。 ## SetupIntent を作成する [サーバー側] サーバー側で *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) を作成し、これをします。決済手段は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から管理できます。Stripe は、決済手段の制約とその他のパラメーターを評価して、利用可能な決済手段のリストを決定します。 コールが成功した場合は、SetupIntent *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)) を返します。コールが失敗した場合は、[エラーを処理](https://docs.stripe.com/error-handling.md)して、エラーメッセージと顧客向けの簡単な説明を返します。 > すべての IntentConfiguration プロパティが SetupIntent ([usage](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-usage) など) と一致していることを確認します。 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') post '/create-intent' do data = JSON.parse request.body.read params = { customer: ..., # The Customer ID you previously created automatic_payment_methods: {enabled: true}, } begin intent = client.v1.setup_intents.create(params) {client_secret: intent.client_secret}.to_json rescue Stripe::StripeError => e {error: e.error.message}.to_json end end ``` ## 保存された支払い方法に後で請求する [サーバー側] > `bancontact` と `ideal` は、デフォルトでは 1 回限りの支払い方法です。以降も使用できるように設定すると、再利用可能な支払い方法タイプ `sepa_debit` が生成されます。このため、保存された支払い方法を照会するには `sepa_debit` を使用する必要があります。 請求する決済手段を見つけるには、顧客に関連付けられている決済手段を一覧表示します。この例ではカードを一覧表示していますが、サポートされている任意の [type](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-type) を一覧表示できます。 > #### Accounts v2 API を使用した顧客の表現 > > Accounts v2 API では、Connect ユーザーには一般提供され、その他の Stripe ユーザーには公開プレビューで提供されます。Accounts v2 プレビューの一部である場合は、コードで[プレビューバージョン](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning)を指定する必要があります。 > > Accounts v2 プレビューへのアクセスをリクエストするには、 > > ほとんどのユースケースでは、[Customer](https://docs.stripe.com/api/customers.md) オブジェクトを使用するのではなく、[顧客を顧客設定済みの Account オブジェクトとしてモデル化する](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md)ことをお勧めします。 #### Accounts v2 ```curl curl -G https://api.stripe.com/v1/payment_methods \ -u "<>:" \ -d "customer_account={{CUSTOMERACCOUNT_ID}}" \ -d type=card ``` #### Customers v1 ```curl curl -G https://api.stripe.com/v1/payment_methods \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d type=card ``` 顧客に *オフセッション* (A payment is described as off-session if it occurs without the direct involvement of the customer, using previously-collected payment information) で請求する準備ができたら、`Customer`または顧客設定の`Account`の ID と `PaymentMethod` ID を使用して、決済の金額と通貨を指定した `PaymentIntent` を作成します。オフセッション決済を行うには、他にもいくつかのパラメーターを設定します。 - 顧客が決済フローにおらず、カード発行会社や銀行などのパートナーからの認証リクエストに対応できないことを示すには、[off_session](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-off_session) を true に設定します。決済フロー中にパートナー (カード発行会社や銀行など) が認証をリクエストした場合、Stripe は以前の *オンセッション* (A payment is described as on-session if it occurs while the customer is actively in your checkout flow and able to authenticate the payment method) 取引の顧客情報を使用して免除をリクエストします。免除の条件が満たされない場合、`PaymentIntent` がエラーを返すことがあります。 - [confirm](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-confirm) を true に設定すると、`PaymentIntent` の作成時に即座に確定がトリガーされる。 - [payment_method](https://docs.stripe.com/api.md#create_payment_intent-payment_method) を `PaymentMethod` の ID に設定します。 - 導入で顧客をどのように表すかに応じて、[customer_account](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-customer_account) を顧客設定の `Account` の ID に設定するか、[customer](https://docs.stripe.com/api.md#create_payment_intent-customer) を `Customer` の ID に設定します。 #### Accounts v2 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" \ -d "customer_account={{CUSTOMERACCOUNT_ID}}" \ -d payment_method={{PAYMENT_METHOD_ID}} \ --data-urlencode "return_url=https://example.com/order/123/complete" \ -d off_session=true \ -d confirm=true ``` #### Customers v1 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" \ -d "customer={{CUSTOMER_ID}}" \ -d payment_method={{PAYMENT_METHOD_ID}} \ --data-urlencode "return_url=https://example.com/order/123/complete" \ -d off_session=true \ -d confirm=true ``` ## 実装をテストする #### カード | カード番号 | シナリオ | テスト方法 | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | 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: 保存済みのカードを有効にする [サーバー側] [クライアント側] `PaymentSheet` では、顧客がカードを保存でき、利用可能な決済手段に顧客が保存済みのカードを含めることもできます。顧客は、サーバー上で関連付けられた顧客設定済みの [Account](https://docs.stripe.com/api/v2/core/accounts/create.md#v2_create_accounts-configuration-customer) オブジェクトまたは [Customer](https://docs.stripe.com/api/customers/create.md) オブジェクトを持っている必要があります。顧客がカードを保存できるようにするチェックボックスを有効にするには、[CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成し、`payment_method_save` を `enabled` に設定します。 #### Accounts v2 ```javascript const stripe = require('stripe')('sk_test_your_secret_key'); app.post('/mobile-payment-element', async (req, res) => { // Use an existing Account ID if this is a returning customer. const customer_account = await stripe.v2.core.accounts.create(); const customerSession = await stripe.customerSessions.create({ customer_account: customer_account.id, components: { mobile_payment_element: { enabled: true, features: { payment_method_save: 'enabled', payment_method_redisplay: 'enabled', payment_method_remove: 'enabled' } }, }, }); res.json({ customerSessionClientSecret: customerSession.client_secret, customer_account: customer_account.id, }); }); ``` 次に、顧客の ID と CustomerSession の client secret を使用して PaymentSheet を設定します。 ```swift @_spi(CustomerSessionBetaAccess) import StripePaymentSheet var configuration = PaymentSheet.Configuration() configuration.customer = .init(id: customerAccountId, customerSessionClientSecret: customerSessionClientSecret) self.paymentSheet = PaymentSheet(..., configuration: configuration) ``` #### Customers v1 ```javascript const stripe = require('stripe')('sk_test_your_secret_key'); app.post('/mobile-payment-element', async (req, res) => { // Use an existing Customer ID if this is a returning customer. const customer = await stripe.customers.create(); const customerSession = await stripe.customerSessions.create({ customer: customer.id, components: { mobile_payment_element: { enabled: true, features: { payment_method_save: 'enabled', payment_method_redisplay: 'enabled', payment_method_remove: 'enabled' } }, }, }); res.json({ customerSessionClientSecret: customerSession.client_secret, customer: customer.id, }); }); ``` 次に、顧客の ID と CustomerSession の client secret を使用して PaymentSheet を設定します。 ```swift @_spi(CustomerSessionBetaAccess) import StripePaymentSheet var configuration = PaymentSheet.Configuration() configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret) self.paymentSheet = PaymentSheet(..., configuration: configuration) ``` ## Optional: 遅延型の支払い方法を許可する [クライアント側] *遅延型の決済手段* (A payment method that can't immediately return payment status when a customer attempts a transaction (for example, ACH debits). Businesses commonly hold an order in a pending state until payment is successful with these payment methods)では、購入の終了時に顧客から売上を受け取ることが保証されません。これは、決済に時間がかかる (アメリカの銀行口座、SEPA デビット、iDEAL、Bancontact など) 場合や、完了に顧客の対応を必要とする (OXXO、コンビニ決済、Boleto など) 場合があるためです。 デフォルトの場合、PaymentSheet には遅延型の決済手段は表示されません。オプトインするには、`PaymentSheet.Configuration` で `allowsDelayedPaymentMethods` を true に設定します。このステップのみでは、特定の決済手段を有効にすることはできませんが、アプリがその決済手段に対応できることが示されます。たとえば、OXXO は PaymentSheet でサポートされていませんが、サポートされるようになり、最新の SDK バージョンに更新すると、実装に関する追加の変更なしで、アプリに OXXO を決済オプションとして表示でます。 ```swift var configuration = PaymentSheet.Configuration() configuration.allowsDelayedPaymentMethods = true self.paymentSheet = PaymentSheet(..., configuration: configuration) ``` 顧客がいずれかの遅延型の支払い方法を PaymentSheet で正常に使用すると、`.completed` の支払い結果が返されます。 ## Optional: Apple Pay を有効にする > 決済画面に専用の **Apple Pay** ボタンがある場合は、[Apple Pay ガイド](https://docs.stripe.com/apple-pay.md#present-payment-sheet)に従い、`ApplePayContext` を使用して **Apple Pay** ボタンから支払いを回収します。`PaymentSheet` を使用して、他のタイプの決済手段に対応することも可能です。 ### Apple 加盟店 ID を登録する Apple Developer Web サイトで [新規 ID を登録](https://developer.apple.com/account/resources/identifiers/add/merchant) して、Apple 加盟店 ID を取得します。 フォームに説明と ID を入力します。説明はお客様の記録用であり、後で変更できます。アプリの名前を ID として使用することをお勧めします (`merchant.com.{{YOUR_APP_NAME}}` など)。 ### 新しい Apple Pay 証明書を作成する 支払いデータを暗号化するためのアプリの証明書を作成します。 ダッシュボードの [iOS certificate settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、**新規アプリケーションを追加**をクリックし、表示されるガイドに従います。 証明書署名リクエスト (CSR) ファイルをダウンロードして、Apple Pay の利用を可能にする安全な証明書を Apple から取得します。 1 つの CSR ファイルを使用して証明書を 1 つだけ発行する必要があります。Apple 加盟店 ID を切り替えた場合、ダッシュボードの [iOS Certificate Settings (iOS 証明書の設定)](https://dashboard.stripe.com/settings/ios_certificates) に移動して、新しい CSR と証明書を取得する必要があります。 ### Xcode を使用して組み込む Apple Pay ケイパビリティをアプリに追加します。Xcode でプロジェクト設定を開き、**Signing & Capabilities (署名およびケイパビリティ)** タブを選択して、**Apple Pay** ケイパビリティを追加します。この段階で開発者アカウントへのログインを要求される場合があります。前の手順で作成した加盟店 ID を選択すると、アプリで Apple Pay を受け付けられるようになります。 ![](https://b.stripecdn.com/docs-statics-srv/assets/xcode.a701d4c1922d19985e9c614a6f105bf1.png) Xcode で Apple Pay ケイパビリティを有効化する ### Apple Pay を追加する #### 1 回限りの支払い Apple Pay を PaymentSheet に追加するには、Apple 加盟店 ID と[お客様のビジネスの国コード](https://dashboard.stripe.com/settings/account)で `PaymentSheet.Configuration` を初期化してから、[applePay](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV8applePayAC05ApplefD0VSgvp) を設定します。 #### iOS (Swift) ```swift var configuration = PaymentSheet.Configuration() configuration.applePay = .init( merchantId: "merchant.com.your_app_name", merchantCountryCode: "US" ) ``` #### 継続支払い Apple Pay を PaymentSheet に追加するには、Apple 加盟店 ID と[お客様のビジネスの国コード](https://dashboard.stripe.com/settings/account)で `PaymentSheet.Configuration` を初期化してから、[applePay](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:6Stripe12PaymentSheetC13ConfigurationV8applePayAC05ApplefD0VSgvp) を設定します。 継続支払いに関する [Apple のガイドライン](https://developer.apple.com/design/human-interface-guidelines/apple-pay#Supporting-subscriptions)に従い、`PKPaymentRequest` で追加の属性を設定する必要もあります。[ApplePayConfiguration.paymentRequestHandlers](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/applepayconfiguration/handlers/paymentrequesthandler) にハンドラーを追加して、請求する予定の金額 (たとえば月額 9.95 USD) を指定して [PKPaymentRequest.paymentSummaryItems](https://developer.apple.com/documentation/passkit/pkpaymentrequest/1619231-paymentsummaryitems) を設定します。 `PKPaymentRequest` で `recurringPaymentRequest` または `automaticReloadPaymentRequest` プロパティを設定することで、[加盟店トークン](https://developer.apple.com/apple-pay/merchant-tokens/)を導入することもできます。 Apple Pay で継続支払いを使用する方法の詳細については、[Apple の PassKit に関するドキュメント](https://developer.apple.com/documentation/passkit/pkpaymentrequest)をご覧ください。 #### iOS (Swift) ```swift let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( paymentRequestHandler: { request in // PKRecurringPaymentSummaryItem is available on iOS 15 or later if #available(iOS 15.0, *) { let billing = PKRecurringPaymentSummaryItem(label: "My Subscription", amount: NSDecimalNumber(string: "59.99")) // Payment starts today billing.startDate = Date() // Payment ends in one year billing.endDate = Date().addingTimeInterval(60 * 60 * 24 * 365) // Pay once a month. billing.intervalUnit = .month billing.intervalCount = 1 // recurringPaymentRequest is only available on iOS 16 or later if #available(iOS 16.0, *) { request.recurringPaymentRequest = PKRecurringPaymentRequest(paymentDescription: "Recurring", regularBilling: billing, managementURL: URL(string: "https://my-backend.example.com/customer-portal")!) request.recurringPaymentRequest?.billingAgreement = "You'll be billed $59.99 every month for the next 12 months. To cancel at any time, go to Account and click 'Cancel Membership.'" } request.paymentSummaryItems = [billing] request.currencyCode = "USD" } else { // On older iOS versions, set alternative summary items. request.paymentSummaryItems = [PKPaymentSummaryItem(label: "Monthly plan starting July 1, 2022", amount: NSDecimalNumber(string: "59.99"), type: .final)] } return request } ) var configuration = PaymentSheet.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers) ``` ### 注文の追跡 iOS 16 以降で[注文の追跡](https://developer.apple.com/design/human-interface-guidelines/technologies/wallet/designing-order-tracking)情報を追加するには、`PaymentSheet.ApplePayConfiguration.Handlers` で [authorizationResultHandler](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/applepayconfiguration/handlers/authorizationresulthandler) を設定します。支払いの完了後、Stripe は iOS が Apple Pay の決済画面を閉じる前に実装を呼び出します。 `authorizationResultHandler` の実装で、完了した注文の注文の詳細をサーバーから取得します。提供された [PKPaymentAuthorizationResult](https://developer.apple.com/documentation/passkit/pkpaymentauthorizationresult) に詳細を追加し、変更された結果を返します。 注文の追跡の詳細については、[Apple のウォレットでの注文に関するドキュメント](https://developer.apple.com/documentation/walletorders)をご覧ください。 #### iOS (Swift) ```swift let customHandlers = PaymentSheet.ApplePayConfiguration.Handlers( authorizationResultHandler: { result in do { // Fetch the order details from your service let myOrderDetails = try await MyAPIClient.shared.fetchOrderDetails(orderID: orderID) result.orderDetails = PKPaymentOrderDetails( orderTypeIdentifier: myOrderDetails.orderTypeIdentifier, // "com.myapp.order" orderIdentifier: myOrderDetails.orderIdentifier, // "ABC123-AAAA-1111" webServiceURL: myOrderDetails.webServiceURL, // "https://my-backend.example.com/apple-order-tracking-backend" authenticationToken: myOrderDetails.authenticationToken) // "abc123" // Return your modified PKPaymentAuthorizationResult return result } catch { return PKPaymentAuthorizationResult(status: .failure, errors: [error]) } } ) var configuration = PaymentSheet.Configuration() configuration.applePay = .init(merchantId: "merchant.com.your_app_name", merchantCountryCode: "US", customHandlers: customHandlers) ``` ## Optional: 画面をカスタマイズする カスタマイズはすべて、[PaymentSheet.Configuration](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) オブジェクトで設定されます。 ### デザイン 色やフォントなどをアプリの見た目や雰囲気に合わせてカスタマイズするには、[appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=ios) を使用します。 ### 決済手段のレイアウト [paymentMethodLayout](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/configuration-swift.struct/paymentmethodlayout) を使用して、画面上の決済手段のレイアウトを設定します。横や縦に表示することも、Stripe がレイアウトを自動で最適化するように設定することもできます。 ![](https://b.stripecdn.com/docs-statics-srv/assets/ios-mpe-payment-method-layouts.9d0513e2fcec5660378ba1824d952054.png) #### Swift ```swift var configuration = PaymentSheet.Configuration() configuration.paymentMethodLayout = .automatic ``` ### ユーザーの住所を収集する [Address Element](https://docs.stripe.com/elements/address-element.md?platform=ios) を使用して、顧客から国内および国外の配送先住所や請求先住所を収集します。 ### 加盟店の表示名 [merchantDisplayName](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:18StripePaymentSheet0bC0C13ConfigurationV19merchantDisplayNameSSvp) を設定し、顧客に表示するビジネス名を指定します。デフォルトではアプリ名になります。 #### Swift ```swift var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "My app, Inc." ``` ### ダークモード `PaymentSheet` は、ユーザーのシステム全体の表示設定 (ライト / ダークモード) に合わせて自動的に調整されます。アプリがダークモードに対応していない場合は、[style](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html#/s:18StripePaymentSheet0bC0C13ConfigurationV5styleAC18UserInterfaceStyleOvp) を `alwaysLight` または `alwaysDark` モードに設定できます。 ```swift var configuration = PaymentSheet.Configuration() configuration.style = .alwaysLight ``` ### デフォルトの請求詳細 支払い画面で収集される請求詳細のデフォルト値を設定するには、`defaultBillingDetails` プロパティーを設定します。`PaymentSheet` の各フィールドに、指定したそれらの値が事前に読み込まれます。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.address.country = "US" configuration.defaultBillingDetails.email = "foo@bar.com" ``` ### 請求の詳細の収集 `billingDetailsCollectionConfiguration` を使用して、決済画面で請求の詳細を収集する方法を指定します。 顧客の名前、メールアドレス、電話番号、住所を収集できます。 支払い方法で必須の請求詳細のみを収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を true に設定します。その場合、`PaymentSheet.Configuration.defaultBillingDetails` が支払い方法の[請求詳細](https://docs.stripe.com/api/payment_methods/object.md?lang=node#payment_method_object-billing_details)として設定されます。 支払い方法で必ずしも必須ではない追加の請求詳細を収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を false に設定します。 その場合、`PaymentSheet` で収集した請求詳細が支払い方法の請求詳細として設定されます。 ```swift var configuration = PaymentSheet.Configuration() configuration.defaultBillingDetails.email = "foo@bar.com" configuration.billingDetailsCollectionConfiguration.name = .always configuration.billingDetailsCollectionConfiguration.email = .never configuration.billingDetailsCollectionConfiguration.address = .full configuration.billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod = true ``` > 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。