Android 版 Google Pay API for Flutter

1. 簡介

建構項目

完成本程式碼研究室後,您將擁有最低可行的 Flutter 應用程式,並整合可運作的 Android 版 Google Pay。這個專案會擷取付款權杖,並傳送給付款服務供應商進行處理。

課程內容

  • 如何安裝及設定 Google Pay Flutter 程式庫
  • 如何顯示 Google Pay 按鈕及處理點擊事件
  • 如何向 Google Pay 申請付款權杖

軟硬體需求

  • 您選擇的文字編輯器,用於編輯 Dart 檔案。
  • 已為 Android 設定 Flutter 開發環境。
  • 如要使用正式版,您需要 Google Pay merchantId。在 Google Pay 和錢包主控台註冊只需一分鐘,不妨現在就完成註冊。

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) 包含所有要求的最低通用設定。我們會根據提出的要求新增其他設定,並在程式碼研究室中進行檢查。

  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. GooglePayButton 小工具中的 paymentConfigurationAsset 會從 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. 結語

恭喜您完成本程式碼研究室!您已學會如何將 Google Pay API 整合至 Android 適用的 Flutter 應用程式。

執行專案

執行下列指令來啟動應用程式:

flutter run

下一步該做什麼?

其他資源