I'm writing a bot for Facebook in PHP. I'm able to send text and send and answer to quickreplies. However is impossible to me to answer to a postback. I use ngrok for localhost testing purposes but I know that it's not that the problem since 1. it doesn't work on my vps neither 2. All the other functionalities work as expected.
My code for sending the post-back :
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"postback",
"title":"Start Chatting",
"payload":"USER_DEFINED_PAYLOAD"
}
]
}
}
}
}';
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
if(!empty($message_body['message'])){
$result = curl_exec($ch);
}
Then, when I receive the post-back I get this from FB messenger :
{
"object": "page",
"entry": [
{
"id": "590445400970275",
"time": 1494251031827,
"messaging": [
{
"recipient": {
"id": "590445400970275"
},
"timestamp": 1494251031827,
"sender": {
"id": "1075794782546272"
},
"postback": {
"payload": "USER_DEFINED_PAYLOAD"
}
}
]
}
]
}
and my code to parse it :
$input = json_decode(file_get_contents('php://input'), true);
$message_body = $input['entry'][0]['messaging'][0];
$sender = $message_body['sender']['id'];
if (isset($message_body['postback'])){
//Reception d'un postback
$postback = $message_body['postback']['payload'];
if ($postback == "USER_DEFINED_PAYLOAD"){
// The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"messagetoreply"
}
}';
}
}
This is sent by the curl function as the message before.
However the messenger never receives an answer :
Could anyone help me finding out where's the problem ?
Thank you very much