コンテンツにスキップ
アカウントを作成
または
サインイン
Stripe ドキュメントのロゴ
/
Ask AI
アカウントを作成
サインイン
始める
支払い
財務の自動化
プラットフォームおよびマーケットプレイス
資金管理
開発者向けのツール
始める
支払い
財務の自動化
始める
支払い
財務の自動化
プラットフォームおよびマーケットプレイス
資金管理
概要
Stripe Payments について
構築済みのシステムをアップグレード
支払いの分析
オンライン決済
概要ユースケースを見つけるManaged Payments
Payment Links を使用する
決済ページを構築
高度なシステムを構築
アプリ内実装を構築
    概要
    Payment Sheet
    Embedded Payment Element
      アプリ内での決済を受け付け
      デザインをカスタマイズする
      カスタムの支払い方法を追加する
      カードブランドを絞り込む
    Link out for in-app purchases
    住所を収集
    アメリカとカナダのカード
支払い方法
決済手段を追加
決済手段を管理
Link による購入の迅速化
支払いインターフェイス
Payment Links
Checkout
Web Elements
アプリ内 Elements
決済シナリオ
カスタムの決済フロー
柔軟なアクワイアリング
オーケストレーション
店頭支払い
端末
他の Stripe プロダクト
Financial Connections
仮想通貨
Climate
ホーム支払いBuild an in-app integrationEmbedded Payment Element

注

このページはまだ日本語ではご利用いただけません。より多くの言語で文書が閲覧できるように現在取り組んでいます。準備が整い次第、翻訳版を提供いたしますので、もう少しお待ちください。

アプリ内での決済を受け付け

iOS、Android、React Native アプリ向けにカスタマイズされた決済連携機能と決済フローを構築します。

ページをコピー

The Embedded Payment Element is a customizable component that renders a list of payment methods that you can add into any screen in your app. When customers interact with payment methods in the list, the component opens individual bottom sheets to collect payment details.

A PaymentIntent flow allows you to create a charge in your app. In this integration, you render the Embedded Payment Element, create a PaymentIntent, and confirm a charge in your app.

Stripe を設定する
サーバー側
クライアント側

サーバー側

この組み込みは、Stripe API と通信するサーバー上にエンドポイントを必要とします。サーバーから Stripe API にアクセスするには、次のように Stripe の公式ライブラリーを使用します。

Command Line
Ruby
# Available as a gem sudo gem install stripe
Gemfile
Ruby
# If you use bundler, you can add this line to your Gemfile gem 'stripe'

クライアント側

Stripe iOS SDK はオープンソースです。詳細なドキュメントが提供されており、iOS 13 以降をサポートするアプリと互換性があります。

SDK をインストールするには、以下のステップに従います。

  1. In Xcode, select File > Add Package Dependencies… and enter https://github.com/stripe/stripe-ios-spm as the repository URL.
  2. リリースページから最新のバージョン番号を選択します。
  3. StripePaymentSheet 製品をアプリのターゲットに追加します。

注

For details on the latest SDK release and past versions, see the Releases page on GitHub. To receive notifications when a new release is published, watch releases for the repository.

You also need to set your publishable key so that the SDK can make API calls to Stripe. To get started quickly, you can hardcode this on the client while you’re integrating, but fetch the publishable key from your server in production.

// 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 =
"pk_test_TYooMQauvdEDq54NiTphI7jx"

支払い方法を有効にする

支払い方法の設定を表示して、サポートする支払い方法を有効にします。PaymentIntent を作成するには、少なくとも 1 つは支払い方法を有効にする必要があります。

By default, Stripe enables cards and other prevalent payment methods that can help you reach more customers, but we recommend turning on additional payment methods that are relevant for your business and customers. See Payment method support for product and payment method support, and our pricing page for fees.

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

The Embedded Mobile Payment Element is designed to be placed on the checkout page of your native mobile app. The element displays a list of payment methods and can be customized to match your app’s look and feel.

When the customer taps the Card row, it opens a sheet where they can enter their payment method details. The button in the sheet says Continue by default and dismisses the sheet when tapped, which lets your customer finish payment in your checkout.

Embedded Payment Element

You can also configure the button to immediately complete payment instead of continuing. To do so, complete this step after following the guide.

Initialize Embedded Payment Element

Call create to instantiate EmbeddedPaymentElement with a EmbeddedPaymentElement.Configuration and a PaymentSheet.IntentConfiguration.

The Configuration object contains general-purpose configuration options for EmbeddedPaymentElement that don’t change between payments, like returnURL. The IntentConfiguration object contains details about the specific payment like the amount and currency, as well as a confirmHandler callback–for now, leave its implementation empty. After it successfully initializes, set its presentingViewController and delegate properties.

@_spi(EmbeddedPaymentElementPrivateBeta) import StripePaymentSheet class MyCheckoutVC: UIViewController { func createEmbeddedPaymentElement() async throws -> EmbeddedPaymentElement { let intentConfig = PaymentSheet.IntentConfiguration( mode: .payment(amount: 1099, currency: "USD") ) { [weak self] _, _, intentCreationCallback in self?.handleConfirm(intentCreationCallback) } var configuration = EmbeddedPaymentElement.Configuration() configuration.returnURL = "your-app://stripe-redirect" // Use the return url you set up in the previous step let embeddedPaymentElement = try await EmbeddedPaymentElement.create(intentConfiguration: intentConfig, configuration: configuration) embeddedPaymentElement.presentingViewController = self embeddedPaymentElement.delegate = self return embeddedPaymentElement } func handleConfirm(_ intentCreationCallback: @escaping (Result<String, Error>) -> Void) { // ...explained later } }

Add Embedded Payment Element view

After EmbeddedPaymentElement has successfully initialized, put its view in your checkout UI.

注

The view must be contained within a UIScrollView or some other scrollable view. This is because it doesn’t have a fixed size and can change height after it initially renders.

class MyCheckoutVC: UIViewController { // ... private(set) var embeddedPaymentElement: EmbeddedPaymentElement? private lazy var checkoutButton: UIButton = { let checkoutButton = UIButton(type: .system) checkoutButton.backgroundColor = .systemBlue checkoutButton.layer.cornerRadius = 5.0 checkoutButton.clipsToBounds = true checkoutButton.setTitle("Checkout", for: .normal) checkoutButton.setTitleColor(.white, for: .normal) checkoutButton.translatesAutoresizingMaskIntoConstraints = false checkoutButton.isEnabled = embeddedPaymentElement?.paymentOption != nil checkoutButton.addTarget(self, action: #selector(didTapConfirmButton), for: .touchUpInside) return checkoutButton }() // ... @objc func didTapConfirmButton() { // ...explained later } override func viewDidLoad() { super.viewDidLoad() Task { @MainActor in do { // Create a UIScrollView let scrollView = UIScrollView() scrollView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(scrollView) // Create the Mobile Embedded Payment Element let embeddedPaymentElement = try await createEmbeddedPaymentElement() embeddedPaymentElement.delegate = self embeddedPaymentElement.presentingViewController = self self.embeddedPaymentElement = embeddedPaymentElement // Add its view to the scroll view scrollView.addSubview(embeddedPaymentElement.view) // Add your own checkout button to the scroll view scrollView.addSubview(checkoutButton) // Set up layout constraints embeddedPaymentElement.view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), embeddedPaymentElement.view.topAnchor.constraint(equalTo: scrollView.topAnchor), embeddedPaymentElement.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), embeddedPaymentElement.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), checkoutButton.topAnchor.constraint(equalTo: embeddedPaymentElement.view.bottomAnchor, constant: 4.0), checkoutButton.leadingAnchor.constraint(equalTo: scrollView.safeAreaLayoutGuide.leadingAnchor, constant: 4.0), checkoutButton.trailingAnchor.constraint(equalTo: scrollView.safeAreaLayoutGuide.trailingAnchor, constant: -4.0), ]) } catch { // handle view not being added to view } } } }

At this point you can run your app and see the Embedded Mobile Payment Element.

Handle height changes

The EmbeddedPaymentElement’s view might grow or shrink in size which might impact the layout of the view.

Handle height changes by implementing the embeddedPaymentElementDidUpdateHeight delegate method. EmbeddedPaymentElement’s view calls this method inside an animation block that updates its height. Your implementation is expected to call setNeedsLayout() and layoutIfNeeded() on the scroll view that contains the EmbeddedPaymentElement’s view to enable a smooth animation of the height change.

extension MyCheckoutVC: EmbeddedPaymentElementDelegate { func embeddedPaymentElementDidUpdateHeight(embeddedPaymentElement: StripePaymentSheet.EmbeddedPaymentElement) { // Handle layout appropriately self.view.setNeedsLayout() self.view.layoutIfNeeded() } }

We recommend that you test that your view properly responds to changes in height. To do this, call testHeightChange() on EmbeddedPaymentElement to simulate showing and hiding a mandate within the element. Make sure that after calling testHeightChange(), your scroll view adjusts smoothly.

class MyCheckoutVC: UIViewController { override func viewDidLoad() { // This is only for testing purposes: #if DEBUG Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in Task { @MainActor in self?.embeddedPaymentElement?.testHeightChange() } } #endif } }

(Optional) Display the selected payment option

If you need to access details about the customer’s selected payment option like a label (for example, “····4242”), image (for example, a VISA logo), or billing details to display in your UI, use the EmbeddedPaymentElement’s paymentOption property.

To be notified when the paymentOption changes, implement the embeddedPaymentElementDidUpdatePaymentOption delegate method.

extension MyCheckoutVC: EmbeddedPaymentElementDelegate { func embeddedPaymentElementDidUpdatePaymentOption(embeddedPaymentElement: EmbeddedPaymentElement) { print("The payment option changed: \(embeddedPaymentElement.paymentOption)") checkoutButton.isEnabled = embeddedPaymentElement.paymentOption != nil } }

(Optional) Update payment details

As the customer performs actions that change the payment details (for example, applying a discount code), update the EmbeddedPaymentElement instance to reflect the new values by calling the update method. Some payment methods, like Apple Pay and Google Pay, show the amount in the UI, so make sure it’s always accurate and up to date.

When the update call completes, update your UI. The update call might change the customer’s currently selected payment option.

extension MyCheckoutVC { func update() { Task { @MainActor in var updatedIntentConfig = oldIntentConfig updatedIntentConfig.mode = PaymentSheet.IntentConfiguration.Mode.payment(amount: 999, currency: "USD") let result = await embeddedPaymentElement?.update(intentConfiguration: updatedIntentConfig) switch result { case .canceled, nil: // Do nothing; this happens when a subsequent `update` call cancels this one break case .failed(let error): // Display error to user in an alert, let users retry case .succeeded: // Update your UI in case the payment option changed } } } }

支払いを確定する

When the customer taps the checkout button, call embeddedPaymentElement.confirm() to complete the payment. Be sure to disable user interaction during confirmation.

extension MyCheckoutVC { @objc func didTapConfirmButton() { Task { @MainActor in guard let embeddedPaymentElement else { return } self.view.isUserInteractionEnabled = false // Disable user interaction, show a spinner, and so on before calling confirm let result = await embeddedPaymentElement.confirm() switch result { case .completed: // Payment completed - show a confirmation screen. case .failed(let error): self.view.isUserInteractionEnabled = true // Encountered an unrecoverable error. You can display the error to the user, log it, etc. case .canceled: self.view.isUserInteractionEnabled = true // Customer canceled - you should probably do nothing. break } } } }

Next, implement the confirmHandler callback you passed to PaymentSheet.IntentConfiguration earlier to send a request to your server. Your server creates a PaymentIntent and returns its client secret, explained in Create a PaymentIntent.

When the request returns, call the intentCreationCallback with your server response’s client secret or an error. The EmbeddedPaymentElement confirms the PaymentIntent using the client secret or displays the localized error message in its UI (either errorDescription or localizedDescription). After confirmation completes, EmbeddedPaymentElement isn’t usable. Instead, direct the user to a receipt screen or similar.

extension MyCheckoutVC { func handleConfirm(_ intentCreationCallback: @escaping (Result<String, Error>)-> Void) { // Make a request to your own server and receive a client secret or an error. let myServerResponse: Result<String, Error> = ... switch myServerResponse { case .success(let clientSecret): // Call the `intentCreationCallback` with the client secret intentCreationCallback(.success(clientSecret)) case .failure(let error): // Call the `intentCreationCallback` with the error intentCreationCallback(.failure(error)) } } }

オプションClear the selected payment option

オプションDisplay the mandate yourself

オプションLet the customer pay immediately in the sheet

PaymentIntent を作成する
サーバー側

サーバー側で、金額と通貨を指定して PaymentIntent を作成します。支払い方法はダッシュボードで管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。悪意のある顧客が金額を恣意的に選択できないようにするために、請求額はクライアント側ではなく、常にサーバー側 (信頼性の高い環境) で指定してください。

コールが成功した場合は、PaymentIntent client secret を返します。コールが失敗した場合は、エラーを処理して、エラーメッセージと顧客向けの簡単な説明を返します。

注

Verify that all IntentConfiguration properties match your PaymentIntent (for example, setup_future_usage, amount, and currency).

main.rb
Ruby
require 'stripe' Stripe.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/create-intent' do data = JSON.parse request.body.read params = { amount: 1099, currency: 'usd', # In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: {enabled: true}, } begin intent = Stripe::PaymentIntent.create(params) {client_secret: intent.client_secret}.to_json rescue Stripe::StripeError => e {error: e.error.message}.to_json end end

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

The customer might navigate away from your app to authenticate (for example, in Safari or their banking app). To allow them to automatically return to your app after authenticating, configure a custom URL scheme and set up your app delegate to forward the URL to the SDK. Stripe doesn’t support universal links.

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 } }

Additionally, set the returnURL on your EmbeddedPaymentElement.Configuration object to the URL for your app.

var configuration = EmbeddedPaymentElement.Configuration() configuration.returnURL = "your-app://stripe-redirect"

支払い後のイベントを処理する
サーバー側

支払いが完了すると、Stripe は payment_intent.succeeded イベントを送信します。ダッシュボードの Webhook ツールを使用するか Webhook のガイドに従ってこれらのイベントを受信し、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。

クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合、また悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう組み込みを設定すると、単一の組み込みで複数の異なるタイプの支払い方法を受け付けることができます。

Payment Element を使用して支払いを回収する場合は、payment_intent.succeeded イベントのほかにこれらのイベントを処理することをお勧めします。

イベント説明アクション
payment_intent.succeeded顧客が正常に支払いを完了したときに送信されます。顧客に注文の確定を送信し、顧客の注文のフルフィルメントを実行します。
payment_intent.processing顧客が正常に支払いを開始したが、支払いがまだ完了していない場合に送信されます。このイベントは、多くの場合、顧客が口座引き落としを開始するときに送信されます。その後、payment_intent.succeeded イベント、また、失敗の場合は payment_intent.payment_failed イベントが送信されます。顧客に注文確認メールを送信し、支払いが保留中であることを示します。デジタル商品では、支払いの完了を待たずに注文のフルフィルメントを行うことが必要になる場合があります。
payment_intent.payment_failed顧客が支払いを試みたが、支払いに失敗する場合に送信されます。支払いが processing から payment_failed に変わった場合は、顧客に再度支払いを試すように促します。

実装をテストする

カード番号シナリオテスト方法
カード支払いは成功し、認証は必要とされません。クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。
カード支払いには認証が必要です。クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。
カードは、insufficient_funds などの拒否コードで拒否されます。クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。
UnionPay カードは、13 ~ 19 桁の可変長です。クレジットカード番号と、任意の有効期限、セキュリティコード、郵便番号を使用してクレジットカードフォームに入力します。

実装内容をテストするためのその他の情報については、テストをご覧ください。

オプション保存済みのカードを有効にする
サーバー側
クライアント側

オプション遅延型の支払い方法を許可する
クライアント側

オプションApple Pay を有効にする

オプションカードのスキャンを有効にする

オプションCustomize the element

オプション確定時のセキュリティコードの再収集を有効にする

このページはお役に立ちましたか。
はいいいえ
お困りのことがございましたら 、サポートにお問い合わせください。
早期アクセスプログラムにご参加ください。
変更ログをご覧ください。
ご不明な点がございましたら、お問い合わせください。
LLM ですか?llms.txt を読んでください。
Powered by Markdoc