这是我的 fcm_test.php 代码
foreach ($allTokens as $token) {
echo $token . "<br>";
//
// 发送 Firebase 通知到 FCM 令牌的代码开始
//
// 通知的数据有效负载
$notification = [
'title' => '通知的标题',
'body' => '这是通知的正文。',
'android' => [
'imageUrl' => 'https://blog.pushwoosh.com/blog/content/images/2021/09/Android-12-Updates-for-Push-Notification-Senders---Pushwoosh.png'
],
];
// 创建 HTTP 请求的头部
$headers = [
'Authorization: key=' . $serverKey,
'Content-Type: application/json'
];
// 创建 HTTP 请求的有效负载
$payload = [
'to' => $token,
'notification' => $notification
];
// 将有效负载转换为 JSON
$jsonPayload = json_encode($payload);
try {
// 初始化 cURL 会话
$ch = curl_init('https://fcm.googleapis.com/fcm/send');
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
// 执行 cURL 会话
$response = curl_exec($ch);
// 检查 cURL 错误
if ($response === false) {
throw new Exception('cURL 错误: ' . curl_error($ch));
}
// 打印响应(用于调试目的)
echo '响应: ' . $response . PHP_EOL;
// 关闭 cURL 会话
curl_close($ch);
// 处理响应
if ($response === false) {
throw new Exception('发送通知失败。');
} else {
echo '通知发送成功。' . "<br><br>";
}
} catch (Exception $e) {
echo '错误: ' . $e->getMessage();
}
// 发送 FCM 令牌的代码结束
}
我在 Android 通知中能够获取标题和正文,但无法获取图片。 我尝试了多种 JSON 语法,但都无效,只能获取文本。
当我使用 Firebase GUI 时,我可以获取图片。
在 Flutter UI 上访问图片时,我使用以下代码:
print("${widget.message?.notification?.android?.imageUrl}");
如果我错了,请随意回答。这将非常有帮助。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是一个你可以尝试的检查清单。
确保你提交图片的表单具有 enctype="multipart/form-data" 属性。
如果你正在使用 API 发送图片,它应该是
base64_encode($image_path);