Last active
September 20, 2022 02:51
-
-
Save visitdigital/58c71acb123870d1ac2ec714d7536587 to your computer and use it in GitHub Desktop.
Very Simple Facebook Chat Bot PHP Webhook Script Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$challenge = $_REQUEST['hub_challenge']; | |
$verify_token = $_REQUEST['hub_verify_token']; | |
// Set this Verify Token Value on your Facebook App | |
if ($verify_token === 'testtoken') { | |
echo $challenge; | |
} | |
$input = json_decode(file_get_contents('php://input'), true); | |
// Get the Senders Graph ID | |
$sender = $input['entry'][0]['messaging'][0]['sender']['id']; | |
// Get the returned message | |
$message = $input['entry'][0]['messaging'][0]['message']['text']; | |
//API Url and Access Token, generate this token value on your Facebook App Page | |
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>'; | |
//Initiate cURL. | |
$ch = curl_init($url); | |
//The JSON data. | |
$jsonData = '{ | |
"recipient":{ | |
"id":"' . $sender . '" | |
}, | |
"message":{ | |
"text":"The message you want to return" | |
} | |
}'; | |
//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, $jsonData); | |
//Set the content type to application/json | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); | |
//Execute the request but first check if the message is not empty. | |
if(!empty($input['entry'][0]['messaging'][0]['message'])){ | |
$result = curl_exec($ch); | |
} | |
?> |
Please help, dont work for me, I do not receive data from facebook.
update please!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I want to get the sender name or profile. How to do that?
I am using this,
$sender = $input['entry'][0]['messaging'][0]['sender']['id']; $url = "https://graph.facebook.com/v8.0/$sender?fields=first_name,last_name,profile_pic&access_token=" . $access_token; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch);
But I get the response,
{"error":{"message":"(#33) This object does not exist or does not support this action","type":"OAuthException","code":33,"fbtrace_id":"AiMUy1AR8LoGXvgta0vE2Of"}}
It looks like the $sender is not the actual user ID, How to get the actual user ID to get sender info.
Please help me. This is a roadblock for me.