Flutter在线支付插件square_web_payments的使用

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

Flutter在线支付插件square_web_payments的使用

square_web_payments 是一个开源的Flutter插件,用于集成Square Web Payments SDK。通过这个插件,开发者可以轻松地在Flutter应用中实现多种支付方式,如Apple Pay、Google Pay、信用卡和礼品卡支付。

完整示例Demo

以下是一个完整的示例代码,展示了如何使用 square_web_payments 插件来集成不同的支付方式。该示例包括Apple Pay、信用卡、礼品卡和Google Pay的实现。

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Square Web Payments Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const PaymentHomePage(),
    );
  }
}

class PaymentHomePage extends StatelessWidget {
  const PaymentHomePage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Square Web Payments Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const ApplePayPage()),
                );
              },
              child: const Text('Apple Pay'),
            ),
            const SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const CardPaymentPage()),
                );
              },
              child: const Text('Credit Card'),
            ),
            const SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const GiftCardPage()),
                );
              },
              child: const Text('Gift Card'),
            ),
            const SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const GooglePayPage()),
                );
              },
              child: const Text('Google Pay'),
            ),
          ],
        ),
      ),
    );
  }
}

class ApplePayPage extends StatelessWidget {
  const ApplePayPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Apple Pay'),
      ),
      body: Center(
        child: PaymentBuilder(
          paymentMethodBuilder: (payments) => payments.applePay(
            payments.paymentRequest(
              const PaymentRequestOptions(
                countryCode: 'US',
                currencyCode: 'USD',
                total: LineItem(amount: '1.00', label: 'Total'),
              ),
            ),
          ),
          tokenBuilder: (applePay, tokenize) => ApplePayView(
            applePay: applePay,
            onPressed: tokenize,
          ),
        ),
      ),
    );
  }
}

class CardPaymentPage extends StatelessWidget {
  const CardPaymentPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Credit Card'),
      ),
      body: Center(
        child: PaymentBuilder(
          paymentMethodBuilder: (payments) => payments.card(),
          tokenBuilder: _buildCardView,
          verifyBuilder: (verify) => Center(
            child: TextButton(
              onPressed: () => verify(
                VerifyBuyerDetails(
                  amount: '1.00',
                  billingContact: const Contact(
                    addressLines: ['123 East Main Street', '#111'],
                    city: 'Seattle',
                    countryCode: 'US',
                    email: 'johndoe@example.com',
                    familyName: 'Doe',
                    givenName: 'John',
                    phone: '+12065551212',
                    postalCode: '98111',
                    state: 'WA',
                  ),
                  currencyCode: 'USD',
                  intent: 'CHARGE',
                ),
              ),
              child: const Text('Verify'),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCardView(PaymentCard card, void Function() tokenize) {
    // 显式请求按钮的焦点,以移除支付输入字段的键盘焦点
    final focusNode = FocusNode();
    return Column(
      children: [
        CardView(card: card),
        TextButton(
          focusNode: focusNode,
          onPressed: () {
            focusNode.requestFocus();
            tokenize();
          },
          child: const Text('Tokenize'),
        ),
      ],
    );
  }
}

class GiftCardPage extends StatelessWidget {
  const GiftCardPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Gift Card'),
      ),
      body: Center(
        child: PaymentBuilder(
          paymentMethodBuilder: (payments) => payments.giftCard(),
          tokenBuilder: _buildCardView,
        ),
      ),
    );
  }

  Widget _buildCardView(PaymentCard card, void Function() tokenize) {
    // 显式请求按钮的焦点,以移除支付输入字段的键盘焦点
    final focusNode = FocusNode();
    return Column(
      children: [
        CardView(card: card),
        TextButton(
          focusNode: focusNode,
          onPressed: () {
            focusNode.requestFocus();
            tokenize();
          },
          child: const Text('Tokenize'),
        ),
      ],
    );
  }
}

class GooglePayPage extends StatelessWidget {
  const GooglePayPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Pay'),
      ),
      body: Center(
        child: PaymentBuilder(
          paymentMethodBuilder: (payments) => payments.googlePay(
            payments.paymentRequest(
              const PaymentRequestOptions(
                countryCode: 'US',
                currencyCode: 'USD',
                total: LineItem(amount: '1.00', label: 'Total'),
              ),
            ),
          ),
          tokenBuilder: (googlePay, tokenize) => GooglePayView(
            googlePay: googlePay,
            googlePayButtonOptions: const GooglePayButtonOptions(buttonSizeMode: 'fill'),
            onPressed: tokenize,
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用square_web_payments插件来实现在线支付的代码示例。这个插件允许你集成Square的在线支付功能。

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

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

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

接下来,你需要配置Square的API密钥。在实际项目中,你应该将这些敏感信息存储在安全的地方,比如环境变量中。但为了示例的简洁性,这里我们直接在代码中硬编码(注意:不要在生产环境中这样做)。

以下是一个简单的Flutter应用示例,展示了如何使用square_web_payments插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Square Web Payments Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PaymentScreen(),
    );
  }
}

class PaymentScreen extends StatefulWidget {
  @override
  _PaymentScreenState createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {
  final String squareLocationId = 'your-square-location-id';  // 替换为你的Square Location ID
  final String squareApplicationId = 'your-square-application-id';  // 替换为你的Square Application ID
  final String squareAccessToken = 'your-square-access-token';  // 替换为你的Square Access Token

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Square Web Payments'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 创建SquareWebPayments实例
            final SquareWebPayments squareWebPayments = SquareWebPayments(
              locationId: squareLocationId,
              applicationId: squareApplicationId,
              accessToken: squareAccessToken,
            );

            try {
              // 发起支付请求
              final result = await squareWebPayments.createPayment(
                amountMoney: Money(
                  amount: 100,  // 支付金额,单位为美分(这里为1美元)
                  currencyCode: 'USD',
                ),
                idempotencyKey: Uuid().v4(),  // 确保唯一性,可以使用Uuid库生成
              );

              // 处理支付结果
              if (result != null) {
                if (result.checkoutId != null) {
                  // 跳转到Square的支付页面
                  final url = Uri.parse(
                    'https://connect.squareup.com/v2/checkout/web?checkoutId=${result.checkoutId}',
                  );
                  if (await canLaunchUrl(url)) {
                    await launchUrl(url);
                  } else {
                    throw 'Could not launch ${url.toString()}';
                  }
                } else {
                  // 处理错误
                  print('Error creating payment: ${result.errorMessage}');
                }
              }
            } catch (e) {
              print('Error: $e');
            }
          },
          child: Text('Pay \$1.00'),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮,当用户点击该按钮时,会尝试通过Square的Web支付API发起一个支付请求。

请注意以下几点:

  1. squareLocationIdsquareApplicationIdsquareAccessToken需要替换为你自己的Square账户信息。
  2. 使用了Uuid库来生成唯一的idempotencyKey,你需要在pubspec.yaml中添加uuid依赖,并运行flutter pub get来安装它。
  3. launchUrl函数用于在Web上打开Square的支付页面。如果你是在移动设备上运行这个应用,你可能需要使用其他方式(比如url_launcher插件的launch函数,它适用于iOS和Android)。

确保你已经正确配置了Square开发者账户,并且你的应用有权限访问Square的API。此外,Square的支付页面将在用户的Web浏览器中打开,因此这个流程可能不适用于所有类型的Flutter应用(比如纯移动端应用)。你可能需要根据具体需求调整用户体验。

回到顶部