Level 58
The error message in the code snippet suggests that the server is returning a 401 Unauthorized error. This could be due to an incorrect API key or an issue with the server's authentication.
Here are a few things to check:
- Make sure that the API key is correct and matches the one in the Firebase console.
- Check that the server's IP address is whitelisted in the Firebase console.
- Verify that the server is using the correct HTTP headers and payload format for the Firebase Cloud Messaging (FCM) API.
Here's an updated version of the code that includes error handling and logging:
$key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$data = [
"registration_ids" => $tokens,
"notification" => [
"title" => $data->title,
"body" => $data->des
]
];
$dataString = json_encode($data);
$headers = [
'Authorization: key='.$key,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
error_log("FCM request failed: $error");
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
error_log("FCM request returned HTTP code $httpCode");
return false;
}
curl_close($ch);
return $response;
This code logs any errors or HTTP status codes that are returned by the FCM API.