laravel callback url with file_get_contents('php://input') - php

in vanilla php i would create a callbak url with just
try
{
//response content type application/json
header("Content-Type:application/json");
//read incoming request
$postData = file_get_contents('php://input');
.......
......
but in laravel i'm yet to get a clear explanation on how to achieve the same
ive tried using
$postData = Request::getContent();
but it returns blank

If you need data in request use (new \Illuminate\Http\Request())->all() or use DI
public function someAction(\Illuminate\Http\Request $request)
{
dd($request->all());
}

Related

how to get http request detail in laravel?

I have an http client request like this?
try {
$request = json_encode($data);
$result = $this->pendingRequest->{$method}('http://test.local/general/wallets/1000000', $data);
// this is my request detail
$request = $result->transferStats ? Message::toString($result->transferStats->getRequest()) : $request;
$result->throw();
$this->setLog($provider, $step, $request, $result->body(), $url, $result->status());
return $result;
} catch (RequestException $exception) {
// I need to http request detail
} catch (ConnectionException $exception) {
// I need to http request detail
}
I need to get my request param and headers and token and every thing that send to third party in cache exceptions. I can get detail in try via: Message::toString($result->transferStats->getRequest())
you can #dd($request);
on blade OR
dd($request); on controllers etc..
Illuminate\Http\Client\Request
headers() : array
Get the request headers.
parameters() : array
Get the request's form parameters.
body() : string
Get the body of the request.
data() : array
Get the request's data (form parameters or JSON).
You can take it as
$request->all();
if you want to see more regular. you can try
dd($request->all());

Laravel HTTP Client - method chaining issue

I have been using the HTTP client in Laravel 8, as follows:
$http = Http::asForm()->post($url, $post_data);
$response = $http->body();
This works great. Now I want to include a file upload as part of this request, but the file is optional. I have tried to structure my request like this:
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
public function index(Request $request)
{
$url = 'my-url';
$post_data = $request->post();
$http = Http::asForm();
if ($request->hasFile('image')) {
$http->attach('image', $request->file('image'));
}
$http->post($url, $post_data);
$response = $http->body();
}
But this is not working. The error I am getting is: Method Illuminate\Http\Client\PendingRequest::body does not exist.
The post() method appears to be returning Illuminate\Http\Client\PendingRequest instead of Illuminate\Http\Client\Response.
Any ideas how to do this?
$response = $http->post($url, $post_data)->body();
// alternatively:
$pendingRequest = $http->post($url, $post_data);
$response = $pendingRequest->body();
In your second code sample, you don't assign the return of post() to a variable. But this return value (Illuminate\Http\Client\PendingRequest) is the object that defines the body() method. So either use a second variable (or reassign $http), or chain the post() and body() calls as shown above.

Laravel get request body with correct encoding

The function is simple, I need to forward a post request to an external API service. I am using Laravel 5.5 and the $client is Guzzle 6 client;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
public function insert(Request $request)
{
try {
$body = $request->json()->all();
$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$body]);
return response($response->getBody(),$response->getStatusCode())>withHeaders($response->getHeaders());
}catch(Exception $e){
.....
}
}
the problem is the $bodyStringRAW = $request->json()->all();
the data send to laravel is
[{"name":"Secion4小明","comment":"","applicationId":"59"}]
the data received by the external API is [{"name":"Secion4\u5c0f\u660e","comment":null,"applicationId":"59"}]
If i change the code to
$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$request->getContent()]);
the external API received the data as
[{\"name\":\"Secion4\u5c0f\u660e\",\"comment\":\"\",\"applicationId\":\"59\"}]
How can I make the encoding correct? I Can't find the way to set the encoding.
Update 1:
$body = utf8_decode($request->getContent());
$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$body]);
External API got
[{\"name\":\"Secion4??\",\"comment\":\"\",\"applicationId\":\"59\"}]
The data is is Unicode, you can convert with utf8_decode.

I can't receive POST data in php with slim framework

I try to make a RESTful api using slim framework.
I do not know details about the slim framework, because i'm beginner of this framework.
So, I followed all steps of how to get data in slimframework. But i can't get POST data.
Follow is my code to get POST data.
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
$app->post('/registration/user', function (Request $request, Response $response) use ($app) {
$data = $request->getParsedBody();
$name = $_POST['name'];
echo '1 : '.$data['name'];
echo '2 : '.$name;
});
That is result of when i send name data.
what i have to do for get post data??
Do you have any idea?
I use \Slim\Http\Request $request->getParsedBody() in my routes. The method contains all the $_POST data.
Example:
$postArr = $request->getParsedBody();
$name = $postArr["name"];
The following can be used:
$body= file_get_contents("php://input");
// $body = $request->getBody();
$data = json_decode($body, true);

Laravel - POST data is null when using external request

I'm new to laravel, and I'm trying to implement a simple rest api.
I have the controller implemented, and tested via unit testing.
My problem is with the POST request.
Via the tests Input:json has data, via an external rest client it returns null.
This is the code on the unit test
$newMenu = array(
'name'=>'Christmas Menu',
'description'=>'Christmas Menu',
'img_url'=>'http://www.example.com',
'type_id'=>1,
);
Request::setMethod('POST');
Input::$json = $newMenu;
$response = Controller::call('menu#index');
What am I doing wrong?
UPDATE:
This is realy driving me crazy
I've instanciated a new laravel project and just have this code:
Routes
Route::get('test', 'home#index');
Route::post('test', 'home#index');
Controller:
class Home_Controller extends Base_Controller {
public $restful = true;
public function get_index()
{
return Response::json(['test'=>'hello world']);
}
public function post_index()
{
return Response::json(['test'=>Input::all()]);
}
}
CURL call:
curl -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test
response:
{"test":[]}
Can anyone point me to what is wrong.
This is really preventing me to use laravel, and I really liked the concept.
Because you are posting JSON as your HTTP body you don't get it with Input::all();
You should use:
$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);
$response = array('test' => $data);
return Response::json($response);
Also you can use
Route::any('test', 'home#index');
instead of
Route::get('test', 'home#index');
Route::post('test', 'home#index');
Remove header Content-type: application/json if you are sending it as key value pairs and not a json
If you use : Route::post('test', 'XYZController#test');
Send data format : Content-type : application/json
For example : {"data":"foo bar"}
And you can get the post (any others:get, put...etc) data with :
Input::get('data');
This is clearly written in here : http://laravel.com/docs/requests
. Correct Content-type is very important!
I am not sure your CURL call is correct. Maybe this can be helpful : How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
I am using Input::get('data') and it works.
I was facing this problem, my response of post was always null. To solve that I put the body key in guzzle object, like this
$client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => config('app.callisto_token'),
]
]);
$body = [
'firstResult'=> 0,
'data' => '05/05/2022'
];
$response = $client->post('http://'.$this->ip.'/IntegracaoERP'.'/status_pedido',
['body' => json_encode($body)]
);
Don't forget the json_encode in body key.
Hope this helps.

Categories