Receive HTTP Response code 400 when sending HTTP Request for Firebase

37 Views Asked by At

I am writing a PHP script to trigger a push notification using firebase. I have tried many ways of doing this - but I always seem to end up with a response of 400.

Is the data I am sending correctly formatted?

function sendGCM($location, $vendor, $id) {
    $json = file_get_contents('lunchbox-c5980-firebase-adminsdk-vg6fh-a1e3d7df91.json');
    $json_data = json_decode($json,true); 
    $API_ACCESS_KEY = $json_data["private_key"];
    $notification = [
    'title' => "Your lunch is here!",
    'body' => $vendor . " has arrived at " . $location,
    //'alert' => “Lunchbox”,
    //'sound' => “default”,
    ];
    $data = [
    'title' => "Your lunch is here!",
    'body' =>$vendor . " has arrived at " . $location,
    'priority' => "high",
    'content_available' => true
    ]; 
    $fcmNotification = [
    'to' => $id,
    'notification' => $notification,
    'data' => $data,
    'priority' => 10
    ]; 
    $headers = [
    'Authorization: key=' . $API_ACCESS_KEY,
    'Content-Type: application/json'
    ];
 $fcmUrl = "https://fcm.googleapis.com/fcm/send";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_URL, $fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
$result = curl_exec($ch);
 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if ( $httpCode != 200 ){
    echo "Return code is {$httpCode} \n"
      .curl_error($ch);
  } else {
    echo "<pre>".htmlspecialchars($response)."</pre>";
  }
    curl_close($ch);
}
1

There are 1 best solutions below

0
martried On

I am not familial with the API that you are using, but I have a quick guess. Check the header definition where it says key=. This should be one of the following options, most likely Bearer:

Authorization: Basic [...]
Authorization: Digest [...]
Authorization: Bearer [...]
Authorization: ApiKey-v1 [...]
Authorization: ApiKey-v2 [...]