根据this文档,有一个字段
data
我正在尝试使用:
$fields = [
'message' => [
'token' => $deviceToken,
'notification' => [
'title' => $notifTitle,
'body' => $notifDesc
],
'data' => $data
]
];
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/bla/messages:send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch) . '<br><br>';
print($result);
这就是
$data
包含的内容:
array(11) {
["title"]=>
string(21) "Antwort auf Kommentar"
["msg"]=>
string(29) "Cornholio hat dir geantwortet"
["image"]=>
string(12) "30321555.jpg"
["notifType"]=>
string(5) "reply"
["channelID"]=>
string(21) "channel_reply_comment"
["memeID"]=>
int(20202)
["memeTitle"]=>
string(10) "meme title"
["meme"]=>
string(19) "TrlNO38.mp4"
["size"]=>
string(7) "460|818"
["commentCount"]=>
int(7)
["mentioned"]=>
int(1)
}
我收到此错误:
{“error”:{“code”:400,“message”:“'message.data[5].value'(TYPE_STRING)处的值无效,20202 “message.data[9].value”处的值无效(TYPE_STRING),7 “message.data[10].value”(TYPE_STRING) 处的值无效,1", "status": "INVALID_ARGUMENT", "details": [ { "@type": "type.googleapis.com/google.rpc. BadRequest", "fieldViolations": [ { "field": "message.data[5].value", "description": "'message.data[5].value' 处的值无效 (TYPE_STRING), 20202" }, { "field": "message.data[9].value", "description": "'message.data[9].value' (TYPE_STRING) 处的值无效,7" }, { "field": "message. data[10].value", "description": "'message.data[10].value' (TYPE_STRING) 处的值无效,1" } ] } ] } }
我能够使用旧 API 发送这样的数据,但如何使用当前 API 发送数据?
您遇到的错误是因为 FCM(Firebase 云消息传递)API 期望数据字段中的所有值都是字符串。但是,在 $data 数组中,某些值是整数(例如 memeID、commentCount 和提到的)。错误消息表明这些整数值不会自动转换为字符串,而这是 FCM API 所要求的。
要解决此问题,您需要将所有非字符串值显式转换为字符串,然后再将它们包含在数据数组中。具体方法如下:
$data = [
"title" => "Antwort auf Kommentar",
"msg" => "Cornholio hat dir geantwortet",
"image" => "30321555.jpg",
"notifType" => "reply",
"channelID" => "channel_reply_comment",
"memeID" => strval(20202), // Cast to string
"memeTitle" => "meme title",
"meme" => "TrlNO38.mp4",
"size" => "460|818",
"commentCount" => strval(7), // Cast to string
"mentioned" => strval(1) // Cast to string
];
$fields = [
'message' => [
'token' => $deviceToken,
'notification' => [
'title' => $notifTitle,
'body' => $notifDesc
],
'data' => $data
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'https://fcm.googleapis.com/v1/projects/bla/messages:send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch) . '<br><br>';
print($result);
通过使用 strval() 将整数值转换为字符串,可以确保数据字段符合 FCM API 的期望,这应该可以解决 INVALID_ARGUMENT 错误。