Skip to content

Instantly share code, notes, and snippets.

@StuMason
Last active April 5, 2024 09:01
Show Gist options
  • Save StuMason/56592376c7c4a68727874f70a23aba2b to your computer and use it in GitHub Desktop.
Save StuMason/56592376c7c4a68727874f70a23aba2b to your computer and use it in GitHub Desktop.
<?php
namespace App\Aws;
use Aws\Credentials\CredentialProvider;
use Aws\Credentials\Credentials;
use Aws\Signature\SignatureV4;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\App;
class SignedRequest
{
private $credentials;
private $role = 'arn:aws:iam::ACCOUNT_NUMBER:role/ROLE_NAME';
private $service = 'lambda';
private $region = 'eu-west-1';
private $client;
public function __construct($service = 'execute-api', $region = 'eu-west-1')
{
$this->service = $service;
$this->region = $region;
$this->client = new Client();
$this->resolveCredentials();
}
private function resolveCredentials()
{
if (in_array(App::environment(), ['local', 'testing'])) {
$this->credentials = CredentialProvider::sso('profile speakcloud');
$this->resolveCredentialsWithRole();
} else {
$this->credentials = CredentialProvider::defaultProvider();
}
}
private function resolveCredentialsWithRole()
{
$sts = App::make('aws')->createClient('sts', [
'region' => $this->region,
'version' => 'latest',
'credentials' => $this->credentials
]);
$assumeRole = $sts->assumeRole([
'RoleArn' => $this->role,
'RoleSessionName' => 'nomad-golf'
]);
$this->credentials = new Credentials(
$assumeRole['Credentials']['AccessKeyId'],
$assumeRole['Credentials']['SecretAccessKey'],
$assumeRole['Credentials']['SessionToken']
);
}
public function post(string $url, array $request, array $headers = []): \Psr\Http\Message\ResponseInterface
{
$guzzleRequest = new Request(
'POST',
$url,
$headers,
json_encode($request)
);
$signedRequest = (new SignatureV4($this->service, $this->region))
->signRequest($guzzleRequest, $this->credentials);
return $this->client->send($signedRequest);
}
}
////
$url = getenv('API_GATEWAY_ENDPOINT')
$request = [
'date' => $date ?? Carbon::tomorrow()->format('Y-m-d'),
'platform' => $this->booking_platform,
'url' => $this->booking_url,
];
$signedRequest = new SignedRequest();
$response = $signedRequest->post($scrappy, $request);
return json_decode($response->getBody()->getContents(), true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment