API Google Pay per React Native su Android

1. Introduzione

Cosa creerai

Al termine di questo codelab, avrai un'app React Native minima e funzionante con un'integrazione di Google Pay per Android. Questo progetto recupera un token di pagamento che può essere inviato a un fornitore di servizi di pagamento per l'elaborazione.

Obiettivi didattici

  • Come installare e configurare la libreria Google Pay React Native
  • Come visualizzare il pulsante Google Pay e gestire i clic
  • Come richiedere un token di pagamento da Google Pay

Che cosa ti serve

  • Un editor di testo a tua scelta per modificare i file JavaScript.
  • Un ambiente di sviluppo React Native configurato per Android.
  • Per la produzione, avrai bisogno di un merchantId Google Pay. La registrazione alla console di Google Pay e Wallet richiede solo un minuto, quindi tanto vale occuparsene subito.

2. Crea il progetto React Native

Creare file di progetto

  1. Crea un nuovo progetto React Native denominato googlepayrn.
    npx @react-native-community/cli@latest init googlepayrn
    
  2. Installa la libreria Google Pay React Native.
    cd googlepayrn
    npm install @google/react-native-make-payment
    
  3. Apri App.tsx nell'IDE che preferisci e sostituisci i contenuti con il seguente codice:
    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. Configurare Google Pay

Una richiesta di pagamento Google Pay richiede un oggetto richiesta. L'oggetto definito qui come baseGooglePayRequest contiene le impostazioni comuni minime per tutte le richieste. A seconda della richiesta effettuata, verranno aggiunte impostazioni aggiuntive che esamineremo in questo codelab.

Aggiungi le costanti di configurazione di 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'
        }
      }
    }
  ]
};

Risorse

  • Riferimento API: documentazione sugli oggetti richiesta dell'API Google Pay
  • Riferimento API: consulta PaymentMethod per ulteriori informazioni sui metodi di autorizzazione consentiti, sulle reti di carte consentite e sulle specifiche di tokenizzazione, incluso il valore del gateway corretto.

4. Effettuare una richiesta di pagamento

Quando viene premuto il pulsante Google Pay, viene creata e visualizzata una richiesta di pagamento.

Aggiungi i dati di pagamento e i metodi di pagamento a App.tsx:

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

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

5. Aggiungere il pulsante Google Pay

La libreria react-native-make-payment include un componente pulsante Google Pay nativo.

  1. Aggiungi l'importazione all'inizio di App.tsx:
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
  1. Aggiungi il gestore dei clic all'interno 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. Aggiungi il pulsante e lo stile al JSX e al relativo stile:
<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 dopo aver aggiunto il pulsante e il gestore:

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;

Spiegazione del codice

  1. paymentDetails descrive la transazione da elaborare.
  2. paymentMethods configura i metodi supportati; per Google Pay utilizza google_pay con baseGooglePayRequest.
  3. checkCanMakePayment mostra il foglio di pagamento quando disponibile e registra la risposta.

6. Conclusione

Congratulazioni per aver completato questo codelab. Hai imparato a integrare l'API Google Pay in un'app React Native per Android.

Esegui il progetto

Esegui questo comando per avviare l'app:

npx react-native run-android

Come procedere

Risorse aggiuntive