Search code examples
phpjsonfacebook-messenger-bot

JSON returns an object but turns into a bool once assigned to a variable


I am integrating broadcasting to a messenger both right now, following the messenger platform API: https://developers.facebook.com/docs/messenger-platform/send-messages/broadcast-messages

I am following the steps and the broadcast message gets send The function below should return

{
 "broadcast_id": <BROADCAST_ID>
}

As mentioned in the documentation, instead it looks like it just echoes it out and when I try to assign it to a variable (to record it in the database later) it turns into a boolean and returns true

public function send_message($message_creative_id, $access_token)
{
    $creativeIdJSON = '{    
    "message_creative_id": "' . $message_creative_id . '"
    }';

    $api_url = 'https://graph.facebook.com/v2.11/me/broadcast_messages?access_token='.$access_token;
    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $creativeIdJSON);
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    //Execute the request
    $result = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($result);

    if(isset($response))
    {
        return $response;
    }
    else
    {
        return false;
    }

}

How can I get the broadcast ID and assign it to a variable?


Solution

  • From the manual for curl_exec:

    Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

    So:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);