Core PHP集成FCM推送通知图片无法显示问题求助
FCM推送通知图片无法加载的解决方法
问题背景
使用Core PHP开发FCM推送通知功能,标题和正文可在Android设备正常显示,但图片无法加载;通过Firebase GUI发送时图片显示正常,Flutter端尝试通过${widget.message?.notification?.android?.imageUrl}获取图片URL。
问题原因
你当前在notification字段下直接嵌套android.imageUrl的写法不符合FCM的规范,标准的通知图片字段需要放在notification根节点(跨平台)或android.notification子节点(Android专属)中,也可通过data字段自定义传递。
解决方法
以下三种方案任选其一:
方案1:使用跨平台
image字段
在notification根节点直接添加image字段,FCM会自动适配Android和iOS的图片展示逻辑:$notification = [ 'title' => 'Title of the notification new', 'body' => 'This is the body of the notification.', 'image' => 'https://blog.pushwoosh.com/blog/content/images/2021/09/Android-12-Updates-for-Push-Notification-Senders---Pushwoosh.png' ];方案2:使用Android专属嵌套结构
若需针对Android单独配置,需将图片字段放在android.notification子节点下:$notification = [ 'title' => 'Title of the notification new', 'body' => 'This is the body of the notification.', 'android' => [ 'notification' => [ 'imageUrl' => 'https://blog.pushwoosh.com/blog/content/images/2021/09/Android-12-Updates-for-Push-Notification-Senders---Pushwoosh.png' ] ] ];方案3:通过
data字段自定义传递
若需要Flutter端手动处理图片展示,可将图片URL放在data字段中,客户端从message.data中读取:$payload = [ 'to' => $token, 'notification' => [ 'title' => 'Title of the notification new', 'body' => 'This is the body of the notification.' ], 'data' => [ 'imageUrl' => 'https://blog.pushwoosh.com/blog/content/images/2021/09/Android-12-Updates-for-Push-Notification-Senders---Pushwoosh.png' ] ];
修正后的完整代码示例(方案1)
foreach ($allTokens as $token) { echo $token . "<br>"; // 发送FCM通知的代码开始 $notification = [ 'title' => 'Title of the notification new', 'body' => 'This is the body of the notification.', 'image' => 'https://blog.pushwoosh.com/blog/content/images/2021/09/Android-12-Updates-for-Push-Notification-Senders---Pushwoosh.png' ]; $headers = [ 'Authorization: key=' . $serverKey, 'Content-Type: application/json' ]; $payload = [ 'to' => $token, 'notification' => $notification ]; $jsonPayload = json_encode($payload); try { $ch = curl_init('https://fcm.googleapis.com/fcm/send'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload); $response = curl_exec($ch); if ($response === false) { throw new Exception('cURL error: ' . curl_error($ch)); } echo 'Response: ' . $response . PHP_EOL; curl_close($ch); if ($response === false) { throw new Exception('Failed to send notification.'); } else { echo 'Notification sent successfully.' . "<br><br>"; } } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } // 发送FCM通知的代码结束 }
内容的提问来源于stack exchange,提问作者sumit ace360
相关产品推荐
相关产品推荐

