Skip to content

Instantly share code, notes, and snippets.

@gazmend-sahiti
Created December 18, 2024 16:03
Show Gist options
  • Save gazmend-sahiti/81d229cc47ab50c397e2c30412d779a1 to your computer and use it in GitHub Desktop.
Save gazmend-sahiti/81d229cc47ab50c397e2c30412d779a1 to your computer and use it in GitHub Desktop.
Laravel HTTP facade example
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class iPaymer
{
private $endpoint = 'http://127.0.0.1:8080/api/v{version}/';
private $secret;
private function __construct($secret, $v)
{
$this->secret = $secret;
$this->endpoint = str_replace('{version}', $v, $this->endpoint);
}
public static function make($secret, $v = '1')
{
return new iPaymer($secret, $v);
}
private function headers()
{
return [
'X-iPaymer-Secret' => $this->secret,
'Accept' => 'Application/json',
];
}
public function sendGetRequest($endpoint, $parameters = [])
{
$url = $this->endpoint . ltrim($endpoint, '/');
$response = Http::withHeaders($this->headers())
->get($url, $parameters);
return $this->constructResponse($url, $response);
}
public function sendPutRequest($endpoint, $parameters)
{
return $this->sendPostRequest($endpoint, array_merge($parameters, [
'_method' => 'PUT',
]));
}
public function sendDeleteRequest($endpoint, $parameters)
{
return $this->sendPostRequest($endpoint, array_merge($parameters, [
'_method' => 'DELETE',
]));
}
public function sendPostRequest($endpoint, $parameters = [])
{
$url = $this->endpoint . ltrim($endpoint, '/');
$response = Http::withHeaders($this->headers())
->asForm()
->post($url, $parameters);
return $this->constructResponse($url, $response);
}
private function constructResponse($url, $response)
{
$body = $response->successful() ? $response->json() : new \stdClass;
return [
'endpoint' => $url,
'response' => $response->body(),
'body' => $body,
'code' => $response->status(),
'error' => $response->failed() ? $response->body() : new stdClass,
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment