Telegram setwebhook not receiving updates - php

I am using Google Cloudshell platform to create an ssl-certified url for hosting a webhook. So I originally began using getupdates to find the chat_id and send the bot messages. The following code, meant to get the user's chat-id and then text him "text" , works fine.
<?php
$botToken = "insert bot token" ;
$website = "https://api.telegram.org/bot".$botToken ;
$update = file_get_contents($website."\getupdates");
$updateArray = json_decode($update, TRUE) ;
$chatId = $updateArray["result"][0]["message"]["chat"]["id"] ;
file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=test") ;
?>
Then I set up a webhook using setwebhook and modified the above code.
<?php
$botToken = "insert bot token" ;
$website = "https://api.telegram.org/bot".$botToken ;
$update = file_get_contents("php://input");
$updateArray = json_decode($update, TRUE) ;
$chatId = $updateArray["result"][0]["message"]["chat"]["id"] ;
file_get_contents($website."/sendmessage?chat_id=".$chatId."&text=test") ;
?>
In other words I changed the \getupdates with "php://input" . It did not work.
I suppose it is possible that google app engine does not automatically sign its ssl certificates and perhaps that's why the webhook does not work.
Any help will be appreciated.
EDIT : In response to the answers/comment below, I tried the getWebhookinfo approach and got
"url:"https://my_url.com" ,"has_custom_certificate":false, "pending_update_count":0, "max_connections":40

You can find out problem via following method:
Check getWebhookInfo method, make sure your webhook URL is correct, and no last_error_message field.
POST similar data to your server, here is some data you can use in curl -d JSON, just copy it and run on your own server.
At last, check your CDN config (if you had applied on that server), temporary disable flooding or any check.

Related

PHP incoming webhook handling

I have a 3rd party website that has webhooks that send to a specific url. I set it up to send to a blank page on my site (example: www.mysite.com/webhook.php)
I have a var_dump set up in the webhook.php that should display any information in the post or get.. I am new to webhooks and might just not understand how they work. I assume that i can have var_dump($_POST) in my php file to display an array of the HTTP request that is coming to my site.
I cannot see any requests on my site from the hook after sending test data.. any ideas?
I would do this to test the webhook.
<?php
$fWrite = fopen("log.txt","a");
$wrote = fwrite($fWrite, var_dump($_POST));
fclose($fWrite);
?>
This will return var_dump data in log.txt file, since as rickdenhaan said 36 mins ago, your current webhook.php return data to the webhook not your view.
You may need to create log.txt manually if you don't have right on directory (755)
I'm currently working with a payment API that use webhook. Webhook send data to X url then do action and return code to webhook. so webhook.php is the place where my order if ispaid or not is proceed or not... here what I did:
if ($payment->isPaid() == TRUE)
{
/*
* At this point you'd probably want to start the process of delivering the product to the customer.
*/
$con->query("UPDATE orders SET bankno = '$bankno', status = 'paid' WHERE ordertr = '$ids'");
}
elseif ($payment->isOpen() == FALSE)
{
/*
* The payment isn't paid and isn't open anymore. We can assume it was aborted.
*/
$con->query("UPDATE orders SET bankno = '$bankno', status = 'closed' WHERE ordertr = '$ids'");
}
So if order paid mark as paid in database if not mark as closed. This show webhook usage. Doing action according to what the webhook data send.
here is how i get content sent to my app:
$varname = json_decode(file_get_contents('php://input'));
well my content are JSON encoded, but I think this would be fine:
$varname = file_get_contents('php://input');

Issue with recaptcha 2.0 php server side

I am desperately trying to make my form works.
But I am having issue with validating the recaptcha server side.
I have been looking around and going over my form a thousand times making tests, I know it doesn't pass the step of the recaptcha, but can't figure it out.
Here is my piece of code :
//variable :
$recaptcha = $_POST['g-recaptcha-response'];
//test captcha
if($recaptcha != '')
{
$secret = " MY KEY HERE";
$ip = $_SERVER['REMOTE_ADDR'];
$var = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$recaptcha."&remoteip=".$ip);
$array = json_decode($var,true);
//check if captcha ok then check fields empty
if($array['success'])
Please let me know if you can find anything wrong.
Thank you.
(indeed I removed my security key)
In my testing, I ran into two problems that you might be having.
The remoteip argument is optional. When I removed it, everything worked. Here's why: I was testing with both client and server machines on private IP's behind a firewall, so the $_SERVER['REMOTE_ADDR'] value on my server was 192.168.x.x. Google saw the public IP of my NAT firewall, so that is what siteverify tried to match against.
You can only check a given response once. If you try to check it again, it will always fail. So during testing you need to use a fresh one each time.
Also, you can simplify your PHP code a bit by using:
"...siteverify?secret=$secret&response=$recaptcha");
Try this:
$secret = "YOUR-SECRET-KEY";
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $_POST['g-recaptcha-response']);
$googleResponse = json_decode($verifyResponse);
if ($googleResponse->success)
{
$captchaVerified = true;
}

Telegram bot - api methods not working on server

I am trying to create a Telegram Bot. I follow this video. my codes are working in localhost, but when I put them on server the result is different. this code just call getUpdates method of Telegram api.
Code :
<?php
$botToken = "146158152:AAHO**********-L3xF08RN7H0xK8E";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents($website."/getUpdates");
var_dump($update);
?>
Localhost result :
string(616) "{"ok":true,"result":[{"update_id":35****293, "message":{"message_id":1,"from":{"id":95*****4,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal"},"chat":{"id":95*****4,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal","type":"private"},"date":1448737853,"text":"\/start"}},{"update_id":356676294, "message":{"message_id":2,"from":{"id":95*****4,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal"},"chat":{"id":95881214,"first_name":"Mahmood","last_name":"Kohansal","username":"mahmoodkohansal","type":"private"},"date":1448737855,"text":"1"}}]}"
and Server result :
bool(false)
Sorry for my poor English.
If your code works in localhost, the first assumption would be that your server was not successful in establishing a connection to the bot api.
Perhaps you should put it in an if statement.
$token = "your token";
$website = "https://api.telegram.org/bot".$token;
if($updates = file_get_contents($website."/getUpdates"))
{
echo "Connection made";
}
else
{
echo "Fail";
}
Also can you make sure a webHook isn't set? getUpdates method does not return results if a webHook is set.
PHP file_get_contents method was the problem. I found the same problem with this method here, and use the solution to solve my problem.

Create own bot on telegram with php

I saw a couple of days ago this tutorial on youtube.
It was very interesting, so I decided to make a own bot.
I used the code from the tutorial as a template:
<?php
$bottoken = "*****";
$website = "https://api.telegram.org/bot".$bottoken;
$update = file_get_contents('php://input');
$updatearray = json_decode($update, TRUE);
$length = count($updatearray["result"]);
$chatid = $updatearray["result"][$length-1]["message"]["chat"]["id"];
$text = $updatearray["result"][$length-1]["message"]["text"];
if($text == 'hy'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=hello");
}
elseif($text == 'ciao'){
file_get_contents($website."/sendmessage?chat_id=".$chatid."&text=bye");
}
The script worked if I execute the script manually. However when I use the webhook it doesn't work anymore. The tutorial said that $update = file_get_contents('php://input'); is the right way, to be used before $update = file_get_contents($website."/getupdates");. My question how can I use php://input to execute my script automatically? The script is on a server from "one.com" and the certificate is also from "one.com".
If you use selfsigned ssl you have to point to the ssl path ,,
use the ssh to run this command after filling it with your real data ,,
curl -F "url=https://example.com/myscript.php" -F "certificate=#/etc/apache2/ssl/apache.crt" https://api.telegram.org/bot<SECRETTOKEN>/setWebhook
After change to WebHook method, you need to put as follows, since now we are going to handle one message at time. For me works perfectly.
instead
$chatId = $updateArray["result"][0]["message"]["chat"]["id"];
to
$chatID = $update["message"]["chat"]["id"];
this is the answer for all of your problems.
follow this step after you got a secret token for your bot:
create file in your website https://yourdomain.com/secret-folder/index.php
create your php file like this :
<?php
$website = 'https://api.telegram.org/bot123456789:1234567890ABCDEF1234567890ABCDEF123/';
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (isset($update["message"])){
$chatID = $update["message"]["chat"]["id"];
$text = $update["message"]["text"];
if ( $text == '/start' ) {
// send welcome message
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=Welcome to my bot");
}else{
// send another message or do your logic (up to you)
file_get_contents($website."sendMessage?chat_id=".$chatID."&text=some text here");
}
}
?>
Set Your Webhook from this bot #set_webhookbot
choose command or type ' ست وب هوک '
reply with your secret bot token ex: ' 123456789:1234567890ABCDEF1234567890ABCDEF123 '
reply with your webhook address 'https://yourdomain.com/secret-folder/index.php'
reply with /setwebhook
if you follow step by step its will work.
enjoy it !!
Sorry for digging up this old question so enthusiastically, I had exactly the same question as you.
I think actually the answer may be easier yet less satisfying as we hoped: I don't think it's possible to get a list of previous messages to the bot while using the webhook.
Namely: what this does, is run the PHP script directly as soon as the bot receives a message. Nothing is stored in an accessible database, hence no updateArray is returned.
I came across this example, which shows how php://input works. I guess the solution to display a list of messages would be, let the php script store the message in a database everytime a message is 'forwarded' via the webhook.
If anyone found something else: I'm very interested.
As per my understanding from your code snippet above, you need to use php://input within double quotes instead of single quotes. In php, we are having bing difference in this use case.

Unable to receive confirm subscription request

Hi i am not able to receive the confirm subscription request from Amazon, tried everything.
My endpoint url is: http://example.com/test/test.
I have tried following snippets of code to receive response:
1) ->
$headers = apache_request_headers();
$body = #file_get_contents('php://input');
file_put_contents(Path to file."json_sns.txt", serialize(print_r($headers, 1)."\n---body---\n".$body));
2) ->
$h= fopen("php://input","r");
$X = stream_get_contents($h);
$J = json_decode( $X , true);
file_put_contents(Path to file."json_sns.txt", serialize(print_r($headers, 1)."\n---body---\n".$body));
3) ->
file_put_contents(Path to file."json_sns.txt", serialize($_POST));
and many more, yet no success. Verified that the endpoint url is accessible through browser.
Subscription is there in sns console with pending confirmation status.
Please help me how to receive the response from amazon, also point out if i have done something wrong in my code or i have missed out any step. Thanks.
Resolved the issue, actually CSRF token was causing the problem, due to which Amazon request wasn't completing, added a exception for its request, and then it worked like a charm. :)

Categories