Flutter支付插件klasha_checkout_v2的使用

Flutter支付插件klasha_checkout_v2的使用

关于

Klasha Flutter SDK允许你在Flutter应用中快速、简单地构建一个出色的支付体验。我们提供了强大的、可自定义的UI屏幕和元素,可以开箱即用,以收集用户通过Klasha Checkout Technology进行支付的详细信息。

Bank Transfer Checkout Card Checkout

Mobile Money Checkout Mpesa Checkout

安装

在你的Flutter项目的pubspec.yaml文件中,添加以下依赖:

dependencies:
  klasha_checkout_v2: ^1.0.2

如何使用

步骤 1

在你的文件中添加以下导入:

import 'package:klasha_checkout_v2/klasha_checkout_v2.dart';

步骤 2

调用checkout方法并处理checkout方法的响应:

KlashaCheckout.checkout(
  context,
  config: KlashaCheckoutConfig(
    email: email!,
    amount: int.parse(amount!),
    checkoutCurrency: _checkoutCurrency,
    authToken: 'your_auth_token',
    onComplete: (KlashaCheckoutResponse klashaCheckoutResponse) {
      print(klashaCheckoutResponse);
    }
  ),
);

自定义

属性 描述
email 客户的电子邮件地址。
amount 付款金额,在选择的货币中,默认为NGN。
checkoutCurrency 要使用的结算货币,默认为NGN。
environment 要使用的环境,默认为TEST。
onComplete 这个方法返回刚刚完成交易的状态、消息和交易参考。

示例代码

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

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:klasha_checkout_v2/klasha_checkout_v2.dart';

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

class MyApp extends StatelessWidget {
  // 这个小部件是您的应用的根。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Klasha Checkout Demo',
      theme: ThemeData(
        primaryColor: Color(0xFFE85243),
      ),
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  [@override](/user/override)
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String? email, amount;
  var formKey = GlobalKey<FormState>();
  CheckoutCurrency _checkoutCurrency = CheckoutCurrency.NGN;

  void _launchKlashaPay() async {
    if ((formKey.currentState?.validate() ?? false) && email != null && amount != null) {
      KlashaCheckout.checkout(
        context,
        config: KlashaCheckoutConfig(
          email: email!,
          amount: double.parse(amount!),
          checkoutCurrency: _checkoutCurrency,
          authToken: 'GByi/gkhn5+BX4j6uI0lR7HCVo2NvTsVAQhyPko/uK4=',
          onComplete: (KlashaCheckoutResponse klashaCheckoutResponse) {
            print(
                'checkout response transaction reference is  ${klashaCheckoutResponse.transactionReference}');
            print(
                'checkout response status is ${klashaCheckoutResponse.status}');
            print(
                'checkout response message is ${klashaCheckoutResponse.message}');
          },
        ),
      );
    }
  }

  void _onRadioChanged(CheckoutCurrency? checkoutCurrency) {
    if (checkoutCurrency == null) return;
    setState(() => _checkoutCurrency = checkoutCurrency);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFfaf1f0),
      appBar: AppBar(
        elevation: 0.0,
        title: Text('Klasha Checkout Demo'),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 20.0),
        child: Form(
          key: formKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 25),
              Text('Customer Email'),
              SizedBox(height: 5),
              TextFormField(
                onChanged: (val) => setState(() => email = val),
                keyboardType: TextInputType.emailAddress,
                textInputAction: TextInputAction.next,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(15.0),
                    borderSide: BorderSide.none,
                  ),
                  hintText: 'john@doe.com',
                  filled: true,
                  fillColor: Color(0xFFFCE5E3),
                ),
                validator: validateEmail,
              ),
              const SizedBox(height: 25),
              Text('Currency'),
              SizedBox(height: 5),
              ...CheckoutCurrency.values.map(
                (e) => RadioListTile(
                  value: e,
                  groupValue: _checkoutCurrency,
                  onChanged: _onRadioChanged,
                  title: Text('${e.name}'),
                  controlAffinity: ListTileControlAffinity.leading,
                  contentPadding: EdgeInsets.zero,
                ),
              ),
              const SizedBox(height: 25),
              Text('Amount'),
              SizedBox(height: 5),
              TextFormField(
                onChanged: (val) => setState(() => amount = val),
                keyboardType: TextInputType.number,
                textInputAction: TextInputAction.done,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(15.0),
                    borderSide: BorderSide.none,
                  ),
                  hintText: '10,000',
                  filled: true,
                  fillColor: Color(0xFFFCE5E3),
                ),
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                validator: (val) {
                  return val?.isEmpty ?? true ? 'Amount is required' : null;
                },
              ),
              const SizedBox(height: 30),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _launchKlashaPay,
                  child: Text('Checkout'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFFE85243),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    fixedSize: Size.fromHeight(55),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String? validateEmail(String? email) {
    String source =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';

    RegExp regExp = new RegExp(source);
    if (email?.trim().isEmpty ?? true) {
      return 'Email is required';
    } else if (!regExp.hasMatch(email!)) {
      return 'Enter a valid email address';
    } else {
      return null;
    }
  }
}

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

1 回复

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


klasha_checkout_v2 是一个Flutter插件,用于集成Klasha支付网关到你的Flutter应用程序中。Klasha是一个非洲的支付解决方案,支持多种支付方式,包括银行卡、移动货币等。使用 klasha_checkout_v2 插件,你可以轻松地在你的应用中实现支付功能。

以下是如何使用 klasha_checkout_v2 插件的步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  klasha_checkout_v2: ^latest_version

然后运行 flutter pub get 来获取插件。

2. 初始化插件

在你的Flutter应用中,你需要初始化 klasha_checkout_v2 插件。通常你可以在 main.dart 文件中进行初始化。

import 'package:klasha_checkout_v2/klasha_checkout_v2.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  KlashaCheckout.init(
    publicKey: 'YOUR_PUBLIC_KEY',
    environment: KlashaEnvironment.SANDBOX, // or KlashaEnvironment.LIVE
  );
  runApp(MyApp());
}

3. 发起支付

在你的应用中的某个地方(例如按钮点击事件),你可以使用 KlashaCheckout 来发起支付请求。

import 'package:klasha_checkout_v2/klasha_checkout_v2.dart';

void initiatePayment() async {
  try {
    final response = await KlashaCheckout.charge(
      email: 'customer@example.com',
      amount: '1000',
      currency: 'NGN',
      txRef: 'unique_transaction_reference',
      phoneNumber: '2348100000000',
      fullName: 'John Doe',
      paymentType: KlashaPaymentType.CARD, // or KlashaPaymentType.MOBILE_MONEY
      onSuccess: (response) {
        print('Payment successful: $response');
      },
      onError: (error) {
        print('Payment error: $error');
      },
    );
    print('Payment response: $response');
  } catch (e) {
    print('Error: $e');
  }
}

4. 处理支付结果

KlashaCheckout.charge 方法会返回一个 Future,你可以通过 onSuccessonError 回调来处理支付结果。

5. 测试支付

在开发阶段,你可以使用 KlashaEnvironment.SANDBOX 环境来测试支付流程。确保你使用的是测试环境的 publicKey

6. 上线前的准备

在上线之前,确保你切换到 KlashaEnvironment.LIVE 环境,并使用生产环境的 publicKey

7. 错误处理

在实际使用中,可能会遇到各种错误,例如网络问题、支付失败等。确保你在 onError 回调中处理这些错误,并给用户提供适当的反馈。

8. 其他功能

klasha_checkout_v2 插件可能还支持其他功能,例如验证支付、获取交易状态等。你可以查看插件的官方文档或源代码来了解更多细节。

9. 参考文档

10. 示例代码

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

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  KlashaCheckout.init(
    publicKey: 'YOUR_PUBLIC_KEY',
    environment: KlashaEnvironment.SANDBOX,
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Klasha Payment Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: initiatePayment,
            child: Text('Pay with Klasha'),
          ),
        ),
      ),
    );
  }

  void initiatePayment() async {
    try {
      final response = await KlashaCheckout.charge(
        email: 'customer@example.com',
        amount: '1000',
        currency: 'NGN',
        txRef: 'unique_transaction_reference',
        phoneNumber: '2348100000000',
        fullName: 'John Doe',
        paymentType: KlashaPaymentType.CARD,
        onSuccess: (response) {
          print('Payment successful: $response');
        },
        onError: (error) {
          print('Payment error: $error');
        },
      );
      print('Payment response: $response');
    } catch (e) {
      print('Error: $e');
    }
  }
}
回到顶部