Build Your First Facebook Messenger Chatbot in PHP

Step by step guide with code samples.

Nadeem Manzoor
3 min readApr 27, 2016

--

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 for Messenger Platform 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 and Page 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.

webhook.php
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.

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

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”.

Click on Message
Simple Text exchange with bot

Your basic chatbot is up and running now.

Through the Messenger Platform’s new Send/Receive API, bots can send more than just text. They will be able to respond with structured messages that include images, links and call to action buttons. These could let users make a restaurant reservation, review an e-commerce order and more. You can swipe through product carousels and pop out to the web to pay for a purchase.

I will be writing more about sending structured messages and receiving post backs in future posts.

Stay tuned!

--

--