Guzzle authentication returning 400 error - laravel

I'm trying to authenticate in an api sandbox but error 400 is returning me, I already got it through an extension but in the code with guzzle it's not working, I need to pass the Header parameter with encrypted authorization as it is.
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Basic $token']]);
$response = $client->post('', [
'grant_type' => 'password',
'scope' => 'forintegration',
'username' => '',
'password' => '',
]);
$body = $response->getBody();
print_r(json_decode((string) $body));

Working with:
$client = new \GuzzleHttp\Client();
$url = "";
$response = $client->request('POST', $url, [
'headers' => [
'Accept' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic $token'
],
'form_params' => [
'grant_type' => 'password',
'scope' => 'forintegration',
'username' => '',
'password' => ''
]
]);
$body = $response->getBody();
print_r(json_decode((string) $body));

Related

Make Guzzle POST Request in Laravel using 2 types of authorization

I am trying to make a post request to a url that first requests for a username and password and then I provide the api_key to authorize myself in Laravel but without success. Can you please help?
$credentials = base64_encode('username1' .':' . 'password1');
try {
$defaultValues = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Basic '. $credentials,
],
'auth' => 'Bearer ' . $api_key,
'verify' => false
];
$client = new Client($defaultValues);
$response = $client->post(config('myurl') . '/payments' . '/createPayment', ['json' => $data]);
Thanks
Change your code to this:
$credentials = base64_encode('username1' .':' . 'password1');
try {
$defaultValues = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Basic '. $credentials,
],
'api_token' => $api_key,
'verify' => false
];
$client = new Client($defaultValues);
$response = $client->post(config('myurl') . '/payments' . '/createPayment', ['json' => $data]);

laravel client api with guzzle

I'm using API from RapidAPI face verification https://rapidapi.com/HiBrainy/api/face-recognition4 and
I have difficulty using the API
this example code PHP from RapidAPI
$client = new http\Client;
$request = new http\Client\Request;
$body = new http\Message\Body;
$body->addForm(array(
'photo1' => array(
'value' => 'image2.jpg',
'data' => 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAQ=='
),
'photo2' => array(
'value' => 'image2.jpg',
'data' => 'data:image/jpeg;base64,/9j/4AAQSkZ630QAMXaf//Z'
)
), NULL);
$request->setRequestUrl('https://face-recognition4.p.rapidapi.com/FaceVerification');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setHeaders(array(
'x-rapidapi-host' => 'face-recognition4.p.rapidapi.com',
'x-rapidapi-key' => $my_api_key,
'content-type' => 'multipart/form-data'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
I applied to laravel with the guzzle package
my code
try {
...other code...
$client = new Client();
$response = $client->post('https://face-recognition4.p.rapidapi.com/FaceVerification', [
'headers' => [
'x-rapidapi-host' => 'face-recognition4.p.rapidapi.com',
'x-rapidapi-key' => $my_api_key,
'content-type' => 'multipart/form-data'
],
'multipart' => [
[
'name' => 'photo1',
'contents' => $image1,
'filename' => 'image1.jpg'
],
[
'name' => 'photo2',
'contents' => $image2,
'filename' => 'image2.jpg'
]
]
]);
}catch (\Exception $error){
dd($error);
}
I got error
#message: """
Client error: `POST https://face-recognition4.p.rapidapi.com/FaceVerification` resulted in a `400 Bad Request` response:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":4 (truncated...)
You should consider removing your API key from the code you're sharing
Try to have a look at the raw request to have further details and verify that your request have been formatted correctly

Guzzle Not Sending Grant Type to Laravel Passport

Im a little stumped with my code, I am running Laravel 6 with Guzzle Http Client version 6.3.3.
I have opted to use a trait which I use on my API Gateway for communicating with micro services instead of bloating code base with repeated code.
The Trait
public function performRequest($method, $requestUrl, $formParams = [], $headers =[])
{
$core = env('CORE_URI');
$client = new Client([
'base_uri' => $core,
]);
$response = $client->request($method, $requestUrl, ['form_params' => $formParams, 'headers' => $headers]);
return $response->getBody()->getContents();
}
The failing code (Not sending the OAuth Grant Type Password even though it works using postman)
$core_client_id = env('CORE_CLIENT_ID');
$core_client_secret = env('CORE_CLIENT_SECRET');
$username = $request->input('username');
$password = $request->input('password');
return $this->performRequest('POST','/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => $core_client_id,
'client_secret' => $core_client_secret,
'username' => $username,
'password' => $password,
'scope' => '',
],
'headers' => [
'content-type' => 'multipart/form-data',
]
]);
The Exception Guzzle is returning is 400 Bad Request 'Unsupported Grant Type'
I fixed it by removing the headers and form params and changing my code to send the data as an array instead.
Working Code
public function attemptLogin(Request $request)
{
$core_client_id = env('CORE_CLIENT_ID');
$core_client_secret = env('CORE_CLIENT_SECRET');
$username = $request->input('username');
$password = $request->input('password');
$data = array(
'grant_type' => 'password',
'client_id' => $core_client_id,
'client_secret' => $core_client_secret,
'username' => $username,
'password' => $password,
'scope' => '',
);
return $this->performRequest('POST','/oauth/token', $data);
}
I searched on the internet a bit and found out that OAuth2 specification for header Content-Type is "application/x-www-form-urlencoded" . To fix your problem simply remove 'content-type' => 'multipart/form-data' from 'headers'
Here is a complete code
$core_client_id = env('CORE_CLIENT_ID');
$core_client_secret = env('CORE_CLIENT_SECRET');
$username = $request->input('username');
$password = $request->input('password');
return $this->performRequest('POST','/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => $core_client_id,
'client_secret' => $core_client_secret,
'username' => $username,
'password' => $password,
'scope' => '',
],
]);

When I post params , Postman not get response, loading forever

Here my Controller
$http = new \GuzzleHttp\Client; $response = $http->post('http://127.0.0.1:8000/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'vZ2wi8dOIJLueXRzP4Dqvraad0V1GBj3DDy8RaXj,
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
When I post params like below
Not get the response.
Please help me

Can't post data via Guzzle request to Laravel 5.4

I'm having troubles posting data to my production Laravel controller to store a post request made with Guzzle from my local WAMP server. I can successfully return data with a get request, but posting data does not seem to work. I have Oauth2 setup using Laravel Passport.
The following is my Guzzle post request from the WAMP server.
$client = new \GuzzleHttp\Client();
$response = $client->post('https://www.website.com/oauth/token', [
'form_params' => [
'client_id' => 99,
'client_secret' => '***',
'grant_type' => 'password',
'username' => 'username#mail.com',
'password' => 'password',
'scope' => '*',
],
]);
$auth = json_decode((string) $response->getBody()->getContents());
$data = [
'first_name' => 'Post', 'last_name' => 'Man',
'email' => 'postman#mail.com', 'phone' => '0400000000',
'country' => 'Internet', 'state' => 'HTTP'
];
$json_data = json_encode($data);
$header = array('Authorization' => 'Bearer '.$auth->access_token, 'Content-Type' => 'application/json');
$response = $client->post('https://www.website.com/api/store_data',
['body' => $json_data, 'headers' => $header]);
$stream = $response->getBody()->getContents();
dd($stream);
Returns:
"{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}"
And when I try to store the data in my production controller nothing comes across in the request:
$enquiry = new Enquiry;
$enquiry->first_name = $request->get('first_name');
$enquiry->last_name = $request->get('last_name');
....
$enquiry->save();
Post data without json_encode & use form_params instead of body
$client = new \GuzzleHttp\Client();
$response = $client->post('https://www.website.com/oauth/token', [
'form_params' => [
'client_id' => 99,
'client_secret' => '***',
'grant_type' => 'password',
'username' => 'username#mail.com',
'password' => 'password',
'scope' => '*',
],
]);
$auth = json_decode((string) $response->getBody()->getContents());
$data = [
'first_name' => 'Post', 'last_name' => 'Man',
'email' => 'postman#mail.com', 'phone' => '0400000000',
'country' => 'Internet', 'state' => 'HTTP'
];
$header = array('Authorization' => 'Bearer '.$auth->access_token, 'Content-Type' => 'application/json');
$response = $client->post('https://www.website.com/api/store_data',
['form_params' => $data, 'headers' => $header]);
$stream = $response->getBody()->getContents();
dd($stream);
For store the data:
$post = $request->all();
Enquiry::create([
'first_name' => $post['first_name'],
'last_name' => $post['last_name']
]);

Resources