Issue while trying to receive message notifications from Slack - php

About
I am trying to receive message posted on my server as soon as user post message the message in group or channel or direct in slack.
App Status
Code in the verified file where challenge was posted.
header('Content-type: application/json');
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
$data = json_decode(file_get_contents('php://input'), true);
fwrite($myfile, $data["challenge"]);
fclose($myfile);
$json = '{"challenge":' . $data["challenge"] . '}';
echo json_encode(["challenge" => $json]);
Question
Now that the above url has been verified successfully, I am still not able to receive the posted messages. I was expecting messages posted at same url which was used to verify challenge parameter. Is that correct?
Am I missing anything retrieving the messages posted on my server?
Update - 1
Due to some reasons I am not even able to verify the url anymore. My server is not receiving any data. I am trying to save whatever is being posted my side but it is always blank everytime,

I think your assumptions are correct.
According to slack documentation you should be receiving posts with the given payload in this endpoint:
https://api.slack.com/apis/connections/events-api#the-events-api__receiving-events__events-dispatched-as-json
I'm still unsure how are you validating that this isn't the case though, if you kept the code above you would see no result of the post data sent by slack, also if you don't return a response status 200, slack will stop posting to this endpoint after 1 hour.
https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
Can you try adding test.php file something like:
<?php
// get all the POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST") {
file_put_contents('test.json', json_encode($_POST, JSON_PRETTY_PRINT), FILE_APPEND);
// return 200
http_response_code(200);
echo json_encode(["success" => true]);
return;
}
At the very beginning, validate the url again and check if the requests start being saved on test.json.
Alternatively can you check if you web server is routing POST requests to this url?
Try using postman to validate that

Related

How to get webhook response data using tradingview and php

I'm trying to get Tradingview signals to my remote php script using webhook and trading view alerts. I can't succeed . I'm following this way
In my trading view strategy I have this
strategy.entry("Long", strategy.long, alert_message = "entry_long")
strategy.exit("Exit Long", "Long", limit=LONG_take_profit, stop=LONG_stop_loss, alert_message = "exit_long")
then I set the alert as follow
Then I set a PHP script as follow to receive the POST curl JSON data from Trading view
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// decode json
$object = json_decode($json);
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
die(header('HTTP/1.0 415 Unsupported Media Type'));
}
$servdate2 = time();
$servdate=date('d-M-Y H:i:s',$servdate2);
file_put_contents("/home/user/public_html/data.txt", "$servdate :".print_r($object, true),FILE_APPEND);
}
I receive the alert via email correctly but I do not receive data in /home/user/public_html/data.txt . What am I doing wrong ? How to send the Tradingview JSON data to my remote PHP script ?
I'm not familiar with PHP, but you've asked:
How to send the Tradingview JSON data to my remote PHP script ?
Your alert message as it is currently written in the alert_message argument, is not valid JSON and therefore it is sent as a txt/plain content type. If you want the alert to be sent as application/json you will need to have it in a valid JSON.
Webhooks allow you to send a POST request to a certain URL every time the alert is triggered. This feature can be enabled when you create or edit an alert. Add the correct URL for your app and we will send a POST request as soon as the alert is triggered, with the alert message in the body of the request. If the alert message is valid JSON, we will send a request with an "application/json" content-type header. Otherwise, we will send "text/plain" as a content-type header.
You can read more about it here.
EDIT:
You can make minor adjustments to your code, and it will be sent as JSON:
strategy.entry("Long", strategy.long, alert_message = '{"message": "entry_long"}')
strategy.exit("Exit Long", "Long", limit=LONG_take_profit, stop=LONG_stop_loss, alert_message = '{"message": "exit_long"}')
Replace the script with:
<?php
file_put_contents("/home/user/public_html/data.txt", print_r([$_GET, $_POST, $_SERVER], true));
to better understand the incoming data.
Maybe the data are present in $_POST variable, if not, post the whole result here (via pastebin).
(also make sure the PHP script starts with <?php)

Sending HTTP POST multipart/form-data from Android client to HTTP server

I am writing an app that will allow the user to take a picture, which is automatically sent to an HTTP server to be classified via HTTP POST multipart/form-data. To build and send these requests, I am using Apache's HTTPClient library. I am somewhat confident that my Java clientside code works, as I have tested with one of the Imgur API endpoints and the images uploaded correctly; therefore, I think it is most likely that there is an error in the endpoint on my server. I am sending the request to server to be received by a PHP script that I wrote to receive the file, save it to directory on the server, and send a response back to the client appropriately. When I test this, the server always sends back a response with status code 200, even though the script obviously is not working. I have tried manually setting the response status code to 500 to force an error code, and even that doesn't work, which makes me think that the entire script does not even run when the request hits the endpoint (if it even hits the endpoint). I expect this to be either an error in server configuration, or an error in the script itself. However, I have pasted the Java code just in case. You may find some errors there too. I am not great with networking or with PHP, so I could definitely use some more experienced eyes.
Note: I know my PHP code looks awful. You will probably find a lot of bad practices; sorry.
My server code:
<?php
$path = '/home/user01/Documents/uploaded_images/';
$ext = '.jpg';
function getFileName() {
return 'image_'.date('Y-m-d_His');
}
//Receive the data from android client
$file = $_FILES['uploadedFile'];
//process the data
$filename = $path . getFileName() . '_' . $_SERVER['REMOTE_ADDR'] . $ext;
if (!is_uploaded_file($file['tmp_name']) ||
!copy($file['tmp_name'], $filename))
{
$message = 'Could not save file as' . $filename;
$error = True;
}
else {
$message = "Image uploaded successfully!";
$error = False;
}
//return response to the server
if ($error) {
http_response_code(500);
}
echo json_encode(
array(
'status' => 'Repsonse Code :' . http_response_code(),
'message' => $message
), JSON_FORCE_OBJECT);
?>
Update and Resolution:
After some troubleshooting with the help of a few of the post commenters, I first tried writing a simple HTML form to submit POST requests locally to the PHP script, and after those requests failed, I then added the die() function at the beginning of the code, and still, nothing happened. This allowed me to figure out that the error.
The problems that I was having were caused by a bad server configuration. It was causing PHP to not be recognized as an installed language; therefore, the script was not being executed at all. Once the configuration was fixed, the script worked exactly as expected.
Much kudos to the commenters for their insight.

Receiving JSON in php, and using data

I have been trying to set up a Shopify webhook (documentation here) through the Shopify admin section. So far I have not been able to grab any of the data being sent in a test webhook using multiple methods, but I know it is sending because I created a Requestbin and have been seeing data come through.
I found this chunk of code here on Stackoverflow.
header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input");
$file = "log.txt";
$current = file_get_contents($file);
$current .= $postdata;
file_put_contents($file, $current);
echo $current;
So far it is the only code I have been able to use to actually see any JSON. But Im not wanting to write the JSON to the "log.txt" file every time the webhook is fired. But once I try to remove or adjust the code in anyway I no longer see any JSON. It seems that I have to write $postdata to a file, and then retrieve the contents to get an array.
Is is possible to access the JSON without having to first write it to another file?
So to begin, my fundamental thought process was flawed on how webhooks worked.
header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input");
$file = "log.txt";
$current = file_get_contents($file);
$current .= $postdata;
file_put_contents($file, $current);
echo $current;
The reason this code needed to write the contents of file_get_contents("php://input") to the text file was because the POST request sent by the Shopify webhook, only hits the page briefly. As soon as you refresh the page, you lose all the POST data...seems obvious I know. That said I needed a way to determine if the JSON Shopify is sending out is working all fine on my server. So I created this...
$json = json_decode(file_get_contents("php://input"));
file_put_contents('./realRequests.txt', $json->id . "\n", FILE_APPEND);
What this does is capture the ID of an order everytime Shopify fires the webhook, and wrties it to a new line in a requests file. That way you know you are able to recive working code from shopify.

how to generate response for webhook get request

I received a get request from a site to my site. I can able to know what kind of request by using $_SERVER['REQUEST_METHOD']. Its returning GET request. Now, i need to know how to know what is the request and also generate response for the request in php.
Thanks in advance.
For reading the request do the following:
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhookContent .= fread($webhook, 4096);
}
fclose($webhook);
Then to respond you can simply echo back like:
echo "I've received your request"
Or you can respond with empty headers. Forexample PayPal doesn't require you to respond with anything just send back the 200 header like:
header('HTTP/1.1 200 OK');
If the received data is in Json format then you can process it's contents by doing something like:
$json = json_decode($webhookContent, true);
If that request has a key like webhookname then you can get it by doing:
$key = $json['webhookname'];
Hope I've covered everything.

Processing POST data from a third party

I have been struggling with the following problem for few days. I am expected to receive POST data from a third party company for certain real time events. I have been in contact with them as to why my script isn't seeing anything. Unfortunately, they are less then helpful and just tell me "it works for everybody else".
I setup a simple PHP script after doing some research on the web but it always shows no post data. This isn't my area of expertise so I may be missing something obvious.
Here is the only documentation they give:
This API will send a real-time http request upon every successful event with all of the conversion data. The data is sent via an http POST method, and the data is JSON formatted.
This is my script which for now is trying to just log it to a file. The file is created and I see the IP address of the request but the output is empty in terms of post data.
ob_start();
echo "Request from :" . $_SERVER[REMOTE_ADDR];
echo "print_r:".print_r($_POST,true);
if(array_key_exists('app_id', $_POST))// me attempting to access a specific key they claim is in the post data
{
echo "app id = " . $_POST['app_id'];
}
//I also tried both of these and neither output anything
//foreach ($_POST as $key => $value) //idea 1
foreach($_POST as $item) //idea 2
{
//echo "key=".$key." value=".$value; //idea 1 log
echo "next=";//idea 2 log
echo $item;
}
$contents = ob_get_flush();
file_put_contents("log.txt",$contents,FILE_APPEND);
There's not a lot to go on here -- who knows what the client is actually sending -- but here's a thought:
POST is just an HTTP command. It's traditional for the body of a POST to be a series of key-value pairs from a form, but it is not actually necessary. It's possible that the remote client is issuing a POST request to your server and then just delivering a JSON blob in the request body, which would not be successfully parsed into the $_POST array.
I recommend exploring the answer at How to get body of a POST in php? to see if that helps shed light on this problem.

Categories