Flutter支付集成插件fastpay_merchant的使用

Flutter支付集成插件fastpay_merchant的使用

Android iOS
支持平台

快速入门

要使用FastPay Flutter SDK,你需要先从FastPay获取商店ID和密码。这可以通过联系FastPay的官方支持渠道完成。


安装

pubspec.yaml文件中添加以下依赖:

dependencies:
  fastpay_merchant: ^1.2.0
  # 处理来自FastPay钱包应用的回调(重定向)
  app_links: ^4.0.0  

注意:

  • iOS 仅支持真实设备测试,模拟器不支持。

初始化FastPaySDK

参数说明

  • Store ID:商户的商店ID以发起交易。
  • Store Password:商户的商店密码以发起交易。
  • Order ID:订单ID/账单编号,每次交易必须唯一。
  • Amount:交易金额,例如:“1000”。
  • IOS callback URI:当用户通过FastPay应用付款时,用于接收支付信息的iOS回调URI。
  • Callback:SDK状态、消息、结果回调。SDK状态包括初始化、支付通过FastPay SDK、支付通过FastPay应用、取消、成功、失败等。
enum SDKStatus{    
  INIT,
  PAYMENT_WITH_FASTPAY_SDK,
  PAYMENT_WITH_FASTPAY_APP, 
  CANCEL, 
  SUCCESS, 
  FAILED
}

示例代码

以下是完整的示例代码,演示了如何在Flutter应用中集成FastPay支付插件。

示例代码:example/lib/main.dart

import 'dart:async';
import 'dart:io';

import 'package:app_links/app_links.dart';
import 'package:fastpay_merchant/fastpay_flutter_sdk.dart';
import 'package:fastpay_merchant/models/fastpay_payment_request.dart';
import 'package:flutter/material.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  AppLinks _appLinks = AppLinks();
  Uri? _deepLink;

  @override
  void initState() {
    super.initState();
    _initDeepLinks();
  }

  void _initDeepLinks() async {
    final appLinksStream = _appLinks.uriLinkStream;

    appLinksStream.listen((Uri? deepLink) {
      if (!mounted) return;
      setState(() {
        _deepLink = deepLink;
        _handleDeepLink(deepLink);
      });
    }).onError((err) {
      // 处理错误
    });

    // 检查应用启动时的初始深度链接
    _deepLink = await _appLinks.getInitialAppLink();
    if (_deepLink != null) {
      _handleDeepLink(_deepLink);
    }
  }

  void _handleDeepLink(Uri? deepLink) {
    if (deepLink != null) {
      if (deepLink.path == '/details') {
        Navigator.pushNamed(context, '/details', arguments: deepLink.queryParameters);
      }
      // 处理其他深度链接路径
    }
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: '插件示例应用',
      home: LauncherScreen(),
    );
  }
}

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

  @override
  State<LauncherScreen> createState() => _LauncherScreenState();
}

class _LauncherScreenState extends State<LauncherScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fastpay SDK 测试'),
      ),
      body: Center(
        child: InkWell(
            onTap: ()async{
              Navigator.of(context).push(MaterialPageRoute(builder: (_) => const MyAppHomePage()));
            },
            child: Text('点击这里开始支付')
        ),
      ),
    );
  }
}

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

  @override
  State<MyAppHomePage> createState() => _MyAppHomePageState();
}

class _MyAppHomePageState extends State<MyAppHomePage> with WidgetsBindingObserver {
  StreamSubscription<Uri>? _linkSubscription;

  @override
  void initState() {
    super.initState();
    _handleIncomingIntent();
    FastpayFlutterSdk.instance.fastpayPaymentRequest = FastpayPaymentRequest(
      "******",       // (必需) 替换为您的实际商店ID
      "******",       // (必需) 替换为您的实际商店密码
      "450",          // 金额
      DateTime.now().microsecondsSinceEpoch.toString(), // 订单ID
      "appfpclientFastpayFlutterSdk", // iOS 回调URI
      false,          // 是否生产环境
      (status, message, {result}) {
        debugPrint('打印堆栈跟踪::消息:${message}');
        debugPrint('打印堆栈跟踪:${result.toString()}');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    FastpayFlutterSdk.instance.context = context;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fastpay SDK 测试'),
      ),
      body: Center(
        child: InkWell(
            onTap: ()async{
              Navigator.of(context).push(MaterialPageRoute(builder: (_) => const SdkInitializeScreen()));
            },
            child: Text('点击这里进行支付')
        ),
      ),
    );
  }

  Future<void> _handleIncomingIntent() async {
    final _appLinks = AppLinks();
    if(Platform.isAndroid){
      final uri = await _appLinks.getLatestAppLink();
      debugPrint("重定向URI:${uri?.queryParameters}");
      final allQueryParams = uri?.queryParameters;
      final status = allQueryParams?['status'];
      final orderId = allQueryParams?['order_id'];
      debugPrint("状态:$status, 订单ID:$orderId");
    }else if(Platform.isIOS){
      final appLink = await _appLinks.getInitialAppLink();
      if (appLink != null) {
        var uri = Uri.parse(appLink.toString());
        debugPrint('您可以根据需要从URL重定向');
      }
      _linkSubscription = _appLinks.uriLinkStream.listen((uriValue) {
        debugPrint('重定向URI:$uriValue');
        debugPrint('您可以监听任何URL更新');
        debugPrint('您可以根据需要从URL重定向');
      },onError: (err){
        debugPrint('错误:$err');
      },onDone: () {
        _linkSubscription?.cancel();
      },);
    }
  }
}

SDK回调URI(仅限iOS)

警告

这将重新启动整个应用程序,并从导航队列顶部的页面传递applinks数据。这意味着,从FastPay应用支付后,它会重定向回您的应用并附带数据。

// 使用app_links
import 'package:app_links/app_links.dart';

Future<void> _handleIncomingIntent() async {
  final _appLinks = AppLinks();
  final appLink = await _appLinks.getInitialAppLink();
  if (appLink != null) {
    var uri = Uri.parse(appLink.toString());
    debugPrint('您可以根据需要从URL重定向');
  }
  _linkSubscription = _appLinks.uriLinkStream.listen((uriValue) {
    debugPrint('重定向URI:$uriValue');
    debugPrint('您可以监听任何URL更新');
    debugPrint('您可以根据需要从URL重定向');
  },onError: (err){
    debugPrint('错误:$err');
  },onDone: () {
    _linkSubscription?.cancel();
  },);
}

iOS 设置

info.plist文件中添加回调URI:

  <key>CFBundleURLTypes</key>
  <array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
  <string>appfpclientFastpayFlutterSdk</string> // 您从SDK初始化请求中给定的URI
  </array>
  </dict>
  </array>

回调URI通过应用深层链接结果

回调URI模式(成功):appfpclientFastpayFlutterSdk/further/paths?status=success&transaction_id=XXXX&order_id=XXXX&amount=XXX&currency=XXX&mobile_number=XXXXXX&time=XXXX&name=XXXX
回调URI模式(失败):appfpclientFastpayFlutterSdk/further/paths?status=failed&order_id=XXXXX

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中集成和使用fastpay_merchant插件的示例代码案例。这个插件假设是用于集成FastPay支付网关的。请注意,由于我无法访问实际的插件文档和最新代码,以下示例是基于一般Flutter插件集成流程编写的,并假设fastpay_merchant插件具有类似的功能接口。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  fastpay_merchant: ^最新版本号  # 请替换为实际可用的最新版本号

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

2. 配置Android和iOS

根据fastpay_merchant插件的文档,你可能需要在AndroidManifest.xmlInfo.plist中添加一些配置。由于具体配置可能随插件版本而变化,这里仅提供一般性的指导:

  • Android: 确保在AndroidManifest.xml中配置了必要的权限和网络设置。
  • iOS: 在Info.plist中添加任何必要的权限或配置。

3. 初始化插件并进行支付

在你的Flutter应用中,你需要初始化fastpay_merchant插件并调用支付功能。以下是一个基本的示例代码:

import 'package:flutter/material.dart';
import 'package:fastpay_merchant/fastpay_merchant.dart'; // 假设插件导入路径正确

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FastPay Payment Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: _initiatePayment,
            child: Text('Pay Now'),
          ),
        ),
      ),
    );
  }

  Future<void> _initiatePayment() async {
    // 初始化插件(假设插件提供了init方法)
    // await FastPayMerchant.init(yourMerchantId, yourSecretKey); // 根据实际API调整

    // 创建支付请求参数
    final Map<String, String> paymentParams = {
      'amount': '100.00', // 支付金额
      'currency': 'USD',  // 货币类型
      'orderId': 'uniqueOrderId123', // 订单ID
      // 其他必要的支付参数...
    };

    try {
      // 发起支付请求
      final result = await FastPayMerchant.startPayment(paymentParams);
      
      if (result['status'] == 'success') {
        // 支付成功处理
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Payment Success'),
            content: Text('Payment was successful!'),
            actions: <Widget>[
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('OK'),
              ),
            ],
          ),
        );
      } else {
        // 支付失败处理
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Payment Failed'),
            content: Text('Payment failed with error: ${result['error']}'),
            actions: <Widget>[
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('OK'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      // 错误处理
      print('Error initiating payment: $e');
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('Error'),
          content: Text('An error occurred while initiating payment.'),
          actions: <Widget>[
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('OK'),
            ),
          ],
        ),
      );
    }
  }
}

注意事项

  1. 实际参数和API: 上述代码中的paymentParamsFastPayMerchant.startPayment方法调用是基于假设的。你需要根据fastpay_merchant插件的实际文档调整这些参数和方法调用。

  2. 错误处理: 在生产环境中,你应该有更详细的错误处理和用户反馈机制。

  3. 安全性: 确保你的支付密钥和其他敏感信息不会硬编码在客户端代码中,并且遵循最佳安全实践。

  4. 插件版本: 由于插件和API可能会更新,请务必参考最新的fastpay_merchant插件文档和示例代码。

希望这个示例能帮助你开始集成fastpay_merchant插件!

回到顶部