Flutter支付功能插件lofter_pay的使用

Flutter支付功能插件lofter_pay的使用

lofter_pay 是一个用于Flutter应用的支付SDK。本文将详细介绍如何在Flutter项目中集成并使用lofter_pay插件。

开始使用

本项目是一个Flutter插件包的起点,该插件包包含适用于Android和/或iOS的平台特定实现代码。

对于Flutter开发的帮助,请参阅官方文档,其中提供了教程、示例、移动开发指导以及完整的API参考。

完整示例

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

示例代码

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

import 'package:flutter/services.dart';
import 'package:lofter_pay/lofter_pay.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> {
  String _platformVersion = '未知';
  String _errorMessage = "";
  final _lofterPayPlugin = LofterPay();

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

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用try/catch来处理PlatformException。
    // 我们也处理了消息可能返回null的情况。
    try {
      platformVersion = await _lofterPayPlugin.getPlatformVersion() ?? 
          '未知平台版本';
    } on PlatformException {
      platformVersion = '获取平台版本失败。';
    }

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

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  /// 唤起苹果支付
  Future<void> payIAPOrderWithTradeId() async {
    String errorMessage;
    try {
      errorMessage = await _lofterPayPlugin.payIAPOrderWithTradeId(
              tradeId: "37705036", productId: "LOFTER_PVEMAN_3") ??
          '';
    } on PlatformException {
      errorMessage = '支付失败。';
    }

    if (!mounted) return;
    setState(() {
      _errorMessage = errorMessage;
    });
  }

  /// 注册支付
  Future<void> registerPay() async {
    await _lofterPayPlugin.registerPay();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Container(
            height: 200,
            color: Colors.yellow,
            child: Column(children: [
              Text('运行在: $_platformVersion\n'),
              Expanded(
                  child: GestureDetector(
                onTap: () {
                  payIAPOrderWithTradeId();
                },
                child: Container(
                    color: Colors.blue,
                    child: const Center(child: Text('点击唤起支付'))),
              ))
            ]),
          ),
        ),
      ),
    );
  }
}

代码解释

  • 导入必要的库:

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:flutter/services.dart';
    import 'package:lofter_pay/lofter_pay.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> {
      String _platformVersion = '未知';
      String _errorMessage = "";
      final _lofterPayPlugin = LofterPay();
    
      [@override](/user/override)
      void initState() {
        super.initState();
        initPlatformState();
        registerPay();
      }
    
  • 获取平台版本信息:

    Future<void> initPlatformState() async {
      String platformVersion;
      try {
        platformVersion = await _lofterPayPlugin.getPlatformVersion() ?? 
            '未知平台版本';
      } on PlatformException {
        platformVersion = '获取平台版本失败。';
      }
      if (!mounted) return;
      setState(() {
        _platformVersion = platformVersion;
      });
    }
    
  • 发起支付请求:

    Future<void> payIAPOrderWithTradeId() async {
      String errorMessage;
      try {
        errorMessage = await _lofterPayPlugin.payIAPOrderWithTradeId(
                tradeId: "37705036", productId: "LOFTER_PVEMAN_3") ??
            '';
      } on PlatformException {
        errorMessage = '支付失败。';
      }
      if (!mounted) return;
      setState(() {
        _errorMessage = errorMessage;
      });
    }
    
  • 注册支付服务:

    Future<void> registerPay() async {
      await _lofterPayPlugin.registerPay();
    }
    
  • 构建UI:

    [@override](/user/override)
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text('插件示例应用'),
          ),
          body: Center(
            child: Container(
              height: 200,
              color: Colors.yellow,
              child: Column(children: [
                Text('运行在: $_platformVersion\n'),
                Expanded(
                    child: GestureDetector(
                  onTap: () {
                    payIAPOrderWithTradeId();
                  },
                  child: Container(
                      color: Colors.blue,
                      child: const Center(child: Text('点击唤起支付'))),
                ))
              ]),
            ),
          ),
        ),
      );
    }
    

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

1 回复

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


lofter_pay 是一个用于 Flutter 应用的支付插件,支持多种支付方式,如支付宝、微信支付等。以下是如何使用 lofter_pay 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  lofter_pay: ^1.0.0  # 请根据实际情况使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 配置支付平台

根据你要支持的支付平台,进行相应的配置。

支付宝配置

AndroidManifest.xml 中添加以下配置:

<activity
    android:name="com.alipay.sdk.app.H5PayActivity"
    android:configChanges="orientation|keyboardHidden|navigation|screenSize"
    android:exported="false"
    android:screenOrientation="behind" >
</activity>

微信支付配置

AndroidManifest.xml 中添加以下配置:

<activity
    android:name=".wxapi.WXPayEntryActivity"
    android:exported="true"
    android:launchMode="singleTop" />

iOS 项目中,确保在 Info.plist 中添加以下配置:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>weixin</string>
    <string>wechat</string>
</array>

3. 初始化支付插件

在你的 Flutter 应用中初始化 lofter_pay 插件。通常可以在 main.dart 中进行初始化:

import 'package:lofter_pay/lofter_pay.dart';

void main() {
  LofterPay.init(
    aliPayScheme: 'your_alipay_scheme', // 支付宝的scheme
    weChatAppId: 'your_wechat_app_id',  // 微信的AppID
  );
  runApp(MyApp());
}

4. 发起支付

在需要发起支付的地方调用 LofterPay 的支付方法。以下是一个简单的示例:

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

class PaymentPage extends StatelessWidget {
  Future<void> _payWithAlipay() async {
    try {
      final result = await LofterPay.aliPay(
        orderInfo: 'your_order_info', // 支付宝订单信息
      );
      print('支付宝支付结果: $result');
    } catch (e) {
      print('支付宝支付失败: $e');
    }
  }

  Future<void> _payWithWeChat() async {
    try {
      final result = await LofterPay.weChatPay(
        orderInfo: 'your_order_info', // 微信支付订单信息
      );
      print('微信支付结果: $result');
    } catch (e) {
      print('微信支付失败: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('支付'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _payWithAlipay,
              child: Text('支付宝支付'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _payWithWeChat,
              child: Text('微信支付'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部