Eseguire richieste HTTP con basic auth in Laravel
Laravel usa Guzzle per eseguire richieste HTTP.
Dovrebbe essere già installato, ma nel caso potete installare Guzzle con composer:
composer require guzzlehttp/guzzle
Detto ciò, oggi vediamo un caso reale di richieste inviando in header le credenziali con basic auth.
Prima di tutto aggiungete le voci sul file .env:
WEBNET_IP=URL
WEBNET_CLIENT=USERNAME
WEBNET_SECRET=PASSWORD
Ovviamente valorizzatele con i vostri dati.
Poi create un controller tipo questo:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
class WebnetController extends Controller {
private $wnUrl;
private $wnClient;
private $wnSecret;
public function __construct() {
$this->wnUrl = env('WEBNET_IP');
$this->wnClient = env('WEBNET_CLIENT');
$this->wnSecret = env('WEBNET_SECRET');
}
private function getRequest($url) {
return Http::withBasicAuth($this->wnClient, $this->wnSecret)
// ->withOptions([
// 'debug' => true
// ])
->get($url)
->json();
}
public function getCards($cards) {
$res = $this->getRequest($this->wnUrl . "/getCard?cards=$cards");
var_dump($res);
}
}
Come vedete usiamo la funzione withBasicAuth per inviare username e password.
Ci penserà la libreria a convertire il tutto in BASE64.
A questo punto non ci resta che richiamare il controller nel file api.php:
Route::group(["prefix" => "webnet"], function () {
Route::get('/cards/{card}', [WebnetController::class, 'getCards']);
});
Enjoy!
php laravel http guzzle withbasicauth
Commentami!