1. Introdução
O que você vai criar
Ao concluir este codelab, você terá um app React Native mínimo viável com uma integração funcional do Google Pay para Android. Esse projeto recupera um token de pagamento que pode ser enviado a um provedor de serviços de pagamento para processamento.
O que você vai aprender
- Como instalar e configurar a biblioteca nativa do Google Pay React Native
- Como mostrar o botão do Google Pay e processar cliques
- Como solicitar um token de pagamento do Google Pay
O que é necessário
- Um editor de texto de sua escolha para editar arquivos JavaScript.
- Um ambiente de desenvolvimento do React Native configurado para Android.
- Para produção, você vai precisar de um
merchantIddo Google Pay. Leva apenas um minuto para se registrar no Console do Google Pay e da Carteira. Então, faça isso agora.
2. Criar o projeto do React Native
Criar arquivos de projeto
- Crie um projeto do React Native chamado
googlepayrn.npx @react-native-community/cli@latest init googlepayrn
- Instale a biblioteca nativa do Google Pay React.
cd googlepayrn npm install @google/react-native-make-payment
- Abra
App.tsxno ambiente de desenvolvimento integrado de sua preferência e substitua o conteúdo pelo código a seguir: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. Configurar o Google Pay
Uma solicitação de pagamento do Google Pay exige um objeto de solicitação. O objeto definido aqui como baseGooglePayRequest contém as configurações comuns mínimas para todas as solicitações. Outras configurações serão adicionadas dependendo da solicitação feita, que vamos analisar neste codelab.
Adicione as constantes de configuração do Google Pay a 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'
}
}
}
]
};
Recursos
- Referência da API: documentação dos objetos de solicitação da API Google Pay
- Referência da API: consulte
PaymentMethodpara mais informações sobre os métodos de autorização e as redes de cartão permitidos, além das especificações de tokenização, incluindo o valor de gateway adequado.
4. Fazer uma solicitação de pagamento
Quando o botão do Google Pay é pressionado, uma solicitação de pagamento é criada e mostrada.
Adicione os detalhes e as formas de pagamento em App.tsx:
const paymentDetails = {
total: {
amount: {
currency: 'USD',
value: '14.95',
},
},
};
const paymentMethods = [
{
supportedMethods: 'google_pay',
data: baseGooglePayRequest,
},
];
5. Adicionar o botão do Google Pay
A biblioteca react-native-make-payment inclui um componente nativo de botão do Google Pay.
- Adicione a importação na parte de cima de
App.tsx:
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
- Adicione o gerenciador de cliques ao componente
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');
}
});
};
- Adicione o botão e o estilo ao JSX e ao estilo dele:
<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 depois de adicionar o botão e o gerenciador:
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;
Explicar códigos
paymentDetailsdescreve a transação que precisa ser processada.paymentMethodsconfigura métodos aceitos. Para o Google Pay, usegoogle_paycombaseGooglePayRequest.- O
checkCanMakePaymentmostra a página de pagamento quando disponível e registra a resposta.
6. Conclusão
Parabéns por concluir este codelab. Você aprendeu a integrar a API Google Pay a um app React Native para Android.
Executar o projeto
Execute o seguinte comando para iniciar o app:
npx react-native run-android
O que fazer depois disso
Outros recursos
- Participe da conversa no canal#payments do Discord
- Siga @GooglePayDevs no X
- Assista vídeos relacionados ao Google Pay no YouTube