Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FCM give success but Notification is not received by android device

When I try to send push notifications via a cURL request, the response from the server indicates that I was successful but the message isn't received on the device. I have tried this with both multicast and single recipient payloads.

Here is my PHP code:

<?php
//API URL of FCM
$url = 'https://fcm.googleapis.com/fcm/send';

/*api_key available in:
Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key*/ $api_key = 'API_KEY';

$device_id = 'eE5U0IQEyTo:APA91bGplai6Bf5ko1hlW5y0oLb0WIa5JytpcuZ7B9lbIay8PNfPv2i1HMUqg1hDtPQqvhy4KLIZgyEh0BHHkfJtdX7E0Ftm-OaN23VahOoWAzjNP2QK8Se7PCibhooVG71jMPmzTHqd';

$fields = array (
    'registration_ids' => array (
            $device_id
    ),
    'data' => array (
        "title" => "test from server",
        "body" => "test lorem ipsum"
    )
);
//header includes Content type and api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);

$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);

if ($result === FALSE) 
{
die('FCM Send Error: ' . curl_error($ch));
}
else
{
    curl_close($ch);
    print_r($result);
    return $result;
}
?>    

Here is the response I get when running this code:

{
    "multicast_id": 1338828245860499776,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [{
        "message_id": "0:1578484075615332%52ec0605f9fd7ecd"
    }]
}
like image 261
shweta Avatar asked Jan 08 '20 12:01

shweta


2 Answers

Rename, "data" to "notification"

If the "notification" object is absent, the device will not show the notification in the drawer.

"data" is interpreted by the app

"notification" is interpreted by the device..

You can use both separately, but "notification" object is required if you want to show the notification.

Reference

like image 154
Chetan Bansal Avatar answered Sep 24 '22 17:09

Chetan Bansal


perfect answer @Chetan , with 'data' notification wont show, but with 'notification' it shows.

so your array should be:

$fields = array (
    'registration_ids' => array (
            $device_id
    ),
    'notification' => array (
        "title" => "test from server",
        "body" => "test lorem ipsum"
    )
);
like image 28
mwanri Avatar answered Sep 25 '22 17:09

mwanri