1. 소개
빌드할 항목
이 Codelab을 완료하면 Android용 Google Pay 통합이 작동하는 최소한의 실행 가능한 React Native 앱이 만들어집니다. 이 프로젝트는 처리할 결제 서비스 제공업체에 전송될 수 있는 결제 토큰을 가져옵니다.
학습할 내용
- Google Pay React Native 라이브러리를 설치하고 구성하는 방법
- Google Pay 버튼을 표시하고 클릭을 처리하는 방법
- Google Pay에서 결제 토큰을 요청하는 방법
필요한 항목
- JavaScript 파일을 수정할 수 있는 텍스트 편집기
- Android용으로 설정된 React Native 개발 환경
- 프로덕션의 경우 Google Pay
merchantId가 필요합니다. Google Pay 및 월렛 콘솔에 등록하는 데는 1분밖에 걸리지 않으므로 지금 등록하는 것이 좋습니다.
2. React Native 프로젝트 만들기
프로젝트 파일 만들기
googlepayrn라는 새 React Native 프로젝트를 만듭니다.npx @react-native-community/cli@latest init googlepayrn
- Google Pay React Native 라이브러리를 설치합니다.
cd googlepayrn npm install @google/react-native-make-payment
- 선택한 IDE에서
App.tsx를 열고 콘텐츠를 다음 코드로 바꿉니다.import React from 'react'; import { SafeAreaView, StatusBar, StyleSheet, Text, useColorScheme, View, } from 'react-native'; const App = () => { const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { backgroundColor: isDarkMode ? '#121212' : '#F3F3F3', }; return ( <SafeAreaView style={backgroundStyle}> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} backgroundColor={backgroundStyle.backgroundColor} /> <View style={styles.container}> <Text style={styles.title}>Google Pay Codelab</Text> <View id="gpay-container" /> <Text>Transaction info and errors will be logged to the console.</Text> </View> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { padding: 24, }, title: { fontSize: 24, fontWeight: '600', marginBottom: 24, }, }); export default App;
3. Google Pay 구성
Google Pay 결제 요청에는 요청 객체가 필요합니다. 여기에서 baseGooglePayRequest로 정의된 객체에는 모든 요청의 최소 공통 설정이 포함됩니다. 요청에 따라 추가 설정이 추가되며 이 Codelab에서 검토합니다.
Google Pay 구성 상수를 App.tsx에 추가합니다.
// This is the base configuration for all Google Pay payment data requests.
const baseGooglePayRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [
{
type: 'CARD',
parameters: {
allowedAuthMethods: [
"PAN_ONLY", "CRYPTOGRAM_3DS"
],
allowedCardNetworks: [
"AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"
]
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
parameters: {
gateway: 'example',
gatewayMerchantId: 'exampleGatewayMerchantId'
}
}
}
]
};
리소스
- API 참조: Google Pay API 요청 객체 문서
- API 참조: 허용된 승인 방법, 허용된 카드 네트워크, 적절한 게이트웨이 값을 비롯한 토큰화 사양에 대한 자세한 내용은
PaymentMethod을 참고하세요.
4. 결제 요청하기
Google Pay 버튼을 누르면 결제 요청이 생성되어 표시됩니다.
결제 세부정보와 결제 수단을 App.tsx에 추가합니다.
const paymentDetails = {
total: {
amount: {
currency: 'USD',
value: '14.95',
},
},
};
const paymentMethods = [
{
supportedMethods: 'google_pay',
data: baseGooglePayRequest,
},
];
5. Google Pay 버튼 추가
react-native-make-payment 라이브러리에는 네이티브 Google Pay 버튼 구성요소가 포함되어 있습니다.
App.tsx상단에 가져오기를 추가합니다.
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
App구성요소 내에 클릭 핸들러를 추가합니다.
const checkCanMakePayment = () => {
const paymentRequest = new PaymentRequest(paymentMethods, paymentDetails);
paymentRequest.canMakePayment().then((canMakePayment) => {
if (canMakePayment) {
paymentRequest.show().then((response) => {
console.log(response);
});
} else {
console.log('Google Pay unavailable');
}
});
};
- JSX와 스타일을 버튼에 추가합니다.
<GooglePayButton
style={styles.googlepaybutton}
onPress={checkCanMakePayment}
allowedPaymentMethods={baseGooglePayRequest.allowedPaymentMethods}
theme={GooglePayButtonConstants.Themes.Dark}
type={GooglePayButtonConstants.Types.Buy}
radius={4}
/>
googlepaybutton: {
width: 200,
height: 48,
},
버튼과 핸들러를 추가한 후의 App.tsx:
import React from 'react';
import {
SafeAreaView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
const baseGooglePayRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [
{
type: 'CARD',
parameters: {
allowedAuthMethods: [
'PAN_ONLY', 'CRYPTOGRAM_3DS'
],
allowedCardNetworks: [
'AMEX', 'DISCOVER', 'INTERAC', 'JCB', 'MASTERCARD', 'VISA'
]
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
parameters: {
gateway: 'example',
gatewayMerchantId: 'exampleGatewayMerchantId'
}
}
}
]
};
const paymentDetails = {
total: {
amount: {
currency: 'USD',
value: '14.95',
},
},
};
const paymentMethods = [
{
supportedMethods: 'google_pay',
data: baseGooglePayRequest,
},
];
const App = () => {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? '#121212' : '#F3F3F3',
};
const checkCanMakePayment = () => {
const paymentRequest = new PaymentRequest(paymentMethods, paymentDetails);
paymentRequest.canMakePayment().then((canMakePayment) => {
if (canMakePayment) {
paymentRequest.show().then((response) => {
// Send 'token' to your payment service provider (PSP)
console.log(response);
});
} else {
console.log('Google Pay unavailable');
}
});
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar
barStyle={isDarkMode ? 'light-content' : 'dark-content'}
backgroundColor={backgroundStyle.backgroundColor}
/>
<View style={styles.container}>
<Text style={styles.title}>Google Pay Codelab</Text>
<GooglePayButton
style={styles.googlepaybutton}
onPress={checkCanMakePayment}
allowedPaymentMethods={baseGooglePayRequest.allowedPaymentMethods}
theme={GooglePayButtonConstants.Themes.Dark}
type={GooglePayButtonConstants.Types.Buy}
radius={4}
/>
<Text>Transaction info and errors will be logged to the console.</Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
padding: 24,
},
title: {
fontSize: 24,
fontWeight: '600',
marginBottom: 24,
},
googlepaybutton: {
width: 200,
height: 48,
},
});
export default App;
코드 설명
paymentDetails는 처리해야 하는 트랜잭션을 설명합니다.paymentMethods는 지원되는 메서드를 구성합니다. Google Pay의 경우baseGooglePayRequest와 함께google_pay를 사용하세요.checkCanMakePayment는 사용 가능한 경우 결제 시트를 표시하고 응답을 기록합니다.
6. 결론
이 Codelab을 완료했습니다. Android용 React Native 앱에 Google Pay API를 통합하는 방법을 알아봤습니다.
프로젝트 실행
다음 명령어를 실행하여 앱을 시작합니다.
npx react-native run-android
다음 단계
추가 리소스
- Discord의 #payments 채널에서 대화에 참여하세요
- X에서 @GooglePayDevs 팔로우하기
- YouTube에서 Google Pay 관련 동영상 시청하기