I'm trying to set up a fb messenger chatbot but don't seem to be able to get the webhook callback url verified. Every time I try to verify it I get this error message - The URL couldn't be validated. Response does not match challenge, expected value = '1596214014', received=''
Here's the screenshot:
Screenshot
Here's the php I'm using -
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token_my_token') {
echo $challenge;
}
I've also tried
echo $_GET['hub_challenge'];
and just
echo file_get_contents('php://input');
All of these result in the same error message as above. Basically, as far as I can tell facebook isn't sending a GET request to my server or if it is it doesn't include any data. Can anyone tell if I am doing something wrong or if there is a setting I need to change to ensure facebook is sending the data correctly?
Edit - When checking the access logs this is what I find, which looks like facebook isn't sending any data in the get request.
2a03:2880:1010:dffb:face:b00c:0:8000 - - [19/Apr/2016:20:50:06 +0000] "GET /wp-content/plugins/applications/fbmessenger.php HTTP/1.0" 200 - "-" "facebookplatform/1.0 (+http://developers.facebook.com)
Thanks
just try my code and it's gonna work.
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'Your's app token') {
echo $challenge;
}
//Token of app
$row = "Token";
$input = json_decode(file_get_contents('php://input'), true);
//Receive user
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
//User's message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//Where the bot will send message
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$row;
$ch = curl_init($url);
//Answer to the message adds 1
if($message)
{
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message. ' 1' .'"
}
}';
};
$json_enc = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_enc);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
you have to return Challenges so Facebook can verify its correct Url and Token Match
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token_my_token') {
echo $challenge;
}
Facebook Docs Link ( In Node.js ) You can see challenge return after verifying the token
https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Could you try my API? https://github.com/Fritak/messenger-platform
If you set it like in example, it should work:
// This is just an example, this method of getting request is not safe!
$stream = file_get_contents("php://input");
$request = empty($stream)? $_REQUEST : $stream;
$bot = new \fritak\MessengerPlatform(
['accessToken' => 'token_for_app',
'webhookToken' => 'my_secret_token',
'facebookApiUrl' => 'https://graph.facebook.com/v2.6/me/' //2.6 is minimum
], $request);
if($bot->checkSubscribe())
{
print $bot->request->getChallenge();
exit;
}
If not, problem is somewhere between Facebook and script, not in PHP itself. Go check apache settings etc.
Well issue might be on facebook side, they had some issues over past few days...
Have only this code in your php file: (fbmessenger.php)
<?php
// header('HTTP/1.1 200 OK');
/* GET ALL VARIABLES GET & POST */
foreach ($_REQUEST AS $key => $value){
$message .= "$key => $value ($_SERVER[REQUEST_METHOD])\n";
}
$input = file_get_contents("php://input");
$array = print_r(json_decode($input, true), true);
file_put_contents('fbmessenger.txt', $message.$array."\nREQUEST_METHOD: $_SERVER[REQUEST_METHOD]\n----- Request Date: ".date("d.m.Y H:i:s")." IP: $_SERVER[REMOTE_ADDR] -----\n\n", FILE_APPEND);
echo $_REQUEST['hub_challenge'];
You will have requests saved in a file called "fbmessenger.txt" in the same directory.
Note that for some strange reason you may need to submit few times to
get it approved & saved! (I had to hit "save" 8-9 times before fb
approved link)
Make sure you use https (SSL) connection and once your connection is done, verify your token with "hub_verify_token" to make sure request is coming from fb.
Related
I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.
So I'm trying to create a Facebook Messenger Chatbot, a very simple one. I have it working with a hardcoded response, but I want it to be able to read the senders message and respond in a specific way if it finds that word - like how chatbots should. I' trying to do so by using preg_match() but when I use my current code, the bot doesn't reply at all. Here's my code:
<?php
/**
* Webhook for Facebook Messenger Bot
*/
$access_token = "{mytoken}";
$verify_token = "{mytoken2}";
$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;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
// perform a case-Insensitive search for the word "time"
if (preg_match('[hi|hello|sup]', $message)) {
$answer = "Hiya!";
}
else {
$answer = "IDK.";
}
// send the response back to sender
// 'text': 'Hiya!'
$jsonData = "{
'recipient': {
'id': $sender
},
'message': {
'text': $answer
}
}";
// initiate cURL.
$ch = curl_init("https://graph.facebook.com/v2.6/me/messages?access_token=$access_token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
curl_exec($ch);
}
Do you know whether you actually receive messages from the Messenger Platform? Your webhook verification ends in an echo, where in fact you need to respond to the platform with a status code 200. You can also check your Facebook Apps dashboard to figure out whether your webhook is verified and being sent messages.
Documentation: https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Once you know that your webhook is verified and you are receiving messages, start with a fixed reply and then work towards dynamic responses. As #Toto suggested, adding logging will be very helpful to debug your code.
I would like to write messenger bot based on this script:
<?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);
}
?>
All works correctly but i receive two responses to variable $message, for example:
Send "Hello";
$message = "Hello";
Receive message: "Hi";
$message = "Hi";
I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible?
Greetings
You should skip any read and delivery messages, like this:
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
// Skipping delivery messages
if (!empty($message['delivery'])) {
continue;
}
// Skipping read messages
if (!empty($message['read'])) {
continue;
}
}
}
Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.
I'm trying to set up a telegram bot with a webhook. I can get it to work with getUpdates, but I want it to work with a webhook.
My site (that hosts the bot php script) has the SSL certificate working (I get the green lock in the address bar):
I set up the webhook with
https://api.telegram.org/bot<token>/setwebhook?url=https://www.example.com/bot/bot.php
And I got: {"ok":true,"result":true,"description":"Webhook was set"}
(I don't know if this matters, but I have given rwx rights to both the folder and the script)
The php bot: (https://www.example.com/bot/bot.php)
<?php
$botToken = <token>;
$website = "https://api.telegram.org/bot".$botToken;
#$update = url_get_contents('php://input');
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch($message) {
case "/test":
sendMessage($chatId, "test");
break;
case "/hi":
sendMessage($chatId, "hi there!");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
url_get_contents($url);
}
function url_get_contents($Url) {
if(!function_exists('curl_init')) {
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
?>
But when I write anything to the bot I receive no answers...
Any ideas why?
Thanks
In your question it's not clear the script location. Seeing your code, it seems that you try to load a request through url_get_contents to retrieve telegram server response. This is the correct method if your bot works without webhook. Otherwise, after setting webhook, you have to process incoming requests.
I.e., if you set webhook to https://example.com/mywebhook.php, in your https://example.com/mywebhook.php script you have to write something like this:
<?php
$request = file_get_contents( 'php://input' );
# ↑↑↑↑
$request = json_decode( $request, TRUE );
if( !$request )
{
// Some Error output (request is not valid JSON)
}
elseif( !isset($request['update_id']) || !isset($request['message']) )
{
// Some Error output (request has not message)
}
else
{
$chatId = $request['message']['chat']['id'];
$message = $request['message']['text'];
switch( $message )
{
// Process your message here
}
}
Am using Curl to send sms using a gateway , a, getting 200 when everything is ok and 400 if its not send now , i should get other things from the gateway such as phone number and other information , so am i missing something ?
// if the Form is submited
//if (isset($_POST['PhoneNumber'])) {
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Fetch Phone Number and escape it for security
$Phone = mysql_real_escape_string($_POST['PhoneNumber']);
// Fetch Text and escape it for security
$Text = mysql_real_escape_string($_POST['Text']);
// Structure the URl
$url = "http://xxxxxxxxxxx:xxxx?PhoneNumber=".urlencode($Phone)."&Text=".urlencode($Text)."&User=xxx&Password=xxx";
// Handeling the Curl
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($httpCode=="200"){
// if everything is okey , the gateway returns 200 which means OK
echo "Massage Was Sent , Thank you ";
} elseif ($httpCode=="400"){
// if there was an error , the form returns a 400 which means that the sms Failed
echo "Massage was not sent , Please Try Again";
}
// Cloase the Curl Connection
curl_close($handle);
Thank you Best regards,
$response should contain the response, try:
echo '<pre>';
print_r($response);
echo '</pre>';
to show its content