Guzzle HTTP POST request in laravel - laravel

how to pass path parameter in guzzle HTTP Post request. I am having url like this - http://base_url/v1/rack/{id}/books
in my url {id} is the path parameter.
$addLibraryUrl = $base_url."v1/rack/{id}/book";
$headers["id"] = $id;
$requestContent['json'] = $data;
$client = new Client();
$response = $client->post($addLibraryUrl, [
"headers" => $headers,
"json" => json_encode($data)
]);

I dont think the latest guzzle uses URI templates, but the functionality to do the parameter replacing is still there:
$addLibraryUrl = \GuzzleHttp\uri_template($base_url. "v1/rack/{id}/book" , [
'id' => $id,
]);
Also you can just put the id into the URI yourself very easily.
$addLibraryUrl = $base_url."v1/rack/{$id}/book";
example:
blah.com/v1/rack/5/book

I solved my issue in this way:
$id = your_rack_id_value;
$client = new Client([ 'base_uri' => $base_url, ]);
$uri = 'v1/rack/.$id.'/book';
$requestEncodedData = json_encode($data);
$response = $client->post($uri, [
'body' => $requestEncodedData,
'headers' => [
'Content-Type' => 'application/json',
]
]);

If you sent form params then you need to sent them as post params like :
// Initialize Guzzle client
$client = new GuzzleHttp\Client(['headers'=> 'Some headers']);
// Create a POST request
$response = $client->request(
'POST',
'http://yoururl.com',
[
'form_params' => [
'key1' => 'value1',
'key2' => 'value2'
]
]
);
Or like in your case change 'json' to form_params:
$addLibraryUrl = $base_url."v1/rack/{id}/book";
$headers["id"] = $id;
$requestContent['json'] = $data;
$client = new Client();
$response = $client->post($addLibraryUrl, [
"headers" => $headers,
"form_params" => json_encode($data)
]);

Related

Foreach Loop not running in Laravel

I want to send a request to external API using guzzle, but not foreach is not running.
public function recursub() {
$usersCheck = User::where('trialExpires', '<=', Carbon::now());
//Get all Check User
foreach ($usersCheck as $user) {
dd('Hello');
$url = 'https://api.##############';
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'#########################',
'Content-Type' => 'application/json'
],
'form_params' => [
'authorization_code' => $user->authorization_code,
'customer' => $user->email,
//'plan' => '#######################',
]
]);
It worked if I hardcode the value into the form paramas.
public function recursub() {
$usersCheck = User::where('trialExpires', '<=', Carbon::now())->get();
//Get all Check User
foreach ($usersCheck as $user) {
dd('Hello');
$url = 'https://api.##############';
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'#########################',
'Content-Type' => 'application/json'
],
'form_params' => [
'authorization_code' => $user->authorization_code,
'customer' => $user->email,
//'plan' => '#######################',
]
]);
get() method is used to get data in array, so now you have to add get() method in the last of the query. Here is the code below:
$usersCheck = User::where('trialExpires', '<=', Carbon::now())->get();
get() method is used for getting multiple records and first is used for single record.

How to create SSO URL in paperlesspipeline

i am trying to create SSO URL for the paperlesspipeline, so it no needs to credential for login
i have to use laravel 5.8 and it's GuzzleHttp package
$timestamp = date(DateTime::ISO8601);
$userID = '*****';
$url = "https://dev.paperlesspipeline.com/sso/signin-v1/";
$hash = hash_hmac('SHA256', $userID.$timestamp,secret key,false);
$client = new \GuzzleHttp\Client(['http_errors' => false]);
$options = [
'form_params' => [
"USERID" => $userID,
"timestamp" => $timestamp,
"hash" => $hash
]
];
$response = $client->post($url, $options);
I am not get sso url, can you halp me what wrong.
You can try this
$response = $client->request('POST', $url, $options);

Laravel - How to pass the result of Post Request

I have this code I have written and tested. The first phase
mokkle_test(Request $request)
is working. I have issue with how to pass the result of the request to the second phase
First phase:
public function mokkle_test(Request $request)
{
$telco_match=['name'=>'Icell'];
$telco=Telco::where($telco_match)->first();
try{
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' =>$request->text,
'correlator' =>$request->correlator,
'serviceid' =>$request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$noti=new Notification_log();
$noti->error_message= (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
}catch(\Exception $e)
{
return $e->getMessage();
}
}
... and its working very well.
How do I pass the result of the response into another function shown below.
Second phase:
function subscribe($request,$telco)
{
try{
$client = new Client();
$response = $client->request(
'POST', $telco->billing_callback_2, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->password,
'amount' =>$request->amount,
'shortcode' => $request->shortcode
],
'headers' => [
'auth' => $telco->authorization,
'key' => $telco->key,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$amount = $request->amount;
$shortcode = $request->shortcode;
$noti=new Notification_log();
$noti->error_message=(string)$response;
$noti->msisdn=$request->msisdn;
$noti->product_id=$request->productid;
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
$request = array();
$request->text= "Weldone";
$request->amount = $amount;
$request->serviceid="100010";
$request->correlator="876543ghj";
$result_sms=self::mokkle_test($request);
return $result;
}catch(\Exception $e)
{
return $e;
}
}
I tried this, but nothing is happening
$result_sms=self::mokkle_test($request);
Kindly assist. How do I achieve my goal. Kindly assist me.
Here you can pass it to the other method
public function mokkle_test(Request $request)
{
$telco_match = ['name' => 'Icell'];
$telco = Telco::where($telco_match)->first();
try {
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' => $request->text,
'correlator' => $request->correlator,
'serviceid' => $request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
// Here you can pass it to the other method
this.subscribe($response, $telco); // <--- $response will be your "$request" parameter
$noti = new Notification_log();
$noti->error_message = (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}

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.

laravel guzzle httpsocket parameters for ssl verify peer & host

I have the following code in CakePHP. I need the same code in laravel using guzzle
$url = "https://xyz?";
$query ='first_name='. $data->FirstName .'&gender=""'. '&home_phone='. $data->HomePhone.'&ip_address='. $data->IPAddress.'&last_name='. $data->LastName.'&user_defined_url='. $result;
$HttpSocket = new HttpSocket(array('ssl_verify_peer' => false, 'ssl_verify_host' => false));
$post_response = $HttpSocket->get($url,$query);
$response = explode('&',$post_response->body);
I have converted it in laravel using guzzle but doesnt work. Following my code that Ive converted in laravel:
$client = new Client(['verify' => false ]);
$post_response = $client->get($url, $query);
$response = explode('&',$post_response->body);
Note: use GuzzleHttp\Client; is written at the top of file.
Thanks in advance for the help!
Can you try like this,
$client = new Client();
$post_response = $client->request('GET', $url, [
'verify' => false,
'form_params' => [
'first_name' => $data->FirstName,
'gender' => "",
'home_phone' => $data->HomePhone,
'ip_address' => $data->IPAddress,
'last_name' => $data->LastName,
'user_defined_url' => $result
]
]);
$response = explode('&',$post_response->body);
Instead of form_params you can use query for sending the parameters as query string.

Resources