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

Laravel+React Native集成FCM推送:iOS端无效参数错误求助

Laravel + React Native FCM推送异常:Android正常,iOS报「Request contains an invalid argument」错误

问题描述

项目基于Laravel和React Native开发,Android端可正常接收FCM推送通知,但仅更换iOS设备的FCM Token调用相同推送函数时,Laravel日志中出现「Firebase send error: Request contains an invalid argument」错误,尝试多种方案未解决。

Laravel端推送代码

function sendFirebaseNotification($to, $title, $body, $data = [])
{
    try {
        $factory = (new Factory)->withServiceAccount(config('firebase.credentials'));
        $messaging = $factory->createMessaging();
        $message = [
            'token' => $to,
            'notification' => [
                'title' => $title,
                'body' => $body,
            ],
            'data' => $data,
        ];

        try {
            $messaging->send($message);
            return true;
        } catch (\Exception $e) {
            Log::error('Firebase send error: ' . $e->getMessage());
            return false;
        }
    } catch (\Exception $e) {
        Log::error('Firebase configuration error: ' . $e->getMessage());
        return false;
    }
}

public function sendNotification()
{
    $fcm_token = "***";
    $title = "title";
    $body = "body";
    $data = [
        'key' => 'value',
    ];
    $response = $this->sendFirebaseNotification($fcm_token, $title, $body, $data);
    Log::info($response);
    if ($response) {
        return response()->json(['success' => 'Notification sent successfully']);
    } else {
        return response()->json(['error' => 'Notification not sent'], 500);
    }
    return response()->json(['success' => 'Notification sent successfully']);
}

React Native端配置代码

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import firebase from '@react-native-firebase/app';
import {
  checkInitialNotification,
  onBackgroundMessageHandler,
  onMessageListener,
  onNotificationOpenedApp,
  registerAppWithFCM,
} from './src/messagingHandler';
import messaging from '@react-native-firebase/messaging';

AppRegistry.registerComponent(appName, () => App);

const firebaseConfig = {
  apiKey: '**********',
  authDomain: '********',
  databaseURL: '**********',
  projectId: '***********',
  storageBucket: '**********',
  messagingSenderId: '*********',
  appId: '***********',
  measurementId: '**********',
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

PushNotification.createChannel({
  channelId: 'fcm_fallback_notification_channel',
  channelName: 'Default Channel',
});

PushNotification.configure({
  onNotification: function (notification) {
    console.log('NOTIFICATION:', notification);

    if (notification.userInteraction) {
      navigationRef.current?.navigate(notification.data.stack.toString(), {
        screen: notification.data.screen,
        params: notification.data.params,
      });
    }
  },

  popInitialNotification: true,
  requestPermissions: true,
});

AppRegistry.registerComponent(appName, () => App);

registerAppWithFCM();

onMessageListener(remoteMessage => {
  console.log('Foreground message received:', remoteMessage);
  PushNotification.localNotification({
    channelId: 'fcm_fallback_notification_channel',
    title: remoteMessage.notification.title,
    message: remoteMessage.notification.body,
    data: remoteMessage.data,
  });
});

onNotificationOpenedApp();

checkInitialNotification();

onBackgroundMessageHandler();

可能的原因及解决方案

1. iOS FCM Token有效性验证

  • 直接在Firebase控制台「Cloud Messaging」模块,使用该iOS Token测试推送,如果控制台也失败,说明Token无效。此时需要检查React Native端Token获取逻辑,确保调用messaging().getToken()获取的是最新有效Token。
  • 确认iOS设备的APNs证书是否有效:Firebase依赖APNs推送iOS设备,证书过期、Bundle ID不匹配、未正确配置都会导致Token失效。

2. 推送消息格式适配iOS要求

  • iOS对FCM的data字段有严格要求:必须是字符串键值对,不能包含嵌套对象或非字符串类型值。修改Laravel端data构造,确保所有值转为字符串:
$data = [
    'key' => (string) 'value',
    // 其他字段同理强制转为字符串
];
  • 检查notification字段的title/body是否包含特殊字符(如emoji或未转义的符号),尝试使用纯文本测试。

3. Firebase SDK与权限配置

  • 更新Laravel的Firebase PHP SDK到最新稳定版:
composer update kreait/firebase-php
  • 确认Firebase服务账号(config('firebase.credentials')对应的JSON文件)拥有「Cloud Messaging Admin」角色,登录Firebase控制台「项目设置-服务账号」查看权限。

4. React Native iOS端FCM配置检查

  • 验证GoogleService-Info.plist是否正确添加到iOS项目的「Copy Bundle Resources」中,且文件中的Bundle ID与Xcode项目的Bundle ID完全一致。
  • 检查react-native-firebase系列依赖版本是否兼容,避免版本冲突导致Token获取异常。
  • 确认iOS设备已授予推送权限:在设备「设置-通知」中检查对应APP的推送权限是否开启,代码中requestPermissions: true仅会发起请求,需用户实际授权。

5. 针对iOS添加APNs专属配置

  • 在Laravel的推送消息中添加apns字段,适配iOS推送规则,比如开启静默推送支持或配置通知优先级:
$message = [
    'token' => $to,
    'notification' => [
        'title' => $title,
        'body' => $body,
    ],
    'data' => $data,
    'apns' => [
        'payload' => [
            'aps' => [
                'content-available' => 1,
                'sound' => 'default',
                'badge' => 1,
            ],
        ],
    ],
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:15:00