I have relatively simple Facebook Messenger bot in php for research purposes:
$access_token = "xxxxxxx";
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'MY_VERIFICATION_TOKEN') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token.';
$ch = curl_init($url);
if($message=="hi")
{
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"hello!"
}
}';
}
$jsonDataEncoded = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
and my cron job is same as in developer guide
curl -ik -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=xxxxxx"
So basically, nothing besides connection and one response. When i personally send "hi" (as a page owner and app owner), my bot always responds correctly, but when other people try to say hi - bot sometimes responds, sometimes not (usually not, in 5 cases bot responded once)
Additionally, when i visit my script url, it gives me error:
{"error":{"message":"(#100) The parameter recipient is required","type":"OAuthException","code":100,"fbtrace_id":"DvrO1UEw5BJ"}}
Please help me to set this right.
Only users listed as Admins or Developers or Testers in your app roles (https://developers.facebook.com/apps/YOUR_APP_ID/roles/) can interact with your chat bot webhook. It won't be available to other users unless your app is approved by Facebook and publicly available. From the Docs:
About your second question, Facebook sends an API call to your webhook in the form of JSON data which includes sender id & recipient id in the HTTP request body. But when you visit your webhook manually, you don't have those parameters in your request body so $sender will be empty in your case. And that's why the CURL request to Facebook API fails with the error "The parameter recipient is required" because
"recipient":{"id":"'.$sender.'"},
will be empty.If you want to try your webhook manually, use actual recipient id, something like:
Curl Command:
This might also happen if you forget to set the content-type as well.