Flutter身份验证插件klippa_identity_verification_sdk的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter Klippa Identity Verification SDK 使用指南

SDK 使用说明

在使用 klippa_identity_verification_sdk 之前,请确保您拥有 Klippa Identity Verification OCR API 密钥。如果您希望使用我们的身份验证 SDK,请联系 Klippa

开始使用

Android 设置

编辑文件 android/key.properties,如果该文件不存在,请创建它,并添加 SDK 凭据:

klippa.identity_verification.sdk.username={your-username}
klippa.identity_verification.sdk.password={your-password}

{your-username}{your-password} 替换为 Klippa 提供的值。

iOS 设置

编辑文件 ios/Podfile,添加 Klippa CocoaPod:

// Add this to the top of your file:
platform :ios, '13.0'
ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_USERNAME'] = '{your-username}'
ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_PASSWORD'] = '{your-password}'

target 'Runner' do
  // ... other instructions

  if "#{ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_URL']}" == ""
    ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_URL'] = File.read(File.join(File.dirname(File.realpath(__FILE__)), '.symlinks', 'plugins', 'klippa_identity_verification_sdk', 'ios', 'sdk_repo')).strip
  end

  if "#{ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_VERSION']}" == ""
    ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_VERSION'] = File.read(File.join(File.dirname(File.realpath(__FILE__)), '.symlinks', 'plugins', 'klippa_identity_verification_sdk', 'ios', 'sdk_version')).strip
  end

  pod 'Klippa-Identity-Verification', podspec: "#{ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_URL']}/#{ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_USERNAME']}/#{ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_PASSWORD']}/KlippaIdentityVerification/#{ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_VERSION']}.podspec"
end

{your-username}{your-password} 替换为 Klippa 提供的值。

编辑文件 ios/{project-name}/Info.plist 并添加 NSCameraUsageDescription 值:

<key>NSCameraUsageDescription</key>
<string>Access to your camera is needed to photograph documents.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Access to your photo library is used to save the images of documents.</string>

Flutter 设置

在您的 pubspec.yaml 文件中添加 klippa_identity_verification_sdk 作为依赖项:

dependencies:
  klippa_identity_verification_sdk: ^latest_version

使用示例

以下是一个完整的示例 Demo,展示了如何使用 klippa_identity_verification_sdk 插件进行身份验证:

import 'package:flutter/material.dart';
import 'package:klippa_identity_verification_sdk/klippa_identity_verification_sdk.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _idVerificationResult = 'Unknown';

  @override
  void initState() {
    super.initState();
  }

  void _startSession() async {
    String sessionResultText = 'Unknown';
    var identityBuilder = IdentityBuilder();
    identityBuilder.isDebug = true; // 启用调试模式
    try {
      // @todo: 获取一个会话令牌通过您的后端API。
      var sessionResult = await KlippaIdentityVerificationSdk.startSession(
          identityBuilder, '{insert-session-token-here}');
      sessionResultText = 'Finished';
    } on PlatformException catch (e) {
      sessionResultText = 'Failed to start session: ' + e.toString();
    }

    setState(() {
      _idVerificationResult = sessionResultText;
    });

    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('ID verification result: $_idVerificationResult\n'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _startSession,
          tooltip: 'Start session',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

如何使用特定版本的 SDK?

Android

编辑文件 android/build.gradle,添加以下内容:

allprojects {
  // ... 其他定义
  project.ext {
      klippaIdentityVerificationVersion = "{version}"
  }
}

{version} 替换为您要使用的版本号。

如果需要更改存储库:

编辑文件 android/key.properties,添加 SDK 存储库 URL:

klippa.identity_verification.sdk.url={repository-url}

{repository-url} 替换为您要使用的 URL。

iOS

编辑文件 ios/Podfile,添加以下行(在用户名/密码下方)以更改版本:

ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_VERSION'] = '{version}'

{version} 替换为您要使用的版本号。

如果需要更改存储库:

编辑文件 ios/Podfile,添加以下行(在用户名/密码下方)以更改 URL:

ENV['KLIPPA_IDENTITY_VERIFICATION_SDK_URL'] = '{repository-url}'

{repository-url} 替换为您要使用的 URL。

如何配置 SDK 设置?

调试模式

启用额外的调试信息:

identityBuilder.isDebug = true;

自动捕获

配置相机是否应在条件合适时自动拍照:

identityBuilder.enableAutoCapture = true;

显示介绍/成功屏幕

配置是否显示介绍/成功屏幕:

identityBuilder.hasIntroScreen = true;
identityBuilder.hasSuccessScreen = true;

重试阈值

配置用户尝试任务的次数,超过该次数将显示“联系支持”按钮:

identityBuilder.retryThreshold = 1;

语言设置

配置语言:

// 支持英语、荷兰语、西班牙语、德语和法语。
identityBuilder.language = KIVLanguage.Dutch;

当未指定语言时,SDK 尝试检测设备的语言并使用支持的语言。

包含/排除列表

您可以编辑包含列表(提取的数据键将在文档图片处理后显示给用户)或排除列表(提取的数据键将隐藏):

identityBuilder.verifyIncludeList = [
     "DateOfBirth",
     "DateOfIssue",
     "DateOfExpiry",
     "DocumentNumber",
     "DocumentSubtype",
     "DocumentType",
     "Face",
     "Gender",
     "GivenNames",
     "Height",
     "IssuingCountry",
     "IssuingInstitution",
     "Nationality",
     "PersonalNumber",
     "PlaceOfBirth",
     "Residency",
     "Signature",
     "Surname"
];

identityBuilder.verifyExcludeList = [];

验证包含/排除列表

您可以编辑验证包含列表(显示给用户的失败验证)或验证排除列表(隐藏的失败验证):

identityBuilder.validationIncludeList = [
    "DetectFace",
    "CompareFace",
    "DetectSignature",
    "CompareSignature",
    "CheckRequiredField",
    "MatchSidesFront",
    "MatchSidesBack",
    "FieldValidation",
    "MatchVizMrz",
    "MrzChecksum"
]

identityBuilder.validationExcludeList = []

如何更改 SDK 的颜色?

Android

添加或编辑文件 android/app/src/main/res/values/colors.xml,添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="kiv_text_color">#808080</color>
    <color name="kiv_background_color">#FFFFFF</color>
    <color name="kiv_button_success_color">#00CC00</color>
    <color name="kiv_button_error_color">#FF0000</color>
    <color name="kiv_button_other_color">#333333</color>
    <color name="kiv_progress_bar_background_color">#EBEFEF</color>
    <color name="kiv_progress_bar_foreground_color">#00CC00</color>
</resources>

您也可以替换字体文件:

  • android/app/src/main/res/font/kiv_font.ttf
  • android/app/src/main/res/font/kiv_font_bold.ttf

iOS

在构建器中使用以下属性:

// 颜色:
identityBuilder.colors.textColor = Color.fromARGB(255, 128, 128, 128);
identityBuilder.colors.backgroundColor = Color.fromARGB(255, 255, 255, 255);
identityBuilder.colors.buttonSuccessColor = Color.fromARGB(255, 0, 204, 0);
identityBuilder.colors.buttonErrorColor = Color.fromARGB(255, 255, 0, 0);
identityBuilder.colors.buttonOtherColor = Color.fromARGB(255, 51, 51, 51);
identityBuilder.colors.progressBarBackground = Color.fromARGB(255, 235, 239, 239);
identityBuilder.colors.progressBarForeground = Color.fromARGB(255, 0, 204, 0);

// 字体:
identityBuilder.fonts.fontName = 'Avenir Next';
identityBuilder.fonts.boldFontName = 'Avenir Next';

更多关于Flutter身份验证插件klippa_identity_verification_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter身份验证插件klippa_identity_verification_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 klippa_identity_verification_sdk 插件在 Flutter 中实现身份验证的示例代码。这个示例假设你已经按照插件的官方文档完成了安装和配置。

首先,确保你已经在 pubspec.yaml 文件中添加了依赖项:

dependencies:
  flutter:
    sdk: flutter
  klippa_identity_verification_sdk: ^最新版本号

然后,运行 flutter pub get 来获取依赖项。

接下来,在你的 Flutter 项目中,你可以按照以下步骤使用 klippa_identity_verification_sdk 进行身份验证:

  1. 导入包

在你的 Dart 文件中导入必要的包:

import 'package:flutter/material.dart';
import 'package:klippa_identity_verification_sdk/klippa_identity_verification_sdk.dart';
  1. 初始化 SDK

通常,你会在应用启动时初始化 SDK。这可以放在你的 main.dart 文件中:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化 Klippa Identity Verification SDK
  KlippaIdentityVerification.initialize(
    apiKey: '你的API密钥', // 替换为你的API密钥
    environment: KlippaEnvironment.sandbox, // 或 KlippaEnvironment.production
  );
  runApp(MyApp());
}
  1. 创建身份验证界面

创建一个新的 Dart 文件(例如 identity_verification_screen.dart)来处理身份验证逻辑:

import 'package:flutter/material.dart';
import 'package:klippa_identity_verification_sdk/klippa_identity_verification_sdk.dart';

class IdentityVerificationScreen extends StatefulWidget {
  @override
  _IdentityVerificationScreenState createState() => _IdentityVerificationScreenState();
}

class _IdentityVerificationScreenState extends State<IdentityVerificationScreen> {
  String result = '';

  void startVerification() async {
    try {
      // 启动身份验证流程
      final KlippaVerificationResult verificationResult = await KlippaIdentityVerification.startVerification(
        configuration: KlippaVerificationConfiguration(
          documentType: KlippaDocumentType.idCard, // 或 KlippaDocumentType.passport 等
          countryCode: 'NL', // 替换为你的国家代码
          faceCapture: true,
          livenessCheck: true,
        ),
      );

      // 处理验证结果
      setState(() {
        result = 'Verification Result: ${verificationResult.result}';
      });
    } catch (e) {
      // 处理错误
      setState(() {
        result = 'Error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Identity Verification'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(result),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: startVerification,
              child: Text('Start Verification'),
            ),
          ],
        ),
      ),
    );
  }
}
  1. 在你的应用中导航到身份验证界面

在你的主应用文件(例如 main.dart)中,添加导航到身份验证界面的逻辑:

import 'package:flutter/material.dart';
import 'identity_verification_screen.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  KlippaIdentityVerification.initialize(
    apiKey: '你的API密钥',
    environment: KlippaEnvironment.sandbox,
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => IdentityVerificationScreen()),
            );
          },
          child: Text('Verify Identity'),
        ),
      ),
    );
  }
}

这个示例展示了如何初始化 klippa_identity_verification_sdk,并创建一个简单的身份验证界面。用户点击按钮后,将启动身份验证流程,并在完成后显示结果。请确保你已经替换了示例代码中的 '你的API密钥' 和其他相关配置。

回到顶部