API de Google Pay para React Native en Android

1. Introducción

Qué compilarás

Cuando completes este codelab, tendrás una app de React Native mínima viable con una integración de Google Pay para Android que funcione. Este proyecto recupera un token de pago que se puede enviar a un proveedor de servicios de pago para su procesamiento.

Qué aprenderás

  • Cómo instalar y configurar la biblioteca de Google Pay React Native
  • Cómo mostrar el botón de Google Pay y controlar los clics
  • Cómo solicitar un token de pago de Google Pay

Requisitos

  • Un editor de texto de tu elección para editar archivos JavaScript
  • Un entorno de desarrollo de React Native configurado para Android
  • Para la producción, necesitarás un Google Pay merchantId. Solo toma un minuto registrarse en la Consola de Google Pay y la Billetera, así que puedes hacerlo ahora.

2. Crea el proyecto de React Native

Crea archivos del proyecto

  1. Crea un nuevo proyecto de React Native llamado googlepayrn.
    npx @react-native-community/cli@latest init googlepayrn
    
  2. Instala la biblioteca de Google Pay React Native.
    cd googlepayrn
    npm install @google/react-native-make-payment
    
  3. Abre App.tsx en el IDE que elijas y reemplaza el contenido por el siguiente código:
    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. Configura Google Pay

Una solicitud de pago de Google Pay requiere un objeto de solicitud. El objeto definido aquí como baseGooglePayRequest contiene la configuración mínima común para todas las solicitudes. Se agregarán parámetros de configuración adicionales según la solicitud realizada, que revisaremos en este codelab.

Agrega las constantes de configuración de 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

  • Referencia de la API: Documentación de los objetos de solicitud de la API de Google Pay
  • Referencia de la API: Consulta PaymentMethod para obtener más información sobre los métodos de autorización permitidos, las redes de tarjetas permitidas y las especificaciones de tokenización, incluido el valor de puerta de enlace adecuado.

4. Realiza una solicitud de pago

Cuando se presiona el botón de Google Pay, se crea y se muestra una solicitud de pago.

Agrega los detalles de pago y las formas de pago a App.tsx:

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

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

5. Agrega el botón de Google Pay

La biblioteca react-native-make-payment incluye un componente de botón nativo de Google Pay.

  1. Agrega la importación en la parte superior de App.tsx:
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
  1. Agrega el controlador de clics dentro del 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. Agrega el botón y el estilo al JSX y su estilo:
<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 después de agregar el botón y el controlador:

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;

Explicación del código

  1. paymentDetails describe la transacción que se debe procesar.
  2. paymentMethods configura los métodos admitidos. Para Google Pay, usa google_pay con baseGooglePayRequest.
  3. checkCanMakePayment muestra la hoja de pago cuando está disponible y registra la respuesta.

6. Conclusión

¡Felicitaciones por completar este codelab! Aprendiste a integrar la API de Google Pay en una app de React Native para Android.

Cómo ejecutar el proyecto

Ejecuta el siguiente comando para iniciar tu app:

npx react-native run-android

Lo que vendrá

Recursos adicionales