适用于 Android 的 Google Pay API for React Native

1. 简介

构建内容

完成此 Codelab 后,您将拥有一个最低可行性 React Native 应用,其中包含适用于 Android 的 Google Pay 集成。此项目会检索付款令牌,该令牌可能会发送给付款服务提供商进行处理。

学习内容

  • 如何安装和配置 Google Pay React Native 库
  • 如何显示 Google Pay 按钮并处理点击事件
  • 如何向 Google Pay 请求付款令牌

所需条件

  • 您选择的文本编辑器,用于修改 JavaScript 文件。
  • 为 Android 设置的 React Native 开发环境。
  • 对于生产环境,您需要 Google Pay merchantId。在 Google Pay & Wallet Console 中注册只需一分钟,因此不妨现在就完成注册。

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 按钮

The 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,请将 google_paybaseGooglePayRequest 搭配使用。
  3. checkCanMakePayment 会在付款表格可用时显示该表格,并记录响应。

6. 总结

恭喜您完成此 Codelab!您已了解如何将 Google Pay API 集成到适用于 Android 的 React Native 应用中。

运行项目

运行以下命令以启动应用:

npx react-native run-android

后续步骤

其他资源