PHP telegram bot, sendmessage webhook - php

I'm writing a telegram robot,
This is my code and I want the user receive the message which they send into the bot:
telegram.php :
<?php
class telegram {
public $token;
public function __construct($token)
{
$this->token = $token;
}
public function recievedText()
{
$text= json_decode(file_get_contents('php://input'),true);
return $text;
}
public function sendMessage($userid,$text)
{
$url='https://api.telegram.org/bot'.$this->token.'/sendMessage?chat_id='.$userid.'&text='.$text;
file_get_contents($url) ;
}
}
?>
index.php :
<?php
require ('config.php');
require('telegram.php');
$telegram = new telegram(TOKEN);
$result = $telegram->recievedText();
$userid = $result->message->from->id;
$text = $result->message->text;
$telegram->sendMessage($userid,$text) ;
?>
config.php :
<?php
define('TOKEN','----');
?>
and I have already set webhook and checked the SSL of my site via this and it was set,
I don't know where is the problem that when I send the message to the bot it doesn't send back any message!

You checked if you have ssl, but you don't check if you really use it. You also don't check what is the response from the request you do
file_get_contents($url) ;
change this line to:
$requestResponse = file_get_contents($url);
var_dump($http_response_header);
var_dump($requestResponse);
to see if you succeed sending the request at first.
Without the response It's just guessing what could go wrong.
You should see response code = 200 if everything is OK if other number not beginning with 2xx then you fail sending the requrest.
Read about HTTPS connections with file_get_contents(), or try to use cURL. Hint: Just for the debugging you can skip SSL verification so at least this problem at the beginning is eliminated. But remember to turn the verification back on after debugging!
If you do the request as GET query you need to encode the text before putting it at the url - use: urlencode() for that.
$url='https://api.telegram.org/bot'.$this->token.'/sendMessage?chat_id='.$userid.'&text='.$text;
change to
$url='https://api.telegram.org/bot'.$this->token.'/sendMessage?chat_id='. urlencode($userid) . '&text='.urlencode($text);
or even better make use of http_build_query() and encode this way all variable besides $this->token. Given link has a plain example so I'll skip giving you code.

You need to set webhook before anything else. Fire a POST request using Postman to
https://api.telegram.org/bot/setWebhook
with Body parameter:
url: https://your-server/api-endpoint
drop_pending_updates : true (false) -> (optional) I use this to drop pending messages

Related

Zoho Sign Webhook - Receiving Response Using PHP

I'm creating a script that will receive response from Zoho Sign Webhook. I use the following condition to trigger the Webhook :
I am able to receive the hit into the Callback URL by saving every response into the database. I'm using a simple code below :
<?php
$data = file_get_contents('php://input');
$escape = mysqli_real_escape_string($conn, $data);
$q=mysqli_query($conn,"INSERT INTO `response` VALUES ('','$escape')");
if($q){
echo "success";
}else{
echo "failed - ".mysqli_error($conn);
}
?>
But i always get empty response using the script above. The $data, $post, or $get variable is always empty.
I tried to find the documentation on the Zoho and other question on stackoverflow but i only can get this discussion here and here. Which is not solving my problem.
Any other way to get the response from Zoho Sign Webhook using PHP?
Thanks #CBroe for the explanation, the problem with my callback was because of missing trailing slash on my callback URL:
http://sub.domain.com/callback
and the problem solved when i change it into :
http://sub.domain.com/callback/

retrofit2 sending a PUT request method is wrong for PHP

I am trying to send a PUT request method from my Android app to my PHP endpoint but in my endpoint the PUT request is not recognized as a PUT request so I return Request method is wrong! message from my endpoint.
Android interface and request execution
Interface for activation
#PUT("device/activate.php")
Call<DeviceRegistry> registryDevice();
Executing the request
DeviceRegistryAPI registryAPI =
RetrofitController.getRetrofit().create(DeviceRegistryAPI.class);
Call<DeviceRegistry> registryCallback = registryAPI.registryDevice();
response = registryCallback.execute();
With this I am expecting a response but I am getting my endpoint error message.
My PHP endpoint
if($_SERVER['REQUEST_METHOD'] == "PUT"){
//doing something with the data
} else {
$data = array("result" => 0, "message" => "Request method is wrong!");
}
I don't know why the $_SERVER['REQUEST_METHOD'] == "PUT" is false but I wonder if I am missing something on Retrofit 2.
More Info.
I am using Retrofit2.
Update 1: Sending json into the body
I am trying to send a json using the body.
It is my json:
{
"number": 1,
"infoList": [
{
"id": 1,
"info": "something"
},
{
"id": 2,
"info": "something"
}
]
}
There are my classes:
class DataInfo{
public int number;
public List<Info> infoList;
public DataInfo(int number, List<Info> list){
this.number = number;
this.infoList = list;
}
}
class Info{
public int id;
public String info;
}
I changed the PUT interface to this:
#PUT("device/activate.php")
Call<DeviceRegistry> registryDevice(#Body DataInfo info);
But I am getting the same problem.
Update 2: Do I need Header
I have this header in my REstfull client:
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Do I need to put this on my request configuration? How do I do that if I need it?
Update 3: checking the request type of my sending post.
Now I am checking the type of the request. Because I am having the same problem with the PUT/POST requests. So If can solved the problem with the put maybe all the problems will be solved.
When I execute the request and asking and inspect the request it is sending the the type (PUT/POST) but in the server php only detect or GET?? (the below example is using POST and the behavior is the same)
Call<UpdateResponse> requestCall = client.updateMedia(downloadItemList);
Log.i("CCC", requestCall .request().toString());
And the output is a POST:
Request{method=POST, url=http://myserver/api/v1/media/updateMedia.php, tag=null}
so I am sending a POST (no matter if I send a PUT) request to the sever but why in the server I am receiving a GET. I am locked!!! I don't know where is the problem.
Update 4: godaddy hosting.
I have my php server hosting on godaddy. Is there any problem with that? I create a local host and everything works pretty good but the same code is not working on godaddy. I did some research but I didn't find any good answer to this problem so Is possible that godaddy hosting is the problem?
PHP doesn't recognize anything other than GET and POST. the server should throw at you some kind of error like empty request.
To access PUT and other requests use
$putfp = fopen('php://input', 'r'); //will be a JSON string (provided everything got sent)
$putdata = '';
while($data = fread($putfp, filesize('php://input')))
$putdata .= $data;
fclose($putfp);
//php-like variable, if you want
$_PUT = json_decode($putdata);
did not tested, but should work.
I guess the problem is that you don't pass any data along with PUT request, that's why PHP recognizes the request as a GET. So I think you just need to try to pass some data using #FormUrlEncoded, #Multipart or probably #Body annotations
To add header in your retrofit2 you should create an interceptor:
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException
{
okhttp3.Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Content-Type", "application/x-www-form-urlencoded");
ongoing.addHeader("Accept", "application/json");
return chain.proceed(ongoing.build());
}
};
and add it to your client builder:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
PHP recognises 'PUT' calls. Extracted from PHP.net:
'REQUEST_METHOD' Which request method was used to access the page;
i.e. 'GET', 'HEAD', 'POST', 'PUT'.
You don't need to send any header if your server isn't expecting any
header.
Prior to use Retrofit or any other networking library, you should check the endpoint using a request http builder, like Postman or Advanced Rest Client. To debug the request/response when running your app or unit tests use a proxy like Charles, it will help you a lot to watch how your request/response really looks.

Set header HTTP code in Flightphp

im developing an API with FlightPHP microframework and I can't set an HTTP response code for my routes.
I can set this and works perfectly:
header('HTTP/1.0 500 Error');
But I want use the native function http_response_code() from PHP. This one don't do anything.
I want to use this because that I don't have to manually type the error message.
To return a HTTP response code using Flight, you can do it like this :
Flight::route('GET /', function(){
Flight::json($data, $code = 500);
});
Where $data is the variable that leads to the array you want to send in json.
If $code is not set, then the default returned HTTP response code is "200".
https://github.com/mikecao/flight/blob/e25f023d4377a2b99b4be8bf7977f3fc0f8089c8/flight/Engine.php#L500
from flight php
Flight::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
Flight::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.
I had a similar problem, to send my own headers, I do so:
$code = 404;
Flight->before('stop', function(&$params) use ($code) {
$params[0] = $code;
});

Google Maps API returns "Invalid Request" in a valid request

i am trying to reverse geocode a bunch of addresses for my database. I have about 200 addresses, and half of them worked like a charm.. i did put the google maps request in a loop and it worked. There were about 100 adresses that returned a "INVALID REQUEST" message. I echoed the request url and put it in my browser and it returned a "Status: OK" and all the data. Why does my script return a invalid request and another browser-tab returns OK?
Thats the function i used:
function getLatLon($strasse, $plz) {
$inhalt = simplexml_load_file('http://maps.googleapis.com/maps/api/geocode/xml?address='.$strasse.',+'.$plz.'&sensor=true');
$geo['lat'] = $inhalt->result->geometry->location->lat;
$geo['lon'] = $inhalt->result->geometry->location->lng;
return $geo;
}
The request url in clear looks like this:
http://maps.googleapis.com/maps/api/geocode/xml?address=Dreik%C3%B6nigstra%C3%9Fe+12,+Erlangen&sensor=true
Would be awesome if someone could help me or detect an error :)
Regards,
Philipp
I am pretty sure the error is caused by the german characters you are sending unencoded. When you do it by browser the URL will be encoded automatically, but not automatically by your PHP-script.
Use rawurlencode for this :
$inhalt = simplexml_load_file('http://maps.googleapis.com/maps/api/geocode/xml?'.
'address='.rawurlencode($strasse).',+'.
rawurlencode($plz).'&sensor=true');

PHP how to loop until confirmation.

I am doing a script to send a string via URL link to an SMS gateway and get the response from them.
They will respond with a code and text for the answer, either '200 = SUCCESS' or an error-code: '-100 = UNKNOWN ERROR' , '-101 = MISSING PARAMETER' , etc.
In my back-end code, I would like to know how to keep looping, waiting for the return message from the SMS Gateway with an error-code and resend my string to the SMS gateway until success or confirmation?
$link = "http://www.smsgateway.com/send.php?phoneno=".$phonenumber."&message=".urlencode($smsMessage);
Next, I use cURL to send this link and get the response:
$returned_content = using_cURL_function_to_get_response($link);
Now, my $returned_content will show:
Success Code: 200 = SUCCESS
Failure Code: -100 = UNKNOWN ERROR
Failure Code: -101 = MISSING PARAMETER
and many more -1xx failure / error-codes
Then, I want to perform a loop to check the $returned_content, if it is a failure / error-code then send again the string via cURL to the SMS gateway.
if ($returned_content = 'ANY FAILURE / ERROR-CODE') {
//redo cURL
$link = "http://www.smsgateway.com/send.php?phoneno=".$phonenumber."&message=".urlencode($smsMessage);
$returned_content = using_cURL_function_to_get_response($link);
// Check the $returned_content
} else {
// inform me the '200 = SUCCESS' via email
mail($myEmail, $successfulSubjectt, $returned_content, $msgHeaders);
}
I'm not sure about this looping part, anyone could help?
I guess what you're trying to do is this:
$link = "http://www.smsgateway.com/send.php?phoneno=".$phonenumber."&message=".urlencode($smsMessage);
while ($returned_content != '200 = SUCCESS')
{
$returned_content = using_cURL_function_to_get_response($link);
}
mail($myEmail, $successfulSubjectt, $returned_content, $msgHeaders);
But it's not a good idea. Suppose you never do get a success? You will have an infinite loop. You should really rethink what you're trying to do.
So when you try to send an SMS and you get an error, you want to retry sending? How would that work?
Also, not sure, but the target server might interpret this as a DoS attack.
I think you should rethink your approach. If your goal is enabling some users to send SMS, then how about presenting them with a message saying that there was an error delivering their SMS and they should try later?

Categories