You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发应用内用户互拨功能:如何从Firebase Auth获取手机号

Hey there! Let's walk through exactly how to get user phone numbers from Firebase Auth and build that in-app calling feature you're working on. I'll break this down into actionable steps with code examples and options to fit your needs:

1. Retrieve User Phone Numbers from Firebase Auth

First, you need to make sure your Firebase setup supports phone number authentication—this is the foundation, since Firebase Auth only stores phone numbers for users who signed up/login with their phone.

Enable Phone Auth in Firebase Console

Head to your Firebase project's Authentication section, go to the Sign-in method tab, and enable the Phone sign-in provider. You'll also need to configure reCAPTCHA protection (Firebase handles most of this out of the box for mobile apps).

Fetch the Phone Number from the Authenticated User

Once a user is signed in, you can directly access their phone number from the FirebaseUser (Android) or User (iOS) object. Here are quick code snippets:

Android (Kotlin)

val currentUser = FirebaseAuth.getInstance().currentUser
currentUser?.phoneNumber?.let { userPhoneNumber ->
    // Store or use this number for calling logic
    Log.d("CallingService", "User's phone number: $userPhoneNumber")
} ?: run {
    // Handle case where phone number isn't available (e.g., user signed in with email)
    Toast.makeText(context, "Phone number not linked to account", Toast.LENGTH_SHORT).show()
}

iOS (Swift)

guard let currentUser = Auth.auth().currentUser, let userPhoneNumber = currentUser.phoneNumber else {
    // Show error if phone number isn't present
    let alert = UIAlertController(title: "Error", message: "Phone number not linked to your account", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    present(alert, animated: true)
    return
}
// Use userPhoneNumber for calling functionality
print("User's phone number: \(userPhoneNumber)")
2. Implement In-App Calling Using Phone Numbers

Now that you have the phone numbers, you need a way to connect users. Here are two practical approaches:

2.1 First: Map Phone Numbers to User Identifiers (Firestore Setup)

To use phone numbers for calling, you'll need a way to look up the target user's device or session info. Store user data in Firestore to create a phone number-to-user mapping:

Firestore Collection Structure

Create a users collection where each document uses the Firebase Auth UID as the document ID, with fields like:

users/
  {uid}/
    phoneNumber: "+1234567890"  // Stored in E.164 format for consistency
    fcmToken: "device-specific-fcm-token"  // For sending call notifications
    isOnline: true  // To track if the user is active in the app

Save User Data to Firestore (Android Example)

val currentUser = FirebaseAuth.getInstance().currentUser
currentUser?.let { user ->
    FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val fcmToken = task.result
            val userData = hashMapOf(
                "phoneNumber" to user.phoneNumber,
                "fcmToken" to fcmToken,
                "isOnline" to true
            )
            FirebaseFirestore.getInstance()
                .collection("users")
                .document(user.uid)
                .set(userData)
                .addOnSuccessListener { Log.d("Firestore", "User data saved successfully") }
                .addOnFailureListener { e -> Log.w("Firestore", "Error saving user data", e) }
        }
    }
}

2.2 Option A: Build a Custom Calling System with WebRTC + FCM

If you want full control, use WebRTC for peer-to-peer calls and FCM to trigger call notifications:

  1. Look up the target user: Query Firestore by phone number to get their FCM token and UID.
  2. Send a call request: Use FCM to send a notification to the target device. When the target user accepts, initiate WebRTC signaling.
  3. Exchange WebRTC signals: Use Firebase Realtime Database or Firestore real-time updates to send offer/answer messages and ICE candidates between the two devices.
  4. Establish the call: Once signals are exchanged, the WebRTC connection will handle audio/video streaming.

2.3 Option B: Use a Third-Party Calling SDK

For a faster implementation, use a third-party SDK that supports phone number-based calling (most have free tiers for testing):

  • Twilio Programmable Voice: Register users with their Firebase Auth phone numbers, then use Twilio's APIs to initiate calls between numbers.
  • Agora SDK: Integrate Agora's voice calling SDK, map Firebase phone numbers to Agora user IDs, and use their service to handle call routing and audio streaming.

The benefit here is that you don't have to maintain your own signaling servers or handle low-level WebRTC logic.

3. Critical Things to Keep in Mind
  • Privacy Compliance: Phone numbers are sensitive data—ensure you have user consent to collect and use them, and encrypt stored data. Follow regulations like GDPR or CCPA.
  • Phone Number Formatting: Always store and use numbers in E.164 format (e.g., +1234567890) to avoid mismatches between different region formats.
  • Online Status Tracking: Update the isOnline field in Firestore when the user opens/closes the app, so you can inform callers if the target is unavailable.
  • Error Handling: Handle cases like "user not found", "target offline", or "call failed" with clear user-facing messages.

内容的提问来源于stack exchange,提问作者isheunesu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:32:33