From abc3f69c4dc3a16733dab901bed4c7b23c4e21f0 Mon Sep 17 00:00:00 2001 From: tolu-paystack Date: Thu, 21 May 2020 16:47:56 +0100 Subject: [PATCH] abstracted http request --- src/Message/AbstractRequest.php | 16 ++++++++++++++++ src/Message/CompletePurchaseRequest.php | 12 ++++-------- src/Message/PurchaseRequest.php | 11 ++--------- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/Message/AbstractRequest.php b/src/Message/AbstractRequest.php index f3f14fb..71e84fa 100644 --- a/src/Message/AbstractRequest.php +++ b/src/Message/AbstractRequest.php @@ -37,4 +37,20 @@ public function setSecretKey($value) { $this->setParameter('secret_key', $value); } + + protected function sendRequest($method, $endpoint, array $data = null) + { + + $headers = [ + 'Authorization' => 'Bearer ' . $this->getSecretKey(), + 'Content-Type' => 'application/json', + 'Cache-Control' => 'no-cache' + ]; + + $response = $this->httpClient->request($method, $this->baseApiEndpoint. $endpoint, $headers, json_encode($data)); + $responseData = json_decode((string)$response->getBody(), true); + + return $responseData; + + } } diff --git a/src/Message/CompletePurchaseRequest.php b/src/Message/CompletePurchaseRequest.php index 30e43b5..4d69a3e 100644 --- a/src/Message/CompletePurchaseRequest.php +++ b/src/Message/CompletePurchaseRequest.php @@ -28,15 +28,11 @@ public function getData() public function sendData($data) { try { - $headers = [ - 'Authorization' => 'Bearer ' . $this->getSecretKey(), - 'Content-Type' => 'application/json', - 'Cache-Control' => 'no-cache' - ]; - - $response = $this->httpClient->request('GET', $this->getApiEndpoint(), $headers, json_encode($data)); - $responseData = json_decode((string)$response->getBody(), true); + + $response = $this->sendRequest('GET', $this->getApiEndpoint(), json_encode($data)); + } catch (\Exception $e) { + throw new InvalidRequestException($e->getMessage(), $e->getCode(), $e); } diff --git a/src/Message/PurchaseRequest.php b/src/Message/PurchaseRequest.php index 9a2d765..c83b45d 100644 --- a/src/Message/PurchaseRequest.php +++ b/src/Message/PurchaseRequest.php @@ -39,19 +39,12 @@ public function getData() public function sendData($data) { try { - $headers = [ - 'Authorization' => 'Bearer ' . $this->getSecretKey(), - 'Content-Type' => 'application/json', - 'Cache-Control' => 'no-cache' - ]; - - $response = $this->httpClient->request('POST', $this->getApiEndpoint(), $headers, json_encode($data)); - $responseData = json_decode((string)$response->getBody(), true); + $response = $this->sendRequest('POST', $this->getApiEndpoint(), $data); } catch (\Exception $e) { throw new InvalidRequestException($e->getMessage(), $e->getCode(), $e); } - return $this->response = new PurchaseResponse($this, $responseData); + return $this->response = new PurchaseResponse($this, $response); } /**