Skip to content

Instantly share code, notes, and snippets.

@gazmend-sahiti
Created December 18, 2024 16:00
Show Gist options
  • Save gazmend-sahiti/17523fabcb4aaabfff66d558dc9d4af0 to your computer and use it in GitHub Desktop.
Save gazmend-sahiti/17523fabcb4aaabfff66d558dc9d4af0 to your computer and use it in GitHub Desktop.
<?php
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, '/');
if (!empty($parameters)) {
$url .= '?' . http_build_query($parameters);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers());
$response = curl_exec($ch);
$error = curl_error($ch);
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $this->constructResponse($url, $response, $responseCode, $error);
}
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, '/');
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers());
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
$response = curl_exec($ch);
$error = curl_error($ch);
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $this->constructResponse($url, $response, $responseCode, $error);
}
private function constructResponse($url, $response, $code, $error)
{
$body = json_decode($response);
return [
'endpoint' => $url,
'response' => $response,
'body' => !empty($response) && json_last_error() === JSON_ERROR_NONE ? $body : new stdClass,
'code' => $code,
'error' => $error,
];
}
}
$iPaymer = iPaymer::make('9dc1479e-0565-4ee2-865c-0220e7e21420', 1);
$response = $iPaymer->sendGetRequest('invoice');
echo '<pre>'; print_r($response);
// var_dump($iPaymer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment