Flutter一键支付插件deposits_oneclick_checkout的使用

Flutter一键支付插件deposits_oneclick_checkout的使用

Deposits One Click Checkout SDK

pub package

Deposits One-Click Checkout SDK允许商家快速注册、上架并完成客户的支付。我们提供强大的且可自定义的UI屏幕,可以开箱即用以收集用户的付款,无论用户是否拥有存款账户。

deposits-one-click-checkout-flutter_cover

特性

简化安全

我们使您能够轻松收集敏感数据,如信用卡号、ACH详情,并保持PCI合规性。这意味着敏感数据直接发送到Deposits,而不是通过您的服务器。

支付方式

接受卡和ACH支付有助于您的业务扩展全球范围并提高结账转化率。

原生UI

我们提供原生屏幕和元素,以在Android和iOS上安全地收集付款详细信息。

安装

pubspec.yaml文件中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  deposits_oneclick_checkout: <最新版本>

然后在终端中执行以下命令来安装插件:

flutter pub add deposits_oneclick_checkout

要求

Android

此插件需要对Android设备进行一些更改才能正常工作。请确保遵循所有这些步骤:

  1. 使用Android 5.0(API级别21)及以上版本。
  2. 重建应用,因为上述更改不会随着热重载更新。

iOS

兼容目标iOS 10及以上的应用。

Web

目前不支持通过此插件实现Web端功能。您可以使用我们的JS SDK。您可以在这里查看如何使用JS SDK的示例。

使用

库提供了用于接受卡支付的UI组件。

示例

main.dart

import 'package:deposits_oneclick_checkout/app/modules/deposits_oneclick_checkout_button.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(PaymentScreen());
}

payment_screen.dart

class PaymentScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('填写表单:'),
          Container(
            child: TextFormField(
              readOnly: isEmailExist,
              controller: userEmailController,
              validator: (val) {
                if (val == null || val.trim().isEmpty) {
                  return '请输入您的电子邮件地址';
                }
                if (!RegExp(r'\S+@\S+\.\S+').hasMatch(val)) {
                  return '请输入有效的电子邮件地址';
                }
                return null;
              },
              keyboardType: TextInputType.emailAddress,
              textInputAction: TextInputAction.next,
              decoration: const InputDecoration(
                hintText: "输入邮箱",
                border: OutlineInputBorder(),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Color(0xFFC0C4C9)),
                ),
                disabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Color(0xFFC0C4C9)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Color(0xFFC0C4C9)),
                ),
              ),
            ),
            margin: const EdgeInsets.only(top: 30.0),
          ),
          Container(
            child: TextFormField(
              validator: (val) => val!.isEmpty ? '金额是必需的!' : null,
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                CurrencyTextInputFormatter(
                  decimalDigits: 2,
                  symbol: '\$ ',
                )
              ],
              textInputAction: TextInputAction.done,
              controller: amountController,
              decoration: const InputDecoration(
                hintText: "输入金额",
                border: OutlineInputBorder(),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Color(0xFFC0C4C9)),
                ),
                disabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Color(0xFFC0C4C9)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Color(0xFFC0C4C9)),
                ),
              ),
            ),
            margin: const EdgeInsets.only(top: 10.0),
          ),
          Container(
            child: FlatButton(
              minWidth: MediaQuery.of(context).size.width,
              height: 56,
              color: Colors.blue, //Color(0xFF0DB9E9),
              child: const Text(
                '结账',
                style: TextStyle(color: Colors.white, fontSize: 16)
              ),
              onPressed: () async {
                if (formKey.currentState!.validate()) {
                  depositsCheckout(
                    context,
                    ButtonConfig(
                      buttonColor: '0xFF0DB9E9',
                      textColor: Colors.white,
                      amount: double.parse(amountController.text.toString()
                        .replaceAll('\$', '')
                        .toString()),
                    ),
                    initialScreen: MyHomePage(
                      title: 'One Click-Checkout Demo',
                    ),
                    userEmail: userEmailController.text.toString(),
                    subClientApiKey: 'money-by-deposits-user',
                    envMode: true,
                    chargeFundsResponse: (response) {
                      // 处理交易完成后的过程
                    },
                  );
                }
              },
            ),
            margin: const EdgeInsets.only(top: 30.0)
          )
        ]
      )
    );
  }
}

Deposit One Click Checkout SDK初始化

要在Flutter应用中初始化Deposit One Click Checkout SDK,请使用pay基类。

pay提供contextbuttonConfiginitialScreenenvModechargeFundsResponseuserEmailsubClientApiKey。只有userEmailsubClientApiKeyenvModechargeFundsResponsebuttonConfig(包含以下参数:amount必需、buttonColor必需十六进制字符串、textStyleheightminwidth等作为可自定义的小部件)是必需的。envMode是一个布尔值,可以是true或false,chargeFundsResponse是一个回调函数,在支付完成后管理或运行其他进程,您可以检查它是否成功。您必须根据envMode的变化更改您的subClientApiKey,并且可以从测试或实时控制台获取密钥,控制台的URL在下一节中列出。

Dart API

deposits

库提供了几个方法来处理与存款结账相关的操作:

void depositsCheckout();

class ButtonConfig()

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

1 回复

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


deposits_oneclick_checkout 是一个用于 Flutter 的一键支付插件,它可以帮助开发者快速集成支付功能到应用中。以下是如何使用该插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  deposits_oneclick_checkout: ^1.0.0  # 请使用最新版本

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

2. 初始化插件

在你的 Dart 代码中,首先需要初始化插件。通常,你可以在 main.dart 或支付相关的文件中进行初始化。

import 'package:deposits_oneclick_checkout/deposits_oneclick_checkout.dart';

void main() {
  runApp(MyApp());
  
  // 初始化插件
  DepositsOneClickCheckout.initialize(
    apiKey: "YOUR_API_KEY",  // 替换为你的 API 密钥
    environment: Environment.sandbox,  // 使用沙箱环境进行测试
  );
}

3. 配置支付参数

在调用支付功能之前,你需要配置支付参数。通常,这些参数包括订单金额、货币类型、商品描述等。

PaymentParams paymentParams = PaymentParams(
  amount: 100.0,  // 订单金额
  currency: "USD",  // 货币类型
  description: "Test Payment",  // 商品描述
  orderId: "ORDER12345",  // 订单 ID
  customerEmail: "customer@example.com",  // 客户邮箱
);

4. 发起支付请求

使用配置好的支付参数,你可以发起支付请求。支付结果将通过回调函数返回。

void initiatePayment() async {
  try {
    PaymentResponse response = await DepositsOneClickCheckout.startPayment(paymentParams);
    
    if (response.status == PaymentStatus.success) {
      // 支付成功
      print("Payment successful: ${response.transactionId}");
    } else {
      // 支付失败
      print("Payment failed: ${response.errorMessage}");
    }
  } catch (e) {
    // 处理异常
    print("Error occurred: $e");
  }
}

5. 处理支付结果

支付结果可以通过 PaymentResponse 对象获取。你可以根据支付状态(PaymentStatus)来处理成功或失败的支付。

enum PaymentStatus { success, failed }

class PaymentResponse {
  final PaymentStatus status;
  final String? transactionId;
  final String? errorMessage;

  PaymentResponse({
    required this.status,
    this.transactionId,
    this.errorMessage,
  });
}

6. 处理回调

在某些情况下,你可能需要处理支付完成后的回调。例如,你可以使用 Navigator 来跳转到支付成功或失败的页面。

void handlePaymentResponse(PaymentResponse response) {
  if (response.status == PaymentStatus.success) {
    Navigator.push(context, MaterialPageRoute(builder: (context) => PaymentSuccessPage()));
  } else {
    Navigator.push(context, MaterialPageRoute(builder: (context) => PaymentFailedPage()));
  }
}

7. 测试支付功能

在开发过程中,建议使用沙箱环境进行测试。确保在发布应用之前切换到生产环境。

DepositsOneClickCheckout.initialize(
  apiKey: "YOUR_API_KEY",
  environment: Environment.production,  // 切换到生产环境
);

8. 处理错误和异常

在实际使用中,可能会遇到各种错误和异常。确保在代码中正确处理这些情况,以提供更好的用户体验。

try {
  PaymentResponse response = await DepositsOneClickCheckout.startPayment(paymentParams);
  handlePaymentResponse(response);
} catch (e) {
  print("Error occurred: $e");
  // 显示错误提示给用户
}
回到顶部