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

Laravel 10使用Firebase发送OTP报错:无效目标类型'phone_number'

问题描述

在Laravel 10应用中尝试通过Firebase向手机号发送OTP,已完成Firebase集成并遵循官方文档,但发送时触发如下错误:

Invalid target type 'phone_number', valid types: condition, token, topic, unknown

错误详情:

"message": "Invalid target type 'phone_number', valid types: condition, token, topic, unknown",
"exception": "Kreait\Firebase\Exception\InvalidArgumentException",
"file": "C:\xampp\htdocs\daralaman-api\server\vendor\kreait\firebase-php\src\Firebase\Messaging\MessageTarget.php",
"line": 58,
"trace": [
相关控制器代码
class OtpRegisterController extends Controller
{
    public function register(Request $request)
    {
        // 验证请求数据
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'phone_number' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 400);
        }

        // 生成随机OTP
        $otp = mt_rand(100000, 999999);

        // 创建用户记录
        $user = User::create([
            'name' => $request->input('name'),
            'phone_no' => $request->input('phone_number'),
        ]);

        // 设置OTP过期时间(2分钟后)
        $expiresAt = Carbon::now()->addMinutes(2); 

        // 存储OTP到数据库
        UserOtp::create([
            'user_id' => $user->id,
            'otp' => $otp,
            'expires_at' => $expiresAt,
        ]);

        // 初始化Firebase消息服务
        $factory = (new Factory)->withServiceAccount(storage_path('firebase/serviceAccountKey.json'));
        $messaging = $factory->createMessaging();

        // 构建消息
        $message = CloudMessage::withTarget('phone_number', $request->input('phone_number'))
            ->withNotification(Notification::create('OTP', "Your OTP is: $otp"))
            ->withData(['otp' => $otp]);

        // 发送消息
        $messaging->send($message);

        return response()->json(['message' => 'OTP sent successfully']);
    }
}
报错原因及解决方法

原因

你当前使用的kreait/firebase-php版本不支持phone_number作为消息目标类型。早期版本的FCM PHP SDK仅支持condition、token、topic三种目标类型,直接通过手机号发送消息的功能是后续版本新增的特性。

解决步骤

  • 升级SDK版本
    打开项目根目录的composer.json,将kreait/firebase-php的版本更新至支持手机号目标的版本(推荐最新稳定版),然后执行:

    composer update kreait/firebase-php
    
  • 修正手机号格式
    即使版本支持,手机号必须符合E.164标准格式(例如+8613800138000),不能仅传数字串。修改代码中的手机号处理逻辑:

    // 示例:为手机号添加中国国家码,根据实际地区调整
    $formattedPhone = "+86" . $request->input('phone_number');
    
    $message = CloudMessage::withTarget('phone_number', $formattedPhone)
        ->withNotification(Notification::create('OTP', "你的OTP验证码是:$otp"))
        ->withData(['otp' => $otp]);
    
  • 检查Firebase项目配置
    确保你的Firebase项目已启用电话认证功能,并且服务账号拥有messaging.send的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 06:37:05