Flutter移动开发集成插件isw_mobile_sdk的使用

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

Flutter移动开发集成插件isw_mobile_sdk的使用

本库用于通过以下渠道处理支付:

  • ✅ 卡片
  • ✅ Verve 钱包
  • ✅ 二维码
  • ✅ USSD

开始使用

要设置SDK并执行交易,您需要完成三个步骤:

  1. 安装SDK作为依赖项
  2. 使用商户信息配置SDK
  3. 使用客户详细信息发起支付

安装

要安装SDK,请在pubspec.yaml文件的依赖项部分添加以下内容:

dependencies:
  #.... 其他依赖项

  # 添加SDK依赖项
  isw_mobile_sdk: '<最新版本>'

配置

您还需要使用您的商户凭证配置项目。

import 'dart:async';
import 'package:isw_mobile_sdk/isw_mobile_sdk.dart';

class _MyAppState extends State<MyApp> {

  [@override](/user/override)
  void initState() {
    super.initState();
    initSdk();
  }

  // 消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initSdk() async {

    // 消息可能会失败,所以我们使用try/catch来捕获PlatformException。
    try {
        String merchantId = "your-merchant-id",
        merchantCode = "your-merchant-code",
        merchantSecret = "your-merchant-secret",
        currencyCode = "currency-code"; // 例如 566 表示 NGN

        var config = new IswSdkConfig (
            merchantId, 
            merchantSecret, 
            merchantCode, 
            currencyCode
        );

        // 初始化SDK
        await IswMobileSdk.initialize(config);
        // 使用环境初始化, 默认是Environment.TEST
        // IswMobileSdk.initialize(config, Environment.SANDBOX);

    } on PlatformException {}
  }
}

一旦SDK已初始化,您可以执行交易。

执行交易

配置SDK后,可以通过提供支付信息和支付回调来执行交易,如下所示:

Future<void> pay(int amount) async {

  var customerId = "<customer-id>",
      customerName = "<customer-name>",
      customerEmail = "<customer.email@domain.com>",
      customerMobile = "<customer-phone>",
      // 为每次交易生成一个唯一的随机引用
      reference = "<your-unique-ref>";

  // 初始化金额
  // 金额表示为最低单位(例如:kobo):"N500.00" -> 50000
  int amountInKobo = amount * 100;

  // 创建支付信息
  var iswPaymentInfo = new IswPaymentInfo(
      customerId, 
      customerName,
      customerEmail, 
      customerMobile, 
      reference, 
      amountInKobo
  );

  // 触发支付
  var result = await IswMobileSdk.pay(iswPaymentInfo);

  // 处理结果
  handleResult(result);
}

处理结果

要处理结果,您需要在回调方法中处理结果。当用户取消时,value将为nullhasValue将为false。当交易完成时,hasValue将为truevalue将有一个IswPaymentResult实例:一个具有以下字段的对象。

字段 类型 含义
responseCode String 交易响应代码
responseDescription String 交易响应代码描述
isSuccessful boolean 标志指示交易是否成功
transactionReference String 交易参考
amount Number 交易金额
channel String 付款所用的通道: CARD, WALLET, QR, USSD 中的一个
void handleResult(Optional<IswPaymentResult> result) {

    if (result.hasValue) {
        // 处理结果
        showPaymentSuccess(result.value);
    } else { 
        showPaymentError()
    }
    
}

就这样,您可以在Flutter应用中开始处理支付了。

注意事项

Android平台可能会出现构建异常,显示dexing问题,您需要启用多DEX才能成功构建。您可以查看Android项目的Application类作为参考。

示例代码

以下是完整的示例代码:

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

import 'package:flutter/services.dart';
import 'package:isw_mobile_sdk/isw_mobile_sdk.dart';
import 'package:isw_mobile_sdk/models/isw_mobile_sdk_payment_info.dart';
import 'package:isw_mobile_sdk/models/isw_mobile_sdk_sdk_config.dart';

import 'certificate.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _amountString = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    // 平台消息可能会失败,所以我们使用try/catch来捕获PlatformException。
    // 我们还处理消息可能返回null的情况。
    try {
      var credential = Config.devConfig;
      var config = IswSdkConfig(
        credential.merchantId, 
        credential.merchantSecret, 
        credential.merchantCode, 
        credential.currencyCode
      );

      // 初始化SDK
      await IswMobileSdk.initialize(config, Environment.TEST);
      // 使用环境初始化, 默认是Environment.TEST
      // IswMobileSdk.initialize(config, Environment.SANDBOX);
    } on PlatformException {
    }

    // 如果小部件从树中被移除,而异步平台消息还在飞行中,我们想丢弃回复而不是调用setState来更新我们的非存在的外观。
    if (!mounted) return;

    // setState(() {});
  }

  Future<void> pay(BuildContext context) async {
    // 保存表单
    _formKey.currentState?.save();
    
    String customerId = "<customer-id>",
        customerName = "<customer-name>",
        customerEmail = "<customer.email@domain.com>",
        customerMobile = "<customer-phone>",
        // 为每次交易生成一个唯一的随机引用
        reference = "<your-unique-ref>";

    int amount;
    // 初始化金额
    if (_amountString.isEmpty) {
      amount = 2500 * 100;
    } else {
      amount = int.parse(_amountString) * 100;
    }

    // 创建支付信息
    IswPaymentInfo iswPaymentInfo = IswPaymentInfo(
      customerId, 
      customerName,
      customerEmail, 
      customerMobile, 
      reference, 
      amount
    );

    print(iswPaymentInfo);

    // 触发支付
    var result = await IswMobileSdk.pay(iswPaymentInfo);

    var message;
    if (result.hasValue) {
      final paymentChannel = result.value?.channel.toString() ?? "Unknown";
      message = "You completed txn using: $paymentChannel";
    } else {
      message = "You cancelled the transaction pls try again";
    }
    
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(message),
      duration: const Duration(seconds: 3),
    ));
  }

  [@override](/user/override)
  Widget build(BuildContext context)  {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Charity Fortune'),
          backgroundColor: Colors.black,
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Form(
              key: _formKey,
              child: Column(
                children: <Widget>[
                  TextFormField(
                    decoration: const InputDecoration(labelText: 'Amount'),
                    keyboardType: TextInputType.number,
                    onSaved: (String? val) => _amountString = val ?? "0",
                  ),
                  Builder(
                    builder: (ctx) => Container(
                      width: MediaQuery.of(ctx).size.width,
                      child: ElevatedButton(
                        onPressed: () => pay(ctx),
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 40.0, 
                            vertical: 20.0
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.0)
                          ),
                          backgroundColor: Colors.black
                        ),
                        child: const Text(
                          "Pay",
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


在Flutter中集成并使用第三方插件,如isw_mobile_sdk,通常涉及几个关键步骤:添加依赖、配置项目、初始化插件以及调用插件提供的功能。以下是一个示例,展示如何在Flutter项目中集成并使用isw_mobile_sdk(假设该插件已经发布在pub.dev上,如果未发布,则可能需要手动添加本地依赖)。

1. 添加依赖

首先,在pubspec.yaml文件中添加isw_mobile_sdk的依赖:

dependencies:
  flutter:
    sdk: flutter
  isw_mobile_sdk: ^x.y.z  # 替换为实际的版本号

运行flutter pub get来安装依赖。

2. 配置项目(如果需要)

某些插件可能需要在ios/Podfileandroid/build.gradle文件中进行额外的配置。由于isw_mobile_sdk的具体配置要求未知,这里假设没有额外的配置步骤(如果有,请参考插件的官方文档)。

3. 初始化插件并调用功能

在Flutter项目中,通常会在main.dart或相应的页面文件中初始化并使用插件。以下是一个示例代码,展示如何初始化isw_mobile_sdk并调用其假设的功能:

import 'package:flutter/material.dart';
import 'package:isw_mobile_sdk/isw_mobile_sdk.dart'; // 假设插件的导入路径

void main() {
  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 StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  IswMobileSdk? _sdk;

  @override
  void initState() {
    super.initState();
    // 初始化插件
    _initSdk();
  }

  Future<void> _initSdk() async {
    // 假设插件有一个名为initialize的初始化方法
    _sdk = IswMobileSdk();
    try {
      await _sdk!.initialize(apiKey: 'your_api_key'); // 替换为你的API密钥
      print('SDK initialized successfully');
    } catch (e) {
      print('Failed to initialize SDK: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Press button to use SDK feature',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _useSdkFeature,
              child: Text('Use SDK Feature'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _useSdkFeature() async {
    if (_sdk != null) {
      try {
        // 假设插件有一个名为performAction的方法
        var result = await _sdk!.performAction(parameters: {'key': 'value'});
        print('SDK feature result: $result');
      } catch (e) {
        print('Failed to use SDK feature: $e');
      }
    } else {
      print('SDK not initialized');
    }
  }
}

注意事项

  1. API密钥:在实际项目中,不要将API密钥硬编码在代码中。考虑使用环境变量或安全的密钥管理服务。
  2. 错误处理:示例代码中包含了基本的错误处理,但在生产环境中,你可能需要更详细的错误日志和恢复策略。
  3. 插件文档:务必参考isw_mobile_sdk的官方文档,因为插件的具体初始化方法和功能调用可能会有所不同。

由于isw_mobile_sdk是一个假设的插件名称,实际使用时请替换为真实的插件名称和方法调用。如果插件未发布在pub.dev上,可能需要手动将插件代码添加到你的Flutter项目中,并按照插件提供的文档进行配置和使用。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!