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 tối thiểu có thể hoạt động với tính năng tích hợp Google Pay 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 gốc 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 công khai, bạn sẽ cần có một merchantId Google Pay. Bạn chỉ mất một phút để đăng ký tại Google Pay & Wallet Console, vậy nên bạn có thể thực hiện ngay bây giờ.

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 rồi thay thế nội dung bằng đoạn 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 vào 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 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 của Google Pay API
  • Tài liệu tham khảo về 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, mạng thẻ được phép và quy cách mã hoá bao gồm cả giá trị cổng phù hợp.

4. Tạo yêu cầu thanh toán

Khi người dùng nhấn vào 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 vào 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 cũng như 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 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 cho thấy 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 đã tìm hiểu cách tích hợp Google Pay API vào một ứng dụng gốc React Native cho Android.

Chạy dự án

Chạy lệnh sau để khởi động ứ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