Home  >  Q&A  >  body text

Firebase Cloud Notification Tutorial for Sending Images Using Core PHP

This is my fcm_test.php code

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 令牌的代码结束
}

I am able to get the title and body in Android notifications, but not the image. I tried various JSON syntaxes but none worked, I can only get the text.

When I use Firebase GUI, I can get the image.

When accessing images on Flutter UI, I use the following code:

print("${widget.message?.notification?.android?.imageUrl}");

If I'm wrong, please feel free to answer. This will be very helpful.

P粉788571316P粉788571316372 days ago580

reply all(1)I'll reply

  • P粉541565322

    P粉5415653222023-09-17 09:05:22

    Here is a checklist you can try.

    1. Make sure the form you submit images to has the enctype="multipart/form-data" attribute.

    2. If you are using the API to send images, it should be
      base64_encode($image_path);

    reply
    0
  • Cancelreply