Google Pay API cho React Native trên Android

1. Giới thiệu

Sản phẩm bạn sẽ tạo ra

Khi hoàn tất lớp học lập trình này, bạn sẽ có một ứng dụng React Native khả thi tối thiểu với tính năng tích hợp Google Pay đang hoạt động cho Android. Dự án này truy xuất một mã thông báo thanh toán có thể được gửi đến một nhà cung cấp dịch vụ thanh toán để xử lý.

Kiến thức bạn sẽ học được

  • Cách cài đặt và định cấu hình thư viện Google Pay React Native
  • Cách hiển thị nút Google Pay và xử lý các lượt nhấp
  • Cách yêu cầu mã thông báo thanh toán từ Google Pay

Bạn cần có

  • Trình chỉnh sửa văn bản mà bạn chọn để chỉnh sửa tệp JavaScript.
  • Môi trường phát triển React Native được thiết lập cho Android.
  • Đối với bản phát hành chính thức, bạn sẽ cần có Google Pay merchantId. Bạn chỉ mất một phút để đăng ký tại Bảng điều khiển Google Pay và Ví, vì vậy, bạn nên thực hiện ngay.

2. Tạo dự án React Native

Tạo tệp dự án

  1. Tạo một dự án React Native mới có tên là googlepayrn.
    npx @react-native-community/cli@latest init googlepayrn
    
  2. Cài đặt thư viện Google Pay React Native.
    cd googlepayrn
    npm install @google/react-native-make-payment
    
  3. Mở App.tsx trong IDE mà bạn chọn và thay thế nội dung bằng mã sau:
    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. Định cấu hình Google Pay

Yêu cầu thanh toán bằng Google Pay cần có một đối tượng yêu cầu. Đối tượng được xác định ở đây là baseGooglePayRequest chứa các chế độ cài đặt chung tối thiểu cho tất cả các yêu cầu. Các chế độ cài đặt bổ sung sẽ được thêm tuỳ thuộc vào yêu cầu được đưa ra mà chúng ta sẽ xem xét trong lớp học lập trình này.

Thêm các hằng số cấu hình Google Pay vào 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'
        }
      }
    }
  ]
};

Tài nguyên

  • Tài liệu tham khảo API: Tài liệu về các đối tượng yêu cầu API Google Pay
  • Tài liệu tham khảo API: Tham khảo PaymentMethod để biết thêm thông tin về các phương thức uỷ quyền được phép, các mạng thẻ được phép và thông số kỹ thuật về mã hoá, bao gồm cả giá trị cổng thích hợp.

4. Đưa ra yêu cầu thanh toán

Khi bạn nhấn nút Google Pay, một yêu cầu thanh toán sẽ được tạo và hiển thị.

Thêm thông tin thanh toán và phương thức thanh toán vào App.tsx:

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

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

5. Thêm nút Google Pay

Thư viện react-native-make-payment bao gồm một thành phần nút Google Pay gốc.

  1. Thêm lệnh nhập ở đầu App.tsx:
import { GooglePayButton, GooglePayButtonConstants, PaymentRequest } from '@google/react-native-make-payment';
  1. Thêm trình xử lý lượt nhấp bên trong thành phần 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. Thêm nút và kiểu vào JSX và kiểu của nút:
<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 sau khi thêm nút và trình xử lý:

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;

Giải thích đoạn mã

  1. paymentDetails mô tả giao dịch cần được xử lý.
  2. paymentMethods định cấu hình các phương thức được hỗ trợ; đối với Google Pay, hãy sử dụng google_pay với baseGooglePayRequest.
  3. checkCanMakePayment hiển thị trang thanh toán khi có và ghi lại phản hồi.

6. Kết luận

Chúc mừng bạn đã hoàn thành lớp học lập trình này! Bạn đã học được cách tích hợp API Google Pay vào ứng dụng React Native cho Android.

Chạy dự án

Chạy lệnh sau để bắt đầu ứng dụng:

npx react-native run-android

Nội dung tiếp theo nên tìm hiểu

Tài nguyên khác