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

标签 php android json firebase firebase-cloud-messaging

我正在尝试使用 cron 作业发送通知。我从 GCM 迁移到 FCM。在我的服务器端,我将 https://android.googleapis.com/gcm/send 更改为 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;
}

最佳答案

尝试将 $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 Cloud Messaging HTTP Protocol

关于php - 字段 "to"必须是 JSON 字符串 [Firebase],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37560767/

相关文章:

android - 带有 SwipeToDismiss 的 LazyColumn

android - setLayoutParams 弄乱了 RelativeLayout

java - 抽象类中的 Rest JSON POST 未编码 unmarshall 通用参数错误 400

java - 字符串数组列表转 JSON

php - 使用 ON DUPLICATE KEY UPDATE 更新表时出错

php - 如何检查复选框是否已选中,并执行必要的查询来更新相应的表?

Android Gallery 应用加载速度很慢

c# - JSON.net反序列化对象嵌套数据

php - 显示通过搜索查询找到的列

php - 上次更新的行 php 脚本中的 Mysql-空查询错误