Flutter支付集成插件flutterwave_flutterflow的使用

Flutter支付集成插件flutterwave_flutterflow的使用

Flutterwave Flutter SDK (标准版)

该Flutter库帮助你在FlutterFlow中创建无缝的支付体验。

Overview

可用功能包括:

  • 收款方式:卡、银行账户、移动钱包、银行转账、USSD、Barter。
  • 定期支付:令牌化与订阅。
  • 分账支付。

目录

  1. 需求
  2. 安装
  3. 使用
  4. 支持
  5. 贡献指南
  6. 许可

需求

  1. Flutterwave for Business API密钥
  2. 支持的Flutter版本 >= 1.17.0

安装

  1. 在项目的pubspec.yaml文件中添加依赖项:
    dependencies:
      flutterwave_flutterflow: 1.0.0
    
  2. 运行以下命令以获取依赖项:
    flutter pub get
    

使用

初始化Flutterwave实例

要创建一个实例,应该调用Flutterwave构造函数。此构造函数接受以下必需参数:

  • 调用上下文(Context
  • publicKey
  • Customer
  • amount
  • currency
  • email
  • fullName
  • txRef
  • isDebug
  • paymentOptions
  • Customization

返回一个Flutterwave实例,然后我们调用异步方法.charge()

_handlePaymentInitialization() async { 
  final style = FlutterwaveStyle(
    appBarText: "My Standard Blue", 
    buttonColor: Color(0xffd0ebff), 
    appBarIcon: Icon(Icons.message, color: Color(0xffd0ebff)),
    buttonTextStyle: TextStyle( 
        color: Colors.black, 
        fontWeight: FontWeight.bold, 
        fontSize: 18), 
    appBarColor: Color(0xffd0ebff), 
    dialogCancelTextStyle: TextStyle(
        color: Colors.redAccent, 
        fontSize: 18
        ),
    dialogContinueTextStyle: TextStyle(
          color: Colors.blue, 
          fontSize: 18
          ) 
        ); 

  final Customer customer = Customer(
          name: "FLW Developer", 
          phoneNumber: "1234566677777", 
          email: "customer@customer.com"
          );  
          
  final Flutterwave flutterwave = Flutterwave(
          context: context, 
          style: style, 
          publicKey: "Public Key", 
          currency: "RWF", 
          redirectUrl: "my_redirect_url", 
          txRef: "unique_transaction_reference", 
          amount: "3000", 
          customer: customer, 
          paymentOptions: "ussd, card, barter, payattitude", 
          customization: Customization(title: "Test Payment"),
          isDebug: true
          ); 
}

处理响应

调用.charge()方法返回一个ChargeResponse的Future,我们可以等待实际的响应。

final ChargeResponse response = await flutterwave.charge(); 
if (response != null) { 
  print(response.toJson()); 
  if(response.success) { 
    // 调用验证交易端点,使用`response.transactionId`返回的交易ID来验证交易
  } else { 
    // 交易不成功
  } 
} else {
  // 用户取消了支付
}

注意事项

  1. 如果用户按下返回键取消交易,ChargeResponse可能为null
  2. 验证交易是否成功。确保txRefamount和状态正确且成功。在提供价值之前,请务必验证交易详情

支持

如需更多帮助,请通过以下方式联系开发体验(DX)团队:

  • 邮件:developers@flutterwavego.com
  • Slack:链接

你也可以关注我们的Twitter账号@FlutterwaveEng,告诉我们你的想法。


贡献指南

有关社区贡献指南的更多信息,请参阅此处


许可

通过为Flutter库做出贡献,您同意您的贡献将根据其MIT许可进行授权。

版权 © Flutterwave Inc.


构建所用技术


示例代码

以下是完整的示例代码:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutterwave_flutterflow/flutterwave.dart';
import 'package:flutterwave_flutterflow/models/subaccount.dart';
import 'package:uuid/uuid.dart';
import 'dart:collection';
import 'package:http/http.dart' as Http;

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Standard Demo',
      home: MyHomePage('Flutterwave Standard'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage(this.title);

  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final formKey = GlobalKey<FormState>();
  final amountController = TextEditingController();
  final currencyController = TextEditingController();
  final narrationController = TextEditingController();
  final publicKeyController = TextEditingController();
  final encryptionKeyController = TextEditingController();
  final emailController = TextEditingController();
  final phoneNumberController = TextEditingController();

  String selectedCurrency = "UGX";

  bool isTestMode = true;
  final pbk = "FLWPUBK_TEST-bef5d259e2f13e98debf9fb18af5cbf5-X";

  [@override](/user/override)
  Widget build(BuildContext context) {
    this.currencyController.text = this.selectedCurrency;

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        width: double.infinity,
        margin: EdgeInsets.fromLTRB(20, 10, 20, 10),
        child: Form(
          key: this.formKey,
          child: ListView(
            children: <Widget>[
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: TextFormField(
                  controller: this.amountController,
                  textInputAction: TextInputAction.next,
                  keyboardType: TextInputType.number,
                  style: TextStyle(color: Colors.black),
                  decoration: InputDecoration(hintText: "Amount"),
                  validator: (value) =>
                      value.isNotEmpty ? null : "Amount is required",
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: TextFormField(
                  controller: this.currencyController,
                  textInputAction: TextInputAction.next,
                  style: TextStyle(color: Colors.black),
                  readOnly: true,
                  onTap: this._openBottomSheet,
                  decoration: InputDecoration(
                    hintText: "Currency",
                  ),
                  validator: (value) =>
                      value.isNotEmpty ? null : "Currency is required",
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: TextFormField(
                  controller: this.publicKeyController,
                  textInputAction: TextInputAction.next,
                  style: TextStyle(color: Colors.black),
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: "Public Key",
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: TextFormField(
                  controller: this.encryptionKeyController,
                  textInputAction: TextInputAction.next,
                  style: TextStyle(color: Colors.black),
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: "Encryption Key",
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: TextFormField(
                  controller: this.emailController,
                  textInputAction: TextInputAction.next,
                  style: TextStyle(color: Colors.black),
                  decoration: InputDecoration(
                    hintText: "Email",
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: TextFormField(
                  controller: this.phoneNumberController,
                  textInputAction: TextInputAction.next,
                  style: TextStyle(color: Colors.black),
                  decoration: InputDecoration(
                    hintText: "Phone Number",
                  ),
                ),
              ),
              Container(
                width: double.infinity,
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: Row(
                  children: [
                    Text("Use Debug"),
                    Switch(
                      onChanged: (value) => {
                        setState(() {
                          isTestMode = value;
                        })
                      },
                      value: this.isTestMode,
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                height: 50,
                margin: EdgeInsets.fromLTRB(0, 20, 0, 10),
                child: ElevatedButton(
                  onPressed: this._onPressed,
                  child: Text(
                    "Make Payment",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  _onPressed() {
    if (this.formKey.currentState.validate()) {
      this._handlePaymentInitialization();
    }
  }

  _handlePaymentInitialization() async {
    final style = FlutterwaveStyle(
      appBarText: "Nyumbani Payment",
      buttonColor: Color.fromARGB(255, 4, 113, 197),
      buttonTextStyle: TextStyle(
        color: Color.fromARGB(255, 255, 255, 255),
        fontSize: 16,
      ),
      appBarColor: Color.fromARGB(255, 212, 118, 2),
      dialogCancelTextStyle: TextStyle(
        color: Color.fromARGB(255, 255, 255, 255),
        fontSize: 18,
      ),
      dialogContinueTextStyle: TextStyle(
        color: Color.fromARGB(255, 255, 255, 255),
        fontSize: 18,
      ),
      mainBackgroundColor: Color.fromARGB(255, 255, 255, 255),
      mainTextStyle: TextStyle(
          color: Color.fromARGB(255, 10, 10, 10),
          fontSize: 19,
          letterSpacing: 2),
      dialogBackgroundColor: Color.fromARGB(255, 251, 173, 7),
      appBarIcon: Icon(Icons.message, color: Colors.purple),
      buttonText: "Pay $selectedCurrency ${amountController.text}",
      appBarTitleTextStyle: TextStyle(
        color: Color.fromARGB(255, 255, 255, 255),
        fontSize: 18,
      ),
    );

    final Customer customer = Customer(
        name: "FLW Developer",
        phoneNumber: this.phoneNumberController.text ?? "12345678",
        email: "customer@customer.com");

    final subAccounts = [
      SubAccount(
          id: "RS_1A3278129B808CB588B53A14608169AD",
          transactionChargeType: "flat",
          transactionPercentage: 25),
      SubAccount(
          id: "RS_C7C265B8E4B16C2D472475D7F9F4426A",
          transactionChargeType: "flat",
          transactionPercentage: 50)
    ];

    final Flutterwave flutterwave = Flutterwave(
        context: context,
        style: style,
        publicKey: this.publicKeyController.text.trim().isEmpty
            ? this.getPublicKey()
            : this.publicKeyController.text.trim(),
        currency: this.selectedCurrency,
        redirectUrl: "https://google.com",
        txRef: Uuid().v1(),
        amount: this.amountController.text.toString().trim(),
        customer: customer,
        // subAccounts: subAccounts,
        paymentOptions:
            "card, barter,  payattitude,mpesa, mobilemoneyuganda, mobilemoneyrwanda, mobilemoneyzambia,mobilemoneyfranco,mobilemoneyghana, ussd, banktransfer",
        customization: Customization(title: "Test Payment"),
        isTestMode: false);
    final ChargeResponse response = await flutterwave.charge();
    if (response != null) {
      this.showLoading(response.status);
      print("${response.toJson()}");
    } else {
      this.showLoading("No Response!");
    }
  }

  String getPublicKey() {
    if (isTestMode) return "FLWPUBK_TEST-895362a74986153380262d89bfdc9b8a-X";
    return "FLWPUBK-aa4cd0b443404147d2d8229a37694b00-X";
  }

  void _openBottomSheet() {
    showModalBottomSheet(
        context: this.context,
        builder: (context) {
          return this._getCurrency();
        });
  }

  Widget _getCurrency() {
    final currencies = ["NGN", "RWF", "UGX", "KES", "ZAR", "USD", "GHS", "TZS"];
    return Container(
      height: 250,
      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
      color: Colors.white,
      child: ListView(
        children: currencies
            .map((currency) => ListTile(
                  onTap: () => {this._handleCurrencyTap(currency)},
                  title: Column(
                    children: [
                      Text(
                        currency,
                        textAlign: TextAlign.start,
                        style: TextStyle(color: Colors.black),
                      ),
                      SizedBox(height: 4),
                      Divider(height: 1)
                    ],
                  ),
                ))
            .toList(),
      ),
    );
  }

  _handleCurrencyTap(String currency) {
    this.setState(() {
      this.selectedCurrency = currency;
      this.currencyController.text = currency;
    });
    Navigator.pop(this.context);
  }

  Future<void> showLoading(String message) {
    return showDialog(
      context: this.context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Container(
            margin: EdgeInsets.fromLTRB(30, 20, 30, 20),
            width: double.infinity,
            height: 50,
            child: Text(message),
          ),
          actions: [
            ElevatedButton(
              child: Text("OK"),
              onPressed: () {},
            ),
          ],
        );
      },
    );
  }
}

更多关于Flutter支付集成插件flutterwave_flutterflow的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


flutterwave_flutterflow 是一个用于在 Flutter 应用中集成 Flutterwave 支付的插件。Flutterwave 是一个非洲的支付网关,支持多种支付方式,包括信用卡、银行转账、移动支付等。通过 flutterwave_flutterflow 插件,你可以轻松地在 Flutter 应用中集成 Flutterwave 支付功能。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutterwave_flutterflow 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutterwave_flutterflow: ^1.0.0  # 请使用最新版本

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

2. 初始化 Flutterwave

在你的 Dart 文件中,导入 flutterwave_flutterflow 并初始化 Flutterwave:

import 'package:flutterwave_flutterflow/flutterwave_flutterflow.dart';

void initializeFlutterwave() {
  FlutterwaveFlutterflow.initialize(
    publicKey: 'YOUR_PUBLIC_KEY',  // 你的 Flutterwave 公钥
    encryptionKey: 'YOUR_ENCRYPTION_KEY',  // 你的 Flutterwave 加密密钥
    currency: 'NGN',  // 货币代码,例如 NGN(尼日利亚奈拉)
    country: 'NG',  // 国家代码,例如 NG(尼日利亚)
  );
}

3. 发起支付

使用 FlutterwaveFlutterflow 发起支付请求。你可以通过 chargeCard 方法来发起支付:

void makePayment() async {
  final response = await FlutterwaveFlutterflow.chargeCard(
    amount: '1000',  // 支付金额
    email: 'user@example.com',  // 用户邮箱
    phoneNumber: '1234567890',  // 用户手机号
    fullName: 'John Doe',  // 用户全名
    txRef: 'unique_transaction_reference',  // 唯一交易参考号
  );

  if (response.status == 'success') {
    print('Payment successful: ${response.transactionId}');
  } else {
    print('Payment failed: ${response.message}');
  }
}

4. 处理支付结果

chargeCard 方法会返回一个 FlutterwaveResponse 对象,你可以根据 status 属性来判断支付是否成功,并处理相应的逻辑。

5. 其他功能

flutterwave_flutterflow 还支持其他功能,例如银行转账、移动支付等。你可以根据 Flutterwave 的文档和插件的 API 来集成这些功能。

6. 注意事项

  • 确保你已经在 Flutterwave 平台上注册并获取了公钥和加密密钥。
  • 在生产环境中,请确保使用正确的公钥和加密密钥,并妥善保管这些敏感信息。
  • 根据你的应用需求,处理支付成功和失败的情况,并提供相应的用户反馈。

7. 示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用中集成 Flutterwave 支付:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PaymentScreen(),
    );
  }
}

class PaymentScreen extends StatelessWidget {
  void initializeFlutterwave() {
    FlutterwaveFlutterflow.initialize(
      publicKey: 'YOUR_PUBLIC_KEY',
      encryptionKey: 'YOUR_ENCRYPTION_KEY',
      currency: 'NGN',
      country: 'NG',
    );
  }

  void makePayment() async {
    final response = await FlutterwaveFlutterflow.chargeCard(
      amount: '1000',
      email: 'user@example.com',
      phoneNumber: '1234567890',
      fullName: 'John Doe',
      txRef: 'unique_transaction_reference',
    );

    if (response.status == 'success') {
      print('Payment successful: ${response.transactionId}');
    } else {
      print('Payment failed: ${response.message}');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutterwave Payment'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            initializeFlutterwave();
            makePayment();
          },
          child: Text('Make Payment'),
        ),
      ),
    );
  }
}
回到顶部