跳转到主要内容
Flutter 采集

通过 platform channel 从 Flutter 应用中打开采集。

Markdown

您的后端使用 Journey 流程和一个采用您应用 URL scheme 的 callbackUri 在 Human Plugin 中创建流程。MethodChannel 会在 iOS 的 ASWebAuthenticationSession 和 Android 的 Custom Tabs 中打开响应里的 link。无需任何外部包。

请保留创建响应中的 Human Plugin id。您的后端用它来读取结果。

前提条件​

  • Flutter 3 或更高版本
  • iOS 需要 Xcode 14 或更高版本
  • Android 需要 Android Studio
  • 您应用独有的 URL scheme,例如 myapp

1. 使用您的 scheme 创建流程​

您的后端将该 scheme 作为 callbackUri 发送:

{
"flow": "humantoken",
"clientId": "client-a",
"correlationId": "order-1001",
"credential": { "type": "DUI_TYPE_NG_BVN", "value": "<document number>" },
"callbackUri": "myapp://callback"
}

并将 id 和 link 返回给应用。

2. 创建 Dart 服务​

// lib/services/capture_service.dart
import 'package:flutter/services.dart';

class CaptureService {
static const _channel = MethodChannel('capture_plugin');

/// Returns true when the capture ended, false when the person closed it.
Future<bool> open(String link) async {
try {
final result = await _channel.invokeMethod<String>('openSession', {'url': link});
return result != null;
} on PlatformException {
return false;
}
}
}

3. 实现 iOS 插件​

// ios/Runner/CapturePlugin.swift
import Flutter
import AuthenticationServices

class CapturePlugin: NSObject, FlutterPlugin, ASWebAuthenticationPresentationContextProviding {
private var session: ASWebAuthenticationSession?

static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "capture_plugin", binaryMessenger: registrar.messenger())
let instance = CapturePlugin()
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 中注册:

CapturePlugin.register(with: self.registrar(forPlugin: "CapturePlugin")!)

4. 实现 Android 插件​

将依赖添加到 android/app/build.gradle:

implementation("androidx.browser:browser:1.5.0")
// android/app/src/main/kotlin/<your.package>/CapturePlugin.kt
package com.yourapp

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 CapturePlugin : 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, "capture_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(CapturePlugin())
}

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
intent.data?.let { uri ->
if (uri.scheme == "myapp") {
val plugin = flutterEngine?.plugins?.get(CapturePlugin::class.java) as? CapturePlugin
plugin?.handleRedirect(uri)
}
}
}

5. 注册您的 scheme​

在 Info.plist 中:

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

6. 启动采集​

final ended = await CaptureService().open(link);

if (ended) {
// The capture ended. Ask your back-end to read the outcome
// with GET /v1/processes/{id}, using the Human Plugin id.
} else {
// The person closed the session.
}

总结​

文件用途
lib/services/capture_service.dartDart MethodChannel 服务
ios/Runner/CapturePlugin.swiftiOS:ASWebAuthenticationSession
ios/Runner/AppDelegate.swift插件注册
android/.../CapturePlugin.ktAndroid:Custom Tabs
android/.../MainActivity.kt插件注册与返回处理
Info.plistiOS URL scheme
AndroidManifest.xmlAndroid intent filter