I'm working on an integration between Slack and Filemaker utilizing PHP. I am successful in having the code create a record in Filemaker based on the json request, and also have no trouble returning the challenge key to Slack.
However, I'm having trouble passing the header response 200 OK to Slack, while passing the challenge back. It looks like it has to be one or the other.
I've tried to move the HTTP header to different areas in the code, but haven't had any success so far.
Here is the current code:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data["challenge"])) {
$body = $_SERVER['HTTP_X_SLACK_RETRY_REASON'];
require_once ('Filemaker.php');
//$body = file_get_contents('php://input');
$fm = new Filemaker();
$fm->setProperty('database', '');
$fm->setProperty('username', '');
$fm->setProperty('password', '');
$command = $fm->newPerformScriptCommand('PHP_RESPONSE', 'script', $body);
$result = $command->execute();
}
else {
header("Content-Type: text/plain");
header('X-PHP-Response-Code: 200', true, 200);
echo $data["challenge"];
}
?>
The result I expect is for the code to return the challenge code for Slack, while also returning an HTTP header of 200 OK.
Currently I can see I am receiving an error of "http_error" from Slack, which is what leads me to believe the problem is that the header is not being passed back successfully.
Any ideas on what is wrong, or suggestions on the right direction to proceed would be greatly appreciated.
The problem was occurring because for events slack doesn't send "challenge" as a parameter when sending events. It looks like echoing "challenge" is only needed when initially setting the URL for the events API.
I enclosed the challenge echo in a if statement that would only trigger if the challenge variable was present. After doing so the 200 OK was successfully passed.
Here is the code I used that solved the problem for me:
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data["challenge"])) {
$message = [
"challenge" => $data["challenge"]
];
header('Content-Type: application/json');
echo json_encode($message);
}
The documentation is actually a bit inconsistent on this topic. It claims you can respond the challenge in plan text, but the example shows it as x-www-form-urlencoded.
To be on the safe side try returning the challenge as JSON. That works perfectly for me. You also do not need to explicitly set the HTTP 200 code.
Example code:
$message = [
"challenge" => $data["challenge"]
];
header('content-type: application/json');
echo json_encode($message);
Related
So what I'm trying to do is: with a link similar to: http://localhost/API-REST/Endpoints/ajoutDeMessage.php?contenu='Hello'&idUser=4. For now, I'm only testing my request with Postman. So I'm putting this URL directly in Postman, and press send.
When I'm doing a request without a body, it works fine.
So, I need to send a string and an id through the URL, and with a function, I'm inserting these data in my database.
With the php://input, I expect to have the variables contenu and idUser in the body for a SQL request.
What I want to do next is a React app which will communicate with the API (but that's not related for now).
So here is my code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once('../Configuration/database.php');
require_once('../Users/messages.php');
$database = new Database();
$db = $database->getConnection();
$json = json_decode(file_get_contents("php://input"),true);
var_dump($json);
if(!empty($json->contenu) && !empty($json->idUser)){
$contenu = strip_tags($json->contenu);
$idUser = strip_tags($json->idUser);
$message = new Messages($db);
if ($message->addMessage($contenu,$idUser)){
http_response_code(201);
$response['message'] = 'GOOD ENTRY';
}else{
http_response_code(400);
$response['message'] = 'BAD ENTRY';
}
}else{
http_response_code(400);
$response['message'] = 'INCOMPREHENSIBLE DATA';
}
echo json_encode($response);
} else {
http_response_code(405);
$response['error_code'] = 405;
$response['message'] = 'BAD REQUEST TYPE';
echo json_encode($response);
}
There is no post body
i'm putting this url directly in postman, and press send.
I don't use postman myself, but doing this will generate a post request with no data it's the equivalent of:
curl -X POST http://example.com
That's not passing a post body at all. The intent is more like:
curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'
This is why file_get_contents("php://input") doesn't return anything.
Note that html form data is available via $_POST - but only for urlencoded POST bodies (which I understand not to be the intent of the question).
Where is the data?
i'm putting this url directly in postman, and press send.
Returning to this quote, the only place for the data is in the url - that is not the normal way to pass data with a post request.
Url arguments are available via $_GET, with the url in the question this code:
<?php
var_dump($_GET);
will output:
array(2) {
["contenu"]=>
string(7) "'Hello'"
["idUser"]=>
string(1) "4"
}
A detail, but note the string includes the single quotes which are in the url (that are probably not desired).
What's the right way to do this?
With a request being made like this:
curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'
That data can be accessed like so:
<?php
$body = file_get_contents('php://input');
$data = json_decode($body, true);
$jsonError = json_last_error();
if ($jsonError) {
print_r(['input' => $body, 'error' => json_last_error_msg()]);
exit;
}
echo $data['contenu']; // Hello
echo $data['idUser']; // 4
...
This is very similar to the code in the question, the error appears to primarily be how the request is being made rather than the php logic.
I'm trying to create a relatively simple PHP endpoint for users to send requests to. I know that the endpoint is working because when I accessed it using cURL the parameters I sent to my database we're added. The problem however is that when I use
var_dump($response);
The page returns "NULL".
So the code is working fine, I just want to know how to print an error/success message
This is what I've tried so far on the endpoint
header("HTTP/1.1 200 OK");
header('Content-Type: text/plain');
echo 'Success message';
the full cURL code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
);
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = json_decode($resp, true);
var_dump($response);
So how can I get the success message to properly show instead of "NULL"?
Test if your curl code returns something by testing: var_dump($resp). It looks like NULL comes from json_decode. You are not returning valid JSON from the endpoint.
php > var_dump(json_decode("Success message", true));
NULL
Try returning a json string such as:
php > echo json_encode("Success", true);
"Success"
Note the " around it. This encodes a json string. See the JSON spec for a reference on how to encode json. Best practice, if your return json, then run your content through json_encode().
Your curl code seems correct.
I want to send a HTTP post request to my node.js server. I pass a JSON object as body (content type is set to application/json).
If I send -exactly- the same JSON object in the body via Postman (https://www.getpostman.com) it works perfectly! If I use this plugin here: https://github.com/Mashape/unirest-php it is not working, I get HTTP error 500 and error message 'Cannot read property '0' of undefined' like something would be wrong with my route/ my passed JSON.. which is definitely not the case because Postman works.
How can I fix this? Is there maybe a better PHP plugin that works as it should?
I hope somebody can help me.
//HTTP Requests an Node Server. Pfade entsprechend abändern sobald live
$teamsMemberOf = Unirest\Request::get("http://localhost:3001/members-matter/mm-teams/".$result['_id']."/get-teams");
$json = $teamsMemberOf->raw_body;
$buildJson = '{"team":'.$json.'}';
//$sendJsonEncoded = json_decode($buildJson, true);
$headers = array("Accept" => "application/json");
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/members-matter/mm-boxes/".$result['_id']."/get-relevant-boxes-amount", $headers, $buildJson);
//$relevantBoxesAmount = Unirest\Request::post("http://mockbin.com/echo?", $headers, $buildJson);
//$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/members-matter/mm-boxes/56954133596dc02d0695cb89/get-relevant-boxes-amount", $headers, $sendJsonEncoded);
echo $relevantBoxesAmount->code;
echo $relevantBoxesAmount->raw_body;
I am receiving Web Service from iOS device. But when I try to print the request that I have received I get data as empty.
Input Sent from iOS device as Service. It is sent as POST from iOS:
{"AccessToken"={"Mykey":"test123"}
Code in my PHP Page:
foreach($_REQUEST as $value)
{
$xml_content_array = trim($value);
}
What else I have tried:
if(empty($xml_content_array) === true)
{
$xml_content_array = trim($HTTP_RAW_POST_DATA);
}
Even $HTTP_RAW_POST_DATA is not printing anything. Also tried the below:
file_get_contents('php://input');
Did not work.
I am pretty sure the data is coming from the iOS end but I am unable to capture the POST request.
Thanks in advance
This should work
$access_token = $_POST["AccessToken"];
echo $access_token;
I'm trying to use Pubsubhubub to get real time RSS feeds update. I'm using PHP for that purpose.
I subscribed to thenextweb as an example;
$hub_url = "http://pubsubhubbub.appspot.com/";
$callback_url = "http://xx.com/rss/callback.php";
$feed = "http://feeds2.feedburner.com/thenextweb";
$sub = new Subscriber($hub_url, $callback_url);
$status = $sub->subscribe($feed);
I receive The hub returns code 202, and after that a "GET" response to my callback.php with the hub_challenge and other stuff. I followed what the tutorials suggest of echoing this number, and hence, the hub will be able to push updates to my callback.
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe') {
$challenge = $_GET['hub_challenge'];
header('HTTP/1.1 200 "OK"', null, 200);
header('Content-Type: text/plain');
echo $challenge;
}
That's how I echo the challenge number. The problem here is that I don't get any other messages from the hub even though i have a condition to handle any POST message in my callback.
else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
//doing stuff with the data here
}
I'm not sure if the problem is with the echo part or after that. Does anyone have similar issues? what am I doing wrong?
I just solved the problem. Apparently I was using a different topic_url, I was using this link: http://feeds.feedburner.com/TheBoyGeniusReport?format=xml. Instead, view the page source and make sure you are using the link inside href. The highlighted link below is what you're supposed to use.
... xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheBoyGeniusReport"...