Flutter支付功能插件flutter_openmoney的使用

Flutter支付功能插件flutter_openmoney的使用

Flutter插件用于OpenMoney SDK。

开始使用

该Flutter插件是围绕OpenMoney Android SDK的封装。

以下文档仅关注围绕原生Android SDK的封装。要了解有关这些SDK及其在项目中的集成方式的更多信息,请参阅以下文档:

Android: https://github.com/eshantmittal/open-payment-android-aar

要发起支付,paymentTokenaccessKey 是必需的变量。 paymentToken - 在服务器端生成。了解更多 accessKey - 从openmoney仪表板获取

安装

该插件可在Pub上找到: https://pub.dev/packages/flutter_openmoney

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

dependencies:
  flutter_openmoney: ^0.0.1

注意对于Android: 确保你的应用的最低API级别为19或更高。

使用

可以在以下位置找到集成示例代码: https://github.com/thoshpathi/flutter_openmoney/blob/main/example/lib/main.dart

导入包

import 'package:flutter_openmoney/flutter_openmoney.dart';

创建FlutterOpenmoney实例

_flutterOpenmoney = FlutterOpenmoney();

添加事件监听器

该插件使用基于事件的通信,并在支付成功或失败时发出事件。

事件名称通过eventPaymentSuccesseventPaymentError常量从FlutterOpenmoney类中暴露出来。

使用FlutterOpenmoney实例上的on(String event, Function handler)方法来附加事件监听器。

_flutterOpenmoney.on(FlutterOpenmoney.eventPaymentSuccess, _handlePaymentSuccess);
_flutterOpenmoney.on(FlutterOpenmoney.eventPaymentError, _handlePaymentError);

处理程序将在其他地方定义为:

void _handlePaymentSuccess(PaymentSuccessResponse response) {
  // 当支付成功时执行某些操作
}

void _handlePaymentError(PaymentFailureResponse response) {
  // 当支付失败时执行某些操作
}

要清除事件监听器,使用FlutterOpenmoney实例上的clear方法。

_flutterOpenmoney.clear(); // 移除所有监听器

设置选项

var options = PaymentOptions('<ACCESS_KEY_HERE>', '<PAYMENT_TOKEN_HERE>', PaymentMode.sandbox);

结账

_flutterOpenmoney.initPayment(options.toMap());

API

initPayment(Map<String, String> options)

optionsPaymentOptions类的一个实例。 options必须包含paymentTokenaccessKey作为必需属性。 使用options.toMap()方法将options转换为Map对象。

on(String eventName, Function listener)

注册支付事件的事件监听器。

  • eventName: 事件的名称。
  • listener: 要调用的函数。监听器应该接受一个单一参数,类型如下:
    • 对于eventPaymentSuccess,类型为PaymentSuccessResponse
    • 对于eventPaymentError,类型为PaymentFailureResponse

clear()

清除所有事件监听器。

错误码

错误码由FlutterOpenmoney类以整数形式暴露。

错误码作为PaymentFailureResponse实例传递给回调的code字段可用。

错误码 描述
invalidOptions FlutterOpenmoney.initPayment中传入的选项存在问题
paymentCancelled 用户取消了支付
paymentFailed 支付过程失败
unknownError 发生未知错误

事件名称

事件名称也由Razorpay类以字符串形式暴露。

事件名称 描述
eventPaymentSuccess 支付成功
eventPaymentError 支付未成功

PaymentSuccessResponse

字段名 类型 描述
paymentId String 支付ID
paymentTokenId String 支付令牌ID

要确认支付详情,请参阅此链接 https://docs.bankopen.com/reference/status-check-api-with-token-id

PaymentFailureResponse

字段名 类型 描述
code int 错误码
message String 错误消息

示例代码

import 'package:flutter/material.dart';
import 'package:flutter_openmoney/flutter_openmoney.dart';
import 'package:fluttertoast/fluttertoast.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  late final FlutterOpenmoney flutterOpenmoney;

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

    flutterOpenmoney = FlutterOpenmoney();
    flutterOpenmoney.on(
      FlutterOpenmoney.eventPaymentSuccess,
      _handlePaymentSuccess,
    );
    flutterOpenmoney.on(
      FlutterOpenmoney.eventPaymentError,
      _handlePaymentError,
    );
  }

  void _initPayment() async {
    /// 从openmoney仪表板获取
    const accessKey = 'xxxxxxxx-xxxx-xxxx-xxxx-cfd6fc92bd19';

    /// 使用openmoney创建令牌API在服务器端生成
    /// 参阅https://docs.bankopen.com/reference/generate-token
    const paymentToken = 'sb_pt_BUFJpEalhWmO6cm';
    final options = PaymentOptions(accessKey, paymentToken);

    try {
      flutterOpenmoney.initPayment(options);
    } catch (e) {
      debugPrint('Error: $e');
    }
  }

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    Fluttertoast.showToast(
      msg: 'SUCCESS: ${response.paymentId}',
      toastLength: Toast.LENGTH_LONG,
    );
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(
      msg: 'ERROR: ${response.code} - ${response.message}',
      toastLength: Toast.LENGTH_LONG,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('FlutterOpenmoney插件示例应用'),
        ),
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: _initPayment,
                child: const Text('initPayment'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


flutter_openmoney 是一个用于在 Flutter 应用中集成支付功能的插件。它通常用于接入 OpenMoney 支付平台。以下是如何在 Flutter 项目中使用 flutter_openmoney 插件的步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_openmoney: ^版本号

请将 ^版本号 替换为最新的插件版本号。你可以在 pub.dev 上查找最新版本。

2. 导入插件

在你的 Dart 文件中导入 flutter_openmoney 插件。

import 'package:flutter_openmoney/flutter_openmoney.dart';

3. 初始化插件

在应用的适当位置(例如 main.dart 或某个具体的支付页面)初始化 flutter_openmoney 插件。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Openmoney.initialize(
    apiKey: "your_api_key", // 你的 OpenMoney API Key
    sandbox: true, // 是否使用沙盒环境,发布时设置为 false
  );
  runApp(MyApp());
}

4. 发起支付

使用 Openmoney 提供的接口发起支付请求。

void initiatePayment() async {
  try {
    final response = await Openmoney.createPayment(
      amount: 1000, // 支付金额,单位为分
      currency: "USD", // 货币类型
      orderId: "order_123", // 订单ID
      description: "Test Payment", // 支付描述
    );

    if (response.status == "success") {
      // 支付成功
      print("Payment successful: ${response.transactionId}");
    } else {
      // 支付失败
      print("Payment failed: ${response.message}");
    }
  } catch (e) {
    // 捕获异常
    print("Error: $e");
  }
}

5. 处理支付结果

根据支付结果更新 UI 或执行其他操作。

FlatButton(
  onPressed: initiatePayment,
  child: Text("Pay with OpenMoney"),
)

6. 监听支付状态(可选)

你可以使用 Openmoney 提供的监听器来监听支付状态的变化。

Openmoney.setPaymentStatusListener((status) {
  if (status == "success") {
    // 支付成功
  } else if (status == "failed") {
    // 支付失败
  } else if (status == "canceled") {
    // 支付取消
  }
});

7. 处理退款(可选)

如果需要处理退款,可以使用 Openmoney 提供的退款接口。

void refundPayment(String transactionId) async {
  try {
    final response = await Openmoney.refundPayment(
      transactionId: transactionId,
      amount: 1000, // 退款金额,单位为分
    );

    if (response.status == "success") {
      // 退款成功
      print("Refund successful: ${response.refundId}");
    } else {
      // 退款失败
      print("Refund failed: ${response.message}");
    }
  } catch (e) {
    // 捕获异常
    print("Error: $e");
  }
}

8. 发布应用

确保在生产环境中将 sandbox 参数设置为 false,以便使用真实的支付环境。

Openmoney.initialize(
  apiKey: "your_api_key",
  sandbox: false, // 生产环境
);
回到顶部