API Google Pay para React Native no Android

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 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 preferência para editar arquivos JavaScript.
  • Um ambiente de desenvolvimento do React Native configurado para Android.
  • Para produção, você vai precisar de um Google Pay merchantId. Leva apenas um minuto para se registrar no console do Google Pay e da Carteira. Então, aproveite para fazer isso agora.

2. Criar o projeto React Native

Criar arquivos de projeto

  1. Crie um novo projeto React Native chamado googlepayrn.
    npx @react-native-community/cli@latest init googlepayrn
    
  2. Instale a biblioteca do Google Pay React Native.
    cd googlepayrn
    npm install @google/react-native-make-payment
    
  3. Abra App.tsx no 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

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 a App.tsx:

const paymentDetails = {
  total: {
    amount: {
      currency: 'USD',
      value: '14.95',
    },
  },
};

const paymentMethods = [
  {
    supportedMethods: 'google_pay',
    data: baseGooglePayRequest,
  },
];

5. Incluir o botão do Google Pay

A biblioteca react-native-make-payment inclui um componente de botão nativo do Google Pay.

  1. Adicione a importação na parte de cima de App.tsx:
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
  1. Adicione o gerenciador de cliques dentro do 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');
    }
  });
};
  1. 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

  1. paymentDetails descreve a transação que precisa ser processada.
  2. paymentMethods configura os métodos aceitos. Para o Google Pay, use google_pay com baseGooglePayRequest.
  3. checkCanMakePayment mostra 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 comando a seguir para iniciar o app:

npx react-native run-android

O que fazer depois disso

Outros recursos