Flutter苹果支付集成插件sc_applepay的使用

Flutter苹果支付集成插件sc_applepay的使用

sc_applepay 插件用于在您的 Flutter 应用中集成 SkipCash Apple Pay。

开始使用

  1. pubspec.yaml 文件中添加 sc_applepay 依赖:
dependencies:
  sc_applepay: ^0.1.1
  1. 导入必要的包并初始化 ScApplepay 对象:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:sc_applepay/payment_response_class.dart';
import 'package:sc_applepay/sc_applepay.dart';

// 初始化 ScApplepay 对象
final _newPayment = ScApplepay(
  merchantIdentifier: "", // 商户标识符,需要从 Apple 开发者账户生成
  createPaymentLinkEndPoint: "" // 支付链接端点,用于创建支付链接
);

// 设置授权头,用于保护您的端点免受未经授权的访问
_newPayment.setAuthorizationHeader();

// 监听 Apple Pay 响应流
StreamSubscription<dynamic>? _applePayResponseSubscription;
StreamSubscription<dynamic>? paymentFinishedWebViewClosedSubscription;

void _setupApplePayResponseListener() {
  _applePayResponseSubscription = _newPayment.applePayResponseStream.listen((response) {
    PaymentResponse paymentResponse = PaymentResponse.fromJson(response);
    // 处理支付响应
    debugPrint("支付成功:${paymentResponse.isSuccess}");
    debugPrint("支付ID:${paymentResponse.paymentId}");
    debugPrint("错误信息:${paymentResponse.errorMessage}");
    debugPrint("返回码:${paymentResponse.returnCode}");
  });
}

// 监听 WebView 关闭事件
void paymentFinishedWebViewClosedListener() {
  paymentFinishedWebViewClosedSubscription = _newPayment.webViewClosedTrigger.listen((response) {
    // 获取支付详情(即成功或失败)
    debugPrint(response);
  });
}

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

[@override](/user/override)
void dispose() {
  _applePayResponseSubscription?.cancel();
  paymentFinishedWebViewClosedSubscription?.cancel();
  super.dispose();
}

// 启动支付流程
void _startPayment() async {
  bool hasCards;
  try {
    hasCards = await _newPayment.isWalletHasCards() ?? false;
    if (hasCards) {
      // 设置支付详细信息
      _newPayment.setFirstName(_firstNameController.text); // 必填
      _newPayment.setLastName(_lastNameController.text); // 必填
      _newPayment.setEmail(_emailController.text); // 必填
      _newPayment.setPhone(_phoneController.text); // 必填
      _newPayment.setAmount(_amountController.text); // 必填
      // 添加支付摘要项
      _newPayment.addPaymentSummaryItem("Tax", "0.0");
      _newPayment.addPaymentSummaryItem("Total", _amountController.text);
      // 启动支付过程
      _newPayment.startPayment();
    } else {
      // 如果没有找到卡,则提示用户设置新卡
      _newPayment.setupNewCard();
    }
  } on PlatformException {
    hasCards = false;
  }
}

完整示例

以下是一个完整的示例,展示了如何在 Flutter 应用中使用 sc_applepay 插件:

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

import 'package:flutter/services.dart';
import 'package:sc_applepay/payment_response_class.dart';
import 'package:sc_applepay/sc_applepay.dart';

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

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

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

class _MyAppState extends State<MyApp> {
  final _newPayment = ScApplepay(
    merchantIdentifier: "", // 商户标识符
    createPaymentLinkEndPoint: ""
  );

  StreamSubscription<dynamic>? _applePayResponseSubscription;
  StreamSubscription<dynamic>? paymentFinishedWebViewClosedSubscription;

  final TextEditingController _firstNameController = TextEditingController();
  final TextEditingController _lastNameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _amountController = TextEditingController();

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

  [@override](/user/override)
  void dispose() {
    _applePayResponseSubscription?.cancel();
    paymentFinishedWebViewClosedSubscription?.cancel();
    super.dispose();
  }

  void paymentFinishedWebViewClosedListener() {
    paymentFinishedWebViewClosedSubscription = _newPayment.webViewClosedTrigger.listen((response) {
      // 获取支付详情(即成功或失败)当原生 WebView 关闭时
      debugPrint(response);
    });
  }

  void _setupApplePayResponseListener() {
    _applePayResponseSubscription = _newPayment.applePayResponseStream.listen((response) {
      PaymentResponse paymentResponse = PaymentResponse.fromJson(response);
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('SkipCash ApplePay'),
            content: Text(
                "是否成功: ${paymentResponse.isSuccess} | 支付ID: ${paymentResponse.paymentId} | 错误信息: ${paymentResponse.errorMessage} | 返回码: ${paymentResponse.returnCode}"
            ),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text('OK'),
              ),
            ],
          );
        },
      );
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('sc_applepay 插件示例应用'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 280,
              child:
              TextField(
                controller: _firstNameController,
                decoration: const InputDecoration(labelText: 'First Name'),
              ),
            ),
            SizedBox(
              width: 280,
              child:
                TextField(
                  controller: _lastNameController,
                  decoration: const InputDecoration(labelText: 'Last Name'),
                ),
            ),
            SizedBox(
              width: 280,
              child:
                TextField(
                  controller: _phoneController,
                  decoration: const InputDecoration(labelText: 'Phone Number'),
                ),
            ),
            SizedBox(
              width: 280,
              child:
                TextField(
                  controller: _emailController,
                  decoration: const InputDecoration(labelText: 'Email'),
                ),
            ),
            SizedBox(
              width: 300,
              child:
              TextField(
                controller: _amountController,
                decoration: const InputDecoration(
                    labelText: 'Amount',
                    hintText: "有效值: 2 和 3.2 和 2.25"
                ),
              ),
            ),
            const SizedBox(
              height: 30,
            ),
            SizedBox(
              width: 250,
              child: ElevatedButton(
                onPressed: () async {
                  bool hasCards;
                  try {
                    hasCards = await _newPayment.isWalletHasCards() ?? false;

                    if(hasCards){
                      // 设置支付详细信息
                      String firstName = _firstNameController.text;
                      String lastName = _lastNameController.text;
                      String phone = _phoneController.text;
                      String email = _emailController.text;
                      String amount = _amountController.text;

                      if(firstName.isEmpty || lastName.isEmpty || phone.isEmpty
                        || email.isEmpty || amount.isEmpty || amount == "0.0"){
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('无效详情'),
                              content: const Text(
                                  "请填写所有字段,并且金额必须大于0.0,例如1.0。"
                              ),
                              actions: [
                                TextButton(
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: const Text('OK'),
                                ),
                              ],
                            );
                          },
                        );

                        return;
                      }

                      _newPayment.setFirstName(firstName);
                      _newPayment.setLastName(lastName);
                      _newPayment.setEmail(email);
                      _newPayment.setPhone(phone);
                      _newPayment.setAmount(amount);
                      _newPayment.addPaymentSummaryItem("Tax", "0.0");
                      _newPayment.addPaymentSummaryItem("Total", amount);
                      _newPayment.startPayment();
                    } else {
                      _newPayment.setupNewCard();
                    }

                  } on PlatformException {
                    hasCards = false;
                  }
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/skipcash.png',
                      width: 24,
                      height: 24,
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      "Pay Using ApplePay",
                      style: TextStyle(color: Color.fromRGBO(1, 125, 251, 1.0)),
                    )
                  ],
                ),
              ),
            ),
            SizedBox(
              width: 240,
              child: ElevatedButton(
                onPressed: () async {
                  _newPayment.setupNewCard();
                },
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "Setup new card in wallet",
                      style: TextStyle(color: Color.fromRGBO(1, 125, 251, 1.0)),
                    )
                  ],
                ),
              ),
            ),
            SizedBox(
              width: 250,
              child: ElevatedButton(
                onPressed: (){
                  _newPayment.loadSCPGW(
                      "", // 生成新的 payURL 并传递到这里
                      "", // WebView 模态框标题
                      "" // 在商户门户中定义的返回 URL
                  );
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/skipcash.png',
                      width: 24,
                      height: 24,
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      "Test NativeWebView",
                      style: TextStyle(color: Color.fromRGBO(1, 125, 251, 1.0)),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


sc_applepay 是一个用于在 Flutter 应用中集成 Apple Pay 的插件。它提供了简单易用的 API,帮助开发者快速实现 Apple Pay 支付功能。以下是使用 sc_applepay 插件的基本步骤和示例代码。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  sc_applepay: ^1.0.0  # 请确保使用最新版本

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

2. 配置 iOS 项目

在 iOS 项目中,确保已经配置了 Apple Pay 功能:

  1. 打开 ios/Runner.xcworkspace 文件。
  2. Runner 目标中,选择 Capabilities 选项卡。
  3. 启用 Apple Pay,并添加所需的支付网络(如 Visa, MasterCard 等)。
  4. Info.plist 文件中添加 NSApplePayMerchantIdentifier 键,并设置你的商户 ID。

3. 使用 sc_applepay 插件

在 Flutter 代码中,你可以使用 sc_applepay 插件来处理 Apple Pay 支付。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ApplePayScreen(),
    );
  }
}

class ApplePayScreen extends StatelessWidget {
  final ScApplePay _applePay = ScApplePay();

  Future<void> _startApplePay() async {
    try {
      // 配置支付请求
      final paymentItems = [
        PaymentItem(label: '商品1', amount: 10.0),
        PaymentItem(label: '商品2', amount: 20.0),
      ];

      // 启动 Apple Pay
      final result = await _applePay.startPayment(
        merchantIdentifier: 'your.merchant.id',
        countryCode: 'US',
        currencyCode: 'USD',
        paymentItems: paymentItems,
      );

      // 处理支付结果
      if (result.status == PaymentStatus.success) {
        print('支付成功');
      } else {
        print('支付失败: ${result.message}');
      }
    } catch (e) {
      print('支付异常: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Apple Pay 示例'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _startApplePay,
          child: Text('使用 Apple Pay 支付'),
        ),
      ),
    );
  }
}
回到顶部