本頁面說明如何在 Android 應用程式中開始使用 Firebase Phone Number Verification。如需這項功能的一般說明,請參閱總覽。
只要按照本頁步驟操作,即可快速開始導入 Firebase PNV 的使用者流程。為了測試,您將產生僅供測試的權杖,解析為假電話號碼。有了這個測試權杖,您就能開始在應用程式中新增 Firebase PNV,不必使用帳單帳戶或具備實體 SIM 卡的裝置。
確認應用程式的 Firebase PNV 使用者體驗符合需求後,您可以按照其他步驟將應用程式正式上線。
事前準備
如果您尚未將 Firebase 新增至 Android 專案,請先新增。
請確認應用程式符合下列規定:
- 應用程式的
minSdk為 24 (Android 7.0) 以上。 - 裝置或模擬器搭載 Android 10 (API 級別 29) 以上版本,且具備 Google Play 服務。如果是模擬器,請使用包含 Google Play 的 Android 10 以上版本系統映像檔。
- 如要在正式環境中驗證真實電話號碼,裝置必須使用支援電信業者的 SIM 卡。本頁說明的測試模式不需要實際 SIM 卡。
- 應用程式的
1. 將 Firebase PNV 程式庫新增至應用程式
在模組 (應用程式層級) Gradle 檔案 (通常是<project>/<app-module>/build.gradle.kts 或 <project>/<app-module>/build.gradle) 中,新增 Android Firebase Phone Number Verification 程式庫的依附元件。建議使用 Firebase Android BoM 控制程式庫版本管理。
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.1.0")) // Add the dependencies for the Firebase Phone Number Verification libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-pnv") }
只要使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
(替代方案) 不使用 BoM,新增 Firebase 程式庫依附元件
如果選擇不使用 Firebase BoM,則必須在依附元件行中指定每個 Firebase 程式庫版本。
請注意,如果您的應用程式使用多個 Firebase 程式庫,強烈建議您使用 BoM 管理程式庫版本,確保所有版本都相容。
dependencies { // Add the dependencies for the Firebase Phone Number Verification libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-pnv:17.0.0") }
2. 在測試模式下初始化 Firebase PNV 程式庫
在 Firebase 控制台中,依序前往「Security」(安全性) >「Phone Verification」(電話驗證) >「Settings」(設定) >「Testing」(測試) 分頁標籤。
按一下「Generate token」(產生權杖),選取國家/地區代碼,然後再次按一下「Generate token」(產生權杖),建立並複製權杖。
請將權杖提供給應用程式的偵錯版本,不要將權杖硬式編碼至原始碼。請將權杖視為憑證,不要納入版本管控。舉例來說,您可以將其新增至專案的
local.properties檔案,該檔案不會簽入版本管控:fpnv.testToken=COPIED_TOKEN_STRING然後在模組 (應用程式層級)
build.gradle.kts檔案中,將其公開為BuildConfig欄位。以下範例也會讀取FPNV_TEST_TOKEN環境變數,這在沒有local.properties檔案的 CI 伺服器上非常實用。發布子版本會取得空白值:// At the top of the file: import java.util.Properties val localProperties = Properties().apply { rootProject.file("local.properties").takeIf { it.exists() } ?.inputStream()?.use { load(it) } } val fpnvTestToken = System.getenv("FPNV_TEST_TOKEN")?.takeIf { it.isNotEmpty() } ?: localProperties.getProperty("fpnv.testToken", "") android { buildFeatures { buildConfig = true } buildTypes { debug { buildConfigField("String", "FPNV_TEST_TOKEN", "\"$fpnvTestToken\"") } release { buildConfigField("String", "FPNV_TEST_TOKEN", "\"\"") } } }在應用程式中,為每個應用程式程序啟用一次測試工作階段:
Kotlin
每次呼叫
FirebasePhoneNumberVerification.getInstance()時,都會傳回預設FirebaseApp的相同例項,因此請在所有 Firebase PNV 呼叫中使用該例項。每個應用程式程序只能呼叫
enableTestSession()一次。第二次呼叫會擲回FirebasePhoneNumberVerificationException,並顯示錯誤代碼TEST_SESSION_ALREADY_ENABLED,因此請勿從可重新建立的Activity呼叫 (例如螢幕旋轉時)。請改為從Application類別呼叫:import android.app.Application import android.util.Log import com.google.firebase.pnv.FirebasePhoneNumberVerification class MyApplication : Application() { override fun onCreate() { super.onCreate() if (!BuildConfig.DEBUG) return if (BuildConfig.FPNV_TEST_TOKEN.isEmpty()) { Log.w("MyApplication", "No Firebase PNV test token; test mode is off.") return } FirebasePhoneNumberVerification.getInstance() .enableTestSession(BuildConfig.FPNV_TEST_TOKEN) } }在應用程式資訊清單中註冊類別:
<application android:name=".MyApplication" ... >
測試權杖的存留時間為 7 天,過後必須產生新的權杖,才能啟用測試工作階段。權杖過期不會導致錯誤,直到您呼叫 getVerifiedPhoneNumber() 為止。測試權杖適用於搭載 Google Play 服務的實體裝置和模擬器,非常適合用於應用程式的使用者體驗原型設計。您也可以在 CI/CD 中使用測試權杖,但至少每 7 天要更換一次權杖。
應用程式在測試模式中取得的電話號碼權杖,會像正式版權杖一樣經過簽署,但會包含 "test_number": true 宣告。請確認正式版後端會拒絕含有這項聲明的權杖。
3. 建議做法:檢查 Firebase PNV 支援
為協助您判斷何時顯示號碼輸入 UI 或說明 UI,建議您在應用程式啟動時,檢查裝置及其 SIM 卡是否支援 Firebase PNV。這項預先檢查不需要使用者同意。您可以根據這項測試的結果,決定是否要啟動 Firebase PNV 流程,或使用其他電話號碼驗證方法,例如簡訊。
如要檢查裝置是否相容,請呼叫 getVerificationSupportInfo() 方法。測試工作階段進行期間,這個方法一律會傳回包含測試權杖單一支援項目的清單,不會與 Firebase PNV 後端聯絡。也就是說,您無法在測試模式中,執行不支援裝置的備用方案。之後,當您將應用程式投入實際工作環境時,這個方法會傳回裝置中每張 SIM 卡的結果。
Kotlin
val fpnv = FirebasePhoneNumberVerification.getInstance()
val supportInfo: Task<List<VerificationSupportResult>> = fpnv.getVerificationSupportInfo()
// Cache this value for 1 hour to avoid exceeding per-device quota.
val dcp: Task<String> = fpnv.getDigitalCredentialPayload("")
Tasks.whenAllSuccess<Any>(supportInfo, dcp)
.addOnSuccessListener { results ->
// Triggered only if BOTH tasks succeed
val supportInfo = results[0] as List<VerificationSupportResult>
val dcp = results[1] as String
if (supportInfo.any { it.isSupported() }) {
// Both checks passed. Proceed to getVerifiedPhoneNumber
// (see the next step).
}
}
.addOnFailureListener { exception ->
// Triggered if AT LEAST ONE task fails. Fallback to SMS
}
4. 啟動驗證流程
如要啟動 Firebase PNV 流程,請呼叫 getVerifiedPhoneNumber() 方法。請傳遞 Activity,因為這個方法會顯示同意畫面。如果 Context 不是 Activity (例如 Application 結構定義),則會失敗並顯示錯誤代碼 ACTIVITY_CONTEXT_REQUIRED。
Kotlin
fpnv.getVerifiedPhoneNumber(this@MainActivity)
.addOnSuccessListener { result ->
// In test mode, this phone number will have a valid country code,
// followed by all zeros.
val phoneNumber = result.getPhoneNumber() // For display only.
val token = result.getToken()
// Verification successful. Send token to your backend, which reads
// the verified phone number from it. (See Next steps.)
}
.addOnFailureListener { e ->
// Handle failures, such as the user declining consent or a network
// error.
}
getVerifiedPhoneNumber() 方法會執行整個電話號碼驗證流程,包括:
- 使用 Android Credential Manager 取得使用者同意,分享他們的電話號碼。
- 正在向 Firebase PNV 後端提出要求。
- 傳回包含裝置已驗證電話號碼的權杖 (在正式版應用程式中,這時會產生帳單)。
5. 處理錯誤
Firebase PNV 呼叫失敗時,例外狀況為 FirebasePhoneNumberVerificationException。請使用 errorCode 決定後續行動,例如在使用者拒絕同意時,改用簡訊驗證。請參閱「在 Android 上處理 Firebase PNV 錯誤」,瞭解每個錯誤代碼、發生時機和應變措施建議。
後續步驟
本頁面詳細說明如何使用統一的單一呼叫 API 整合 Firebase PNV。呼叫單一方法即可處理整個 Firebase PNV 使用者流程,包括取得使用者同意聲明,以及向 Firebase PNV 後端發出必要的網路呼叫。使用這個方法,可將整合步驟簡化為單一方法呼叫。
我們建議大多數開發人員使用這個 API。不過,如果您有程式庫無法滿足的特定需求,請參閱「自訂 Firebase Phone Number Verification 流程」頁面,瞭解如何實作自訂流程。
如果您在應用程式用戶端以外使用已驗證的電話號碼,請傳遞權杖,而非電話號碼本身,以便在使用時驗證其完整性。請參閱「驗證 Firebase PNV 權杖」。
如要讓使用者透過已驗證的電話號碼登入Firebase Authentication,請參閱「使用Firebase Phone Number Verification透過 Firebase 驗證」。
如需建構完整範例應用程式的逐步操作說明,請參閱 Firebase Phone Number Verification 程式碼研究室。
實作並測試應用程式的 Firebase PNV 流程和後端整合後,即可將應用程式投入正式環境,開始取得實際驗證的電話號碼。請參閱「升級至正式環境模式」。
如需完整的 API,請參閱 Firebase PNV API 參考資料。