pimax / fb-messenger-php-example Goto Github PK
View Code? Open in Web Editor NEWFacebook Messenger Bot PHP API Example
Facebook Messenger Bot PHP API Example
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?
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.
I implemented default: just the way it is in this example code and it doesn't work. can someone please help?
After typing "image" in the chat box, Bot does not respond.
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:
- Page: "So tell me, what do you have in your fridge ?"
Reply: "milk"- Page: "What else ?"
Reply: "banana"- 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
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
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.
Hi ,
I tried the repo , everything is fine but when you try to display : Image , Profile and Receipt nothing work.
Maybe i missed something ?
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).
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.
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.
i cannot find this file
where is autoload file ?
should i upload any other pachages ?
struggling to implement persistent view. case 'set menu' doesn't work. Any Help would be appreciated @wittfabian
Hi! I suggest to use in the example index.php:
$data = json_decode(file_get_contents("php://input"), true, 512, JSON_BIGINT_AS_STRING);
because large int facebook ID converted to float by json_decode PHP by default
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
new MessageButton(MessageButton::TYPE_SHARE)
not
new MessageButton(MessageButton::TYPE_SHARE, 'Share')
Do you support Buy Botton?
https://developers.facebook.com/docs/messenger-platform/send-api-reference/buy-button
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?
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
Dear Mr pimax,
I don't known how to get 'verify_token' & 'token'. Can you show me how to get them?
Thanks!
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!')
]
));
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!
How to implement List Template Structured Message with global button @wittfabian ?
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')
])
]
]
));
How do i pull the message elements and button elements in a structured message from the database?
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.
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
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
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
Hi,
How can i intergrate the messenger on godaddy?
Please assist
Hi how to make quick replies?
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:
When I do this:
`$data = json_decode(file_get_contents("php://input"), true, 512, JSON_BIGINT_AS_STRING);
echo json_encode($data);`
Need example how to add image message with buttons like in https://developers.facebook.com/docs/messenger-platform/send-messages/template/media#buttons.
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>
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.