firebase messaging api php subscribe to topic 411 error

3.7k views Asked by At

I am trying to implement notifications into my web app. I have this php file in which I send notifications:

<?php
  function sendGCM($title,$message, $id) {
    $url = 'https://fcm.googleapis.com/fcm/send';

    $fields = array (
        'registration_ids' => array (
                $id
        ),
        "notification" => array(
            "title" => $title,
            "body" => $message,
            "click_action" => "https://google.com"
        )
    );
    $fields = json_encode ( $fields );

    $headers = array (
        'Authorization: key=' . $MY_KEY,
        'Content-Type: application/json'
    );

    $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 );

    $result = curl_exec ( $ch );
    echo $result;
    curl_close ( $ch );
  }
?>

Now what I want to do is to send a notification to a topic instead of individual ids. On this page it shows how you can subscribe an id to a topic. Here is the function I created to do that:

function createTopic($topic,$id) {
  $url = 'https://iid.googleapis.com/iid/v1/' . $id . '/rel/topics/' . $topic;
  $headers = array (
    'Authorization: key=MY_KEY'
  );
  $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 );

  $result = curl_exec ( $ch );
  echo $result;
  curl_close ( $ch );
}

I am getting this error from Google and I can't figure out what is going wrong:

  1. That’s an error.

POST requests require a Content-length header. That’s all we know.

Any help?

1

There are 1 answers

0
Bob Snyder On BEST ANSWER

The example in the documentation shows use of a Content-Length header:

https://iid.googleapis.com/iid/v1/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA/rel/topics/movies
Content-Type:application/json
Content-Length: 0
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

Add that to your request:

$headers = array (
    'Authorization: key=' . $MY_KEY,
    'Content-Length: 0'
);