字段 "to" 必须是 JSON 字符串 [Firebase]

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

我正在尝试使用 cron 作业发送通知。我从 GCM 迁移到 FCM。在我的服务器端,我更改了 https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send 并更新了如何请求将 registration_ids 更改为 to 的数据。检查通过的 json 是有效的 json 但我遇到错误 Field "to" must be a JSON string。无论如何要解决这个问题?

这是我的代码

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;
}

尝试将 to 设为字符串:

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
   ...
 },
}

尝试将 $registrationIDs 显式转换为 string

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

已编辑答案

'to' 参数需要 string - 这是邮件的收件人。

$registrationIDs 可以将一个单独的参数(作为字符串数组)传递给 'registration_ids'

将您的代码编辑成如下内容:

$recipient = "YOUR_MESSAGE_RECIPIENT";

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

其中 $recipient

a registration token, notification key, or topic.

参考这个: Firebase 云消息传递 HTTP 协议

我遇到了类似的问题。事实证明,当我从我的 Firebase 数据库中检索注册令牌时(使用此 Firebase PHP Client),它在令牌的开头和结尾用双引号返回。所以我必须在使用它之前从令牌中删除第一个和最后一个字符。下面的代码解决了我的问题

substr($registrationToken, 1, -1)
// if you are using an array like
$fcm_ids = array();
$fcm_ids[] = "id_1";
$fcm_ids[] = "id_2";
$fcm_ids[] = "id_3";
//.
//.
//.
$fcm_ids[] = "id_n";
// note: limit is 1000 to send notifications to multiple ids at once.
// in your messsage send notification function use ids like this
$json_data = [
"to" => implode($fcm_ids),
"notification" => [
    "title" => $title,
    "body" => $body,
    ],
"data" => [
    "str_1" => "something",
    "str_2" => "something",
    .
    .
    .
    "str_n" => "something"
    ]
];