Flutter支付身份验证插件stripe_identity_plugin的使用

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

Flutter支付身份验证插件stripe_identity_plugin的使用

stripe_identity_plugin

A Flutter插件用于在您的Flutter应用程序中实现Stripe身份验证。此包为Android和iOS平台提供了与Stripe身份验证服务的无缝集成。

pub package

Demo

调试模式下的测试

如果您提供正确的验证会话和临时密钥:

调试成功截图

否则,您将看到以下屏幕:

调试失败截图

开始使用

您可以访问Stripe身份验证网站获取更多有关如何开始的信息。 此包未得到Stripe的认可,但它旨在为您提供无缝的体验。有关此包如何为Android、iOS和其他平台工作的更多信息,请参阅Stripe身份文档

功能

  • 与Stripe身份验证轻松集成
  • 支持Android和iOS平台
  • 可自定义品牌logo显示
  • 简单的错误处理和结果解析
  • 类型安全的验证结果

安装

在您的包的pubspec.yaml文件中添加以下内容:

dependencies:
  stripe_identity_plugin: ^1.0.1

使用

基本实现

final stripeIdentity = StripeIdentityPlugin();

// 启动验证
final (status, message) = await stripeIdentity.startVerification(
  id: 'verification_session_id_from_your_server', // 您服务器上的验证会话ID
  key: 'ephemeral_key_secret_from_your_server', // 您服务器上的临时密钥
  brandLogoUrl: 'https://your-domain.com/logo.png', // 可选的品牌logo URL
);

// 处理结果
switch (status) {
  case VerificationResult.completed:
    print('验证完成成功');
  case VerificationResult.canceled:
    print('用户取消了验证');
  case VerificationResult.failed:
    print('验证失败: $message');
  case VerificationResult.unknown:
    print('未知错误发生: $message');
}

重要注意事项

  1. 在启动验证过程之前,请调用您的服务器端点以获取verificationSessionIdephemeralKeySecret
  2. 当提供品牌logo时,请确保它是推荐尺寸为32x32点的正方形图像。
  3. 验证流程完全由Stripe的原生SDK处理,确保了一个安全的验证过程。

验证结果

该插件返回一个包含以下内容的元组:

  • VerificationResult: 一个枚举,指示验证的状态
  • String?: 可选的消息,提供额外的详细信息

可能的验证结果:

  • completed: 用户已上传并完成文档验证过程
  • canceled: 用户取消了验证或未完成过程
  • failed: 验证失败(包括错误消息)
  • unknown: 发生意外错误

要求

  • iOS 13.0 或更高版本
  • Android API 级别 21 或更高版本
  • Flutter 3.0.0 或更高版本

许可证

该项目根据MIT许可证授权 - 详情请参阅LICENSE文件。

贡献

欢迎贡献!请随时提交拉取请求。


示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用stripe_identity_plugin

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:stripe_identity_plugin/stripe_identity_plugin.dart';
import 'package:stripe_identity_plugin/utils/enum.dart';

void main() async {
  await dotenv.load(fileName: ".env");
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _identityPlugin = StripeIdentityPlugin();
  bool isLoading = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Stripe Identity Plugin'),
        ),
        body: Builder(builder: (context) {
          return Center(
            child: ElevatedButton(
                onPressed: () async {
                  // 显示加载指示器
                  setState(() {
                    isLoading = true;
                  });

                  // 调用身份插件
                  final response = await _identityPlugin.startVerification(
                      id: dotenv.env['VERIFICATION_ID']!,
                      key: dotenv.env['VERIFICATION_KEY']!,
                      brandLogoUrl:
                          "https://img.icons8.com/?size=128&id=77153&format=png");

                  // 隐藏加载指示器
                  setState(() {
                    isLoading = false;
                  });

                  // 根据验证状态显示不同的Snackbar
                  if (!context.mounted) return;
                  switch (response.$1) {
                    case VerificationResult.completed:
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content:
                              Text(response.$2 ?? "验证完成")));
                      break;
                    case VerificationResult.failed:
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content: Text(response.$2 ?? "验证失败")));
                    default:
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          content: Text(response.$2 ??
                              "验证无法完成")));
                  }
                },
                child: isLoading
                    ? const CircularProgressIndicator.adaptive(
                        backgroundColor: Colors.black,
                      )
                    : const Text("开始验证")),
          );
        }),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中集成并使用stripe_identity_plugin进行支付身份验证的示例代码。这个插件允许你使用Stripe Identity来验证用户的身份,这对于符合KYC(了解你的客户)法规的应用非常有用。

首先,确保你的Flutter项目已经设置好了,并且已经添加了stripe_identity_plugin依赖。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  stripe_identity_plugin: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

接下来,你需要进行一些配置,包括在Stripe Dashboard中为你的应用创建一个Stripe Identity Verification Session。这里我们假设你已经完成了这些配置,并且有了必要的session ID。

Flutter代码示例

  1. 导入插件

在你的Dart文件中导入stripe_identity_plugin

import 'package:stripe_identity_plugin/stripe_identity_plugin.dart';
  1. 初始化插件

在适当的位置(例如,在应用启动时),初始化Stripe Identity插件:

void initStripeIdentity() async {
  try {
    await StripeIdentityPlugin.initialize();
    print("Stripe Identity initialized");
  } catch (e) {
    print("Failed to initialize Stripe Identity: $e");
  }
}
  1. 启动身份验证流程

使用你从Stripe Dashboard获取的session ID启动身份验证流程:

void startIdentityVerification(String sessionId) async {
  try {
    // 启动Stripe Identity Verification流程
    await StripeIdentityPlugin.startVerificationSession(sessionId: sessionId);
    print("Started identity verification session");
  } catch (e) {
    print("Failed to start identity verification session: $e");
  }
}
  1. 处理验证结果

你可以通过监听插件提供的结果回调来处理验证结果。通常,这会在用户完成身份验证流程后触发。

void listenToVerificationResults() {
  StripeIdentityPlugin.verificationResultStream.listen((result) {
    if (result.isSuccess) {
      print("Identity verification successful: ${result.data}");
      // 处理成功的情况,例如更新用户界面或发送数据到服务器
    } else {
      print("Identity verification failed: ${result.error}");
      // 处理失败的情况,例如显示错误消息给用户
    }
  }, onError: (error) {
    print("Error listening to verification results: $error");
  });
}
  1. 完整示例

将上述步骤整合到一个完整的示例中:

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

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

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    initStripeIdentity();
    listenToVerificationResults();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stripe Identity Demo'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              // 假设你已经有了sessionId
              String sessionId = "你的_stripe_identity_session_id";
              startIdentityVerification(sessionId);
            },
            child: Text('Start Identity Verification'),
          ),
        ),
      ),
    );
  }

  void initStripeIdentity() async {
    try {
      await StripeIdentityPlugin.initialize();
      print("Stripe Identity initialized");
    } catch (e) {
      print("Failed to initialize Stripe Identity: $e");
    }
  }

  void startIdentityVerification(String sessionId) async {
    try {
      await StripeIdentityPlugin.startVerificationSession(sessionId: sessionId);
      print("Started identity verification session");
    } catch (e) {
      print("Failed to start identity verification session: $e");
    }
  }

  void listenToVerificationResults() {
    StripeIdentityPlugin.verificationResultStream.listen((result) {
      if (result.isSuccess) {
        print("Identity verification successful: ${result.data}");
      } else {
        print("Identity verification failed: ${result.error}");
      }
    }, onError: (error) {
      print("Error listening to verification results: $error");
    });
  }
}

这个示例展示了如何在Flutter应用中集成Stripe Identity插件,并启动一个身份验证流程。请确保你已经在Stripe Dashboard中正确配置了Identity Verification Session,并替换了示例代码中的sessionId

注意:实际项目中,你可能需要处理更多的边缘情况和用户交互细节。此外,请务必遵循Stripe的文档和最佳实践来确保安全和合规性。

回到顶部