-1

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."

  • Try removing `curl_setopt($ch, CURLOPT_POST, json_encode(null));` Not sure what sense that was supposed to make to begin with, this option expects a true/false value. – CBroe Mar 17 '23 at 13:55
  • Thanks @CBroe - I tweaked the code as you suggested, but still no luck. Tried every permutation and combination at this point. Also updated code above to be more in line with other posts, but it doesn't work – Dhwanit Zaveri Mar 18 '23 at 09:58

1 Answers1

0

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