You need to enable JavaScript to run this app. 如何在Firebase中用手机号和密码创建用户?createUserWithPhoneAndPassword无法使用怎么办?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase中用手机号和密码创建用户?createUserWithPhoneAndPassword无法使用怎么办?

问题核心原因

Firebase 身份认证服务没有提供createUserWithPhoneAndPassword这个原生API,这是你调用后无返回的根本原因。createUserWithEmailAndPassword是官方原生支持的邮箱+密码注册接口,手机号注册的原生逻辑走短信OTP验证流程,不支持直接传入密码注册。

两种可行实现方案

方案1:模拟手机号+密码注册(适配你原有代码逻辑,改动最小)

你可以将用户输入的手机号拼接为自定义邮箱格式,复用原有邮箱+密码的注册逻辑,示例如下:

const sendOTP=(e)=>{
  e.preventDefault();
  // 把手机号拼接为自定义邮箱格式,后缀不需要是真实存在的域名
  const fakeEmail = `${values.phone}@yourapp.local`
  firebase.auth().createUserWithEmailAndPassword(fakeEmail, values.password).then((u)=>{
      // 注册成功后可以把手机号、用户名写入用户资料
      return u.user.updateProfile({
        displayName: values.name,
        phoneNumber: values.phone
      })
  }).then(()=>{
    console.log('注册成功')
  }).catch((err)=>{
      console.log(err);
  })
}

后续用户登录时,同样把输入的手机号拼接为相同格式的邮箱,调用signInWithEmailAndPassword即可实现手机号+密码登录。

方案2:走官方原生手机号OTP注册流程

如果需要严格使用官方手机号认证逻辑,按以下步骤修改:

  1. 先初始化reCAPTCHA验证,添加到组件中:
import {useEffect} from 'react'

// 组件内添加useEffect初始化reCAPTCHA
useEffect(()=>{
  window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha', {
    'size': 'normal',
    'callback': (response) => {
      // reCAPTCHA验证通过后可调用发送短信接口
    }
  });
  window.recaptchaVerifier.render()
},[])
  1. 修改sendOTP方法发送验证码:
const sendOTP=(e)=>{
  e.preventDefault();
  const phoneNumber = values.phone;
  const appVerifier = window.recaptchaVerifier;
  firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
    .then((confirmationResult) => {
      // 保存验证结果,后续用来验证OTP
      window.confirmationResult = confirmationResult;
      // 这里弹出OTP输入框让用户填写收到的短信验证码,实际项目可替换为自定义弹窗组件
      const otp = prompt('请输入收到的6位验证码')
      return confirmationResult.confirm(otp)
    }).then((result) => {
      // 注册/登录成功,给用户设置密码
      return result.user.updatePassword(values.password)
    }).then(()=>{
      console.log('注册成功')
    }).catch((error) => {
      console.log(error)
    });
}

注意:原生流程下用户首次登录是靠短信OTP,设置密码后后续可以用方案1的方式实现手机号+密码登录,或者使用自定义令牌登录。

额外注意事项

  • 手机号要符合E.164格式,也就是要带国家码,比如+9779812345678,不能有横杠等特殊字符,否则会调用失败。
  • 你当前代码中手机号输入框用了type="number",会导致无法输入+号等国家码前缀,建议改为type="tel"。
  • 要在Firebase控制台开启手机号登录的权限,否则接口会返回权限错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 08:54:09