Facebook Messenger bot in PHP, what am I doing wrong?

687 views Asked by At

UPDATE: I rewrote this script 4 times, and I understand the mechanism, but unfortunately I don't understand what's missing.. The error code is the same..

<?php
// parameters
$hubVerifyToken = 'XXXXXX';
$accessToken = "xxxxxxxxxxxxxx";
// check token at setup
if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
echo $_REQUEST['hub_challenge'];
exit;
}
// handle bot's anwser
$input = json_decode(file_get_contents('php://input'), true);
$senderId = $input['entry'][0]['messaging'][0]['sender']['id'];
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$answer = "I don't understand. Ask me 'hi'.";
if($messageText == "hi") {
  $answer = "Hello";
}
$response = [
  'recipient' => [ 'id' => $senderId ],
  'message' => [ 'text' => $answer ]
];
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($response));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);
//based on http://stackoverflow.com/questions/36803518

But if I open the API's page, I get the following error message:

{
 "error": {
 "message": "(#100) The parameter user_id is required",
 "type": "OAuthException",
 "code": 100,
 "fbtrace_id": "G8FOo08+EsE"
 }
}

If user_id is missing, where and how can I write in it? What user_id should I use? PHP codes are not possible to use anymore? should I use for example the this site instead of PHP?

1

There are 1 answers

1
user1032531 On

Try this...

$response = [
  'recipient' => [ 'user_id' => $senderId ],
  'message' => [ 'text' => $answer ]
];