---
title: Ionic
description: Capacitorプラグインを使用してIonicアプリにHuman Token Journeyを統合します — AndroidではCustom Tabs、iOSではASWebAuthenticationSession。
canonical: https://developer.unico.io/ja/human-plugin/integrations/app/ionic
locale: ja
generated_by: markdown-export
---

Ionic

Capacitorプラグインを使用してIonicアプリにHuman Token Journeyを統合します。

この統合は、AndroidではCustom Tabs、iOSでは`ASWebAuthenticationSession`に委譲するローカルCapacitorプラグインを使用します。ジャーニーが完了すると、ディープリンクが`@capacitor/app`を介して戻ります。

### 前提条件

- Ionic（Capacitor v4+）
- `@capacitor/app`がインストール済み
- Xcode 14+およびAndroid Studio
- アプリ固有のURLスキーム（例：`myapp`）

### ステップ 1：URLスキームを定義する

一意のスキームを選択します（例：`myapp`）。プロセス作成時に`callbackUri`として使用されます：

```text
callbackUri: myapp://callback
```

Human Plugin APIでプロセスを作成し、この値を`callbackUri`として送信します。[プロセスの作成](/ja/human-plugin/api-reference/create-process)を参照してください。

### ステップ 2：Capacitorプラグインインターフェースを作成する

```typescript
import { registerPlugin } from '@capacitor/core';

export interface UnicoPlugin {
  openSession(options: { url: string }): Promise<{ callbackUrl: string }>;
}

const Unico = registerPlugin<UnicoPlugin>('UnicoPlugin');
export default Unico;
```

### ステップ 3：iOSプラグインを実装する

```swift
import Capacitor
import AuthenticationServices

@objc(UnicoPlugin)
public class UnicoPlugin: CAPPlugin, ASWebAuthenticationPresentationContextProviding {
    private var session: ASWebAuthenticationSession?

    @objc func openSession(_ call: CAPPluginCall) {
        guard let urlString = call.getString("url"),
              let url = URL(string: urlString) else {
            call.reject("Invalid URL")
            return
        }

        DispatchQueue.main.async {
            let newSession = ASWebAuthenticationSession(
                url: url,
                callbackURLScheme: "myapp"
            ) { callbackURL, error in
                self.session = nil
                if let callbackURL = callbackURL {
                    call.resolve(["callbackUrl": callbackURL.absoluteString])
                } else {
                    call.reject(error?.localizedDescription ?? "Session cancelled")
                }
            }
            newSession.presentationContextProvider = self
            newSession.prefersEphemeralWebBrowserSession = true
            newSession.start()
            self.session = newSession
        }
    }

    public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let window = windowScene.windows.first else {
            return ASPresentationAnchor()
        }
        return window
    }
}
```

### ステップ 4：Androidプラグインを実装する

```kotlin
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin

@CapacitorPlugin(name = "UnicoPlugin")
class UnicoPlugin : Plugin() {

    private var pendingCall: PluginCall? = null

    @PluginMethod
    fun openSession(call: PluginCall) {
        val url = call.getString("url") ?: return call.reject("Missing URL")
        pendingCall = call

        activity.runOnUiThread {
            CustomTabsIntent.Builder().build()
                .launchUrl(activity, Uri.parse(url))
        }
    }

    override fun handleOnNewIntent(intent: Intent) {
        super.handleOnNewIntent(intent)
        intent.data?.let { uri ->
            if (uri.scheme == "myapp") {
                pendingCall?.resolve(com.getcapacitor.JSObject().put("callbackUrl", uri.toString()))
                pendingCall = null
            }
        }
    }
}
```

### ステップ 5：URLスキームを設定する

- iOS
- Android

`Info.plist`に追加：

```xml
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myapp</string>
        </array>
    </dict>
</array>
```

メインの`<activity>`内の`AndroidManifest.xml`に追加：

```xml
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="myapp" android:host="callback" />
</intent-filter>
```

`build.gradle`に追加：

```groovy
implementation("androidx.browser:browser:1.5.0")
```

### ステップ 6：Angularサービスを作成する

```typescript
import { Injectable } from '@angular/core';
import Unico from '../plugins/unico-plugin';

@Injectable({ providedIn: 'root' })
export class UnicoService {
  async openSession(url: string): Promise<string | null> {
    try {
      const result = await Unico.openSession({ url });
      const params = new URL(result.callbackUrl).searchParams;
      return params.get('id');
    } catch {
      return null;
    }
  }
}
```

### ステッ プ 7：ディープリンクをリッスンする

`AppComponent`内で：

```typescript
import { App } from '@capacitor/app';

App.addListener('appUrlOpen', (event) => {
  // Handle the callback URL if needed
  console.log('Deep link received:', event.url);
});
```

### ファイルの概要

| ファイル | 目的 |
| --- | --- |
| `unico-plugin.ts` | Capacitorプラグインインターフェース |
| `UnicoPlugin.swift` | iOS — ASWebAuthenticationSession |
| `UnicoPlugin.kt` | Android — Custom Tabs |
| `Info.plist` | iOS URLスキーム |
| `AndroidManifest.xml` | Android Intentフィルター |
| `unico.service.ts` | Angularサービスラッパー |

最終更新 **2026年11月23日**に