|

|  How to Use Facebook Messenger Platform API for Chatbots in PHP

How to Use Facebook Messenger Platform API for Chatbots in PHP

October 31, 2024

Learn how to use Facebook Messenger Platform API for creating chatbots in PHP. This guide covers setup, integration, and coding essentials.

How to Use Facebook Messenger Platform API for Chatbots in PHP

 

Integrate Facebook Messenger Platform API

 

  • Begin by installing necessary libraries. Use Composer to install the Facebook SDK for PHP:
  •  

composer require facebook/graph-sdk

 

  • Ensure your server is running on HTTPS due to Facebook's security requirements for webhooks.

 

Set Up Webhooks Endpoint

 

  • Create an endpoint that Facebook Messenger will communicate with. This endpoint will be set up to receive POST requests from Messenger when users send messages to your chatbot.
  •  

  • Configure webhook verification using the verify token you set in your Facebook App Dashboard. The server should respond with the verify token if successfully challenged by Facebook:

 

$hub_verify_token = null;
if (isset($_REQUEST['hub_challenge'])) {
    $challenge = $_REQUEST['hub_challenge'];
    $hub_verify_token = $_REQUEST['hub_verify_token'];
}

if ($hub_verify_token === 'YOUR_VERIFY_TOKEN') {
    header('HTTP/1.1 200 OK');
    echo $challenge;
    exit;
}

 

  • Implement logic to handle incoming messages and send responses. Use the SDK to parse and reply to messages:

 

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $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'];

    if ($messageText) {
        respondToMessage($senderId, "Received your message: " . $messageText);
    }
}

function respondToMessage($recipientId, $message) {
    $endpoint = 'https://graph.facebook.com/v2.6/me/messages?access_token=YOUR_PAGE_ACCESS_TOKEN';
    $responseData = [
        'recipient' => ['id' => $recipientId],
        'message' => ['text' => $message]
    ];

    $curl = curl_init($endpoint);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($responseData));
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_exec($curl);
    curl_close($curl);
}

 

  • Replace `YOUR_PAGE_ACCESS_TOKEN` and `YOUR_VERIFY_TOKEN` with your Facebook application's page access token and verify token, respectively.

 

Utilize Persistent Menu

 

  • Enhance user interaction with the Persistent Menu feature. Set up pre-defined actions that users can perform at any time directly from Messenger's menu:

 

$menuData = [
    'persistent_menu' => [
        [
            'locale' => 'default',
            'composer_input_disabled' => false,
            'call_to_actions' => [
                [
                    'title' => 'My Account',
                    'type' => 'nested',
                    'call_to_actions' => [
                        [
                            'title' => 'Pay Bill',
                            'type' => 'postback',
                            'payload' => 'PAYBILL_PAYLOAD'
                        ]
                    ]
                ]
            ]
        ]
    ]
];

$menuEndpoint = 'https://graph.facebook.com/v2.6/me/messenger_profile?access_token=YOUR_PAGE_ACCESS_TOKEN';

$curl = curl_init($menuEndpoint);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($menuData));
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($curl);
curl_close($curl);

 

Handle User Events

 

  • Detect and process different types of user interactions like quick replies, postbacks, and more by analyzing incoming webhook events:

 

function handleEvents($event) {
    if (isset($event['message']) && isset($event['message']['quick_reply'])) {
        $quickReplyPayload = $event['message']['quick_reply']['payload'];
        // Handle quick reply payload
    } elseif (isset($event['postback'])) {
        $postbackPayload = $event['postback']['payload'];
        // Handle postback payload
    }
}