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 プロジェクトを作成する
プロジェクト ファイルを作成する
googlepay_flutterという名前の新しい Flutter プロジェクトを作成します。flutter create googlepay_flutter
- Google Pay Flutter ライブラリをインストールします。
cd googlepay_flutter flutter pub add pay
- 任意の 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 で確認します。
- Google Pay の構成定数を
lib/main.dartに追加します。
import 'package:pay/pay.dart';
const _paymentItems = [
PaymentItem(
label: 'Total',
amount: '14.95',
status: PaymentItemStatus.final_price,
)
];
- デフォルトのお支払い構成 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.'),
],
),
),
);
}
}
コードの説明
_paymentItemsは、このボタンのクリックで処理されるトランザクションを記述します。GooglePayButtonウィジェットのpaymentConfigurationAssetは、assets/google_pay_config.jsonファイルから構成を読み込みます。GooglePayButtonが押されると、onGooglePayResult関数が呼び出されます。この関数は支払い結果を受け取ります。- レスポンスから支払いトークンを取得したら、トランザクションを処理するために支払いゲートウェイに送信します。
5. クリック時に支払いをトリガーする
GooglePayButton をタップすると、Google Pay シートが開き、結果が返されます。別の「支払い」呼び出しは必要ありません。トークンのログ記録、エラーの表示、ボタン押下のログ記録(任意)を行うハンドラを追加します。
_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');
}
}
- プレス ハンドラとエラー ハンドラを含めるように
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
次のステップ
参考情報
- Discord の #payments チャンネルで会話に参加する
- X で @GooglePayDevs をフォローする
- YouTube で Google Pay 関連の動画を見る