PHP GuzzleHttp . How to send a json post? - php

I have this post:
{"latitude":"","longitude":"","countryCode":"ES","filterPostalCode":"","filterCity":"","filterCountryCode":"ES","searchText":"","nextPageToken":0,"storeType":"normal","checkStoreAvailability":false}
And i'm trying to send it like this on Guzzle 6.0+
'headers' => [
'Content-Type' => 'application/json',
'Referer' => 'https://www.rituals.com/es-es/stores'],
'body' => '{"latitude":"","longitude":"","countryCode":"ES","filterPostalCode":"","filterCity":"","filterCountryCode":"ES","searchText":"","nextPageToken":0,"storeType":"normal","checkStoreAvailability":false}']
But it's not working, any way to send everything without formating it like I posted? thanks!

First of create Client object
$client = new Client([
'http_errors' => false,
'verify' => false,
]);
And then your request with params
$response = $client->request($requestMethod, $url, array_merge(
['json' => $body],
['headers' => $headers]
));

Related

send url in form params guzzle http

I use laravel and GuzzleHttp for send post request same as following
$client = new Client(['verify' => false]);
$data = [
'headers' => [
'Authorization' => 'code',
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form-params' => [
'redirect_uri' => 'http://localhost',
'code' => 'MZTADnFF6m'
]
];
$response = $client->request('POST', 'https://oom.com', $data);
but my problem is 'http://localhost' send as 'http:\/\/localhost' to api server
how can i fix this problem?
You can use stripslashes() for achieve this. You can try
stripslashes("http:\/\/localhost");
it will resultd in
http://localhost
as a result
use urlencode
here it is
'redirect_uri' => urlencode('http://localhost'),

How to use linkedin and guzzle?

How do I make calls to the linkedin api using guzzle? So far I've tried
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$access_token = 'the_access_token';
$req = $client->request('POST', '/v1/people/~?format=json', [
'headers' => ["Authorization" => "Bearer " . $access_token,
"Content-Type" => "application/json", "x-li-format"=>"json"],
'client_id' => 'the_client_id',
'client_secret' => 'the_client_secret',
'connection' => 'Keep-Alive'
]);
dd($req);
but I just get an error that reads:
Client error: POST https://api.linkedin.com/v1/people/~?format=json resulted in a 405
Im working with laravel 5.1 and guzzle 6.2.
Silly mistake simply had to change $client->request('POST', from POST to GET so it would be:
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$access_token = 'the_access_token';
$req = $client->request('GET', '/v1/people/~?format=json', [
'headers' => ["Authorization" => "Bearer " . $access_token,
"Content-Type" => "application/json", "x-li-format"=>"json"],
'client_id' => 'the_client_id',
'client_secret' => 'the_client_secret',
'connection' => 'Keep-Alive'
]);
dd($req);
I also decoded the response which makes it readable by using json_decode($request->getBody()).
Hope it helps if someone else gets stuck on the same problem.

Bigcommerce API - Creating Webhooks - Invalid Header

I'm making small steps into this project I am working on. Now creating and registering a webhook. I'm getting the below response:
400 - Invalid Header
I have tried the following code:
// Send a request to register a web hook
$http2 = new Client('https://api.bigcommerce.com', array(
'request.options' => array(
'exceptions' => false,
'headers' => array(
'X-Auth-Client' => $client_id,
'X-Auth-Token' => $access_token,
'Content-Type' => 'application/json',
'X-Custom-Auth-Header' => $access_token,
)
)
));
$request = $http2->post('/'.$store_hash.'/v2/hooks', null, array(
'scope' => 'store/order/*',
'destination' => 'https://example.com/process_order.php',
'is_active' => true
));
$response = $request->send();
$body = $response->getBody(true);
var_dump($body);
echo '<p>Status Code: ' . $response->getStatusCode() . '</p>';
... and
// Send a request to register a web hook
$http2 = new Client('https://api.bigcommerce.com', array(
'request.options' => array(
'exceptions' => false,
'headers' => array(
'X-Auth-Client' => $client_id,
'X-Auth-Token' => $access_token,
'Content-Type' => 'application/json',
)
)
));
$request = $http2->post('/'.$store_hash.'/v2/hooks', null, array(
'scope' => 'store/order/*',
'headers' => array(
'X-Custom-Auth-Header' => $access_token,
),
'destination' => 'https://example.com/process_order.php',
'is_active' => true
));
$response = $request->send();
$body = $response->getBody(true);
var_dump($body);
echo '<p>Status Code: ' . $response->getStatusCode() . '</p>';
I am working with the documentation here:
https://developer.bigcommerce.com/api/stores/v2/webhooks#create-a-hook
However, I can't seem to work out what {secret_auth_password} is as well? The documentation doesn't explain this. I am sending the Client ID and Client Header as part of the headers as well.
Still getting Invalid Header as a response.
I am using Guzzle.
Can anyone assist me on this please?
I have finally worked out what I did wrong after numerous attempts.
Answer: send the data in JSON format.
Resolved Code:
// Send a request to register a web hook
$http3 = new Client('https://api.bigcommerce.com', array(
'request.options' => array(
'exceptions' => false,
'headers' => array(
'X-Auth-Client' => $client_id,
'X-Auth-Token' => $access_token,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
)
)
));
$request = $http3->post('/'.$store_hash.'/v2/hooks', null, json_encode(array(
'scope' => 'store/order/statusUpdated',
'destination' => 'https://example.com/process_order.php',
)));
$response = $request->send();

Can't set Guzzle Content Type

I'm trying to request this way:
$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'defaults' => [
'auth' => [$publishable_key, ''],
],
'body' => json_encode($body),
]);
The problem is that this request is being set without Content-Type.
What am I doing wrong?
Ok .. the problem was that I was setting body and headers outside of defautls. the solution is:
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'defaults' => [
'auth' => [$publishable_key, ''],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($body),
],
]);
Guzzle 6
Guzzle will set the Content-Type header to
application/x-www-form-urlencoded when no Content-Type header is
already present.
You have 2 options.
Option 1: On the Client directly
$client = new GuzzleHttp\Client(
['headers' => [
'Content-Type' => 'application/json'
]
]
);
Option 2: On a Per Request basis
// Set various headers on a request
$client = new GuzzleHttp\Client();
$client->request('GET', '/whatever', [
'headers' => [
'Content-Type' => 'application/json'
]
]);
You can refer to Guzzle 6: Request Options
I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.
I fixed it this way
$client = new Client([
'base_uri' => 'https://api.hubapi.com/',
'timeout' => 5,
'headers' => ['Content-Type' => 'application/json']
]);
And then performing my requests the regular way
try
{
$response = $client->request('POST', '/contacts/v1/contact/email/test#test.com/profile',
['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }
I hope this helps.

How do I send parameters for a PUT request in Guzzle 5?

I have this code for sending parameters for a POST request, which works:
$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'http://example.com/test.php');
$body = $request->getBody();
$request->getBody()->replaceFields([
'name' => 'Bob'
]);
However, when I change POST to PUT, I get this error:
Call to a member function replaceFields() on a non-object
This is because getBody is returning null.
Is it actually correct to send PUT parameters in the body? Or should I do it in the URL?
According to the manual,
The body option is used to control the body of an entity enclosing
request (e.g., PUT, POST, PATCH).
The documented method of put'ing is:
$client = new GuzzleHttp\Client();
$client->put('http://httpbin.org', [
'headers' => ['X-Foo' => 'Bar'],
'body' => [
'field' => 'abc',
'other_field' => '123'
],
'allow_redirects' => false,
'timeout' => 5
]);
Edit
Based on your comment:
You are missing the third parameter of the createRequest function - an array of key/value pairs making up the post or put data:
$request = $client->createRequest('PUT', '/put', ['body' => ['foo' => 'bar']]);
when service ise waiting json raw data
$request = $client->createRequest('PUT', '/yourpath', ['json' => ['key' => 'value']]);
or
$request = $client->createRequest('PUT', '/yourpath', ['body' => ['value']]);
If you're using Guzzle version 6 you can make PUT request this way:
$client = new \GuzzleHttp\Client();
$response = $client->put('http://example.com/book/1', [
'query' => [
'price' => '50',
]
]);
print_r($response->getBody()->getContents());
In Guzzle 6, if you want to pass JSON data to your PUT request then you can achieve it as below:
$aObj = ['name' => 'sdfsd', 'language' => 'En'];
$headers = [
"User-Agent" => AGENT,
"Expect" => "100-continue",
"api-origin" => "LTc",
"Connection" => "Keep-Alive",
"accept" => "application/json",
"Host" => "xyz.com",
"Accept-Encoding"=> " gzip, deflate",
"Cache-Control"=> "no-cache",
"verify" => false,
"Content-Type" => "application/json"
];
$client = new GuzzleHttp\Client([
'auth' => ['testUsername', 'testPassword'],
'timeout' => '10000',
'base_uri' => YOUR_API_URL,
'headers' => $headers
]);
$oResponse = $client->request('PUT', '/user/UpdateUser?format=json', ['body' => json_encode( $aObj, JSON_UNESCAPED_SLASHES)]);
$oUser = json_decode( $oResponse->getBody());

Categories