Flutter中如何使用api.flutterwave

在Flutter应用中集成Flutterwave支付时,如何正确配置和使用api.flutterwave?具体步骤是什么?需要哪些依赖和权限?能否提供一个完整的代码示例,包括初始化、支付请求和回调处理?另外,如何处理常见的错误和异常情况?

2 回复

在Flutter中使用Flutterwave API,需先添加flutterwave_rave依赖。然后初始化Flutterwave对象,传入公钥、金额、邮箱等参数。最后调用charge()方法发起支付。示例代码可在官方文档查看。

更多关于Flutter中如何使用api.flutterwave的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中使用Flutterwave API,主要通过集成flutterwave_flutter包来实现支付功能。以下是详细步骤:

1. 添加依赖

pubspec.yaml文件中添加依赖:

dependencies:
  flutterwave_flutter: ^3.0.5

运行 flutter pub get 安装包。

2. 配置Android清单

android/app/src/main/AndroidManifest.xml 中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

3. 初始化支付

在Dart文件中导入包并初始化支付:

import 'package:flutterwave_flutter/flutterwave_flutter.dart';

class PaymentService {
  static Future<void> initializePayment({
    required String publicKey,
    required String encryptionKey,
    required String currency,
    required String email,
    required double amount,
    required String fullName,
    required String txRef,
  }) async {
    try {
      final Flutterwave flutterwave = Flutterwave(
        context: context, // 需要BuildContext
        publicKey: publicKey,
        currency: currency,
        redirectUrl: "https://your-website.com/redirect", // 自定义重定向URL
        txRef: txRef,
        amount: amount.toString(),
        customer: Customer(
          name: fullName,
          email: email,
        ),
        paymentOptions: "card, payattitude, barter", // 支持的支付方式
        customization: Customization(title: "Test Payment"),
        isTestMode: true, // 测试环境设为true,生产环境设为false
      );

      final ChargeResponse response = await flutterwave.charge();
      if (response != null) {
        print("Payment Status: ${response.status}");
        print("Transaction ID: ${response.transactionId}");
        if (response.status == "success") {
          // 支付成功逻辑
        } else {
          // 支付失败处理
        }
      }
    } catch (e) {
      print("Payment Error: $e");
    }
  }
}

4. 调用支付方法

在需要支付的地方调用:

PaymentService.initializePayment(
  publicKey: "YOUR_PUBLIC_KEY", // 从Flutterwave仪表板获取
  encryptionKey: "YOUR_ENCRYPTION_KEY", // 从Flutterwave仪表板获取
  currency: "NGN", // 例如:NGN、USD、KES等
  email: "customer@example.com",
  amount: 100.0,
  fullName: "John Doe",
  txRef: "unique_transaction_ref_${DateTime.now().millisecondsSinceEpoch}",
);

注意事项:

  • 密钥管理:不要将公钥和加密密钥硬编码在代码中,建议使用环境变量或安全配置。
  • 重定向URL:确保在Flutterwave仪表板中配置正确的重定向URL。
  • 错误处理:根据ChargeResponse.status处理成功、失败或取消状态。
  • 测试模式:上线前将isTestMode设为false

通过以上步骤,即可在Flutter应用中集成Flutterwave支付功能。

回到顶部