# Connect の埋め込みコンポーネントの使用を開始する

ダッシュボードの機能をウェブサイトに埋め込む方法をご紹介します。

Connect の埋め込みコンポーネントを使用して、連結アカウントのダッシュボード機能をウェブサイトに追加します。これらのライブラリ、およびそのサポート API を使用することで、ダッシュボードやモバイルアプリケーションから Stripe プロダクトに直接アクセスできる許可をユーザーに付与できます。

- **統合 UI の追加**: 埋め込みコンポーネントを使用して、ダッシュボードに統合 UI を追加できます。[利用可能なすべてのコンポーネント](https://docs.stripe.com/connect/supported-embedded-components.md)をご覧ください。
- **外観のカスタマイズ**: ブランドに合わせて[外観](https://docs.stripe.com/connect/customize-connect-embedded-components.md)を調整できます。
- **常に最新の状態を維持**: Connect の埋め込みコンポーネントは Stripe API と同期しているため、実装を常に最新の状態に保てます。

## StripeConnect を設定する [クライアント側] [サーバー側]

Stripe は [AccountSession](https://docs.stripe.com/api/account_sessions.md) を使用して、API アクセスを連結アカウントに委任する意図を表します。

AccountSessions API は *client secret* (The client secret is a unique string returned from Stripe as part of an AccountSession. This string lets the client access a specific Stripe account with Connect embedded components) を返し、連結アカウントに対して API コールを行うときと同じように、埋め込みコンポーネントが連結アカウントのリソースにアクセスできるようにします。

### AccountSession を作成する (サーバー)

アカウントセッションを取得するために、アプリからサーバーへのリクエストを開始する必要があります。Client Secret をアプリに返すための新しいエンドポイントをサーバーに作成します。

#### Ruby

```ruby
require 'sinatra'
require 'stripe'
# This is a placeholder - it should be replaced with your API key.
# Sign in to see your own test API key embedded in code samples.
# Don't put any keys in code. We recommend using a restricted API key with access only to the account sessions resource. See https://docs.stripe.com/keys-best-practices
client = Stripe::StripeClient.new('<<YOUR_SECRET_KEY>>')

post '/account_session' do
  content_type 'application/json'

  # Create an AccountSession
  begin
    account_session = client.v1.account_sessions.create({
      account: {{CONNECTED_ACCOUNT_ID}},
      components: {
        account_onboarding: {
          enabled: true,
          features: {
            # We recommend disabling authentication for a better user experience when possible
            disable_stripe_user_authentication: true,
          }
        }
      }
    })

    {
      client_secret: account_session[:client_secret]
    }.to_json
  rescue => error
    puts "An error occurred when calling the Stripe API to create an account session: #{error.message}";
    return [500, { error: error.message }.to_json]
  end
end
```

### Create Account Session API

[ Account Session 作成 API](https://docs.stripe.com/api/account_sessions/create.md) によって、Connect 埋め込みコンポーネントでどのコンポーネントを表示し、どの機能へのアクセスを可能にするかが決定されます。Stripe はアカウントセッションに対応するすべてのコンポーネントにこれらのパラメーターを適用します。お客様のアプリが複数のユーザーの役割をサポートしている場合には、そのアカウントセッションで有効にされたコンポーネントと機能が現在のユーザーの役割に対応していることをご確認ください。 例えば、[返金の管理](https://docs.stripe.com/api/account_sessions/create.md#create_account_session-components-payments-features-refund_management)はお客様のサイトの管理者に対してのみ有効になり、他のユーザーはアクセスできません。ユーザーの役割へのアクセスを適用するには、サイトのユーザーの役割をアカウントセッションコンポーネントにマッピングする必要があります。

### StripeConnect SDK をインストールする (クライアント)

[Stripe Android SDK](https://github.com/stripe/stripe-android) はオープンソースであり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-android/)。

SDK をインストールするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `connect` を追加します。

#### Kotlin

```kotlin
plugins {
    id("com.android.application")
}

android { ... }

dependencies {
  // ...

  // Connect Android SDK
  implementation("com.stripe:connect:23.13.1")
}
```

> SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。

### EmbeddedComponentManager を初期化する (クライアント)

公開可能キーと、サーバー上に作成した新しいエンドポイントを呼び出して client secret を取得するラムダを使用して、[EmbeddedComponentManager](https://stripe.dev/stripe-android/connect/com.stripe.android.connect/-embedded-component-manager/index.html) をインスタンス化します。設定の変更を処理するには、アクティビティーまたはフラグメントの `ViewModel` に `EmbeddedComponentManager` インスタンスを保持します。

#### Kotlin

```kotlin
class MyActivityViewModel : ViewModel() {
    val embeddedComponentManager: EmbeddedComponentManager =
        EmbeddedComponentManager(
            // This is a placeholder - it should be replaced with your publishable API key.
            // Sign in to see your own test API key embedded in code samples.
            // Don't submit any personally identifiable information in requests made with this key.
            publishableKey = "<<YOUR_PUBLISHABLE_KEY>>",
            fetchClientSecret = ::fetchClientSecret,
        )

    private suspend fun fetchClientSecret(): String? =
        try {
            // Fetch the AccountSession client secret
            Fuel.post("https://{{YOUR_SERVER_BASE_URL}}/account_session")
                .awaitString()
                .let { JSONObject(it).getString("client_secret") }
        } catch (error: CancellationException) {
            throw error
        } catch (error: Exception) {
            // Handle errors on the client side here
            println("Error fetching client secret: ${error.message}")
            null
        }
}
```

コンポーネントを作成するには、まず、Activity の `onCreate` メソッドで `EmbeddedComponentManager.onActivityCreate()` を呼び出します。次に、上記でインスタンス化した `EmbeddedComponentManager` の適切な create メソッドを呼び出します。

[アカウントのユーザー登録](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding.md) は、独自のプレゼンテーションを管理するコントローラを返します。[Payments](https://docs.stripe.com/connect/supported-embedded-components/payments.md) のような他のコンポーネントは、[View](https://developer.android.com/reference/android/view/View) を返します。

#### コントローラのレンダリング

#### Kotlin

```kotlin
class MyActivity : FragmentActivity() {
    private val viewModel: MyActivityViewModel by viewModels()
    private lateinit var accountOnboardingController: AccountOnboardingController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EmbeddedComponentManager.onActivityCreate(this)
        setContentView(R.layout.my_activity)

        accountOnboardingController =
            viewModel.embeddedComponentManager.createAccountOnboardingController(this)
    }

    private fun openAccountOnboarding() {
        accountOnboardingController.show()
    }
}
```

#### `View` のレンダリング

#### Kotlin

```kotlin
class MyActivity : FragmentActivity() {
    private val viewModel: MyActivityViewModel by viewModels()
    private lateinit var paymentsView: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EmbeddedComponentManager.onActivityCreate(this)
        setContentView(R.layout.my_activity)

        paymentsView = viewModel.embeddedComponentManager.createPaymentsView(this)

        // Add the view to your layout
        val container = findViewById<ViewGroup>(R.id.payments_container)
        container.addView(paymentsView)
    }
}
```

## Configure the Embedded Component Manager [クライアント側]

[参考資料 :external: をご覧ください](https://stripe.dev/stripe-android/connect/com.stripe.android.connect/-embedded-component-manager/index.html)。

### Connect 埋め込みコンポーネントのデザインをカスタマイズする

[埋め込みコンポーネント Figma UI ツールキット](https://www.figma.com/community/file/1438614134095442934)には、すべてのコンポーネント、一般的なパターン、サンプルアプリケーションが含まれています。これを使用して、ウェブサイトに埋め込まれた UI を可視化してデザインできます。

Stripe は、Connect 埋め込みコンポーネントのデザインをカスタマイズするための[一連のオプション](https://docs.stripe.com/connect/embedded-appearance-options.md)を提供しています。これらをカスタマイズすると、デザインシステムのボタン、アイコン、その他のアクセントに影響します。

> #### 必要なポップアップ
> 
> [ユーザー認証](https://docs.stripe.com/connect/get-started-connect-embedded-components.md#user-authentication-in-connect-embedded-components)などの埋め込みコンポーネントの一部の動作は、認証済みの WebView に表示する必要があります。埋め込みコンポーネントをカスタマイズして、これらの WebView を排除することはできません。

これらのオプションは、`EmbeddedComponentManager` の初期化時に [Appearance (デザイン)](https://stripe.dev/stripe-android/connect/com.stripe.android.connect.appearance/-appearance/index.html) を使用して設定できます。

#### Kotlin

```kotlin
// Specify custom fonts
val customFonts = listOf(
    CustomFontSource(
        // Font file located in `assets/` folder
        assetsFilePath = "fonts/myCustomFont.ttf",
        name = "myCustomFont",
        weight = 1000,
    )
)

// Customize appearance
val appearance = Appearance.Builder()
    .typography(
        Typography.Builder()
            .fontFamily("myCustomFont") // Same name as the custom font above
            .fontSizeBase(16f) // Unscaled font size
            .build()
    )
    .colors(
        Colors.Builder()
            .primary(Color.RED)
            .build()
    )
    .build()

val embeddedComponentManager = EmbeddedComponentManager(
    publishableKey = "<<YOUR_PUBLISHABLE_KEY>>",
    fetchClientSecret = ::fetchClientSecret,
    appearance = appearance,
    customFonts = customFonts,
)
```

フォントサイズを指定する場合は、デバイスのデフォルトサイズクラスに表示される、拡大縮小されていないフォントサイズを使用します。埋め込みコンポーネントは、ユーザー[補助機能のフォント設定](https://support.google.com/accessibility/android/answer/11183305?sjid=3094445894544346025-NA#fontsize)に基づいてフォントサイズを自動的に拡大縮小します。

 Android の[デザインオプションの一覧](https://docs.stripe.com/connect/embedded-appearance-options.md?platform=android)をご覧ください。

### カスタムフォントを使用する

アプリでカスタムフォントを使用する場合 (たとえば、アプリのバイナリに埋め込まれた `.otf` ファイルや `.tff` ファイルなど)、`EmbeddedComponentManager` の初期化時に `customFonts` 引数に渡される [CustomFontSource](https://stripe.dev/stripe-android/connect/com.stripe.android.connect.appearance.fonts/-custom-font-source/index.html) でフォントファイルを指定する必要があります。そうすることで、Connect 埋め込みコンポーネントがフォントファイルにアクセスできるようになり、フォントを適切にレンダリングできます。

`appearance` で指定されたフォントが正しくレンダリングされるようにするには、初期化時に `EmbeddedComponentManager` に渡される [CustomFontSource](https://stripe.dev/stripe-android/connect/com.stripe.android.connect.appearance.fonts/-custom-font-source/index.html) を使用する必要があります。

[リファレンスドキュメントをご覧ください :external:](https://stripe.dev/stripe-android/connect/com.stripe.android.connect.appearance.fonts/-custom-font-source/index.html)。

### 初期化後に Connect 埋め込みコンポーネントを更新する

`update` メソッドを呼び出して、初期化後に埋め込みコンポーネントのデザインを変更します。

#### Kotlin

```kotlin
val appearance = Appearance.Builder()
    .colors(
        Colors.Builder()
            .primary(ContextCompat.getColor(context, R.color.primary))
            .build()
    )
    .build()
embeddedComponentManager.update(appearance = appearance)
```

## 認証

Stripe は、Connect 埋め込みコンポーネントでアカウントセッションとユーザー認証情報を管理するための一連の API を提供しています。

### Client Secret を更新する

長時間実行されるセッションでは、最初に提供された *Client Secret* (The client secret is a unique string returned from Stripe as part of an AccountSession. This string lets the client access a specific Stripe account with Connect embedded components) によるセッションが期限切れになることがあります。有効期限が切れると、Stripe は自動的に `fetchClientSecret` を使用して新しい Client Secret を取得し、セッションを更新します。貴社が追加のパラメーターを渡す必要はありません。

#### Kotlin

```kotlin
val embeddedComponentManager: EmbeddedComponentManager =
    EmbeddedComponentManager(
        publishableKey = "<<YOUR_PUBLISHABLE_KEY>>",
        fetchClientSecret = ::fetchClientSecret,
    )

private suspend fun fetchClientSecret(): String? =
    try {
        Fuel.post("https://{{YOUR_SERVER_BASE_URL}}/account_session")
            .awaitString()
            .let { JSONObject(it).getString("client_secret") }
    } catch (error: CancellationException) {
        throw error
    } catch (error: Exception) {
        null
    }
```

## 各地域への適応

Connect 埋め込みコンポーネントは、次のロケールに対応しています。

| 言語 | ロケールコード |
| --- | --- |
| ブルガリア語 (ブルガリア) | `bg-BG` |
| 中国語 (簡体字) | `zh-Hans` |
| 中国語 (繁体字 - 香港) | `zh-Hant-HK` |
| 中国語 (繁体字 - 台湾) | `zh-Hant-TW` |
| クロアチア語 (クロアチア) | `hr-HR` |
| チェコ語 (チェコ) | `cs-CZ` |
| デンマーク語 (デンマーク) | `da-DK` |
| オランダ語 (オランダ) | `nl-NL` |
| 英語 (オーストラリア) | `en-AU` |
| 英語 (インド) | `en-IN` |
| 英語 (アイルランド) | `en-IE` |
| 英語 (ニュージーランド) | `en-NZ` |
| 英語 (シンガポール) | `en-SG` |
| 英語 (イギリス) | `en-GB` |
| 英語 (アメリカ) | `en-US` |
| エストニア語 (エストニア) | `et-EE` |
| フィリピノ語 (フィリピン) | `fil-PH` |
| フィンランド語 (フィンランド) | `fi-FI` |
| フランス語 (カナダ) | `fr-CA` |
| フランス語 (フランス) | `fr-FR` |
| ドイツ語 (ドイツ) | `de-DE` |
| ギリシャ語 (ギリシャ) | `el-GR` |
| ハンガリー語 (ハンガリー) | `hu-HU` |
| インドネシア語 (インドネシア) | `id-ID` |
| イタリア語 (イタリア) | `it-IT` |
| 日本語 (日本) | `ja-JP` |
| 韓国語 (韓国) | `ko-KR` |
| ラトビア語 (ラトビア) | `lv-LV` |
| リトアニア語 (リトアニア) | `lt-LT` |
| マレー語 (マレーシア) | `ms-MY` |
| マルタ語 (マルタ) | `mt-MT` |
| ノルウェーブークモール語 (ノルウェー) | `nb-NO` |
| ポーランド語 (ポーランド) | `pl-PL` |
| ポルトガル語 (ブラジル) | `pt-BR` |
| ポルトガル語 (ポルトガル) | `pt-PT` |
| ルーマニア語 (ルーマニア) | `ro-RO` |
| スロバキア語 (スロバキア) | `sk-SK` |
| スロベニア語 (スロベニア) | `sl-SI` |
| スペイン語 (アルゼンチン) | `es-AR` |
| スペイン語 (ブラジル) | `es-BR` |
| スペイン語 (中南米) | `es-419` |
| スペイン語 (メキシコ) | `es-MX` |
| スペイン語 (スペイン) | `es-ES` |
| スウェーデン語 (スウェーデン) | `sv-SE` |
| タイ語 (タイ) | `th-TH` |
| トルコ語 (トルコ) | `tr-TR` |
| ベトナム語 (ベトナム) | `vi-VN` |

## Connect の埋め込みコンポーネントでのユーザー認証

通常、Connect の埋め込みコンポーネントはユーザー認証を必要としません。特定のシナリオで Connect の埋め込みコンポーネントは、必要な機能 (例: [アカウント登録](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding.md)コンポーネントを使用したアカウントの法人情報の入力) にアクセスする前に、連結アカウントが Stripe アカウントでサインインする必要があります。その他のコンポーネントの場合、最初にレンダリングされた後でコンポーネント内での認証が必要になることがあります。

要件が変更された場合に Stripe が更新情報を収集する責任を負う場合、認証は必須です。要件が期限切れになったときや変更されたときに最新情報を収集する責任を負う連結アカウント (Custom アカウントなど) の場合、Stripe の認証はアカウントセッション機能 ([disable_stripe_user_authentication](https://docs.stripe.com/api/account_sessions/create.md#create_account_session-components-account_onboarding-features-disable_stripe_user_authentication)) によって制御されます。[ベストプラクティス](https://docs.stripe.com/connect/risk-management/best-practices.md#prevent-account-take-overs)として、2 段階認証または同等のセキュリティ対策を導入することをお勧めします。Custom など、この機能をサポートするアカウント設定では、連結アカウントが[マイナス残高](https://docs.stripe.com/connect/risk-management/best-practices.md#decide-your-approach-to-negative-balance-liability)を返済できない場合、お客様がそのアカウントに対する責任を負うことになります。

### 認証が必要なコンポーネント

連結アカウントには、アプリケーション内で認証済みの [WebView](https://developer.chrome.com/docs/android/custom-tabs) が表示されます。WebView 内でワークフローを続行する前に、連結アカウントは認証を終える必要があります。

Stripe のオンライン認証フローには、[Connect の設定](https://dashboard.stripe.com/account/applications/settings)で設定されているブランド名、色、アイコンが表示され、認証が完了するまで[埋め込みコンポーネントマネージャー](https://docs.stripe.com/connect/get-started-connect-embedded-components.md#configuring-connect)のカスタムデザインとフォントは適用されません。

> #### Android の制限事項
> 
> Android API の制限により、埋め込みコンポーネントは、認証が完了した後でも認証済みの WebView 内でカスタムフォントを使用することはできません。

以下のコンポーネントは、特定のシナリオでは連結アカウントによる認証が必要になります。

- [アカウント登録](https://docs.stripe.com/connect/supported-embedded-components/account-onboarding.md)
- [入金](https://docs.stripe.com/connect/supported-embedded-components/payouts.md)

## 読み込みエラーを処理する [クライアント側]

コンポーネントの `onLoadError` リスナーメソッドを実装することにより、コンポーネントのロードの失敗に対応します。

さまざまな失敗原因によって `onLoadError` メソッドが複数回呼び出される可能性があります。したがって、`onLoadError` によってトリガーされるロジックはすべてべき等である必要があります。

#### Kotlin

```kotlin
// All components emit load errors. This example uses AccountOnboarding.
// All components support onLoadError.
class MyActivity : FragmentActivity() {
    private lateinit var accountOnboardingController: AccountOnboardingController

    override fun onCreate(savedInstanceState: Bundle?) {
        accountOnboardingController =
            embeddedComponentManager.createAccountOnboardingController(this)
        accountOnboardingController.listener = MyAccountOnboardingListener()
    }

    private fun openAccountOnboarding() {
        accountOnboardingController.show()
    }

    private inner class MyAccountOnboardingListener : AccountOnboardingListener {
        override fun onLoadError(error: Throwable) {
            println("Error loading account onboarding: ${error.message}")
        }
    }
}
```
