Flutter
使用 Platform Channels 将 Human Token Journey 集成到您的 Flutter 应用中。
集成使用 MethodChannel 委托给 iOS 上的 ASWebAuthenticationSession 和 Android 上的 Custom Tabs。无需外部包。
前提条件
- Flutter 3.x 或更高版本
- 用于 iOS 的 Xcode 14+
- 用于 Android 的 Android Studio
- 您应用的唯一 URL scheme(例如
myapp)
步骤 1:定义 URL scheme
选择一个唯一的 scheme(例如 myapp)。创建流程时将其用作 callbackUri:
callbackUri: myapp://callback
步骤 2:创建 Dart 服务
// lib/services/unico_service.dart
import 'package:flutter/services.dart';
class UnicoService {
static const _channel = MethodChannel('unico_plugin');
Future<String?> openSession(String url) async {
try {
final result = await _channel.invokeMethod<String>('openSession', {'url': url});
if (result != null) {
final uri = Uri.parse(result);
return uri.queryParameters['id'];
}
return null;
} on PlatformException {
return null;
}
}
}
步骤 3: 实现 iOS 插件
// ios/Runner/UnicoPlugin.swift
import Flutter
import AuthenticationServices
class UnicoPlugin: NSObject, FlutterPlugin, ASWebAuthenticationPresentationContextProviding {
private var session: ASWebAuthenticationSession?
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "unico_plugin", binaryMessenger: registrar.messenger())
let instance = UnicoPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard call.method == "openSession",
let args = call.arguments as? [String: Any],
let urlString = args["url"] as? String,
let url = URL(string: urlString) else {
result(FlutterMethodNotImplemented)
return
}
let newSession = ASWebAuthenticationSession(
url: url,
callbackURLScheme: "myapp"
) { callbackURL, error in
self.session = nil
if let callbackURL = callbackURL {
result(callbackURL.absoluteString)
} else {
result(FlutterError(code: "SESSION_ERROR",
message: error?.localizedDescription ?? "Session cancelled",
details: nil))
}
}
newSession.presentationContextProvider = self
newSession.prefersEphemeralWebBrowserSession = true
newSession.start()
session = newSession
}
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
}
}
在 AppDelegate.swift 中注册:
UnicoPlugin.register(with: self.registrar(forPlugin: "UnicoPlugin")!)
步骤 4:实现 Android 插件
将依赖添加到 android/app/build.gradle:
implementation("androidx.browser:browser:1.5.0")
// android/app/src/main/kotlin/<your.package>/UnicoPlugin.kt
package com.yourapp
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class UnicoPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {
private var channel: MethodChannel? = null
private var binding: ActivityPluginBinding? = null
private var pendingResult: MethodChannel.Result? = null
override fun onAttachedToEngine(flutterBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterBinding.binaryMessenger, "unico_plugin")
channel?.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "openSession") {
val url = call.argument<String>("url") ?: return result.error("MISSING_URL", "URL is required", null)
pendingResult = result
val activity = binding?.activity ?: return result.error("NO_ACTIVITY", "No activity", null)
CustomTabsIntent.Builder().build().launchUrl(activity, Uri.parse(url))
} else {
result.notImplemented()
}
}
fun handleRedirect(uri: Uri) {
if (uri.scheme == "myapp") {
pendingResult?.success(uri.toString())
pendingResult = null
}
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) { this.binding = binding }
override fun onDetachedFromActivity() { binding = null }
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { this.binding = binding }
override fun onDetachedFromActivityForConfigChanges() { binding = null }
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel = null }
}
在 MainActivity.kt 中注册并处理重定向:
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(UnicoPlugin())
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
intent.data?.let { uri ->
if (uri.scheme == "myapp") {
val plugin = flutterEngine?.plugins?.get(UnicoPlugin::class.java) as? UnicoPlugin
plugin?.handleRedirect(uri)
}
}
}
步骤 5:配置 URL scheme
- iOS
- Android
添加到 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>
步骤 6:启动旅程
final unicoService = UnicoService();
final processId = await unicoService.openSession(processLink);
if (processId != null) {
// Journey completed — send processId to your backend via Get Process
} else {
// User canceled
}
文件概览
| 文件 | 用途 |
|---|---|
lib/services/unico_service.dart | Dart MethodChannel 服务 |
ios/Runner/UnicoPlugin.swift | iOS — ASWebAuthenticationSession |
ios/Runner/AppDelegate.swift | 插件注册 |
android/.../UnicoPlugin.kt | Android — Custom Tabs |
android/.../MainActivity.kt | 插件注册 + 重定向处理 |
Info.plist | iOS URL scheme |
AndroidManifest.xml | Android Intent 过滤器 |