How to add phone number to existing email account?

Resolved

I have tried custom actions but i always get an error saying "Hostname match not found". i have tried it in web and iOS.

Code for sending SMS:

import 'package:firebase_auth/firebase_auth.dart';

Future<String?> sendVerificationCode(String phoneNumber) async {
  FirebaseAuth auth = FirebaseAuth.instance;
  String? verificationId;

  await auth.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    verificationCompleted: (PhoneAuthCredential credential) async {
      // Auto-resolve the SMS code if possible
      await auth.currentUser?.updatePhoneNumber(credential);
    },
    verificationFailed: (FirebaseAuthException e) {
      // Handle the error if verification fails
      print("Verification failed: ${e.message}");
    },
    codeSent: (String verId, int? resendToken) {
      // The verification code was sent successfully.
      verificationId = verId;
    },
    codeAutoRetrievalTimeout: (String verId) {
      // Auto-retrieval timeout
    },
  );

  return verificationId;
}

Code for verifying and adding to user account:

import 'package:firebase_auth/firebase_auth.dart';

// Assuming this method is called after receiving the SMS code from the user
Future<bool> linkPhoneNumberToUser(
    String verificationId, String smsCode) async {
  FirebaseAuth auth = FirebaseAuth.instance;
  // Create a PhoneAuthCredential with the code
  PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.credential(
      verificationId: verificationId, smsCode: smsCode);

  try {
    // Link the phone number to the current user
    await auth.currentUser?.linkWithCredential(phoneAuthCredential);
    return true; // Phone number linked successfully
  } catch (e) {
    print("Failed to link phone number: $e");
    return false; // Linking failed
  }
}
3 replies