# 支払いを受け付ける

オンライン支払いを安全に受け付けます。

Stripe は、ほとんどの実装で Payment Intents ではなく Payment Element とともに Checkout Sessions API を使用することを推奨します。Checkout Sessions は、Payment Intents と同様のユースケースに対応しています (`price_data` を使用した基本的な決済の回収、または項目、税金などを含む網羅的な決済画面の構築など)。Adaptive Pricing などの一部の機能は、Checkout Sessions でのみ利用できます。ユーザーが明示的に要求しない限り、Payment Intents API は使用しないでください。必要となるコード量が大幅に多くなるためです。Checkout Sessions API と Elements の詳細: https://docs.stripe.com/payments/quickstart. Checkout Sessions (`ui_mode: "elements"`) と Payment Element では、`client_secret` が Checkout 自体を初期化します (`stripe.initCheckoutElementsSdk`、または React で CheckoutElementsProvider を使用)。そのうえで、クライアント側での決済の確定方法が異なります。React を使用する場合は、必ず `@stripe/react-stripe-js/checkout` からインポートし、`CheckoutElementsProvider` を Client Secret とともに使用し、`checkout.confirm` を使用して決済を確定します。HTML を使用する場合は、必ず `checkout = stripe.initCheckoutElementsSdk({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` を使用し、`loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();` で決済を確定します。

 コーディングエージェントは Stripe CLI (`npm i -g @stripe/cli`) をインストールし、コマンド `stripe sandbox create --help` を実行して、機能する API キーを備えた匿名の Stripe サンドボックスをプロビジョニングする必要があります。アカウント登録は不要です。

支払いフォームを作成するか、構築済みの決済ページを使用して、オンライン決済の受け付けを開始します。

# iOS でのアプリ内実装

![](https://b.stripecdn.com/docs-statics-srv/assets/ios-overview.9e0d68d009dc005f73a6f5df69e00458.png)

[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) クラスを使用して、Stripe の構築済み決済 UI を iOS アプリの決済フローに組み込みます。[GitHub](https://github.com/stripe/stripe-ios/tree/master/Example/PaymentSheet%20Example) のサンプル実装をご覧ください。

または、[コードクイックスタート](https://docs.stripe.com/payments/mobile/quickstart.md?platform=ios)から始めて、実行可能なサンプルを構築またはダウンロードします。

> #### Accounts v2 API に対応する
> 
> Payment Sheet は*顧客設定のアカウント* (Account configurations represent role-based functionality that you can enable for accounts, such as merchant, customer, or recipient)をサポートしていません。`Customer`オブジェクトのみをサポートしています。

## 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` を入力します。
2. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。
3. **StripePaymentSheet** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。

#### 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)して、新しいリリースの公開時に通知を受け取ることも可能です。

## 支払い方法を有効にする

[支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)を表示して、サポートする支払い方法を有効にします。*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) を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。

多くの顧客から決済を受け付けられるよう、Stripe では、カードやその他一般的な決済手段がデフォルトで有効になっていますが、ビジネスや顧客に適した追加の決済手段を有効にすることをお勧めします。プロダクトと決済手段のサポートについては[決済手段のサポート](https://docs.stripe.com/payments/payment-methods/payment-method-support.md)を、手数料については[料金体系ページ](https://stripe.com/pricing/local-payment-methods)をご覧ください。

## エンドポイントを追加する [サーバー側]

> #### 注
> 
> PaymentIntent の作成前に PaymentSheet を表示するには、[インテントを作成する前に支払いの詳細を収集する](https://docs.stripe.com/payments/accept-a-payment-deferred.md?type=payment)をご覧ください。

この接続方法では、以下の 3 つの Stripe API オブジェクトを使用します。

1. [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md): Stripe はこれを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して支払いの試行と支払い状態の変化を追跡します。
2. (オプション) [Customer](https://docs.stripe.com/api/customers.md): 将来の支払いに備えて決済手段を設定するには、顧客に関連付ける必要があります。顧客がアカウントを作成する際に、顧客を表すオブジェクトを作成します。顧客がゲストとして支払いを行う場合は、支払い前に `Customer` オブジェクトを作成し、後から、顧客アカウントを表す独自の内部情報と関連付けることができます。
3. (オプション) [CustomerSession](https://docs.stripe.com/api/customer_sessions.md): 顧客を表すオブジェクトの情報はセンシティブな情報であるため、アプリから直接取得することはできません。`CustomerSession` により、SDK には `Customer` への一時的な限定アクセス権が付与され、その他の[設定オプション](https://docs.stripe.com/api/customer_sessions/create.md#create_customer_session-components)も提供されます。

> 顧客のカードを保存しない場合は、実装から `Customer` オブジェクトと `CustomerSession` オブジェクトを省略できます。

セキュリティ上の理由により、アプリでこれらのオブジェクトを作成することはできません。代わりに、サーバー側で以下を行うエンドポイントを追加します。

1. `Customer` オブジェクトを取得するか、新しく作成します。
2. `Customer` の [CustomerSession](https://docs.stripe.com/api/customer_sessions.md) を作成します。
3. [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` を作成します。
4. `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://dashboard.stripe.com/apikeys)をアプリに返します。

`CustomerSession` に設定したものと同じ `Customer` を `PaymentIntent` に設定します。

決済プロセス中に顧客に表示される支払い方法は、PaymentIntent にも含まれています。Stripe にダッシュボードの設定から支払い方法を取得するよう指定することも、手動でリストに表示することもできます。選択したオプションにかかわらず、顧客に表示される支払い方法は、PaymentIntent で渡す通貨によって絞り込まれることにご注意ください。たとえば、PaymentIntent で `eur` を渡し、ダッシュボードで OXXO が有効になっている場合、OXXO は `eur` による決済に対応していないため、顧客に表示されません。

構築済みのシステムで、決済手段を提供するためにコードベースのオプションが必要になる場合を除き、自動化されたオプションを使用することをお勧めします。これは、Stripe が通貨、決済手段の制約、その他のパラメーターを評価して、対応可能な決済手段を決定するためです。自動化されたオプションでは、購入完了率の向上につながり、使用通貨と顧客の所在地に最適な決済手段が優先的に表示されます。

#### ダッシュボードで支払い方法を管理する

[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から決済手段を管理できます。Stripe は、取引の金額、通貨、決済フローなどの要素に基づいて、設定済みの対象となる決済手段を使用して `PaymentIntent` を作成します。ダッシュボードを使用しない場合や、利用する決済手段を手動で指定する場合は、`allowed_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 <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"

# Create a CustomerSession for the Customer
curl https://api.stripe.com/v1/customer_sessions \
  -u <<YOUR_SECRET_KEY>>: \
  -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 <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -d "customer"="{{CUSTOMER_ID}}" \
  -d "amount"=1099 \
  -d "currency"="eur" \

  -d "automatic_payment_methods[enabled]"=true \
```

#### 支払い方法を手動で一覧表示する

#### curl

```bash
# Create a Customer (use an existing Customer ID if this is a returning customer)
curl https://api.stripe.com/v1/customers \
  -u <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"

# Create a CustomerSession for the Customer
curl https://api.stripe.com/v1/customer_sessions \
  -u <<YOUR_SECRET_KEY>>: \
  -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 <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -d "customer"="{{CUSTOMER_ID}}" \
  -d "amount"=1099 \
  -d "currency"="eur" \
  -d "allowed_payment_method_types[]"="bancontact" \
  -d "allowed_payment_method_types[]"="card" \
  -d "allowed_payment_method_types[]"="ideal" \
  -d "allowed_payment_method_types[]"="klarna" \
  -d "allowed_payment_method_types[]"="sepa_debit" \
```

> 各決済手段は PaymentIntent で渡された通貨に対応している必要があり、ビジネスは、各決済手段を使用できる国のいずれかに所在する必要があります。対応状況について、詳細は[決済手段の導入オプション](https://docs.stripe.com/payments/payment-methods/integration-options.md)ページをご覧ください。

## 支払いの詳細を収集する [クライアント側]

決済画面にモバイル Payment Element を表示するには、以下を実行します。

- 顧客が購入している商品を合計金額とともに表示する
- [Address Element](https://docs.stripe.com/elements/address-element.md?platform=ios) を使用して、必要な配送先情報を顧客から収集する
- Stripe の UI を表示する購入ボタンを追加する

#### UIKit

アプリの決済画面で、前のステップで作成したエンドポイントから PaymentIntent の Client Secret、`CustomerSession` の Client Secret、`Customer` ID、公開可能キーを取得します。`STPAPIClient.shared` を使用して公開可能キーを設定し、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) を初期化します。

#### iOS (Swift)

```swift
import UIKit
@_spi(CustomerSessionBetaAccess) import StripePaymentSheet

class CheckoutViewController: UIViewController {
  @IBOutlet weak var checkoutButton: UIButton!
  var paymentSheet: PaymentSheet?
  let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet")! // Your backend endpoint

  override func viewDidLoad() {
    super.viewDidLoad()

    checkoutButton.addTarget(self, action: #selector(didTapCheckoutButton), for: .touchUpInside)
    checkoutButton.isEnabled = false

    // MARK: Fetch the PaymentIntent client secret, CustomerSession client secret, Customer ID, and publishable key
    var request = URLRequest(url: backendCheckoutUrl)
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
      guard let data = data,
            let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
            let customerId = json["customer"] as? String,
            let customerSessionClientSecret = json["customerSessionClientSecret"] as? String,
            let paymentIntentClientSecret = json["paymentIntent"] as? String,
            let publishableKey = json["publishableKey"] as? String,
            let self = self else {
        // Handle error
        return
      }

      STPAPIClient.shared.publishableKey = publishableKey
      // MARK: Create a PaymentSheet instance
      var configuration = PaymentSheet.Configuration()
      configuration.merchantDisplayName = "Example, Inc."
      configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret)
      // Set `allowsDelayedPaymentMethods` to true if your business handles
      // delayed notification payment methods like US bank accounts.
      configuration.allowsDelayedPaymentMethods = true
      self.paymentSheet = PaymentSheet(paymentIntentClientSecret:paymentIntentClientSecret, configuration: configuration)

      DispatchQueue.main.async {
        self.checkoutButton.isEnabled = true
      }
    })
    task.resume()
  }

}
```

顧客が**購入**ボタンをタップしたら、`present` を呼び出して PaymentSheet を表示します。顧客が支払いを完了したら、Stripe は PaymentSheet を閉じ、[PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) とともに完了ブロックを呼び出します。

#### iOS (Swift)

```swift
@objc
func didTapCheckoutButton() {
  // MARK: Start the checkout process
  paymentSheet?.present(from: self) { paymentResult in
    // MARK: Handle the payment result
    switch paymentResult {
    case .completed:
      print("Your order is confirmed")
    case .canceled:
      print("Canceled!")
    case .failed(let error):
      print("Payment failed: \(error)")
    }
  }
}
```

#### SwiftUI

決済画面用の `ObservableObject` モデルを作成します。このモデルは、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) と [PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) を公開します。

```swift
import StripePaymentSheet
import SwiftUI

class CheckoutViewModel: ObservableObject {
  let backendCheckoutUrl = URL(string: "Your back-end endpoint/payment-sheet")! // Your back-end endpoint
  @Published var paymentSheet: PaymentSheet?
  @Published var paymentResult: PaymentSheetResult?
}
```

前のステップで作成したエンドポイントから PaymentIntent の Client Secret、CustomerSession の Client Secret、`Customer` ID、公開可能キーを取得します。`STPAPIClient.shared` を使用して公開可能キーを設定し、[PaymentSheet](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet.html) を初期化します。

```swift

@_spi(CustomerSessionBetaAccess) import StripePaymentSheet
import SwiftUI

class CheckoutViewModel: ObservableObject {
  let backendCheckoutUrl = URL(string: "Your back-end endpoint/payment-sheet")! // Your back-end endpoint
  @Published var paymentSheet: PaymentSheet?
  @Published var paymentResult: PaymentSheetResult?

  func preparePaymentSheet() {
    // MARK: Fetch thePaymentIntent and Customer information from the back end
    var request = URLRequest(url: backendCheckoutUrl)
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
      guard let data = data,
            let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
            let customerId = json["customer"] as? String,
            let customerSessionClientSecret = json["customerSessionClientSecret"] as? String,
            letpaymentIntentClientSecret = json["paymentIntent"] as? String,
            let publishableKey = json["publishableKey"] as? String,
            let self = self else {
        // Handle error
        return
      }

      STPAPIClient.shared.publishableKey = publishableKey
      // MARK: Create a PaymentSheet instance
      var configuration = PaymentSheet.Configuration()
      configuration.merchantDisplayName = "Example, Inc."
      configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret)
      // Set `allowsDelayedPaymentMethods` to true if your business handles
      // delayed notification payment methods like US bank accounts.
      configuration.allowsDelayedPaymentMethods = true

      DispatchQueue.main.async {
        self.paymentSheet = PaymentSheet(paymentIntentClientSecret:paymentIntentClientSecret, configuration: configuration)
      }
    })
    task.resume()
  }
}

struct CheckoutView: View {
  @ObservedObject var model = CheckoutViewModel()

  var body: some View {
    VStack {
      if model.paymentSheet != nil {
        Text("Ready to pay.")
      } else {
        Text("Loading…")
      }
    }.onAppear { model.preparePaymentSheet() }
  }
}
```

[PaymentSheet.PaymentButton](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/PaymentButton.html) を `View` に追加します。これは、SwiftUI の `Button` と同様に動作し、`View` を追加することでカスタマイズされます。ボタンをタップすると PaymentSheet が表示されます。支払いが完了すると、Stripe は PaymentSheet を閉じ、[PaymentSheetResult](https://stripe.dev/stripe-ios/stripe-paymentsheet/Enums/PaymentSheetResult.html) オブジェクトとともに `onCompletion` ハンドラが呼び出されます。

```swift
@_spi(CustomerSessionBetaAccess) import StripePaymentSheet
import SwiftUI

class CheckoutViewModel: ObservableObject {
  let backendCheckoutUrl = URL(string: "Your back-end endpoint/payment-sheet")! // Your back-end endpoint
  @Published var paymentSheet: PaymentSheet?
  @Published var paymentResult: PaymentSheetResult?

  func preparePaymentSheet() {
    // MARK: Fetch the PaymentIntent and Customer information from the back end
    var request = URLRequest(url: backendCheckoutUrl)
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
      guard let data = data,
            let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
            let customerId = json["customer"] as? String,
            let customerSessionClientSecret = json["customerSessionClientSecret"] as? String,
            let paymentIntentClientSecret = json["paymentIntent"] as? String,
            let publishableKey = json["publishableKey"] as? String,
            let self = self else {
        // Handle error
        return
      }

      STPAPIClient.shared.publishableKey = publishableKey
      // MARK: Create a PaymentSheet instance
      var configuration = PaymentSheet.Configuration()
      configuration.merchantDisplayName = "Example, Inc."
      configuration.customer = .init(id: customerId, customerSessionClientSecret: customerSessionClientSecret)
      // Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods
      // that complete payment after a delay, like SEPA Debit and Sofort.
      configuration.allowsDelayedPaymentMethods = true

      DispatchQueue.main.async {
        self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration)
      }
    })
    task.resume()
  }

  func onPaymentCompletion(result: PaymentSheetResult) {
    self.paymentResult = result
  }
}

struct CheckoutView: View {
  @ObservedObject var model = CheckoutViewModel()

  var body: some View {
    VStack {
      if let paymentSheet = model.paymentSheet {
        PaymentSheet.PaymentButton(
          paymentSheet: paymentSheet,
          onCompletion: model.onPaymentCompletion
        ) {
          Text("Buy")
        }
      } else {
        Text("Loading…")
      }
      if let result = model.paymentResult {
        switch result {
        case .completed:
          Text("Payment complete")
        case .failed(let error):
          Text("Payment failed: \(error.localizedDescription)")
        case .canceled:
          Text("Payment canceled.")
        }
      }
    }.onAppear { model.preparePaymentSheet() }
  }
}
```

`PaymentSheetResult` が `.completed` の場合は、顧客に通知します (注文確認画面を表示するなど)。

`allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。

## 戻り先 URL を設定する [クライアント側]

顧客はお客様のアプリから離れて、(Safari やバンキングアプリなどで) 認証する場合があります。ユーザーが認証後にアプリに自動的に戻れるようにするには、[カスタム URL スキームを構成](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)し、URL を SDK に転送するようにアプリのデリゲートを設定します。Stripe は[ユニバーサルリンク](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content)には対応していません。

#### SceneDelegate

#### Swift

```swift
// This method handles opening custom URL schemes (for example, "your-app://stripe-redirect")
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    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)をご覧ください。

## Optional: Enable Link

[決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)で Link を有効にすると、顧客は Link の 1 クリックのエクスプレス決済ボタンを使用して、決済情報を安全に保存および再利用できるようになります。

### 顧客のメールアドレスを Mobile Payment Element に渡す

Link はメールアドレスを使用して顧客を認証します。Stripe では、決済プロセスを効率化するために、できるだけ多くの情報を事前入力することを推奨しています。

顧客の氏名、メールアドレス、電話番号を事前入力するには、`PaymentSheet.Configuration` を初期化した後に `defaultBillingDetails` に顧客情報を指定します。

```swift
var configuration = PaymentSheet.Configuration()
configuration.defaultBillingDetails.name = "Jenny Rosen"
configuration.defaultBillingDetails.email = "jenny.rosen@example.com"
configuration.defaultBillingDetails.phone = "888-888-8888"
```

### ユーザーのログアウトを処理

`PaymentSheet` は、ユーザーがアプリ内でLinkを使用したかどうかを記憶するために、情報をローカルに保存します。`PaymentSheet` の内部状態をクリアするには、ユーザーがログアウトした際に `PaymentSheet.resetCustomer()` メソッドを呼び出します。

```swift
import UIKit
import StripePaymentSheet

class MyViewController: UIViewController {

  @objc
  func didTapLogoutButton() {
    PaymentSheet.resetCustomer()
    // Other logout logic required by your app
  }

}
```

## 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)
```

## カードのスキャンを有効化する

iOS をサポートするカードスキャン機能を有効にするには、アプリケーションの `Info.plist` の `NSCameraUsageDescription` (**プライバシー - カメラ利用の詳細**)を設定し、カメラにアクセスする理由を入力して下さい (例:「カードをスキャンするため」)。

## Optional: ACH 決済を有効にする

ACH デビット支払いを有効にするには、アプリの依存関係として `StripeFinancialConnections`を含めます。

[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. **StripeFinancialConnections** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。

#### 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/StripeFinancialConnections/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. **StripeFinancialConnections.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。
3. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripeFinancialConnections/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)して、新しいリリースの公開時に通知を受け取ることも可能です。

## 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` を使用します。

顧客の名前、メールアドレス、電話番号、住所を収集できます。

完全な住所の収集には、対応している国での Stripe 提供オートコンプリート機能が含まれています。追加の設定は不要です。

> [Google Maps Platform 許容される使用ポリシー](https://cloud.google.com/maps-platform/terms/aup)に同意したうえで、オートコンプリートを使用します。この規定に違反した場合、Stripe はオートコンプリートを無効化するか、その他の必要な措置を講じる可能性があります。

決済手段によって必須となる請求情報のみを収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を true に設定します。その場合、`configuration.defaultBillingDetails` が決済手段の[請求情報](https://docs.stripe.com/api/payment_methods/object.md?lang=node#payment_method_object-billing_details)として設定されます。

決済手段によって必ずしも必須ではない追加の請求情報を収集する場合は、`billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` を false に設定します。その場合、UI を通じて収集された請求情報が決済手段の請求情報として設定されます。

```swift
var configuration = PaymentSheet.Configuration()
configuration.defaultBillingDetails.email = "foo@bar.com"
configuration.billingDetailsCollectionConfiguration.name = .always
configuration.billingDetailsCollectionConfiguration.email = .never
configuration.billingDetailsCollectionConfiguration.address = .full
configuration.billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod = true
```

> 情報の収集に適用される法律については、弁護士に相談してください。電話番号は、取引に必要な場合にのみ収集してください。

## Optional: UI で支払いを完了する

支払い方法の詳細を収集するためにのみ支払い画面を表示して、後で `confirm` メソッドを呼び出して、アプリの UI で支払いを完了できます。これは、カスタムの購入ボタンがある場合や、支払いの詳細を収集した後で追加のステップが必要な場合に便利です。
![](https://b.stripecdn.com/docs-statics-srv/assets/ios-multi-step.cd631ea4f1cd8cf3f39b6b9e1e92b6c5.png)

アプリの UI で支払いを完了する

#### UIKit

以下のステップでは、アプリの UI で支払いを完了する方法を説明します。[GitHub](https://github.com/stripe/stripe-ios/blob/master/Example/PaymentSheet%20Example/PaymentSheet%20Example/ExampleCustomCheckoutViewController.swift) でサンプルの実装をご覧下さい。

1. 最初に、`PaymentSheet` ではなく、[PaymentSheet.FlowController](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller) を初期化し、その `paymentOption` プロパティで UI を更新します。このプロパティには、顧客が最初に選択したデフォルトの支払い方法を表す画像とラベルが含まれています。

```swift
PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in
  switch result {
  case .failure(let error):
    print(error)
  case .success(let paymentSheetFlowController):
    self?.paymentSheetFlowController = paymentSheetFlowController
    // Update your UI using paymentSheetFlowController.paymentOption
  }
}
```

1. 次に、`presentPaymentOptions` を呼び出し、支払いの詳細を収集します。完了したら、`paymentOption` プロパティで再度 UI を更新します。

```swift
paymentSheetFlowController.presentPaymentOptions(from: self) {
  // Update your UI using paymentSheetFlowController.paymentOption
}
```

1. 最後に、`confirm` を呼び出します。

```swift
paymentSheetFlowController.confirm(from: self) { paymentResult in
  // MARK: Handle the payment result
  switch paymentResult {
  case .completed:
    print("Payment complete!")
  case .canceled:
    print("Canceled!")
  case .failed(let error):
    print(error)
  }
}
```

#### SwiftUI

以下のステップでは、アプリの UI で支払いを完了する方法を説明します。[GitHub](https://github.com/stripe/stripe-ios/blob/master/Example/PaymentSheet%20Example/PaymentSheet%20Example/ExampleSwiftUICustomPaymentFlow.swift) でサンプルの実装をご覧下さい。

1. 最初に、`PaymentSheet` ではなく、[PaymentSheet.FlowController](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller) を初期化します。その `paymentOption` プロパティには、顧客が現在選択している支払い方法を表す画像とラベルが含まれており、これを UI で使用することができます。

```swift
PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) { [weak self] result in
  switch result {
  case .failure(let error):
    print(error)
  case .success(let paymentSheetFlowController):
    self?.paymentSheetFlowController = paymentSheetFlowController
    // Use the paymentSheetFlowController.paymentOption properties in your UI
    myPaymentMethodLabel = paymentSheetFlowController.paymentOption?.label ?? "Select a payment method"
    myPaymentMethodImage = paymentSheetFlowController.paymentOption?.image ?? UIImage(systemName: "square.and.pencil")!
  }
}
```

1. [PaymentSheet.FlowController.PaymentOptionsButton](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/paymentoptionsbutton) を使用して、支払いの詳細を収集するための画面を表示するボタンをラップします。`PaymentSheet.FlowController` が `onSheetDismissed` 引数を呼び出すと、`PaymentSheet.FlowController` インスタンスの `paymentOption` に現在選択されている支払い方法が反映されます。

```swift
PaymentSheet.FlowController.PaymentOptionsButton(
  paymentSheetFlowController: paymentSheetFlowController,
  onSheetDismissed: {
    myPaymentMethodLabel = paymentSheetFlowController.paymentOption?.label ?? "Select a payment method"
    myPaymentMethodImage = paymentSheetFlowController.paymentOption?.image ?? UIImage(systemName: "square.and.pencil")!
  },
  content: {
    /* An example button */
    HStack {
      Text(myPaymentMethodLabel)
      Image(uiImage: myPaymentMethodImage)
    }
  }
)
```

1. [PaymentSheet.FlowController.PaymentOptionsButton](https://stripe.dev/stripe-ios/stripepaymentsheet/documentation/stripepaymentsheet/paymentsheet/flowcontroller/paymentoptionsbutton) を使用して、支払いを確定するボタンをラップします。

```swift
PaymentSheet.FlowController.ConfirmButton(
  paymentSheetFlowController: paymentSheetFlowController,
  onCompletion: { result in
    // MARK: Handle the payment result
    switch result {
    case .completed:
      print("Payment complete!")
    case .canceled:
      print("Canceled!")
    case .failed(let error):
      print(error)
    }
  },
  content: {
    /* An example button */
    Text("Pay")
  }
)
```

`allowsDelayedPaymentMethods` を true に設定すると、アメリカの銀行口座などの [遅延通知型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の支払い方法を使用できます。これらの支払い方法では、`PaymentSheet` が完了した時点では最終的な支払いステータスが判明せず、後になって成功または失敗が確定します。このようなタイプの支払い方法に対応する場合は、注文が確定済みであることを顧客に通知し、支払いが成功した場合にのみ注文のフルフィルメント (商品の発送など) を実行するようにします。

## Optional: 確定時のセキュリティコードの再収集を有効にする

PaymentIntent の確定時に、保存されたカードのセキュリティコードを再収集する次の手順は、実装システムに以下が含まれていることを前提としています。

- 決済の詳細を収集する前の PaymentIntent の作成

### インテント作成のパラメーターを更新する

支払いの確定時にセキュリティコードを再収集するには、PaymentIntent の作成時に `require_cvc_recollection` を含めます。

#### curl

```bash
# Create a Customer (use an existing Customer ID if this is a returning customer)
curl https://api.stripe.com/v1/customers \
  -u <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -H "Stripe-Account: {{CONNECTED_ACCOUNT_ID}}"

# Create an Ephemeral Key for the Customer
curl https://api.stripe.com/v1/ephemeral_keys \
  -u <<YOUR_SECRET_KEY>>: \
  -H "Stripe-Version: 2026-09-30.endive" \
  -H "Stripe-Account: 2026-09-30.endive" \
  -X "POST" \
  -d "customer"="{{CUSTOMER_ID}}" \

# Create a PaymentIntent
curl https://api.stripe.com/v1/payment_intents \
  -u <<YOUR_SECRET_KEY>>: \
  -X "POST" \
  -d "customer"="{{CUSTOMER_ID}}" \
  -d "amount"=1099 \
  -d "currency"="eur" \
  -d "payment_method_options[card][require_cvc_recollection]"=true \

  -d "automatic_payment_methods[enabled]"=true \
```

