I have page which checks data sent via HTTP POST (http://example.com/http_post). If the data is good I add to database and wish to set http response code 201 and a success message as http response. If not I collect the errors in a an array and wish to set http response code and message as serialized JSON array as http response.
1) Whats the syntax to serialze the errors array as JSON in php?
Example
{
"message": "The request is invalid.",
"modelState": {
"JobType": [ "Please provide a valid job type eg. Perm"]
}
}
Whats the syntax to set and return the http response to 412.
Whats the syntax to set and return the serialized JSON in the http response body as above.
An example would be helpful on how to set all these http response headers.
Thanks
You are probably looking for...
$arr = array('message' => 'blah'); //etc
header('HTTP/1.1 201 Created');
echo json_encode($arr);
Related
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)
I'm using the below code to return JSON data to my mobile application (I'm posting data to the Stripe server to create a customer and return a key to my iOS application). That said, when I post to this endpoint, the customer and key are created in the Stripe backend (awesome), but the following error comes back to my app - is my PHP formatted incorrectly? I'm under the impression that my code should be returning JSON... but my error is telling me it's not.
Error message:
Error Domain=com.alamofire.error.serialization.response Code=-1016
"Request failed: unacceptable content-type: text/html"
PHP:
<?php
$customer = \Stripe\Customer::create(array(
));
$key = \Stripe\EphemeralKey::create(
["customer" => $customer->id],
["stripe_version" => $_POST['api_version']]
);
header('Content-Type: application/json');
exit(json_encode($key));
}
JSON response when navigating to PHP file in browser:
{"id":"ephkey_000","object":"ephemeral_key","associated_objects":[{"id":"cus_iD","type":"customer"}],"created":1601166469,"expires":1601170069,"livemode":false,"secret":"ek_test_key_here"}
You can test your script in the browser by adding $_POST = ['api_version' => 'whatever' ]; just to see what JSON the script outputs. I'm guessing something else in the script is throwing an error, causing PHP to output a Content-Type: text/html header.
I have been asked to write a program that takes a list of numbers and sends a post to ms.4url.eu via JSON/HTTP Post in format:
{
"username":"a",
"password":"b",
"msisdn":"071231231234",
"webhook":"http://example.com"
}
it receives a JSON Response,
{
"status":"ok",
"id":"1234-1234-12344423-123123"
}
I have been told I can use ngrok for the webhook and I have to send a HTTP Response 200 within 1s.
I should receive a Webhook Response:
{
"id":"1234-1234-12344423-123123",
"msisdn":"071231231234",
"status":"unavaliable",
"error":"1b",
"errorDesc":"Abscent Subscriber"
}
How would I go about grabbing the data from the JSON response and Responding with a HTTP 200 in order to receive the second response with the data?
I can get the first response in curl but I am unable to get the webhook working to a php file using ngrok and HTTP response sent to request the main information in the second response.
Edited :
I have executed the curl command,
curl -H 'content-type: application/json' \
-d '{"username":"a", "password":"b", "msisdn":"07123123124","webhook":"http://example.com/"}' \
HTTPS://ms.4url.eu/lookup
of which I get the first response "status ok". I would like to know how to get the response(Json format) in php using http post to the URL and the using a webhook to respond with 1second with a http 200 response to receive the further information from the API URL.
I ended up using ngrok and viewing the Raw POST response and getting the JSON and viewing the Raw data I still had more code to do in order t make this question valid as there are too many points to answer.
I'm making a Guzzle request to an api, and
$request = $this->client->request('GET', 'https://etc', ['http_errors' => false]);
I've had to turn http_errors off as if the API wants to tell me something it does it as a JSON response but it also has a header code of 402.
I can get the response headers back from Guzzle, but I'm unable to get the actual body $request->getBody() as this is just an empty stream on the response object.
Does anyone know how I retrieve the original page despite it providing a 402 http error.
NB: If I don't turn off http_errors, it will throw an exception but the message is wrapped (and truncated).
Any suggestions would be gratefully received.
I stumbled across the answer I was looking for.
If I don't turn off http_errors and catch the exception I can run
$e->getResponse()->getBody()->getContents();
to retrieve the contents of the request.
Greetings,
I was trying to discover a proper way to send captured errors or business logic exceptions to the client in an Ajax-PHP system. In my case, the browser needs to react differently depending on whether a request was successful or not. However in all the examples I've found, only a simple string is reported back to the browser in both cases. Eg:
if (something worked)
echo "Success!";
else
echo "ERROR: that failed";
So when the browser gets back the Ajax response, the only way to know if an error occurred would be to parse the string (looking for 'error' perhaps). This seems clunky.
Is there a better/proper way to send back the Ajax response & notify the browser of an error?
Thank you.
You could send back an HTTP status code of 500 (Internal server error) , and then include the error message in the body. Your client AJAX library should then handle it as an error (and call an appropriate callback etc.) without you having to look for strings in the response.
I generally send back a JSON response like this:
$response = array('status' => 'error', 'message' => 'an unknown error occured');
if( some_process() ) {
$response['status'] = 'success';
$response['message'] = 'Everything went better than expected.';
} else {
$response['message'] = "Couldn't reticulate splines.";
}
die( json_encode($response) );
So, I can check the status of response.status in my JavaScript and look for a value of "sucess" or "error" and display response.message appropriately.
showing to the user a status of what is happening and what has happened is very important.
I you want to structure your ajax responses, you should look into the json format.
if (something worked)
echo '{ "error": 0 }';
else
echo '{ "error": 1 }';
Once you set foot into the json world, you will be able to send more structured output. For example :
if (something worked)
echo '{ "error": 0 }';
else
echo '{ "error": 1, "code": 889, "desc": "Something bad happened" }';
When you receive this output in javascript, you can transform it into an object and take actions depending on the different keys.
The library json2.js will help you transform your output into an object
Sending the appropriate http headers should do the trick and tell your ajax scripts to execute the right callback. Each javascript framework i know of has a success and error callback for it's XHR requests.
header('HTTP/1.1 500 Internal Server Error');
You can send back a JSON object which contains a custom error code and error message which you can then either handle or display directly to your users:
{
"response": 10,
"message": "The database didn't work or something"
}
It would work for success as well:
{
"response": 1,
"message": "It worked! Yippee!"
}