PHP code sample for Facebook Messenger Bots

Mike David Smith
2 min readApr 14, 2016

Facebook has produced an excellent getting started guide for their Messenger API, only issue is that it’s written for Node.js. I wanted it for PHP to save the faff of setting up a Node.js sever, but there are no code templates. So I’ve put a sample together. This is a really simple bot that will echo a users responses, where you go from there is up to you.

Note: the code may not be elegant, but it’s functional.

So first follow the instructions in the Facebook guide to setup your page and app token. Once that’s done, put the following code onto a server (that is HTTPS) as your WEBHOOK and continue to work through the Facebook guide.

UPDATE: The code below has been added to a simple PHP class for the facebook messenger bot API you can download over on GitHub

<?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;
}

--

--

Mike David Smith

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