laravel client api with guzzle - laravel

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

Related

error trying to create order in paypal with guzzle and laravel

I am trying to create an order in paypal with laravel and guzzle and it throws me this error:
GuzzleHttp\Exception\ClientException Client error: POST https://api-m.sandbox.paypal.com/v2/checkout/orders resulted in a
400 Bad Request response:
{"name":"INVALID_REQUEST","message":"Request is not well-formed,
syntactically incorrect, or violates schema.","debug_id (truncated...)
my controller code:
$accessToken = $this->getAccessToken(); $client = new Client(['base_uri' => 'https://api-m.sandbox.paypal.com/v2/checkout/']);
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $accessToken,
];
$params = [
'intent' => 'CAPTURE',
'purchase_units' => [
'amount' => [
'currency_code' => 'USD',
'value' => '100.00'
]
]
];
//dd($params);
$response = $client->request('POST', 'orders', [
'headers' => $headers,
'form_params' => $params
]);
Your $params object is invalid. It should be a list of purchase_unit items, not an associative array.
$params = [
'intent' => 'CAPTURE',
'purchase_units' => [
[
'amount' => [
'currency_code' => 'USD',
'value' => '100.00'
]
]
]
];
https://developer.paypal.com/api/orders/v2/#orders-create-request-body
'form_params' => $params
This is used to send an application/x-www-form-urlencoded POST request, which the PayPal API does not use.
You should be posting a plain string, JSON encoded. In place of form_params try passing the json key to guzzle in the request, or read its documentation on how to send json
edit: not sure whether that change makes a difference, but the other answer is correct that purchase_units needs to be an indexed array of purchase_unit objects -- likely only one of them.

Guzzle authentication returning 400 error

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));

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']
]);

Guzzle - Laravel. How to make request with x-www-form-url-encoded

I need to integrate an API so I write function:
public function test() {
$client = new GuzzleHttp\Client();
try {
$res = $client->post('http://example.co.uk/auth/token', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'json' => [
'cliend_id' => 'SOMEID',
'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
'grant_type' => 'client_credentials'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
dd($res);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
as a responde I got message:
{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}
Now when I try to run the same url with same data in POSTMAN app then I get correct results:
What is bad in my code? I send correct form_params also I try to change form_params to json but again I got the same error...
How to solve my problem?
The problem is that in Postman you're sending the data as a form, but in Guzzle you're passing the data in the 'json' key of the options array.
I bet that if you would switch the 'json' to 'form_params' you would get the result you're looking for.
$res = $client->post('http://example.co.uk/auth/token', [
'form_params' => [
'client_id' => 'SOMEID',
'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
'grant_type' => 'client_credentials'
]
]);
Here's a link to the docs in question: http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields
Also, I noticed a typo - you have cliend_id instead of client_id.

Post Multipart and Json together with Guzzle in Laravel

I'm trying to POST multipart and json data with Guzzle to build my apps with Phonegap Build API. I've tried many adjustment but still got error results. Here's the latest function I'm using:
public function testBuild(Request $request)
{
$zip_path = storage_path('zip/testing.zip');
$upload = $this->client->request('POST', 'apps',
['json' =>
['data' => array(
'title' => $request->title,
'create_method' => 'file',
'share' => 'true',
'private' => 'false',
)],
'multipart' =>
['name' => 'file',
'contents' => fopen($zip_path, 'r')
]
]);
$result = $upload->getBody();
return $result;
}
This is my the correct curl format that has success result from the API, but with file I have in my desktop:
curl -F file=#/Users/dedenbangkit/Desktop/testing.zip
-u email#email.com
-F 'data={"title":"API V1 App","version":"0.1.0","create_method":"file"}'
https://build.phonegap.com/api/v1/apps
As mentioned before, you cannot use multipart and json together.
In your curl example it's just a multipart form, so use the same in Guzzle:
$this->client->request('POST', 'apps', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($zip_path, 'r'),
],
[
'name' => 'data',
'contents' => json_encode(
[
'title' => $request->title,
'create_method' => 'file',
'share' => 'true',
'private' => 'false',
]
),
]
]
]);

Resources