Android での Flutter 向け Google Pay API

1. はじめに

作成するアプリの概要

この Codelab を完了すると、Android 向けに Google Pay 統合が機能する実用最小限の Flutter アプリが完成します。このプロジェクトは、処理のために決済サービス プロバイダに送信される決済トークンを取得します。

学習内容

  • Google Pay Flutter ライブラリのインストールと設定方法
  • Google Pay ボタンを表示してクリックを処理する方法
  • Google Pay から支払いトークンをリクエストする方法

必要なもの

  • Dart ファイルを編集するための任意のテキスト エディタ。
  • Android 用にセットアップされた Flutter 開発環境。
  • 本番環境では、Google Pay merchantId が必要になります。Google Pay & Wallet Console での登録は 1 分で完了します。今すぐ登録しましょう。

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. 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. まとめ

これでこの Codelab は終了です。Android 向け Flutter アプリに Google Pay API を統合する方法を学びました。

プロジェクトを実行する

次のコマンドを実行してアプリを起動します。

flutter run

次のステップ

参考情報