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

Firebase signInWithPhoneNumber验证reCAPTCHA后未返回confirmationResult

手机号认证无法获取confirmationResult,无法接收OTP短信(测试手机号正常)

我正在尝试使用Firebase的signInWithPhoneNumber方法实现手机号认证。reCAPTCHA验证已正常完成(通过日志确认),但调用signInWithPhoneNumber后未返回confirmationResult,因此无法收到OTP短信;不过使用测试手机号可成功登录。

额外信息

  • 使用Firebase v9模块化SDK
  • 通过RecaptchaVerifier实现reCAPTCHA验证
  • Firebase控制台已启用手机号认证

相关代码

const signInWithPhone = async (phoneNumber: string): Promise<string> => {
  try {
    const normalizedPhone = phoneNumber.startsWith('+91') ? phoneNumber : `+91${phoneNumber}`;

    if (normalizedPhone === TEST_PHONE) {
      const testUserWithMethods = {
        ...TEST_USER,
        isTestUser: true
      };
      await setupTestUserData();
      localStorage.setItem('testUser', JSON.stringify(testUserWithMethods));
      setUser(testUserWithMethods as unknown as User);
      toast.success('Test account activated!');
      navigate('/profile');
      return 'test-verification-id';
    }


    // Clear any existing state
    clearRecaptcha();

    // Set up new reCAPTCHA
    const verifier = setupRecaptcha();

    // Explicitly render and wait for reCAPTCHA
    try {
      await verifier.render();
    } catch (error) {
      console.error('reCAPTCHA render error:', error);
      clearRecaptcha();
      throw new Error('Please refresh the page and try again');
    }

    // Attempt phone authentication
    const confirmationResult = await signInWithPhoneNumber(auth, normalizedPhone, verifier);

    if (!confirmationResult) {
      throw new Error('Failed to send verification code');
    }

    // Store confirmation result
    confirmationResultRef.current = confirmationResult;

    toast.success('Verification code sent!');
    return confirmationResult.verificationId;
  } catch (error: any) {
    clearRecaptcha();
    console.error('Phone sign-in error:', error);

    // Handle specific error cases
    if (error.code === 'auth/invalid-app-credential' ||
        error.message?.includes('reCAPTCHA')) {
      throw new Error('Please refresh the page and try again');
    }

    const errorMessages = {
      'auth/invalid-phone-number': 'Invalid phone number format',
      'auth/quota-exceeded': 'SMS quota exceeded. Please try again later',
      'auth/captcha-check-failed': 'Security check failed. Please refresh and try again',
      'auth/network-request-failed': 'Network error. Please check your connection',
      'auth/too-many-requests': 'Too many attempts. Please try again later'
    } as const;

    const message = errorMessages[error.code as keyof typeof errorMessages] ||
        error.message ||
        'Failed to send verification code';

    throw new Error(message);
  }
};

Firebase控制台设置截图

Firebase控制台手机号认证设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:02:25