Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. … Middleware system allows you to augment and compose client behavior.Apr 22, 2018
How GuzzleHttp helps?
The idea is to create an endpoint at our back end, that we can make a request to the backend endpoint that contain those secret information that we need to keep secret. This way we can avoid to embed / hard coded all the important information on our javascript request each time..
Install the package on our Laravel.
composer require guzzlehttp/guzzle
Make a route on our api. Let say AuthController
Route::post('/login','Auth\AuthController@login');
Create a controller route.
php artisan make:controller Auth/AuthController
Paste this on our controller
public function login(Request $request) { $http = new \GuzzleHttp\Client; try{ $response = $http->post('http://localhost:8888/test/public/oauth/token',[ 'form_params' => [ 'grant_type' => 'password', 'client_id' => 2, 'client_secret' => 'Fi7uzcm31Luf3LTz5ZevBVL', 'username' => $request->username , 'password' => $request->password , ] ]); return $response->getBody(); } catch (\GuzzleHttp\Exception\BadResponseException $e){ if($e->getCode()==400){ return response()->json('Invalid Request. Please enter a username or a password', $e->getCode()); }else if($e->getCode()==401){ return response()->json('Your credential is incorrect. Please try again.', $e->getCode()); } return response()->json('Something wrong on the server.',$e->getCode()); } }
Leave a Reply