開始在 Android 上使用 Firebase 電話號碼驗證

本頁面說明如何在 Android 應用程式中使用 Firebase Phone Number Verification。如需這項功能的概略說明,請參閱總覽

本頁面詳細說明如何使用統一的單一呼叫 API,與 Firebase PNV 整合。呼叫單一方法即可處理整個 Firebase PNV 使用者流程,包括取得使用者同意聲明,以及對 Firebase PNV 後端發出必要的網路呼叫。使用這個方法可將整合步驟簡化為單一方法呼叫。

建議大多數開發人員使用這個 API。不過,如果程式庫無法滿足您的特定需求,請參閱「自訂 Firebase Phone Number Verification 流程」頁面,瞭解如何實作自訂流程。

事前準備

您必須在公開網站上發布應用程式的隱私權政策。您必須在這份頁面中,向使用者說明您如何使用透過 Firebase Phone Number Verification 擷取的電話號碼。當 Firebase PNV 程式庫要求使用者同意與您的應用程式分享電話號碼時,會連結至這個頁面。

1. 設定 Firebase 專案

  1. 如果您尚未將 Firebase 新增至 Android 專案,請先新增。

  2. Firebase PNV需要 Blaze 方案。如果尚未將專案升級至即付即用 Blaze 定價方案,請先完成升級。

    雖然 Firebase PNV 需要將帳單帳戶附加至 Firebase 專案,但在預先發布階段,您不會因使用這項服務而產生費用。

  3. 如果您尚未在 Firebase 控制台中指定應用程式的 SHA-256 指紋,請從「專案設定進行設定。如要瞭解如何取得應用程式的 SHA-256 指紋,請參閱「驗證用戶端」。

  4. 在 Google Cloud 控制台中開啟 Firebase 專案,然後啟用 Firebase Phone Number Verification API

  5. 在控制台的「憑證」頁面中,開啟 Android API 金鑰,然後將 Firebase Phone Number Verification API 新增至所選 API 清單。

2. 將 Firebase PNV 程式庫新增至應用程式

模組 (應用程式層級) Gradle 檔案 (通常為 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle) 中,新增 Android 適用的 Firebase Phone Number Verification 程式庫依附元件。

dependencies {
    // Add the dependency for the Firebase Phone Number Verification library
    implementation("com.google.firebase:firebase-pnv:16.0.0-beta01")
}

3. 選用:檢查 Firebase PNV 支援情形

啟動驗證流程前,您可以先檢查裝置和 SIM 卡是否支援以 API 為基礎的電話號碼驗證。這是預先檢查,不需要使用者同意。您可以根據這項測試的結果,決定是否啟動 Firebase PNV 流程,或使用其他電話號碼驗證方法,例如簡訊。

如要檢查裝置是否相容,請呼叫 getVerificationSupportInfo() 方法:

Kotlin

import com.google.firebase.pnv.FirebasePhoneNumberVerification
// Get an instance of the SDK.
val fpnv = FirebasePhoneNumberVerification.getInstance()

// Check all SIMs for support.
fpnv.getVerificationSupportInfo()
  .addOnSuccessListener { results ->
    if (results.any { it.isSupported() }) {
      // At least one SIM is supported; proceed with FPNV flow
    } else {
      // No SIMs are supported, so fall back to SMS verification.
    }
  }
  .addOnFailureListener { e ->
    // Handle error.
  }

getVerificationSupportInfo() 會傳回 VerificationSupportResult 物件的清單,每個 SIM 卡插槽對應一個物件。如果至少支援一張 SIM 卡,即可繼續進行 Firebase PNV 流程。

4. 啟動驗證流程

如要啟動 Firebase PNV 流程,請建立 FirebasePhoneNumberVerification 的新例項,並傳遞 Activity 內容。SDK 必須有Activity內容,才能向使用者顯示同意畫面。然後呼叫物件的 getVerifiedPhoneNumber() 方法:

Kotlin

// Get an instance of the SDK _with an Activity context_:
val fpnv = FirebasePhoneNumberVerification.getInstance(this@MainActivity)

// Call getVerifiedPhoneNumber
fpnv.getVerifiedPhoneNumber("https://example.com/privacy-policy")
  .addOnSuccessListener { result ->
    val phoneNumber = result.getPhoneNumber()
    val token = result.getToken()
    // Verification successful. Send token to your backend.
  }
  .addOnFailureListener { e ->
    // Handle failures, such as the user declining consent or a network error.
  }

getVerifiedPhoneNumber() 方法會執行完整的電話號碼驗證流程,包括:

  • 使用 Android 認證管理工具取得使用者同意聲明,允許分享電話號碼。
  • Firebase PNV 後端發出要求。
  • 傳回裝置的已驗證電話號碼。

5. 使用 Firebase PNV 權杖

如果流程成功,getVerifiedPhoneNumber() 方法會傳回已驗證的電話號碼,以及包含該號碼的簽署權杖。您可以在應用程式中使用這項資料,但必須遵守隱私權政策的規定。

如果您在應用程式用戶端以外使用已驗證的電話號碼,請傳遞權杖,而非電話號碼本身,以便在使用時驗證完整性。如要驗證權杖,可以使用任何 JWT 驗證程式庫。使用程式庫驗證下列所有項目:

  • 權杖是使用 Firebase PNV JWKS 端點發布的金鑰簽署:

    https://fpnv.googleapis.com/v1beta/jwks
    
  • 對象和簽發者聲明包含 Firebase 專案編號,格式如下:

    https://fpnv.googleapis.com/projects/FIREBASE_PROJECT_NUMBER
    

    您可以在 Firebase 主控台的「專案設定」頁面中找到 Firebase 專案編號。

  • 權杖尚未過期。

範例

以下是簡單範例,說明 Express.js 應用程式如何從 HTTP POST 要求接收 Firebase PNV 權杖,並使用 JWT 驗證程式庫檢查權杖的簽名和聲明:

Node.js

import express from "express";
import { JwtVerifier } from "aws-jwt-verify";

// Find your Firebase project number in the Firebase console.
const FIREBASE_PROJECT_NUMBER = "123456789";

// The issuer and audience claims of the FPNV token are specific to your
// project.
const issuer = `https://fpnv.googleapis.com/projects/${FIREBASE_PROJECT_NUMBER}`;
const audience = `https://fpnv.googleapis.com/projects/${FIREBASE_PROJECT_NUMBER}`;

// The JWKS URL contains the current public signing keys for FPNV tokens.
const jwksUri = "https://fpnv.googleapis.com/v1beta/jwks";

// Configure a JWT verifier to check the following:
// - The token is signed by Google
// - The issuer and audience claims match your project
// - The token has not yet expired (default behavior)
const fpnvVerifier = JwtVerifier.create({ issuer, audience, jwksUri });

const app = express();

app.post('/verifiedPhoneNumber', async (req, res) => {
    if (!req.body) return res.sendStatus(400);
    // Get the token from the body of the request.
    const fpnvToken = req.body;
    try {
        // Attempt to verify the token using the verifier configured above.
        const verifiedPayload = await fpnvVerifier.verify(fpnvToken);

        // If verification succeeds, the subject claim of the token contains the
        // verified phone number. You can use this value however it's needed by
        // your app.
        const verifiedPhoneNumber = verifiedPayload.sub;
        // (Do something with it...)

        return res.sendStatus(200);
    } catch {
        // If verification fails, reject the token.
        return res.sendStatus(400);
    }
});

app.listen(3000);

登入 Firebase 應用程式

如要查看在 Firebase Authentication 登入流程中使用 Firebase PNV 權杖的範例,請參閱「使用 Firebase Phone Number Verification 透過 Firebase 驗證」頁面。