Android 向け Google Pay API for React Native

1. はじめに

作成するアプリの概要

この Codelab を完了すると、Android 向けに Google Pay 統合が機能する最小限の実行可能な React Native アプリが完成します。このプロジェクトは、処理のために決済サービス プロバイダに送信される決済トークンを取得します。

学習内容

  • Google Pay React Native ライブラリをインストールして構成する方法
  • Google Pay ボタンを表示してクリックを処理する方法
  • Google Pay から支払いトークンをリクエストする方法

必要なもの

  • JavaScript ファイルを編集するための任意のテキスト エディタ。
  • Android 用にセットアップされた React Native 開発環境。
  • 本番環境では、Google Pay merchantId が必要になります。Google Pay & Wallet Console での登録は 1 分で完了します。今すぐ登録しましょう。

2. React Native プロジェクトを作成する

プロジェクト ファイルを作成する

  1. googlepayrn という名前の新しい React Native プロジェクトを作成します。
    npx @react-native-community/cli@latest init googlepayrn
    
  2. Google Pay React Native ライブラリをインストールします。
    cd googlepayrn
    npm install @google/react-native-make-payment
    
  3. 任意の 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 ボタン コンポーネントが含まれています。

  1. App.tsx の先頭にインポートを追加します。
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
  1. 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. 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;

コードの説明

  1. paymentDetails は、処理されるトランザクションを記述します。
  2. paymentMethods はサポートされているメソッドを構成します。Google Pay の場合は baseGooglePayRequestgoogle_pay を使用します。
  3. checkCanMakePayment は、利用可能な場合は支払いシートを表示し、レスポンスをログに記録します。

6. まとめ

これでこの Codelab は終了です。Android 向け React Native アプリに Google Pay API を統合する方法を学びました。

プロジェクトを実行する

次のコマンドを実行してアプリを起動します。

npx react-native run-android

次のステップ

参考情報