React Native đăng nhập bằng Google (Quick tutorial)

Bài viết này sẽ hướng dẫn nhanh các bước cài đặt ứng dụng React Native đăng nhập bằng tài khoản Google.

Khởi tạo ứng dụng React Native.

npx react-native init ExampleApp
Need to install the following packages:
  react-native
Ok to proceed? (y) y

Cài đặt thư viện https://github.com/react-native-google-signin/google-signin

yarn add @react-native-google-signin/google-signin

Tạo ứng dụng trên Firebase


Truy cập https://console.firebase.google.com/ và nhấn Create a project, sau đó điền các thông tin liên quan tới ứng dụng (Project name) và chờ cho tới khi quá trình tạo thành công.

Tạo file google-services cho Android và iOS:

Thao tác này sẽ gần giống nhau cho cả Android và iOS. Chọn vào biểu tượng iOS hoặc Android.

Điền các thông tin liên quan đến ứng dụng.

Đối với Android, trường SHA-1 lấy bằng cách:

cd android && ./gradlew signingReport

Xem thêm thông tin hướng dẫn cho android tại: https://github.com/react-native-google-signin/google-signin/blob/master/docs/android-guide.md

Sau khi nhấn Register app xong, đối với Android ta sẽ có file google-services.jsoniOS sẽ là file GoogleService-Info.plist.

Tải các file trên để cài đặt vào trong ứng dụng của bạn.

Dành cho Android
Dành cho iOS

Kích hoạt tính năng đăng nhập bằng Google


Tại màn hình chính (Project Overview) chọn mục Authentication

Chọn Sign-in method và chọn Google

Bật chế độ kích hoạt sử dụng (Enable), điền thông tin email trong trường hợp cần hỗ trợ và nhấn Save.

Như vậy là đã hoàn tất các bước cài đặt ứng dụng React Native đăng nhập bằng Google.

import { GoogleSignin } from '@react-native-google-signin/google-signin';

GoogleSignin.configure({
  webClientId: '', // lấy nhanh từ file google-services: trường client_id và client_type = 3
  offlineAccess: false,
});

// import statusCodes along with GoogleSignin
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';

// Somewhere in your code
signIn = async () => {
  try {
    await GoogleSignin.hasPlayServices();
    const userInfo = await GoogleSignin.signIn();
    this.setState({ userInfo });
  } catch (error) {
    if (error.code === statusCodes.SIGN_IN_CANCELLED) {
      // user cancelled the login flow
    } else if (error.code === statusCodes.IN_PROGRESS) {
      // operation (e.g. sign in) is in progress already
    } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
      // play services not available or outdated
    } else {
      // some other error happened
    }
  }
};

Xem thông tin của thư viện ở: https://github.com/react-native-google-signin/google-signin