Search code examples
phpvonage

NEXMO: Content type error while sending a message to facebook via nexmo


Hullo Geeks, am trying to intergrate nexmo facebook-messager massaging api to my application using PHP However, after submiting my data, i get this error

{"title":"Content type 'application/x-www-form-urlencoded' not supported for bodyType=com.nexmo.chatapp.sandbox.messages.Message"}

Here is the code

$message = array(
            "from" => array("type" => "messenger", "id" => "107XXXXXXXX"),
            "to" => array("type" => "messenger", "id" => $FB_RECIPIENT_ID),
            "message" => array("content" => array(
                "type" => "text",
                "text" => "This is a Facebook Messenger Message sent from the Messages API. Ashan, please enjoy"
            )
            )
        );

    $message = json_encode($message);

    //echo $message; die();
    $ch = curl_init();
    $url = "https://messages-sandbox.nexmo.com/v0.1/messages";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_USERNAME, "7af532c1:lWk9QFKaaGFgLz6u");
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, "Content-Type: application/json");
    curl_setopt($ch, CURLOPT_HEADER, "Accept: application/json");
    curl_setopt($ch, CURLOPT_NOBODY, FALSE); // remove body

    curl_setopt($ch, CURLOPT_POSTFIELDS, $message);

    $head = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

My goal is to send a message to messenger through nexmo API.


Solution

  • The error has been with the headers sent along with the content. As the error was,

    {"title":"Content type 'application/x-www-form-urlencoded' not supported for bodyType=com.nexmo.chatapp.sandbox.messages.Message"} The HTTP HEADERS where not defined. thus default Content type 'application/x-www-form-urlencoded applied

    Solved the issue by adding this line of code

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Accept: application/json"));
            //curl_setopt($ch, CURLOPT_HTTPHEADER, "Accept: application/json");
    

    For NEXMO uses JSON type data. Now am up in the air