Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field "to" must be a JSON string [Firebase]

I'm trying to send notification using a cron job. I migrated from GCM to FCM. In my server side, I changed https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and also updated on how to request the data changing registration_ids to to. Checking the json passed it is a valid json but I'm having an error Field "to" must be a JSON string. Is there anyway to solve this?

Here is my code

function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {


    $headers = array(
            'Content-Type:application/json',
            'Authorization:key=' . $apiKey
    );

    $message = array(
            'to' => $registrationIDs,
            'data' => array(
                    "message" => $messageText,
                    "id" => $id,
            ),
    );


    $ch = curl_init();

    curl_setopt_array($ch, array(
            CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => json_encode($message)
    ));

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}
like image 708
natsumiyu Avatar asked Jun 01 '16 06:06

natsumiyu


1 Answers

Try explicitly converting $registrationIDs to string.

$message = array(
        'to' => (string)$registrationIDs,
        'data' => array(
                "message" => $messageText,
                "id" => $id,
        ),
);

Edited Answer

The 'to' parameter requires a string - which is the recipient of the message.

The $registrationIDs could be passed a separate parameter (as string array) to 'registration_ids'

Edit your code to something like this:

$recipient = "YOUR_MESSAGE_RECIPIENT";

$message = array(
        'to' => $recipient,
        'registration_ids' => $registrationIDs,
        'data' => array(
                "message" => $messageText,
                "id" => $id,
        ),
);

Where $recipient is

a registration token, notification key, or topic.

Refer this: Firebase Cloud Messaging HTTP Protocol

like image 67
jayeshsolanki93 Avatar answered Sep 20 '22 12:09

jayeshsolanki93