I am trying to send notifications to devices using FCM. On the server-side, i have got the authorisation token through the FCM Admin SDK in python ($auth_token
), and the device $token
. On running the code, I get the following function:
function sendNotification($token, $title,$body){
$command = escapeshellcmd('/usr/bin/python3 api/fcm.py');
$auth_token = shell_exec($command);
// set request data
$request_data = array(
'message' => array(
'token' => $token,
'notification' => array(
'body' => $body,
'title' => $title
)
)
);
$fields = json_encode($request_data);
$request_length = strlen($fields);
print($request_length);
// set headers
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $auth_token,
'Content-Length: '. $request_length
);
$url = 'https://fcm.googleapis.com/v1/projects/black-queen/8eff3/messages:send';
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$result = curl_exec ( $ch );
echo $result;
// check for errors
if(curl_errno($ch)) {
print('Error: ' . curl_error($ch));
}
// close cURL session
curl_close($ch);
// print response
print($response);
}
However, I am getting the following error: "411. That’s an error. POST requests require a Content-length header. That’s all we know."
In case anyone else faces this issue, the issue on my end was white space. I put trim()
around all the header inputs (in particular the $auth_token
for me) which fixed it