May 5, 2016
223 Views

Facebook Messenger Chatbot Setup in PHP

Written by

Here is a step by step guide to make your first chatbot.

Widely anticipated, Facebook has announced their messenger platform enabling businesses to build their own chat bots — automated response tools within Messenger which will be able to handle increasingly complex customer queries.

Official Facebook Getting started guide https://developers.facebook.com/docs/messenger-platform/quickstart for Messenger Platform https://developers.facebook.com/products/messenger/ only have examples for Node.js. If you want to build your bot in PHP, I have put together same examples, follow these instructions and you will have a chat bot working in no time.

1. Create a Facebook App and Facebook Page

First step is to create a new Facebook App https://developers.facebook.com/quickstarts/?platform=web and Page https://www.facebook.com/pages/ create or use existing ones. Your Facebook App can remain in sandbox mode and your Page does NOT have to be publicly visibile.

2. Setup Web Hook

A web hook, in this case, is a php file which Facebook will call with a payload every time a user sends a message to bot. We will parse the message and send a post message back to Facebook with JSON formatted payload.

We need to have php file on the server and server has to have SSL, as only https links are accepted.Copy the following code and create webhook.php file and upload on your secure server.

<?php

/* validate verify token needed for setting up web hook */ 
if (isset($_GET['hub_verify_token'])) { 
    if ($_GET['hub_verify_token'] === 'YOUR_SECRET_TOKEN') {
        echo $_GET['hub_challenge'];
        return;
    } else {
        echo 'Invalid Verify Token';
        return;
    }
}

/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['entry'][0]['messaging'][0]['sender']['id'])) {

    $sender = $input['entry'][0]['messaging'][0]['sender']['id']; //sender facebook id
    $message = $input['entry'][0]['messaging'][0]['message']['text']; //text that user sent

    $url = 'https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN';

    /*initialize curl*/
    $ch = curl_init($url);
    /*prepare response*/
    $jsonData = '{
    "recipient":{
        "id":"' . $sender . '"
        },
        "message":{
            "text":"You said, ' . $message . '"
        }
    }';
    /* curl setting to send a json post data */
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    if (!empty($message)) {
        $result = curl_exec($ch); // user will get the message
    }
}

?>
webhook.php
 fb1
Setting up web hook (put the same verify token in php and Facebook dialog) and check all checkboxes

3. Get Page Access Token

Select your page from the dropdown, an access token will show up in the text field, copy the token and replace in the webhook.php file on line 21 and upload the file on the server.

 fb3
Getting Page Access Token

4. Subscribe the App to the Page

You do not need to make a CURL call to subscribe, they have this option under the webhook section as you can see below

 fb4
Select your page and Subscribe

5. Test your bot

We are ready to test, go to your page which you have subscribed and click on message. In the chat window, type any text and box will respond back with the same prefixed message “You said, XYZ”.

 fb5
Click on Message
 fb6
Simple Text exchange with bot

Your basic chatbot is up and running now.

Stay tuned!

Article Tags:
· · · · · · · · · · · · · · · · · · · · ·
Article Categories:
Code/Web
    http://linholiver.com

    https://linholiver.com/diary/about/