Flutter网页支付集成插件unipass_web_sdk的使用

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

Flutter网页支付集成插件unipass_web_sdk的使用

Requirements(需求)

  • Dart SDK: >=2.18.1 <3.0.0
  • Flutter: >=2.5.0

Installation(安装)

在你的 pubspec.yaml 文件中添加 unipass_web_sdk 作为依赖。

dependencies:
  unipass_web_sdk: ^x.y.z

Usage(使用)

Interface(接口)
/// 接口声明
enum Environment { testnet, mainnet }

enum ChainType { polygon, bsc, rangers }

enum Protocol { https, http }

enum UnipassTheme { light, dark }

class AppSetting {
  String? appName;
  String? appIcon;
  UnipassTheme theme;
  ChainType chainType;

  AppSetting({this.appName, this.appIcon, required this.theme, required this.chainType});
}

class UniPassOption {
  String? nodeRPC;
  ChainType? chainType;
  Environment? env;
  String? domain;
  String? protocol;
  AppSetting? appSetting;

  UniPassOption({this.nodeRPC, this.chainType, this.env, this.domain, this.protocol, this.appSetting});
}
Full Creation Example(完整创建示例)
UniPassWeb uniPassWeb = UniPassWeb(
  UniPassOption(
    dev: Environment.testnet,
    nodeRPC: "https://node.wallet.unipass.id/polygon-mumbai",
    domain: "testnet.wallet.unipass.id",
    protocol: "https",
    appSetting: AppSetting(
      appName: "demo dapp",
      appIcon: "",
      theme: UnipassTheme.dark,
      chainType: ChainType.polygon,
    ),
  ),
);

完整示例代码

import 'package:example/page.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:unipass_web_sdk/unipass_web_sdk.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return OKToast(
      textStyle: const TextStyle(fontSize: 19.0, color: Colors.white),
      backgroundColor: Colors.grey,
      animationCurve: Curves.easeIn,
      animationDuration: const Duration(milliseconds: 300),
      duration: const Duration(seconds: 3),
      child: MaterialApp(
        builder: (context, child) => Scaffold(
          body: GestureDetector(
            onTap: () {
              FocusScopeNode currentFocus = FocusScope.of(context);
              if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
                FocusManager.instance.primaryFocus?.unfocus();
              }
            },
            child: child,
          ),
        ),
        home: const HomePage(),
      ),
    );
  }
}

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

  [@override](/user/override)
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  UnipassTheme theme = UnipassTheme.light;
  ChainType chainType = ChainType.polygon;
  bool returnEmail = false;

  String domain = "testnet.wallet.unipass.id";

  int count = 0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return ListView(
      children: [
        const SizedBox(height: 40),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text("light"),
            Radio<UnipassTheme>(
              value: UnipassTheme.light,
              groupValue: theme,
              onChanged: (UnipassTheme? value) {
                setState(() {
                  theme = value!;
                });
              },
            ),
            const Text("dark"),
            Radio<UnipassTheme>(
              value: UnipassTheme.dark,
              groupValue: theme,
              onChanged: (UnipassTheme? value) {
                setState(() {
                  theme = value!;
                });
              },
            ),
          ],
        ),
        const SizedBox(height: 40),
        Center(
          child: Wrap(
            alignment: WrapAlignment.center,
            runAlignment: WrapAlignment.center,
            children: ChainType.values.map((item) {
              return Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(item.name),
                  Radio<ChainType>(
                    value: item,
                    groupValue: chainType,
                    onChanged: (ChainType? value) {
                      setState(() {
                        chainType = value!;
                      });
                    },
                  ),
                ],
              );
            }).toList(),
          ),
        ),
        const SizedBox(height: 40),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Checkbox(
              checkColor: Colors.white,
              fillColor: MaterialStateProperty.resolveWith(getColor),
              value: returnEmail,
              onChanged: (bool? value) {
                setState(() {
                  returnEmail = value!;
                });
              },
            ),
            const Text("returnEmail"),
          ],
        ),
        const SizedBox(height: 10),
        GestureDetector(
          child: Text("domain: $domain", textAlign: TextAlign.center),
          onTap: () {
            setState(() {
              count++;
            });
            if (count == 10) {
              setState(() {
                domain = "t.wallet.unipass.vip";
              });
            }
          },
        ),
        const SizedBox(height: 30),
        const Text("Onboarding users through Google and Email", textAlign: TextAlign.center),
        Align(
          alignment: Alignment.center,
          child: OutlinedButton(
            onPressed: () async {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) {
                  return TestPage(
                      theme: theme,
                      chainType: chainType,
                      domain: domain,
                      connectType: ConnectType.google,
                      returnEmail: returnEmail);
                }),
              );
            },
            child: const Text("Connect With Google"),
          ),
        ),
        Align(
          alignment: Alignment.center,
          child: OutlinedButton(
            onPressed: () async {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) {
                  return TestPage(
                      theme: theme,
                      chainType: chainType,
                      domain: domain,
                      connectType: ConnectType.email,
                      returnEmail: returnEmail);
                }),
              );
            },
            child: const Text("Connect With Email"),
          ),
        ),
        const SizedBox(height: 30),
        const Text("Onboarding users through one button", textAlign: TextAlign.center),
        Align(
          alignment: Alignment.center,
          child: OutlinedButton(
            onPressed: () async {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) {
                  return TestPage(theme: theme, chainType: chainType, domain: domain, returnEmail: returnEmail);
                }),
              );
            },
            child: const Text("Connect UniPass"),
          ),
        ),
      ],
    );
  }

  Color getColor(Set<MaterialState> states) {
    return Colors.blue;
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中集成并使用unipass_web_sdk插件进行网页支付的代码示例。这个示例假设你已经有一个Flutter项目,并且已经配置好了基本的开发环境。

1. 添加依赖

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

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

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

2. 配置web支持

确保你的Flutter项目已经配置了web支持。如果还没有,可以通过以下命令添加:

flutter config --enable-web

3. 使用unipass_web_sdk进行支付

以下是一个简单的示例,展示如何在Flutter Web应用中使用unipass_web_sdk进行支付。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Unipass Web SDK Example'),
        ),
        body: Center(
          child: PaymentButton(),
        ),
      ),
    );
  }
}

class PaymentButton extends StatefulWidget {
  @override
  _PaymentButtonState createState() => _PaymentButtonState();
}

class _PaymentButtonState extends State<PaymentButton> {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () async {
        // 替换为你的实际支付配置
        final paymentConfig = UnipassPaymentConfig(
          appId: '你的AppId',
          channelId: '你的ChannelId',
          orderId: '订单号',
          amount: '金额', // 注意金额格式,比如'100.00'
          currency: 'CNY', // 货币类型
          // 其他必要的配置参数...
        );

        try {
          // 调用支付方法
          final result = await UnipassWebSdk.startPayment(paymentConfig);
          if (result.success) {
            // 支付成功处理
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('支付成功')),
            );
          } else {
            // 支付失败处理
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('支付失败: ${result.message}')),
            );
          }
        } catch (e) {
          // 错误处理
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('发生错误: $e')),
          );
        }
      },
      child: Text('发起支付'),
    );
  }
}

4. 运行应用

确保你已经配置好了开发服务器(通常是通过flutter run -d web-server命令),然后在浏览器中打开提供的URL来查看你的Flutter Web应用。点击“发起支付”按钮,应该会触发支付流程。

注意事项

  1. 支付配置:确保你提供的支付配置参数(如appId, channelId, orderId, amount等)是正确的,并且与你的支付平台相匹配。
  2. 错误处理:在实际应用中,你可能需要更详细的错误处理逻辑,以应对各种可能的异常情况。
  3. 安全性:在实际应用中,务必注意支付信息的安全性,避免敏感信息泄露。

以上代码提供了一个基本的框架,你可以根据实际需求进行调整和扩展。

回到顶部