7

我正在尝试使用 cron 作业发送通知。我从 GCM 迁移到 FCM。在我的服务器端,我更改https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send并更新了如何请求将数据更改registration_idsto. 检查传递的 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;
}
4

4 回答 4

10

尝试显式转换$registrationIDsstring.

$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在哪里

注册令牌、通知键或主题。

请参阅: Firebase 云消息传递 HTTP 协议

于 2016-06-01T06:24:11.833 回答
2

尝试将 to 作为字符串:

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

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
   ...
 },
}
于 2016-06-01T06:23:35.620 回答
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"
    ]
];
于 2019-03-27T05:34:49.167 回答
0

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

substr($registrationToken, 1, -1)
于 2017-03-05T17:40:50.963 回答