PHP code sample for Facebook Messenger Bots

<?php//Code to verify the website
$verify_token = $_GET[‘hub_verify_token’];
if (isset($verify_token)) {
$challenge = $_GET[‘hub_challenge’];
if ($verify_token == “verification_token”) {
print $challenge;
} elseif ($verify_token != “verification_token”) {
print ‘Error, wrong validation token’;
}
}
//Code to process requests
$postData = file_get_contents(‘php://input’);
$postData = preg_replace(‘/”id”:(\d+)/’, ‘”id”:”$1"’, $postData); //Important - to prevent ID becoming a float
if(getMessage($postData)){
sendMessage(getSender($postData), “Echo: “.getMessage($postData));
}
function getMessage($input){
$postdata = json_decode($input);
return $postdata->entry[0]->messaging[0]->message->text;
}
function getSender($input){
$postdata = json_decode($input);
return $postdata->entry[0]->messaging[0]->sender->id;
}
function sendMessage($recipient, $textMessage) {$token = YOUR_TOKEN_HERE $json = ‘{
“recipient”:{“id”:”’ . $recipient . ‘”},
“message”:{
“text”:”’ . $textMessage . ‘”
}
}’;
$options = array(
‘http’ => array(
‘method’ => ‘POST’,
‘content’ => $json,
‘header’ => “Content-Type: application/json\r\n” .
“Accept: application/json\r\n”
)
);

$url = ‘https://graph.facebook.com/v2.6/me/messages?access_token=’ . $token;
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $json;
}

--

--

Doctor working in North East England with a keen interest in technology

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store