Giter Site home page Giter Site logo

fb-messenger-php-example's Introduction

FB Messenger Bot PHP API Sample

This is an example for Facebook Messenger PHP Bot API - https://github.com/pimax/fb-messenger-php

REQUIREMENTS

The minimum requirement is that your Web server supports PHP 5.4.

INSTALLATION

composer install
cp config_sample.php config.php

Specify token and verify_token in the config.php

EXAMPLES

Persistent Menu

This code should create 2 menus:

  1. menu for users with Arabic locale: contains one item "promotions"
  2. menu for users from any other locale which is in this hierarchy:
    .......My Account
    ..............|- Pay Bill
    ..............|- History
    .....................|- History Old
    .....................|- History new
    ..............|- Contact info
    ......Promotions
$myAccountItems[] = new MenuItem('postback', 'Pay Bill', 'PAYBILL_PAYLOAD');
$historyItems[]   = new MenuItem('postback', 'History Old', 'HISTORY_OLD_PAYLOAD');
$historyItems[]   = new MenuItem('postback', 'History New', 'HISTORY_NEW_PAYLOAD');
$myAccountItems[] = new MenuItem('nested', 'History', $historyItems);
$myAccountItems[] = new MenuItem('postback', 'Contact_Info', 'CONTACT_INFO_PAYLOAD');

$myAccount = new MenuItem('nested', 'My Account', $myAccountItems);
$promotions = new MenuItem('postback', 'Promotions', 'GET_PROMOTIONS_PAYLOAD');

$enMenu = new LocalizedMenu('default', false, [
    $myAccount,
    $promotions
]);

$arMenu = new LocalizedMenu('ar_ar', false, [
    $promotions
]);

$localizedMenu[] = $enMenu;
$localizedMenu[] = $arMenu;

//Create the FB bot
$bot = new FbBotApp(PAGE@TOKEN);
$bot->deletePersistentMenu();
$bot->setPersistentMenu($localizedMenu);

fb-messenger-php-example's People

Contributors

kingbbq avatar maxpinyugin avatar wittfabian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fb-messenger-php-example's Issues

unable to handle button click via payload

First of all, i'm greatfull for what you have done, it feels great when people still writing things via php rather than getting fancy with nodejs, secondly, i'm trying to capture button payload but unable to do so, it shows bot is typing and then nothing happens, is there something i'm missing, or functionality yet to be added ?
i'm copy and pasted your code

Dont send image with text "local image"

With text "local image" code not run and log

[09-Jan-2017 22:32:00 Asia/Ho_Chi_Minh] PHP Fatal error: Class 'pimax\Messages\Attachment' not found in /home/.../Messages/ImageMessage.php on line 49

Documentation?

Is there any chance we can get some documentation here? It's a wicked starting point, but I'm tripping up on a few things so documentation would be wicked!

Multiple payloads on sequence

Hello, I'm wondering how I can create multiple structured message.

I tried with

$bot->send(new StructuredMessage($message['sender']['id'],
	StructuredMessage::TYPE_BUTTON,
	[
		'text' => 'Choose category',
		'buttons' => [
			new MessageButton(MessageButton::TYPE_POSTBACK, 'First button', 
			StructuredMessage::TYPE_BUTTON,
			[
				'text' => 'Choose category',
				'buttons' => [
					new MessageButton(MessageButton::TYPE_POSTBACK, 'First button', 'PAYLOAD 1'),
					new MessageButton(MessageButton::TYPE_POSTBACK, 'Second button', 'PAYLOAD 2'),
					new MessageButton(MessageButton::TYPE_POSTBACK, 'Third button', 'PAYLOAD 3')
				]
			]),
			new MessageButton(MessageButton::TYPE_POSTBACK, 'Second button', 'PAYLOAD 2'),
			new MessageButton(MessageButton::TYPE_POSTBACK, 'Third button', 'PAYLOAD 3')
		]
	]
));

But it won't work. I'm wondering how I can create sequence paylods?

Regards,
vankk.

How to get Postback button value in the callback url in Facebook messenger bot?

I am trying to get Start button payload value in my call back url, its not happening. But i can get user typed text messages, and based on text messages I am able to send response as well. Lets given an example if user typing PHP (as a text message) I can send short description about PHP and i am showing 2 button 1 is more info it contains url, and one more button Start (to continuing the chat).
screen shot 2017-06-05 at 1 05 56 pm
whatsapp image 2017-06-05 at 1 03 20 pm

if user click Start button, i am not getting the value for the same in my callback url. Note i have selected all the events in my app settings
And my callback code

<?php
date_default_timezone_set('Asia/Calcutta');
$access_token = "sERREEREREZBPLgjMN7k8hXZAtBHktERWlm4uZCkSDVRo9r7PhKUZC1celZA9117Xcc6FDUKZCEbxRpZCM80rVDlb4H7ZAJkDVKJ2iuIFkDBoeG37a60KZBkCEtTVlCFIG8YWsQtHjKa7xP0TCF1kzZAcAZDZD";
$verify_token = "hdb20174_token";
$hub_verify_token = null;
if(isset($_REQUEST['hub_challenge'])) 
{
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token)
{
echo $challenge;
}

$message_to_reply = '';
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];

$postback = $input['entry'][0]['messaging'][0]['postback']['payload'];
if (!empty($postback)) {
$message = $input['entry'][0]['messaging'][0]['postback']['payload'];

}
else
{
$message = $input['entry'][0]['messaging'][0]['message']['text'];

}

$message = trim($message);


if($message=='start')
{
$message_to_reply = "Thanks to continue, You can use bot now";

}


else
{


function getDescription($keyword)
{
$url='http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString='.urlencode($keyword).'&MaxHits=1';
$xml=simplexml_load_file($url);
return $xml->Result->Description;
}

$message_to_reply = getDescription($message);



}


$message_to_reply = trim($message_to_reply); 

//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{

"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"sharable":true,
"text":"'.$message_to_reply.'",
"buttons":[
{
"type":"web_url",
"url":"http://php.net/manual/en/intro-whatis.php",
"title":"More Info"
},
{
"type":"postback",
"title":"Start",
"payload":"start"
}
]
}
}
}
}';

//$abb = json_encode($jsonData);
//print_r($abb);
//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>

I am using core php.

Issue with require file

Hi,
Nice Example
This file not included in index.php file
echo require_once(dirname(FILE) . '/vendor/autoload.php'); nothing to display in this file just comment the return "return ComposerAutoloaderInit304c70e3a9fe78bbc8b5b092ab75ab50::getLoader();" , it will display 1 ,
how to achieve this.

Oudated?

The example does not detect messages as of text, image etc and gives key error

<br />
<b>Notice</b>:  Undefined index: text in <b>/path/hook.php</b> on line <b>46</b><br />
COMMAND = <br>

Receipt error

Hi ,

I tried the repo , everything is fine but when you try to display : Image , Profile and Receipt nothing work.

Maybe i missed something ?

default: doesn't work.

I implemented default: just the way it is in this example code and it doesn't work. can someone please help?

Can you show us an example how i can send a message depending by last 2-3 replies ?

Can you show us an example how i can send a message depending by last 2-3 replies ?

I want to try something like here: https://www.messenger.com/t/recipidea

Example - scenario:

  1. Page: "So tell me, what do you have in your fridge ?"
    Reply: "milk"
  2. Page: "What else ?"
    Reply: "banana"
  3. Page: "Hmmm milk and banana that looks yummy 😋. Let me think a minute ... " ... And bellow show recipes...

Practicaly in the step 3) exists replies from 1) and 2). I would like to know how can i get last 2 replies in this step.

I suppose in step 2) is colected reply from step 1) and in step 3 what is in step 2).

Have you idea how is made that ?

Thank You

How can I make generic structured message with many elements?

for example, I want show several items from databaes, how can I iterate using this structure? thanks

$bot->send(new StructuredMessage($message['sender']['id'],
StructuredMessage::TYPE_GENERIC,
[
'elements' => [
new MessageElement("First item", "Item description", "", [
new MessageButton(MessageButton::TYPE_POSTBACK, 'First button'),
new MessageButton(MessageButton::TYPE_WEB, 'Web link', 'http://facebook.com')
]),
new MessageElement("Second item", "Item description", "", [
new MessageButton(MessageButton::TYPE_POSTBACK, 'First button'),
new MessageButton(MessageButton::TYPE_POSTBACK, 'Second button')
]),
new MessageElement("Third item", "Item description", "", [
new MessageButton(MessageButton::TYPE_POSTBACK, 'First button'),
new MessageButton(MessageButton::TYPE_POSTBACK, 'Second button')
])
]
]
));

button POSTBACK is not working

I am not sure if this only me , when you click postback and define the playload it does not work.

anybody help me with an example?

MessageButton Questions

Hi,

I am new in this project.

I am using this code and want to change the description "Share". No matter what I did, the "wording" is not changed. Can anyone suggest how can I change it ?? Thanks.

new MessageButton(MessageButton::TYPE_SHARE, 'Share'),

my coding is working fine for less than 3 MessageButton. When I created 4 MessageButton, the respond seems stopped. is there any limitation for the numbers of MessageButton? Please advise Thanks

this code not run

hello sir,
I download your source and config on my host. But when i send a message to Bot, Bot not reply.
If i set $command in line 71 (before switch ($command)), bot Reply.
Pls help me

Receive the Button payload

Can you please show me the right way to receive the payload? In your example if i send the test 'button' 3 buttons will be appeared as 'First Button', 'Second Button', Third Button'. But how can i receive and process the response if The 'First Button' is pressed?

Guys, you have an error in your PersistentMenu example

It actuually killed me two hours to figure out what the issue was =( :

In your file index.php

you have

                    new LocalizedMenu('default', false, [
                        new MenuItem('nested', 'My Account',
                            new MenuItem('nested', 'History',
                                new MenuItem('postback', 'History Old', 'HISTORY_OLD_PAYLOAD'),
                                new MenuItem('postback', 'History New', 'HISTORY_NEW_PAYLOAD')
                            ),
                            new MenuItem('postback', 'Contact_Info', 'CONTACT_INFO_PAYLOAD')
                        )
                    ])

Although it must be:

        new LocalizedMenu('default', false, [
            new MenuItem('nested', 'My Account', [
                new MenuItem('nested', 'History', [
                    new MenuItem('postback', 'History Old', 'HISTORY_OLD_PAYLOAD'),
                    new MenuItem('postback', 'History New', 'HISTORY_NEW_PAYLOAD')
                ]),
                new MenuItem('postback', 'Contact_Info', 'CONTACT_INFO_PAYLOAD')
            ])
        ]);

This was actually very confusing and hard to notice, please fix this

Infinite loop

Hi,
when I try to run your example I have received infinite loop with message 'Sorry. I don’t understand you.' for any message I sent to my bot.

What can it be?

2016-10-22 10 52 40

'text' switch case is never executed in index.php

hi,
Thanks for such a wonderful API it really helped me. Now coming onto issue, the first switch case in index.php

    // When bot receive message from user
            if (!empty($message['message'])) {
                $command = $message['message']['text'];

`
which is then used in case 1

        // When bot receive "text"
                case 'text':
                    $bot->send(new Message($message['sender']['id'], 'This is a simple text message.'));
                    break;

is never executed.
as $message['message']['text'] returns the text message that user sent and not the message type. It should have type param which should be equal to text. But unfortunately json file sent by fb doesn't have any such parameter.
So what we can do is
1.
use ```
if (!empty($message['message'])) {
$command = 'text';


or 
1.  sending the message from if statement itself thus separating cases for message and postback.

Should be check X-Hub-Signature headers

We should check X-Hub-Signature to make sure the request was sent by Facebook.
This is my code example (using Yii2 framework)

        $raw = file_get_contents("php://input");
        // ....
        $signature = Yii::$app->request->headers->get('X-Hub-Signature');
        if (empty ($signature)) {
            throw new NotFoundHttpException();
        }

        $appSecret = Yii::$app->params['facebook_secret'];
        $shaAppSecret = hash_hmac('sha1', $raw, $appSecret);
        if ("sha1=".$shaAppSecret == $signature) {
            // Process message
        } else {
            // Process when someone fake the request.
        }

If we don't implement this, somebody can fake the request to make some spam message.
Please add it to your code for all dev reference.

ImageMessage

hello , very nice your example , I immediately wanted to do a test ...
I mounted on heroku , but I have this problem on ImageMessage :

2016-06-01T19:11:51.946371+00:00 app[web.1]: [01-Jun-2016 19:11:51 UTC] PHP Fatal error: Uncaught Error: Class 'pimax\Messages\ImageMessage' not found in /app/index.php:68

text work fine ...

Can help me ?? tnks

Add QuickReply to objects

Like:

                    $bot->send(new StructuredMessage($message['sender']['id'],
                        StructuredMessage::TYPE_GENERIC,
                        [
                            'elements' => [
                                new MessageElement("First item", "Item description", "", [
                                    new MessageButton(MessageButton::TYPE_POSTBACK, 'First button'),
                                    new MessageButton(MessageButton::TYPE_WEB, 'Web link', 'http://facebook.com')
                                ]),
                                new MessageElement("Second item", "Item description", "", [
                                    new MessageButton(MessageButton::TYPE_POSTBACK, 'First button'),
                                    new MessageButton(MessageButton::TYPE_POSTBACK, 'Second button')
                                ]),
                                new MessageElement("Third item", "Item description", "", [
                                    new MessageButton(MessageButton::TYPE_POSTBACK, 'First button'),
                                    new MessageButton(MessageButton::TYPE_POSTBACK, 'Second button')
                                ])
                            ]
                        ],
                        [ 
                        	new QuickReplyButton(QuickReplyButton::TYPE_TEXT, 'First button','THIS PARAM is required, atleast put a whitespace!') 
                        ]
                    ));

Bot is not answering

I configured the bot with the token and verify_token, I run the curl command and It worked (success: true)
I'm using ngrok for the make public my server. However the bot is not answering anything. I'm getting this response from the server:

GET
captura de pantalla de 2017-03-30 14-20-49

POST
captura de pantalla de 2017-03-30 14-20-58

captura de pantalla de 2017-03-30 14-21-01

When I do this:
`$data = json_decode(file_get_contents("php://input"), true, 512, JSON_BIGINT_AS_STRING);

echo json_encode($data);`

I'm getting a null value:
captura de pantalla de 2017-03-30 14-25-06

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.