Getting null when posting data using Guzzle Client in Laravel - laravel

Am working on an a Laravel application whereby am posting some data to an API using Guzzle Http Client. The APIhas passport authentication which requires the token of the authenticated user to be passed on the headers. The headers also accept application/json as content-type and accept type.
I am also passing the data via POST request
The problem is that I keep getting a null response.
public
function post_policies($data, $token, $url) {
$client = new Client();
$serverURL = 'http://localhost/digital-apps-apis/public'.
'/'.$url;
$body = $client - > request('POST', $serverURL, $data, [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer '.$token,
]) - > getBody();
$contents = $body - > getbody() - > getContents();
$data = json_decode($contents);
dd($data);
}

$body = $client->request('POST', $serverURL , $data, [
'debug' => true, //switch it to false before go live
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token,
]]
)->getBody();
You must define your headers in the headers array.
Since it's a post i don't see you actually sending any data in the body. But if you do use the form_params array exactly like i used the headers array.

Related

How to make this postman request with laravel httpClient

I want to make a postman request with Laravel httpClient,the request in postman is like this:
The Content-Type in the header is: application/x-www-form-urlencoded
I tried many ways to make this request with Laravel httpClient, but it either return null or return all of the datas, not the data I am looking for.
I tried this:
$res = Http::withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic XXXXXXXXXX'
])->withBody(http_build_query(["uuid"=>$uuid]),"application/json")->post("https://xxx.com.cn/entity.find");
and also tried this:
$res = Http::withHeaders([
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ZHh5LWVpbnRlbGxpZxxxxxxxx'
])->post("https://xxxx.com.cn/entity.find", [
"form_params" => [
"filter" => ['uuid'=>$uuid],
]
]);
All are not work. Could anyone give me some tips about this?

How to do concurrent guzzle http post request to rest api in laravel?

I want to make concurrent Guzzle http requests in laravel to rest api i have users in 100k i want to perform billing for users.
Currently my guzzle http is doing synchronous calls to rest api which is taking 6 hours to complete 100k post requests and the requests does not have any call backs they are just post request with users msisdn and unique id in json format.
How to do concurrent 50 requests per second so that billing is performed quickly.
Following is part of my code which i use taken from https://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests
$requests = function ($total) {
$url = "url here";
$auth = base64_encode($username . ":" . $password);
for ($i = 0; $i < $total; $i++) {
$msgdata =[
'msisdn'=>$msisdn,
$subscription
=>$subscriptionInfo];
yield new Request('post', $url,
[
'headers' =>
[
'Content-Type' => 'application/json',
'Authorization' => $authorizaton
],
'body' => json_encode($msgdata)
]);
}
$pool = new Pool($client, $requests(50), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
echo $response;
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
echo $reason;
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
i am getting response as
"status":401,"error":"Unauthorized"
But request params are not incorect idk why it is giving response as incorect
finally i found the solution to my problem, the problem was in request header and body parameters.
changed this
yield new Request('post', $url,
[
'headers' =>
[
'Content-Type' => 'application/json',
'Authorization' => $authorizaton
],
'body' => json_encode($msgdata)
]);
to
yield new Request('post', $url,
[
'Content-Type' => 'application/json',
'Authorization' => $authorizaton
],
json_encode($msgdata)
);

Laravel EBay API Client Credential Grant Request Gives Error, Unsupported Grant Type

I am using Laravel 8 and the Http Client library. Here is my code:
public function mintNewApplicationAccessToken()
{
$response = Http::withHeaders([
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode(config('ebay.ebay_client_id_sandbox') . ":" . config('ebay.ebay_client_secret_sandbox')),
])->post(config('ebay.ebay_token_request_endpoint_url_sandbox'), [
'grant_type' => 'client_credentials',
'scope' => urlencode(config('ebay.ebay_client_credentials_scopes_sandbox')),
]);
dd($response->json());
}
I have double checked my client_id and client secret, I am using the Ebay sandbox at the moment, have checked the sandbox url is correct, I can't figure out what is wrong with my request? I get a 400 error back saying unsupported_grant_type and the error description says grant type in request is not supported by the authorization server. I have checked my scopes and everything seems in order?
I finally figured it out. As per the documentation on the Laravel website, I changed the code from:
public function mintNewApplicationAccessToken()
{
$response = Http::withHeaders([
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode(config('ebay.ebay_client_id_sandbox') . ":" . config('ebay.ebay_client_secret_sandbox')),
])->post(config('ebay.ebay_token_request_endpoint_url_sandbox'), [
'grant_type' => 'client_credentials',
'scope' => urlencode(config('ebay.ebay_client_credentials_scopes_sandbox')),
]);
dd($response->json());
}
To:
$auth = base64_encode(config('ebay.ebay_client_id_sandbox') . ':' . config('ebay.ebay_client_secret_sandbox'));
$response = Http::asForm()->withOptions([
'debug' => true,
])->withHeaders([
'Authorization' => 'Basic ' . $auth,
])->post(config('ebay.ebay_token_request_endpoint_url_sandbox'), [
'grant_type' => 'client_credentials',
'scope' => config('ebay.ebay_client_credentials_scopes_sandbox'),
]);
dd($response->json());
So. I added asForm to the code rather than the Content-Type line, and removed the url encode from the scopes.
What surprised me most was when I removed the url encode method from the scopes it started working? Very strange.
i have also same this problem and solution is that your account is not veriyfied or still waiting for aproval kindly contact support.

Laravel not making Guzzle HTTP POST request correctly

I am working on a megento integration and trying to get the admin access token by making a post request with form data. I tested the route out on Postman and it worked correctly:
However, when I tried to implement the same request in Laravel with Guzzle Http Client, it seem just cannot make the request properly as if the form data post body is not being recognized, and it keeps showing me errors saying the field values are required. Here is my request:
$client = new \GuzzleHttp\Client();
$response = $client->post($request['magento_domain'] . '/rest/V1/integration/admin/token', [
'form_params' => [
'username' => $magento_admin_username,
'password' => $magento_admin_password
], [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
]
]);
and then this is the error I keep getting:
Update: I had also tried the request like this, it throws the same error:
$response = $client->post($request['magento_domain'] . '/rest/V1/integration/admin/token', [
'form_params' => [
'username' => $magento_admin_username,
'password' => $magento_admin_password
]
]);
I would appreciate any help!
The "Content-Type: application/json" request header is incorrect when sending a form-data body.
Just remove it, Guzzle automatically adds the correct Content-Type when using "form_params". Just JSON is wrong because the body is obviously not JSON.
I am using a JSON request in production successfully:
$res = $this->client->request('POST', 'https://.../rest/V1/integration/admin/token', [
'headers' => [
'Accept' => 'application/json',
'content-type' => 'application/json'
],
'json' => [
'username' => config('app.shopUser'),
'password' => config('app.shopPw')
]
]);
Or try using "multipart" instead of "form_params" - this should send a multipart/form-data request which is what Postman means with "form-data".
"form_params" is equivalent to "x-www-form-urlencoded".

PROBLEM with HEADER for test API Jetstream Sanctum Laravel 8x with PERMISSION

i generated two tokens:
tokenA = As2 ... xxxxx //can perform ONLY create
tokenB = Bs2 ... xxxxx //can perform ONLY update
i have the following problem
$response = $this->withHeaders([
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$tokenA],
])->post('/api/store',$data);
$response->assertStatus(201);
//the store is made without problems
$response = $this->withHeaders([
'Accept' => 'application/json',
'Authorization' => 'Bearer '.tokenB,
])->put('/api/update',$dataUpdate);
$respone->assertStatus(200);
//the test fails and returns 403. As if you don't have permission to do that
while if I call only
$response = $this->withHeaders([
'Accept' => 'application/json',
'Authorization' => 'Bearer '.tokenB,
])->put('/api/update',$dataUpdate);
$response->assertStatus(200);
the update is performed without problems.
How can I run the store and then the update in sequence?
it appears that $response continues to hold the value of tokenA

Resources