---
title: Ionic
description: 使用 Capacitor 插件将 Human Token Journey 集成到您的 Ionic 应用中 — Android 上使用 Custom Tabs，iOS 上使用 ASWebAuthenticationSession。
canonical: https://developer.unico.io/zh-CN/human-token/integrations/app/ionic
locale: zh-CN
generated_by: markdown-export
---

- [/zh-CN/](/zh-CN/)
- [集成](/zh-CN/human-token/integrations)
- 应用
- Ionic

**本页内容Ionic使用 Capacitor 插件将 Human Token Journey 集成到您的 Ionic 应用中。

集成使用本地 Capacitor 插件，在 Android 上委托给 Custom Tabs，在 iOS 上委托给 `ASWebAuthenticationSession`。当旅程完成时，深层链接通过 `@capacitor/app` 返回。
### 前提条件​

Ionic（Capacitor v4+）
`@capacitor/app` 已安装
Xcode 14+ 和 Android Studio
您应用的唯一 URL scheme（例如 `myapp`）

### 步骤 1：定义 URL scheme​

选择一个唯一的 scheme（例如 `myapp`）。创建流程时将其用作 `callbackUri`：
```
callbackUri: myapp://callback
```

### 步骤 2：创建 Capacitor 插件接口​

```
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 插件​

```
import Capacitorimport 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 插件​

```
import android.content.Intentimport android.net.Uriimport androidx.browser.customtabs.CustomTabsIntentimport com.getcapacitor.Pluginimport com.getcapacitor.PluginCallimport com.getcapacitor.PluginMethodimport 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 scheme​

iOSAndroid添加到 `Info.plist`：```
<key>CFBundleURLTypes</key><array>    <dict>        <key>CFBundleURLSchemes</key>        <array>            <string>myapp</string>        </array>    </dict></array>
```

在主 `<activity>` 内的 `AndroidManifest.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`：```
implementation("androidx.browser:browser:1.5.0")
```

### 步骤 6：创建 Angular 服务​

```
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` 中：
```
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 scheme`AndroidManifest.xml`Android Intent 过滤器`unico.service.ts`Angular 服务封装最后更新 于 2026年10月21日**