1. 소개
빌드할 항목
이 Codelab을 완료하면 Android용 Google Pay 통합이 작동하는 최소 실행 가능한 Flutter 앱이 만들어집니다. 이 프로젝트는 처리할 결제 서비스 제공업체에 전송될 수 있는 결제 토큰을 가져옵니다.
학습할 내용
- Google Pay Flutter 라이브러리를 설치하고 구성하는 방법
- Google Pay 버튼을 표시하고 클릭을 처리하는 방법
- Google Pay에서 결제 토큰을 요청하는 방법
필요한 항목
- Dart 파일을 수정할 수 있는 텍스트 편집기
- Android용으로 설정된 Flutter 개발 환경
- 프로덕션의 경우 Google Pay
merchantId가 필요합니다. Google Pay 및 월렛 콘솔에 등록하는 데는 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 관련 동영상 시청하기