PHP code sample for Facebook Messenger Bots

Mike David Smith
Apr 14, 2016 · 2 min read

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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