Currently I am authorizing the Amadeus API and receiving an access token through a service class, i.e. Amadeus\Client
. There are several API endpoints for multiple functions, so I want to maintain separate classes for separate endpoints. Each endpoint requires access token to process the request. How can I transfer the authorization token form the Amadeus\Client
to Amadeus\FlightOffersSearch
so I can pass the access token into the headers of the endpoint. Please can someone help me here?
Amadeus\Client
class Client
{
public function __construct(
protected string $uri,
protected string $client_id,
protected string $client_secret,
protected string $grant_type,
) {}
public function authorization() {
$uri = $this->uri;
$auth_data = array(
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => $this->grant_type
);
$requests_response = Http::asForm()->post($uri, $auth_data);
$response_body = json_decode($requests_response->body());
$access_token = $response_body->access_token;
return $access_token;
}
Amadeus\FlightOffersSearch
class Flight
{
public function get_flight() {
if(isset($access_token)){
$endpoint = 'https://test.api.amadeus.com/v2/shopping/flight-offers';
$travel_data = array(
'originLocationCode' => 'BOS',
'destinationLocationCode' => 'PAR',
'departureDate' => '2022-06-14',
'adults' => 2
);
$params = http_build_query($travel_data);
$url = $endpoint.'?'.$params;
$headers = array('Authorization' => 'Bearer '.$access_token);
}
}
}
CodePudding user response:
This is more PHP specific than Laravel. I suggest you make the client a singleton class where you encapsulate all the authentication logic and just get the client instance when you need it using a static method.
I also highly recommend using GuzzleHttp for HTTP client.
Something like this draft.
<?php
namespace App;
use GuzzleHttp\Client;
class AmadeusClient
{
private static $instance;
private $client;
private $token;
public function __construct()
{
throw_if(static::$instance, 'There should be only one instance of this class');
static::$instance = $this;
$this->client = new Client([
'base_uri' => 'https://test.api.amadeus.com/v2/',
]);
}
private function authenticate()
{
if (!$this->token) {
$client_id = env('api_client_id');
$client_secret = env('api_client_secret');
$grant_type = env('api_grant_type$a');
$this->token = ''; // TODO: get authorization token using $this->client;
}
}
public static function getInstance()
{
return static::$instance;
}
public function get($uri, array $options = [])
{
$this->authenticate();
return $this->client->get($uri, $options);
}
public function post($uri, array $options = [])
{
$this->authenticate();
return $this->client->post($uri, $options);
}
}
You would then use it like this:
$client = AmadeusClient::getInstance();
$client->get('shopping/flight-offers', $options);