Laravel 7.0.1中Firebase推送通知失效,报DeprecatedApi错误求助
排查Laravel 7.0.1中FCM推送通知突然失效的问题
问题背景
使用Laravel 7.0.1版本,未修改代码及Firebase配置,但推送通知服务突然失效,以下是相关代码及错误信息。
发送通知函数代码
function sendNotification($data) { $url = 'https://fcm.googleapis.com/fcm/send'; $serverKey = getenv('FIREBASE_SERVERKEY'); $encodedData = json_encode($data); $headers = [ 'Authorization:key=' . $serverKey, 'Content-Type: application/json', ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Disabling SSL Certificate support temporarly curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData); // Execute post $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } // Close connection curl_close($ch); // Decode the result $response = json_decode($result, true); // Check for errors in the FCM response if (isset($response['error'])) { die('FCM error: ' . $response['error']); } // Optionally, print the entire response for debugging dd($response); return true; }
错误响应信息
array:5 [ // app/Http/Controllers/Api/BaseController.php:254 "multicast_id" => 830795794971026898 "success" => 0 "failure" => 1 "canonical_ids" => 0 "results" => array:1 [ 0 => array:1 [ "error" => "DeprecatedApi" ] ] ]
排查及解决方法
错误原因
你调用的FCM旧端点 https://fcm.googleapis.com/fcm/send 已被Google官方弃用,因此返回DeprecatedApi错误,导致推送失败。Google在2024年6月12日之后停止了对该旧端点的支持。
解决方案
方案一:迁移到FCM v1 API(推荐)
FCM v1 API是当前官方支持的标准接口,安全性和功能更完善,步骤如下:
- 在Firebase控制台生成服务账号密钥(JSON格式),将密钥文件放置在Laravel项目的
config目录下。 - 安装Firebase Admin SDK的Laravel集成包:
composer require kreait/laravel-firebase - 在
.env文件中添加服务账号密钥的路径:FIREBASE_CREDENTIALS=config/firebase-service-account.json - 修改发送通知的函数,使用SDK发送:
use Kreait\Firebase\Messaging\CloudMessage; use Kreait\Firebase\Messaging\Notification; use Kreait\Laravel\Firebase\Facades\Firebase; function sendNotification($data) { $messaging = Firebase::messaging(); // 根据原$data结构调整消息构建逻辑 $message = CloudMessage::withTarget('token', $data['to']) ->withNotification(Notification::create( $data['notification']['title'], $data['notification']['body'] )) ->withData($data['data'] ?? []); try { $response = $messaging->send($message); dd($response); return true; } catch (\Exception $e) { die('FCM错误: ' . $e->getMessage()); } }
方案二:临时使用Legacy HTTP API(不推荐)
虽然旧端点已被弃用,但部分项目可能暂时需要过渡,需确认Firebase项目中Legacy API是否仍被允许(Google会逐步完全关闭),同时确保使用正确的认证方式,但该方案无法长期保障服务可用性,建议尽快迁移到v1 API。
额外注意事项
- 确保Firebase服务账号拥有
Cloud Messaging Admin角色权限,避免权限不足导致的错误。 - 检查设备推送令牌是否有效,令牌过期也会导致推送失败,可配合FCM的反馈机制清理无效令牌。
内容的提问来源于stack exchange,提问作者umang primocys
相关产品推荐
相关产品推荐

