Android 上的 Google Pay API for Flutter

1. 简介

构建内容

完成此 Codelab 后,您将拥有一个最低可行性 Flutter 应用,其中包含适用于 Android 的 Google Pay 集成。此项目会检索付款令牌,该令牌可能会发送给付款服务提供商进行处理。

学习内容

  • 如何安装和配置 Google Pay Flutter 库
  • 如何显示 Google Pay 按钮并处理点击操作
  • 如何向 Google Pay 请求付款令牌

所需条件

  • 您选择的文本编辑器,用于修改 Dart 文件。
  • 为 Android 设置的 Flutter 开发环境。
  • 在生产环境中,您需要 Google Pay merchantId。在 Google Pay & Wallet Console 中注册只需一分钟,因此不妨现在就完成注册。

2. 创建 Flutter 项目

创建项目文件

  1. 创建一个名为 googlepay_flutter 的新 Flutter 项目。
    flutter create googlepay_flutter
    
  2. 安装 Google Pay Flutter 库。
    cd googlepay_flutter
    flutter pub add pay
    
  3. 在您选择的 IDE 中打开 lib/main.dart,并将内容替换为以下代码:
    import 'package:flutter/material.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: PaySampleApp(),
        );
      }
    }
    
    class PaySampleApp extends StatefulWidget {
      const PaySampleApp({super.key});
    
      @override
      State<PaySampleApp> createState() => _PaySampleAppState();
    }
    
    class _PaySampleAppState extends State<PaySampleApp> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Google Pay Codelab'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('Transaction info and errors will be logged to the console.'),
              ],
            ),
          ),
        );
      }
    }
    

3. 配置 Google Pay

Google Pay 付款请求需要请求对象。此处定义为 _paymentItems 的对象包含所有请求的最低通用设置。我们将根据发出的请求添加其他设置,并在此 Codelab 中进行审核。

  1. 将 Google Pay 配置常量添加到 lib/main.dart
import 'package:pay/pay.dart';

const _paymentItems = [
  PaymentItem(
    label: 'Total',
    amount: '14.95',
    status: PaymentItemStatus.final_price,
  )
];
  1. 将默认付款配置 JSON 添加到路径 assets/google_pay_config.json
  {
    "provider": "google_pay",
    "data": {
      "environment": "TEST",
      "apiVersion": 2,
      "apiVersionMinor": 0,
      "allowedPaymentMethods": [
        {
          "type": "CARD",
          "tokenizationSpecification": {
            "type": "PAYMENT_GATEWAY",
            "parameters": {
              "gateway": "example",
              "gatewayMerchantId": "exampleGatewayMerchantId"
            }
          },
          "parameters": {
            "allowedCardNetworks": ["VISA", "MASTERCARD"],
            "allowedAuthMethods": ["PAN_ONLY", "CRYPTOGRAM_3DS"],
            "billingAddressRequired": true,
            "billingAddressParameters": {
              "format": "FULL",
              "phoneNumberRequired": true
            }
          }
        }
      ],
      "merchantInfo": {
        "merchantName": "Example Merchant Name"
      },
      "transactionInfo": {
        "countryCode": "US",
        "currencyCode": "USD"
      }
    }
  }

资源

  • API 参考文档:Google Pay API 请求对象文档
  • API 参考文档:如需详细了解允许的授权方法、允许的银行卡网络和令牌化规范(包括正确的网关值),请参阅 PaymentMethod

4. 添加 Google Pay 按钮

pay 库包含原生 Google Pay 按钮组件。

使用以下代码更新 lib/main.dart 中的 _PaySampleAppState 类:

class _PaySampleAppState extends State<PaySampleApp> {
  late final Future<PaymentConfiguration> _gpayConfig;

  void onGooglePayResult(paymentResult) {
    // Send 'token' to your payment service provider (PSP)
    print(paymentResult);
  }

  @override
  void initState() {
    super.initState();
    _gpayConfig = PaymentConfiguration.fromAsset('google_pay_config.json');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Google Pay Codelab')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FutureBuilder<PaymentConfiguration>(
              future: _gpayConfig,
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError || !snapshot.hasData) {
                  return const Text('Error loading Google Pay config');
                }
                return GooglePayButton(
                  paymentConfiguration: snapshot.data!,
                  onPaymentResult: onGooglePayResult,
                  paymentItems: _paymentItems,
                  height: 48,
                  type: GooglePayButtonType.buy,
                  theme: GooglePayButtonTheme.dark,
                  margin: const EdgeInsets.only(top: 15.0),
                  loadingIndicator: const Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              },
            ),
            const Text('Transaction info and errors will be logged to the console.'),
          ],
        ),
      ),
    );
  }
}

代码说明

  1. _paymentItems 描述了应通过此按钮点击操作处理的交易。
  2. paymentConfigurationAsset widget 中的 GooglePayButton 会从 assets/google_pay_config.json 文件加载配置。
  3. 按下 GooglePayButton 时,系统会调用 onGooglePayResult 函数。此函数会接收付款结果。
  4. 从响应中获取付款令牌后,您需要将其发送到付款网关以处理交易。

5. 点击时触发付款

点按 GooglePayButton 会打开 Google Pay 页面并返回结果,无需单独调用“付款”操作。添加处理程序以记录令牌、显示错误,并选择性地记录按钮按下操作。

  1. _PaySampleAppState 中添加或更新结果处理程序:
void onGooglePayResult(dynamic paymentResult) {
  try {
    final token = paymentResult['paymentMethodData']['tokenizationData']['token'];
    debugPrint('Google Pay payment token: $token');
  } catch (e) {
    debugPrint('Unexpected payment result: $e');
  }
}
  1. 更新 GooglePayButton 以包含按下和错误处理程序:
GooglePayButton(
  paymentConfiguration: snapshot.data!,
  paymentItems: _paymentItems,
  onPaymentResult: onGooglePayResult,
  onError: (Object err) => debugPrint('Google Pay error: $err'),
  onPressed: () => debugPrint('Google Pay button pressed'),
  height: 48,
  type: GooglePayButtonType.buy,
  theme: GooglePayButtonTheme.dark,
  margin: const EdgeInsets.only(top: 15.0),
  loadingIndicator: const Center(child: CircularProgressIndicator()),
)

备注

  • 点按操作本身会触发付款页面;onPaymentResult 会接收载荷。
  • 在生产环境中,将令牌发送给付款服务提供商以完成扣款。

6. 总结

恭喜您完成此 Codelab!您已了解如何将 Google Pay API 集成到适用于 Android 的 Flutter 应用中。

运行项目

运行以下命令以启动应用:

flutter run

后续步骤

其他资源